@chronodivide/game-api 0.40.0 → 0.42.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),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:()=>rc,AiRules:()=>cr,ApiEventType:()=>sc,ArmorType:()=>si,AttackState:()=>ho,Bot:()=>Vc,BuildCat:()=>Xi,BuildStatus:()=>Do,CombatDamageRules:()=>hr,Country:()=>kn,CountryRules:()=>Oi,CrateRules:()=>gr,CrewRules:()=>Pi,DMislRules:()=>ji,FactoryStatus:()=>qn,FactoryType:()=>Yi,GameApi:()=>xc,GameInstanceApi:()=>sm,GeneralRules:()=>Vi,HoverRules:()=>Wi,InfDeathType:()=>ei,IniFile:()=>c,IniSection:()=>h,LandTargeting:()=>ai,LandType:()=>Kt,LightningStormRules:()=>Mi,LocomotorType:()=>ii,MapApi:()=>bc,MissileRules:()=>Li,MovementZone:()=>ri,NavalTargeting:()=>ni,ObjectRules:()=>Ii,ObjectType:()=>Bt,OrderType:()=>Ho,OverlayRules:()=>rr,ParadropRules:()=>Di,PipColor:()=>ti,PrereqCategory:()=>Xt,PrismRules:()=>Ni,ProductionApi:()=>Uc,ProjectileRules:()=>qi,PublicApi:()=>bm,QueueStatus:()=>bn,QueueType:()=>Tn,RadarEventType:()=>Qt,RadarRules:()=>Bi,RadiationRules:()=>dr,RepairRules:()=>Ei,RulesApi:()=>Ac,SideType:()=>Zt,SpeedType:()=>Jt,StanceType:()=>Nr,SuperWeaponStatus:()=>Br,SuperWeaponType:()=>Ji,Tag:()=>vm,TagRepeatType:()=>Gt,TechnoRules:()=>ir,TerrainRules:()=>sr,TerrainType:()=>Yt,TheaterType:()=>I,ThreatRules:()=>Ri,V3RocketRules:()=>Fi,VeteranAbility:()=>hi,VeteranLevel:()=>ea,VeteranRules:()=>xi,VhpScan:()=>li,WarheadRules:()=>$i,WeaponRules:()=>Ai,WeaponType:()=>oi,ZoneType:()=>fr,cdapi:()=>Sm});__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(/\,$/,"").replace(/\,+/g,","),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;let a;if(r){let e=Object.getOwnPropertyNames(t);r=e.find(e=>e.toLowerCase()===s.toLowerCase());r&&(a=t[r])}else t.hasOwnProperty(s)&&(a=t[s]);return void 0===a?(console.warn(`Invalid value for key "${e}". "${s}" is not an accepted enum value.`),i):a}getEnumNumeric(e,t,i){var r=this.getString(e).trim();if(!r)return i;let s;return Number.isInteger(parseInt(r,10))&&t.hasOwnProperty(r)&&(s=parseInt(r,10)),void 0===s?(console.warn(`Invalid value for key "${e}". "${r}" is not an accepted enum value.`),i):s}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(e<0||this.images.length<=e)throw new RangeError(`Image index out of bounds (file=${this.filename}, index=${e}, length=${this.images.length})`);return this.images[e]}addImage(e){this.images.push(e),this.numImages++}clip(e,t){let i=new 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=G.REMAP_START_IDX;e<G.REMAP_START_IDX+i.length;e++)this.colors[e].r=Math.floor(t.r/255*i[e-G.REMAP_START_IDX]*4),this.colors[e].g=Math.floor(t.g/255*i[e-G.REMAP_START_IDX]*4),this.colors[e].b=Math.floor(t.b/255*i[e-G.REMAP_START_IDX]*4);return this._hash=this.computeHash(this.colors),this}}G.REMAP_START_IDX=16;class ${constructor(e,t){this.owner=e,this.index=t,this.files=[]}addFile(e){this.files.push(e)}setAnimation(e){this.animation=e}getAnimation(){return this.animation}getTmpFile(e,t=!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("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===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 extends l{constructor(){super(...arguments),this.name="NameNotAllowedError"}}class me{constructor(e,t=!1){this.handle=e,this.caseSensitive=t}get name(){return this.handle.name}async*getEntries(){try{for await(var e of this.handle.keys())yield e}catch(e){if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${this.handle.name}" could not be read (${e.name})`,{cause:e});throw e}}async listEntries(){let e=[];for await(var t of this.getEntries())e.push(t);return e}async*getFileHandles(){try{for await(const e of this.handle.values())"file"===e.kind&&(yield e)}catch(e){if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${this.handle.name}" could not be read (${e.name})`,{cause:e});throw e}}async*getRawFiles(){for await(const e of this.getFileHandles())yield await e.getFile()}async containsEntry(e){return void 0!==await this.resolveEntryName(e)}async resolveEntryName(e){if(this.caseSensitive)return(await this.handle.getFileHandle(e).catch(()=>this.handle.getDirectoryHandle(e)).catch(()=>{}))?.name;for await(const t of this.getEntries())if(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 TypeError&&e.message.includes("not allowed"))throw new ge(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be read (${e.name})`,{cause:e});throw e}t=await 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 TypeError&&e.message.includes("not allowed"))throw new ge(`File name "${r}" is not allowed`,{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 TypeError&&e.message.includes("not allowed"))throw new ge(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}async getDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);let 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 TypeError&&e.message.includes("not allowed"))throw new ge(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be read (${e.name})`,{cause:e});throw e}return new me(r,e)}async getOrCreateDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);try{return new me(await this.handle.getDirectoryHandle(i,{create:!0}),e)}catch(e){if("QuotaExceededError"===e.name)throw new pe({cause:e});if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be created (${e.name})`,{cause:e});throw e}}async deleteDirectory(t,e=!1){t=await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t,{recursive:e})}catch(e){if("QuotaExceededError"===e.name)throw new pe({cause:e});if("InvalidModificationError"===e.name)throw new l("Can't delete non-empty directory when recursive = false");if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}}class fe{constructor(){this.directories=[]}addRootDirectoryHandle(e){this.rootDirectory=this.addDirectoryHandle(e),this.rootDirectoryHandle=e}getRootDirectoryHandle(){return this.rootDirectoryHandle}addDirectoryHandle(e){e=new me(e);return this.directories.push(e),e}addDirectory(e){this.directories.push(e)}async getDirectory(e){var t=await this.findDirectory(e);if(!t)throw new Error(`Directory "${e}" not found in real file system`);return t}async findDirectory(e){for(const t of this.directories)if(await t.containsEntry(e))return 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 ye{constructor(e){this.resourceFactory=e,this.resources=new Map}setVfs(e){this.vfs=e}set(e,t){this.resources.set(e,t)}has(e){return!!this.resources.has(e)||(this.vfs?.fileExists(e)??!1)}get(e){let t;return t=this.resources.get(e),!t&&this.vfs?.fileExists(e)&&(t=this.resourceFactory(this.vfs.openFile(e)),this.resources.set(e,t)),t}clear(e){e?this.resources.delete(e):this.resources.clear()}}const we="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Te(r,e,s,t){if(-1<["32f","64"].indexOf(e)&&-1<["32f","64"].indexOf(t))s.set(r);else{_e(e),_e(t);let i=function(e,t){let i=function(e){return e};e!=t&&(i=["32f","64"].includes(e)?ve:["32f","64"].includes(t)?Se:be);return i}(e,t);var a={oldMin:Math.pow(2,parseInt(e,10))/2,newMin:Math.pow(2,parseInt(t,10))/2,oldMax:Math.pow(2,parseInt(e,10))/2-1,newMax:Math.pow(2,parseInt(t,10))/2-1};ke(e,r,!0);for(let e=0,t=r.length;e<t;e++)s[e]=i(r[e],a);ke(t,s,!1)}}function be(e,t){return e=0<e?parseInt(e/t.oldMax*t.newMax,10):parseInt(e/t.oldMin*t.newMin,10)}function ve(e,t){return parseInt(0<e?e*t.newMax:e*t.newMin,10)}function Se(e,t){return 0<e?e/t.oldMax:e/t.oldMin}function _e(e){if("32f"!=e&&"64"!=e&&(parseInt(e,10)<"8"||"53"<parseInt(e,10)))throw new Error("Invalid bit depth.")}function ke(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 Oe=[-1,-1,-1,-1,2,4,6,8,-1,-1,-1,-1,2,4,6,8],Ie=[7,8,9,10,11,12,13,14,16,17,19,21,23,25,28,31,34,37,41,45,50,55,60,66,73,80,88,97,107,118,130,143,157,173,190,209,230,253,279,307,337,371,408,449,494,544,598,658,724,796,876,963,1060,1166,1282,1411,1552,1707,1878,2066,2272,2499,2749,3024,3327,3660,4026,4428,4871,5358,5894,6484,7132,7845,8630,9493,10442,11487,12635,13899,15289,16818,18500,20350,22385,24623,27086,29794,32767];function Ae(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){Be(e,t);let i=[];return i.push(255&e),i.push(e>>8&255),i.push(t.index),i.push(0),i}(i[0],r);for(let e=3,t=i.length;e<t;e+=2){var a=Be(i[e],r),n=Be(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=Ie[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(Ee(a,r)),s.push(Ee(n,r))}return s}(s,i);r.set(l,a),a+=l.length,s=[],n-=e}return r.slice(0,a)}function Be(e,t){let i=e-t.predicted,r=0;0<=i?r=0:(r=8,i=-i);let s=Ie[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+=Oe[7&e],i.index<0?i.index=0:88<i.index&&(i.index=88)}(r,a,t),r}function Ee(e,t){let i=0;return 4&e&&(i+=t.step),2&e&&(i+=t.step>>1),1&e&&(i+=t.step>>2),i+=t.step>>3,8&e&&(i=-i),t.predicted+=i,32767<t.predicted?t.predicted=32767:t.predicted<-32768&&(t.predicted=-32768),function(e,t){t.index+=Oe[e],t.index<0?t.index=0:88<t.index&&(t.index=88);t.step=Ie[t.index]}(e,t),t.predicted}const xe=[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=xe[e>>8&127])<<4|e>>i+3&15:e>>4,85^t^r}(i[e]);return r}function Ne(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 Re=132,De=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],Le=[0,132,396,924,1980,4092,8316,16764];function Fe(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+=Re)>De&&(s=De),~(a|(a=Me[s>>7&255])<<4|s>>a+3&15));var s,a;return r}function je(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=Le[i]+(e<<3+i),0!=t&&(r=-r),r}(i[e]);return r}function We(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 Ve=new Array(8).fill(0).map((e,t)=>Math.pow(2,8*t));class ze{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/Ve[e]),s++;return s}unpack_(t,i=0){let r=0;for(let e=0;e<this.offset;e++)r+=t[i+e]*Ve[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 He{constructor(e,t){this.offset=Math.ceil((e+t)/8),this.ebits=e,this.fbits=t,this.bias=(1<<e-1)-1,this.biasP2=Math.pow(2,this.bias+1),this.ebitsFbits=e+t,this.fbias=Math.pow(2,-(8*this.offset-1-e))}pack(e,t,i){var 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=Ge(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,Ge(a)-Math.pow(2,this.fbits))):(a=Ge(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 Ge(e){var t=Math.floor(e),e=e-t;return!(e<.5)&&(.5<e||t%2)?t+1:t}function $e(e,t=0,i=e.length){return function(o,e=0,t=o.length){let h="";for(let n=e;n<t;){let i=128,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 qe(e){var t=[];return Ue(e,t),t}function Ze(e,t,i=0){return Ue(e,t,i)}function Qe(e,t,i,r=0){let s=tt((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&&We(i,a,o,r),r}function Xe(e,t,i,r=0,s=e.length){var a,n=tt((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&&We(a,n.offset,r,s),et(a,i,r,s,n)):et(e,i,r,s,n)}function Ye(e,t,i,r=0){return Qe([e],t,i,r)}function Ke(e,t){var i=[];return Ye(e,t,i,0),i}function Je(e,t,i=0){var r=[];return Xe(e,t,r,i,i+Math.ceil(t.bits/8)),r[0]}function et(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 tt(e,t,i){return t&&32==e?new He(8,23):t&&64==e?new He(11,52):new ze(e,i)}function it(e,t){let i=qe(e);for(let e=i.length;e<t;e++)i.push(0);return i}(class _m 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=$e(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Je(e,this.uInt32,this.head),this.head+=4,e}getSubChunksIndex_(e){let t=[],i=this.head;for(;i<=e.length-8;)t.push(this.getSubChunkIndex_(e,i)),i+=8+t[t.length-1].chunkSize,i=i%2?i+1:i;return t}getSubChunkIndex_(e,t){let i={chunkId:this.getChunkId_(e,t),chunkSize:this.getChunkSize_(e,t)};return"LIST"==i.chunkId?(i.format=$e(e,t+8,t+12),this.head+=4,i.subChunks=this.getSubChunksIndex_(e)):(e=i.chunkSize%2?i.chunkSize+1:i.chunkSize,this.head=t+8+e,i.chunkData={start:t+8,end:this.head}),i}getChunkId_(e,t){return this.head+=4,$e(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Je(e,this.uInt32,t+4)}}{constructor(){super(),this.supported_containers.push("RF64"),this.fmt={chunkId:"",chunkSize:0,audioFormat:0,numChannels:0,sampleRate:0,byteRate:0,blockAlign:0,bitsPerSample:0,cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]},this.fact={chunkId:"",chunkSize:0,dwSampleLength:0},this.cue={chunkId:"",chunkSize:0,dwCuePoints:0,points:[]},this.smpl={chunkId:"",chunkSize:0,dwManufacturer:0,dwProduct:0,dwSamplePeriod:0,dwMIDIUnityNote:0,dwMIDIPitchFraction:0,dwSMPTEFormat:0,dwSMPTEOffset:0,dwNumSampleLoops:0,dwSamplerData:0,loops:[]},this.bext={chunkId:"",chunkSize:0,description:"",originator:"",originatorReference:"",originationDate:"",originationTime:"",timeReference:[0,0],version:0,UMID:"",loudnessValue:0,loudnessRange:0,maxTruePeakLevel:0,maxMomentaryLoudness:0,maxShortTermLoudness:0,reserved:"",codingHistory:""},this.iXML={chunkId:"",chunkSize:0,value:""},this.ds64={chunkId:"",chunkSize:0,riffSizeHigh:0,riffSizeLow:0,dataSizeHigh:0,dataSizeLow:0,originationTime:0,sampleCountHigh:0,sampleCountLow:0},this.data={chunkId:"",chunkSize:0,samples:new Uint8Array(0)},this.LIST=[],this.junk={chunkId:"",chunkSize:0,chunkData:[]},this._PMX={chunkId:"",chunkSize:0,value:""},this.uInt16={bits:16,be:!1,signed:!1,fp:!1}}fromBuffer(e,t=!0){if(this.clearHeaders(),this.setSignature(e),this.uInt16.be=this.uInt32.be,"WAVE"!=this.format)throw Error('Could not find the "WAVE" format identifier');this.readDs64Chunk_(e),this.readFmtChunk_(e),this.readFactChunk_(e),this.readBextChunk_(e),this.readiXMLChunk_(e),this.readCueChunk_(e),this.readSmplChunk_(e),this.readDataChunk_(e,t),this.readJunkChunk_(e),this.readLISTChunk_(e),this.read_PMXChunk_(e)}clearHeaders(){var e=new _m;Object.assign(this.fmt,e.fmt),Object.assign(this.fact,e.fact),Object.assign(this.cue,e.cue),Object.assign(this.smpl,e.smpl),Object.assign(this.bext,e.bext),Object.assign(this.iXML,e.iXML),Object.assign(this.ds64,e.ds64),Object.assign(this.data,e.data),this.LIST=[],Object.assign(this.junk,e.junk),Object.assign(this._PMX,e._PMX)}readFmtChunk_(e){var t=this.findChunk("fmt ");if(!t)throw Error('Could not find the "fmt " chunk');this.head=t.chunkData.start,this.fmt.chunkId=t.chunkId,this.fmt.chunkSize=t.chunkSize,this.fmt.audioFormat=this.readUInt16_(e),this.fmt.numChannels=this.readUInt16_(e),this.fmt.sampleRate=this.readUInt32(e),this.fmt.byteRate=this.readUInt32(e),this.fmt.blockAlign=this.readUInt16_(e),this.fmt.bitsPerSample=this.readUInt16_(e),this.readFmtExtension_(e)}readFmtExtension_(e){16<this.fmt.chunkSize&&(this.fmt.cbSize=this.readUInt16_(e),18<this.fmt.chunkSize&&(this.fmt.validBitsPerSample=this.readUInt16_(e),20<this.fmt.chunkSize&&(this.fmt.dwChannelMask=this.readUInt32(e),this.fmt.subformat=[this.readUInt32(e),this.readUInt32(e),this.readUInt32(e),this.readUInt32(e)])))}readFactChunk_(e){var t=this.findChunk("fact");t&&(this.head=t.chunkData.start,this.fact.chunkId=t.chunkId,this.fact.chunkSize=t.chunkSize,this.fact.dwSampleLength=this.readUInt32(e))}readCueChunk_(t){var e=this.findChunk("cue ");if(e){this.head=e.chunkData.start,this.cue.chunkId=e.chunkId,this.cue.chunkSize=e.chunkSize,this.cue.dwCuePoints=this.readUInt32(t);for(let e=0;e<this.cue.dwCuePoints;e++)this.cue.points.push({dwName:this.readUInt32(t),dwPosition:this.readUInt32(t),fccChunk:this.readString(t,4),dwChunkStart:this.readUInt32(t),dwBlockStart:this.readUInt32(t),dwSampleOffset:this.readUInt32(t)})}}readSmplChunk_(t){var e=this.findChunk("smpl");if(e){this.head=e.chunkData.start,this.smpl.chunkId=e.chunkId,this.smpl.chunkSize=e.chunkSize,this.smpl.dwManufacturer=this.readUInt32(t),this.smpl.dwProduct=this.readUInt32(t),this.smpl.dwSamplePeriod=this.readUInt32(t),this.smpl.dwMIDIUnityNote=this.readUInt32(t),this.smpl.dwMIDIPitchFraction=this.readUInt32(t),this.smpl.dwSMPTEFormat=this.readUInt32(t),this.smpl.dwSMPTEOffset=this.readUInt32(t),this.smpl.dwNumSampleLoops=this.readUInt32(t),this.smpl.dwSamplerData=this.readUInt32(t);for(let e=0;e<this.smpl.dwNumSampleLoops;e++)this.smpl.loops.push({dwName:this.readUInt32(t),dwType:this.readUInt32(t),dwStart:this.readUInt32(t),dwEnd:this.readUInt32(t),dwFraction:this.readUInt32(t),dwPlayCount:this.readUInt32(t)})}}readDataChunk_(e,t){var i=this.findChunk("data");if(!i)throw Error('Could not find the "data" chunk');this.data.chunkId="data",this.data.chunkSize=i.chunkSize,t&&(this.data.samples=e.slice(i.chunkData.start,i.chunkData.end))}readBextChunk_(e){var t=this.findChunk("bext");t&&(this.head=t.chunkData.start,this.bext.chunkId=t.chunkId,this.bext.chunkSize=t.chunkSize,this.bext.description=this.readString(e,256),this.bext.originator=this.readString(e,32),this.bext.originatorReference=this.readString(e,32),this.bext.originationDate=this.readString(e,10),this.bext.originationTime=this.readString(e,8),this.bext.timeReference=[this.readUInt32(e),this.readUInt32(e)],this.bext.version=this.readUInt16_(e),this.bext.UMID=this.readString(e,64),this.bext.loudnessValue=this.readUInt16_(e),this.bext.loudnessRange=this.readUInt16_(e),this.bext.maxTruePeakLevel=this.readUInt16_(e),this.bext.maxMomentaryLoudness=this.readUInt16_(e),this.bext.maxShortTermLoudness=this.readUInt16_(e),this.bext.reserved=this.readString(e,180),this.bext.codingHistory=this.readString(e,this.bext.chunkSize-602))}readiXMLChunk_(e){var t=this.findChunk("iXML");t&&(this.head=t.chunkData.start,this.iXML.chunkId=t.chunkId,this.iXML.chunkSize=t.chunkSize,this.iXML.value=$e(e,this.head,this.head+this.iXML.chunkSize))}readDs64Chunk_(e){var t=this.findChunk("ds64");if(t)this.head=t.chunkData.start,this.ds64.chunkId=t.chunkId,this.ds64.chunkSize=t.chunkSize,this.ds64.riffSizeHigh=this.readUInt32(e),this.ds64.riffSizeLow=this.readUInt32(e),this.ds64.dataSizeHigh=this.readUInt32(e),this.ds64.dataSizeLow=this.readUInt32(e),this.ds64.originationTime=this.readUInt32(e),this.ds64.sampleCountHigh=this.readUInt32(e),this.ds64.sampleCountLow=this.readUInt32(e);else if("RF64"==this.container)throw Error('Could not find the "ds64" chunk')}readLISTChunk_(t){var i=this.findChunk("LIST",!0);if(null!==i)for(let e=0;e<i.length;e++){var 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=$e(e,this.head,this.head+this._PMX.chunkSize))}readZSTR_(t,i=0){for(let e=i;e<t.length&&(this.head++,0!==t[e]);e++);return $e(t,i,this.head-1)}readUInt16_(e){return e=Je(e,this.uInt16,this.head),this.head+=2,e}});function rt(e,t,i){return!(i<1||4294967295<e*(t/8)*i)}class st extends class extends class _m 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=$e(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Je(e,this.uInt32,this.head),this.head+=4,e}getSubChunksIndex_(e){let t=[],i=this.head;for(;i<=e.length-8;)t.push(this.getSubChunkIndex_(e,i)),i+=8+t[t.length-1].chunkSize,i=i%2?i+1:i;return t}getSubChunkIndex_(e,t){let i={chunkId:this.getChunkId_(e,t),chunkSize:this.getChunkSize_(e,t)};return"LIST"==i.chunkId?(i.format=$e(e,t+8,t+12),this.head+=4,i.subChunks=this.getSubChunksIndex_(e)):(e=i.chunkSize%2?i.chunkSize+1:i.chunkSize,this.head=t+8+e,i.chunkData={start:t+8,end:this.head}),i}getChunkId_(e,t){return this.head+=4,$e(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Je(e,this.uInt32,t+4)}}{constructor(){super(),this.supported_containers.push("RF64"),this.fmt={chunkId:"",chunkSize:0,audioFormat:0,numChannels:0,sampleRate:0,byteRate:0,blockAlign:0,bitsPerSample:0,cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]},this.fact={chunkId:"",chunkSize:0,dwSampleLength:0},this.cue={chunkId:"",chunkSize:0,dwCuePoints:0,points:[]},this.smpl={chunkId:"",chunkSize:0,dwManufacturer:0,dwProduct:0,dwSamplePeriod:0,dwMIDIUnityNote:0,dwMIDIPitchFraction:0,dwSMPTEFormat:0,dwSMPTEOffset:0,dwNumSampleLoops:0,dwSamplerData:0,loops:[]},this.bext={chunkId:"",chunkSize:0,description:"",originator:"",originatorReference:"",originationDate:"",originationTime:"",timeReference:[0,0],version:0,UMID:"",loudnessValue:0,loudnessRange:0,maxTruePeakLevel:0,maxMomentaryLoudness:0,maxShortTermLoudness:0,reserved:"",codingHistory:""},this.iXML={chunkId:"",chunkSize:0,value:""},this.ds64={chunkId:"",chunkSize:0,riffSizeHigh:0,riffSizeLow:0,dataSizeHigh:0,dataSizeLow:0,originationTime:0,sampleCountHigh:0,sampleCountLow:0},this.data={chunkId:"",chunkSize:0,samples:new Uint8Array(0)},this.LIST=[],this.junk={chunkId:"",chunkSize:0,chunkData:[]},this._PMX={chunkId:"",chunkSize:0,value:""},this.uInt16={bits:16,be:!1,signed:!1,fp:!1}}fromBuffer(e,t=!0){if(this.clearHeaders(),this.setSignature(e),this.uInt16.be=this.uInt32.be,"WAVE"!=this.format)throw Error('Could not find the "WAVE" format identifier');this.readDs64Chunk_(e),this.readFmtChunk_(e),this.readFactChunk_(e),this.readBextChunk_(e),this.readiXMLChunk_(e),this.readCueChunk_(e),this.readSmplChunk_(e),this.readDataChunk_(e,t),this.readJunkChunk_(e),this.readLISTChunk_(e),this.read_PMXChunk_(e)}clearHeaders(){var e=new _m;Object.assign(this.fmt,e.fmt),Object.assign(this.fact,e.fact),Object.assign(this.cue,e.cue),Object.assign(this.smpl,e.smpl),Object.assign(this.bext,e.bext),Object.assign(this.iXML,e.iXML),Object.assign(this.ds64,e.ds64),Object.assign(this.data,e.data),this.LIST=[],Object.assign(this.junk,e.junk),Object.assign(this._PMX,e._PMX)}readFmtChunk_(e){var t=this.findChunk("fmt ");if(!t)throw Error('Could not find the "fmt " chunk');this.head=t.chunkData.start,this.fmt.chunkId=t.chunkId,this.fmt.chunkSize=t.chunkSize,this.fmt.audioFormat=this.readUInt16_(e),this.fmt.numChannels=this.readUInt16_(e),this.fmt.sampleRate=this.readUInt32(e),this.fmt.byteRate=this.readUInt32(e),this.fmt.blockAlign=this.readUInt16_(e),this.fmt.bitsPerSample=this.readUInt16_(e),this.readFmtExtension_(e)}readFmtExtension_(e){16<this.fmt.chunkSize&&(this.fmt.cbSize=this.readUInt16_(e),18<this.fmt.chunkSize&&(this.fmt.validBitsPerSample=this.readUInt16_(e),20<this.fmt.chunkSize&&(this.fmt.dwChannelMask=this.readUInt32(e),this.fmt.subformat=[this.readUInt32(e),this.readUInt32(e),this.readUInt32(e),this.readUInt32(e)])))}readFactChunk_(e){var t=this.findChunk("fact");t&&(this.head=t.chunkData.start,this.fact.chunkId=t.chunkId,this.fact.chunkSize=t.chunkSize,this.fact.dwSampleLength=this.readUInt32(e))}readCueChunk_(t){var e=this.findChunk("cue ");if(e){this.head=e.chunkData.start,this.cue.chunkId=e.chunkId,this.cue.chunkSize=e.chunkSize,this.cue.dwCuePoints=this.readUInt32(t);for(let e=0;e<this.cue.dwCuePoints;e++)this.cue.points.push({dwName:this.readUInt32(t),dwPosition:this.readUInt32(t),fccChunk:this.readString(t,4),dwChunkStart:this.readUInt32(t),dwBlockStart:this.readUInt32(t),dwSampleOffset:this.readUInt32(t)})}}readSmplChunk_(t){var e=this.findChunk("smpl");if(e){this.head=e.chunkData.start,this.smpl.chunkId=e.chunkId,this.smpl.chunkSize=e.chunkSize,this.smpl.dwManufacturer=this.readUInt32(t),this.smpl.dwProduct=this.readUInt32(t),this.smpl.dwSamplePeriod=this.readUInt32(t),this.smpl.dwMIDIUnityNote=this.readUInt32(t),this.smpl.dwMIDIPitchFraction=this.readUInt32(t),this.smpl.dwSMPTEFormat=this.readUInt32(t),this.smpl.dwSMPTEOffset=this.readUInt32(t),this.smpl.dwNumSampleLoops=this.readUInt32(t),this.smpl.dwSamplerData=this.readUInt32(t);for(let e=0;e<this.smpl.dwNumSampleLoops;e++)this.smpl.loops.push({dwName:this.readUInt32(t),dwType:this.readUInt32(t),dwStart:this.readUInt32(t),dwEnd:this.readUInt32(t),dwFraction:this.readUInt32(t),dwPlayCount:this.readUInt32(t)})}}readDataChunk_(e,t){var i=this.findChunk("data");if(!i)throw Error('Could not find the "data" chunk');this.data.chunkId="data",this.data.chunkSize=i.chunkSize,t&&(this.data.samples=e.slice(i.chunkData.start,i.chunkData.end))}readBextChunk_(e){var t=this.findChunk("bext");t&&(this.head=t.chunkData.start,this.bext.chunkId=t.chunkId,this.bext.chunkSize=t.chunkSize,this.bext.description=this.readString(e,256),this.bext.originator=this.readString(e,32),this.bext.originatorReference=this.readString(e,32),this.bext.originationDate=this.readString(e,10),this.bext.originationTime=this.readString(e,8),this.bext.timeReference=[this.readUInt32(e),this.readUInt32(e)],this.bext.version=this.readUInt16_(e),this.bext.UMID=this.readString(e,64),this.bext.loudnessValue=this.readUInt16_(e),this.bext.loudnessRange=this.readUInt16_(e),this.bext.maxTruePeakLevel=this.readUInt16_(e),this.bext.maxMomentaryLoudness=this.readUInt16_(e),this.bext.maxShortTermLoudness=this.readUInt16_(e),this.bext.reserved=this.readString(e,180),this.bext.codingHistory=this.readString(e,this.bext.chunkSize-602))}readiXMLChunk_(e){var t=this.findChunk("iXML");t&&(this.head=t.chunkData.start,this.iXML.chunkId=t.chunkId,this.iXML.chunkSize=t.chunkSize,this.iXML.value=$e(e,this.head,this.head+this.iXML.chunkSize))}readDs64Chunk_(e){var t=this.findChunk("ds64");if(t)this.head=t.chunkData.start,this.ds64.chunkId=t.chunkId,this.ds64.chunkSize=t.chunkSize,this.ds64.riffSizeHigh=this.readUInt32(e),this.ds64.riffSizeLow=this.readUInt32(e),this.ds64.dataSizeHigh=this.readUInt32(e),this.ds64.dataSizeLow=this.readUInt32(e),this.ds64.originationTime=this.readUInt32(e),this.ds64.sampleCountHigh=this.readUInt32(e),this.ds64.sampleCountLow=this.readUInt32(e);else if("RF64"==this.container)throw Error('Could not find the "ds64" chunk')}readLISTChunk_(t){var i=this.findChunk("LIST",!0);if(null!==i)for(let e=0;e<i.length;e++){var 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=$e(e,this.head,this.head+this._PMX.chunkSize))}readZSTR_(t,i=0){for(let e=i;e<t.length&&(this.head++,0!==t[e]);e++);return $e(t,i,this.head-1)}readUInt16_(e){return e=Je(e,this.uInt16,this.head),this.head+=2,e}}{toBuffer(){this.uInt16.be="RIFX"===this.container,this.uInt32.be=this.uInt16.be;var t=[this.getJunkBytes_(),this.getDs64Bytes_(),this.getBextBytes_(),this.getiXMLBytes_(),this.getFmtBytes_(),this.getFactBytes_(),qe(this.data.chunkId),Ke(this.data.samples.length,this.uInt32),this.data.samples,this.getCueBytes_(),this.getSmplBytes_(),this.getLISTBytes_(),this.get_PMXBytes_()];let i=0;for(let e=0;e<t.length;e++)i+=t[e].length;let r=new Uint8Array(i+12),s=0;s=Ze(this.container,r,s),s=Ye(i+4,this.uInt32,r,s),s=Ze(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(qe(this.bext.chunkId),Ke(602+this.bext.codingHistory.length,this.uInt32),it(this.bext.description,256),it(this.bext.originator,32),it(this.bext.originatorReference,32),it(this.bext.originationDate,10),it(this.bext.originationTime,8),Ke(this.bext.timeReference[0],this.uInt32),Ke(this.bext.timeReference[1],this.uInt32),Ke(this.bext.version,this.uInt16),it(this.bext.UMID,64),Ke(this.bext.loudnessValue,this.uInt16),Ke(this.bext.loudnessRange,this.uInt16),Ke(this.bext.maxTruePeakLevel,this.uInt16),Ke(this.bext.maxMomentaryLoudness,this.uInt16),Ke(this.bext.maxShortTermLoudness,this.uInt16),it(this.bext.reserved,180),it(this.bext.codingHistory,this.bext.codingHistory.length))),this.enforceByteLen_(e),e}enforceBext_(){for(var e in this.bext)if(this.bext.hasOwnProperty(e)&&this.bext[e]&&"timeReference"!=e){this.bext.chunkId="bext";break}(this.bext.timeReference[0]||this.bext.timeReference[1])&&(this.bext.chunkId="bext")}getiXMLBytes_(){let e=[];var t;return this.iXML.chunkId&&(t=qe(this.iXML.value),this.iXML.chunkSize=t.length,e=e.concat(qe(this.iXML.chunkId),Ke(this.iXML.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getDs64Bytes_(){let e=[];return this.ds64.chunkId&&(e=e.concat(qe(this.ds64.chunkId),Ke(this.ds64.chunkSize,this.uInt32),Ke(this.ds64.riffSizeHigh,this.uInt32),Ke(this.ds64.riffSizeLow,this.uInt32),Ke(this.ds64.dataSizeHigh,this.uInt32),Ke(this.ds64.dataSizeLow,this.uInt32),Ke(this.ds64.originationTime,this.uInt32),Ke(this.ds64.sampleCountHigh,this.uInt32),Ke(this.ds64.sampleCountLow,this.uInt32))),this.enforceByteLen_(e),e}getCueBytes_(){let e=[];var t;return this.cue.chunkId&&(t=this.getCuePointsBytes_(),e=e.concat(qe(this.cue.chunkId),Ke(t.length+4,this.uInt32),Ke(this.cue.dwCuePoints,this.uInt32),t)),this.enforceByteLen_(e),e}getCuePointsBytes_(){let t=[];for(let e=0;e<this.cue.dwCuePoints;e++)t=t.concat(Ke(this.cue.points[e].dwName,this.uInt32),Ke(this.cue.points[e].dwPosition,this.uInt32),qe(this.cue.points[e].fccChunk),Ke(this.cue.points[e].dwChunkStart,this.uInt32),Ke(this.cue.points[e].dwBlockStart,this.uInt32),Ke(this.cue.points[e].dwSampleOffset,this.uInt32));return t}getSmplBytes_(){let e=[];var t;return this.smpl.chunkId&&(t=this.getSmplLoopsBytes_(),e=e.concat(qe(this.smpl.chunkId),Ke(t.length+36,this.uInt32),Ke(this.smpl.dwManufacturer,this.uInt32),Ke(this.smpl.dwProduct,this.uInt32),Ke(this.smpl.dwSamplePeriod,this.uInt32),Ke(this.smpl.dwMIDIUnityNote,this.uInt32),Ke(this.smpl.dwMIDIPitchFraction,this.uInt32),Ke(this.smpl.dwSMPTEFormat,this.uInt32),Ke(this.smpl.dwSMPTEOffset,this.uInt32),Ke(this.smpl.dwNumSampleLoops,this.uInt32),Ke(this.smpl.dwSamplerData,this.uInt32),t)),this.enforceByteLen_(e),e}getSmplLoopsBytes_(){let t=[];for(let e=0;e<this.smpl.dwNumSampleLoops;e++)t=t.concat(Ke(this.smpl.loops[e].dwName,this.uInt32),Ke(this.smpl.loops[e].dwType,this.uInt32),Ke(this.smpl.loops[e].dwStart,this.uInt32),Ke(this.smpl.loops[e].dwEnd,this.uInt32),Ke(this.smpl.loops[e].dwFraction,this.uInt32),Ke(this.smpl.loops[e].dwPlayCount,this.uInt32));return t}getFactBytes_(){let e=[];return this.fact.chunkId&&(e=e.concat(qe(this.fact.chunkId),Ke(this.fact.chunkSize,this.uInt32),Ke(this.fact.dwSampleLength,this.uInt32))),this.enforceByteLen_(e),e}getFmtBytes_(){if(this.fmt.chunkId){var e=[].concat(qe(this.fmt.chunkId),Ke(this.fmt.chunkSize,this.uInt32),Ke(this.fmt.audioFormat,this.uInt16),Ke(this.fmt.numChannels,this.uInt16),Ke(this.fmt.sampleRate,this.uInt32),Ke(this.fmt.byteRate,this.uInt32),Ke(this.fmt.blockAlign,this.uInt16),Ke(this.fmt.bitsPerSample,this.uInt16),this.getFmtExtensionBytes_());return this.enforceByteLen_(e),e}throw Error('Could not find the "fmt " chunk')}getFmtExtensionBytes_(){let e=[];return 16<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.cbSize,this.uInt16))),18<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.validBitsPerSample,this.uInt16))),20<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.dwChannelMask,this.uInt32))),24<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.subformat[0],this.uInt32),Ke(this.fmt.subformat[1],this.uInt32),Ke(this.fmt.subformat[2],this.uInt32),Ke(this.fmt.subformat[3],this.uInt32))),e}getLISTBytes_(){let t=[];for(let e=0;e<this.LIST.length;e++){var i=this.getLISTSubChunksBytes_(this.LIST[e].subChunks,this.LIST[e].format);t=t.concat(qe(this.LIST[e].chunkId),Ke(i.length+4,this.uInt32),qe(this.LIST[e].format),i)}return this.enforceByteLen_(t),t}getLISTSubChunksBytes_(i,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=it(e.value,e.value.length);return t=t.concat(qe(e.chunkId),Ke(i.length+1,this.uInt32),i),t.push(0),t}getLISTadtlSubChunksBytes_(e){let t=[];var i;return-1<["labl","note"].indexOf(e.chunkId)?(i=it(e.value,e.value.length),t=t.concat(qe(e.chunkId),Ke(i.length+4+1,this.uInt32),Ke(e.dwName,this.uInt32),i),t.push(0)):"ltxt"==e.chunkId&&(t=t.concat(this.getLtxtChunkBytes_(e))),t}getLtxtChunkBytes_(e){return[].concat(qe(e.chunkId),Ke(e.value.length+20,this.uInt32),Ke(e.dwName,this.uInt32),Ke(e.dwSampleLength,this.uInt32),Ke(e.dwPurposeID,this.uInt32),Ke(e.dwCountry,this.uInt16),Ke(e.dwLanguage,this.uInt16),Ke(e.dwDialect,this.uInt16),Ke(e.dwCodePage,this.uInt16),it(e.value,e.value.length))}get_PMXBytes_(){let e=[];var t;return this._PMX.chunkId&&(t=qe(this._PMX.value),this._PMX.chunkSize=t.length,e=e.concat(qe(this._PMX.chunkId),Ke(this._PMX.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getJunkBytes_(){let e=[];return this.junk.chunkId?e.concat(qe(this.junk.chunkId),Ke(this.junk.chunkData.length,this.uInt32),this.junk.chunkData):(this.enforceByteLen_(e),e)}enforceByteLen_(e){e.length%2&&e.push(0)}}{constructor(){super(),this.bitDepth="0",this.dataType={bits:0,be:!1},this.WAV_AUDIO_FORMATS={4:17,8:1,"8a":6,"8m":7,16:1,24:1,32:1,"32f":3,64:3}}fromScratch(e,t,i,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 Xe(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 Je(this.data.samples.slice(e,e+this.dataType.bits/8),this.dataType)}setSample(e,t){if((e*=this.dataType.bits/8)+this.dataType.bits/8>this.data.samples.length)throw new Error("Range error");Ye(t,this.dataType,this.data.samples,e)}getiXML(){return this.iXML.value}setiXML(e){if("string"!=typeof e)throw new TypeError("iXML value must be a string.");this.iXML.value=e,this.iXML.chunkId="iXML"}get_PMX(){return this._PMX.value}set_PMX(e){if("string"!=typeof e)throw new TypeError("_PMX value must be a string.");this._PMX.value=e,this._PMX.chunkId="_PMX"}newWavFile_(e,t,i,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),Qe(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(!rt(this.fmt.numChannels,this.fmt.bitsPerSample,this.fmt.sampleRate))throw new Error("Invalid sample rate.")}}class at extends st{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 nt extends at{listCuePoints(){let i=this.getCuePoints_();for(let e=0,t=i.length;e<t;e++)i[e].position=i[e].dwSampleOffset/this.fmt.sampleRate*1e3,i[e].dwSampleLength?(i[e].end=i[e].dwSampleLength/this.fmt.sampleRate*1e3,i[e].end+=i[e].position):i[e].end=null,delete i[e].value;return i}setCuePoint(e){this.cue.chunkId="cue ",e.label||(e.label="");var t=this.getCuePoints_();this.clearLISTadtl_(),this.cue.points=[],e.dwSampleOffset=e.position*this.fmt.sampleRate/1e3,e.dwSampleLength=0,e.end&&(e.dwSampleLength=e.end*this.fmt.sampleRate/1e3-e.dwSampleOffset),0===t.length?this.setCuePoint_(e,1):this.setCuePointInOrder_(t,e),this.cue.dwCuePoints=this.cue.points.length}deleteCuePoint(t){this.cue.chunkId="cue ";var i=this.getCuePoints_();this.clearLISTadtl_();var 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 ot{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||ht,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 ht(e){return Math.exp(-e/2*e/2)}const lt={point:!1,linear:!1,cubic:!0,sinc:!0},ct={IIR:16,FIR:71},ut={IIR:class{constructor(t,i,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 dt(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 ot(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=lt[r.method]),r.LPF){r.LPFType=r.LPFType||"IIR";const n=ut[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||ct[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]);pt(i,e,t)}(e,s,a,new n(r.LPForder||ct[r.LPFType],t,i/2))}else pt(e,s,a);return s}function pt(i,r,s){for(let e=0,t=r.length;e<t;e++)r[e]=s.interpolate(e,i)}class gt extends nt{toRIFF(){var e=new Float64Array(mt(this.data.samples.length,this.dataType.bits/8));Xe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,this.bitDepth,e,{container:"RIFF"})}toRIFX(){var e=new Float64Array(mt(this.data.samples.length,this.dataType.bits/8));Xe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,this.bitDepth,e,{container:"RIFX"})}toIMAADPCM(){if(8e3!==this.fmt.sampleRate)throw new Error("Only 8000 Hz files can be compressed as IMA-ADPCM.");if(1!==this.fmt.numChannels)throw new Error("Only mono files can be compressed as IMA-ADPCM.");this.assure16Bit_();var e=new Int16Array(mt(this.data.samples.length,2));Xe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"4",Ae(e),{container:this.correctContainer_()})}fromIMAADPCM(e="16"){let 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(mt(this.data.samples.length,2));Xe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"8a",Pe(e),{container:this.correctContainer_()})}fromALaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Ne(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toMuLaw(){this.assure16Bit_();var e=new Int16Array(mt(this.data.samples.length,2));Xe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"8m",Fe(e),{container:this.correctContainer_()})}fromMuLaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",je(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toBitDepth(e,t=!0){let i=e,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);Te(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=dt(r,this.fmt.sampleRate,t,i);else for(let e=0;e<r.length;e++)s.push(dt(r[e],this.fmt.sampleRate,t,i));this.fromExisting_(this.fmt.numChannels,t,this.bitDepth,s,{container:this.correctContainer_()})}validateResample_(e){if(!rt(this.fmt.numChannels,this.fmt.bitsPerSample,e))throw new Error("Invalid sample rate.");if(-1<["4","8a","8m"].indexOf(this.bitDepth))throw new Error("wavefile can't change the sample rate of compressed files.")}assure16Bit_(){this.assureUncompressed_(),"16"!=this.bitDepth&&this.toBitDepth("16")}assureUncompressed_(){"8a"==this.bitDepth?this.fromALaw():"8m"==this.bitDepth?this.fromMuLaw():"4"==this.bitDepth&&this.fromIMAADPCM()}correctContainer_(){return"RF64"==this.container?"RIFF":this.container}fromExisting_(e,t,i,r,s){var a=new nt;Object.assign(this.fmt,a.fmt),Object.assign(this.fact,a.fact),Object.assign(this.ds64,a.ds64),Object.assign(this.data,a.data),this.newWavFile_(e,t,i,r,s)}}function mt(e,t){let i=e/t;return i%2&&i++,i}class ft extends gt{constructor(e){super(),e&&this.fromBuffer(e)}fromBase64(e){this.fromBuffer(function(i){let r=new Uint8Array(256);for(let e=0;e<we.length;e++)r[we.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+=we[t[e]>>2],i+=we[(3&t[e])<<4|t[e+1]>>4],i+=we[(15&t[e+1])<<2|t[e+2]>>6],i+=we[63&t[e+2]];return t.length%3==2?i=i.substring(0,i.length-1)+"=":t.length%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(this.toBuffer())}toDataURI(){return"data:audio/wav;base64,"+this.toBase64()}fromDataURI(e){this.fromBase64(e.replace("data:audio/wav;base64,",""))}}class yt{constructor(e){e instanceof Uint8Array?this.fromRawData(e):e instanceof i&&this.fromVirtualFile(e)}fromRawData(e){return this.rawData=e,this}fromVirtualFile(e){e=e.stream;return this.rawData=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this}getRawData(){return this.rawData}getData(){if(!this.decodedData){if(!this.rawData)throw new Error("No data loaded");this.decodedData=this.decodeData(this.rawData),this.rawData=void 0}return this.decodedData}setData(e){this.rawData=void 0,this.decodedData=e}decodeData(e){let t=new ft(e);return"4"===t.bitDepth&&t.fromIMAADPCM(),t.toBuffer()}isRawImaAdpcm(){return this.rawData&&"4"===new ft(this.rawData).bitDepth}}class wt{constructor(e,t=!0){this.resourceFactory=e,this.cache=t,this.resources=new Map}setDir(e){this.rfsDir=e}set(e,t){this.resources.set(e,t)}async has(e){return!!this.resources.has(e)||(await this.rfsDir?.containsEntry(e)??!1)}async get(e){let t;return t=this.resources.get(e),!t&&await this.rfsDir?.containsEntry(e)&&(t=await this.resourceFactory(await this.rfsDir.getRawFile(e)),this.cache&&this.resources.set(e,t)),t}clear(){this.resources.clear()}}class Tt{constructor(e){this.file=e}asFile(){return new File([this.file],this.file.name,{type:"audio/mp3"})}}const bt=(new Map).set("cameo.mix",["adogicon.shp","adoguico.shp","aengicon.shp","aenguico.shp","agapgen.shp","agisicon.shp","ahrvicon.shp","ahrvuico.shp","aparicon.shp","apchicon.shp","apcicon.shp","artyicon.shp","asaticon.shp","ayaricon.shp","batricon.shp","beagicon.shp","bggyicon.shp","bolticon.shp","brrkicon.shp","carricon.shp","ccomicon.shp","ccomuico.shp","chemicon.shp","chroicon.shp","clckicon.shp","clegicon.shp","cleguico.shp","clonicon.shp","cnsticon.shp","crryicon.shp","csphicon.shp","darken.shp","desoicon.shp","desouico.shp","desticon.shp","detnicon.shp","dlphicon.shp","dlphuico.shp","dogicon.shp","doguico.shp","dredicon.shp","dronicon.shp","e1icon.shp","e1uico.shp","e2icon.shp","e2uico.shp","e4icon.shp","empicon.shp","engnicon.shp","facticon.shp","falcicon.shp","fixicon.shp","flakicon.shp","flkticon.shp","flktuico.shp","forticon.shp","fsdicon.shp","fspicon.shp","fstdicon.shp","fvicon.shp","fvuico.shp","gapicon.shp","gat2icon.shp","gateicon.shp","gbayicon.shp","gcanicon.shp","giicon.shp","giuico.shp","gorep.shp","gtnkicon.shp","gtnkuico.shp","gwepicon.shp","handicon.shp","harvicon.shp","harvuico.shp","heliicon.shp","hindicon.shp","hmecicon.shp","hovricon.shp","htkicon.shp","htkuico.shp","htnkicon.shp","htnkuico.shp","ioncicon.shp","ircricon.shp","ironicon.shp","ivanicon.shp","ivanuico.shp","ivncicon.shp","ivncuico.shp","jjeticon.shp","jjetuico.shp","landicon.shp","lasricon.shp","liteicon.shp","lpsticon.shp","mcvicon.shp","mcvuico.shp","metricon.shp","mltiicon.shp","mmchicon.shp","msslicon.shp","mtnkicon.shp","mtnkuico.shp","mutcicon.shp","nga2icon.shp","ngaticon.shp","nhpdicon.shp","npsiicon.shp","npwricon.shp","nradicon.shp","nrcticon.shp","nreficon.shp","ntchicon.shp","nukeicon.shp","nwalicon.shp","nwepicon.shp","obliicon.shp","obmbicon.shp","orcaicon.shp","otrnicon.shp","paraicon.shp","pillicon.shp","plticon.shp","plugicon.shp","podsicon.shp","powricon.shp","prisicon.shp","proicon.shp","psicicon.shp","psicuico.shp","psisicon.shp","psiticon.shp","psituico.shp","rad1icon.shp","rad2icon.shp","rad3icon.shp","radricon.shp","rboticon.shp","reficon.shp","rfixicon.shp","rtnkicon.shp","rtnkuico.shp","samicon.shp","sapcicon.shp","sapicon.shp","sbagicon.shp","sealicon.shp","sealuico.shp","seekicon.shp","shadicon.shp","shaduico.shp","shkicon.shp","shkuico.shp","smchicon.shp","smcvicon.shp","smcvuico.shp","snipicon.shp","snipuico.shp","soniicon.shp","spoticon.shp","spyicon.shp","spyuico.shp","sqdicon.shp","sreficon.shp","srefuico.shp","stnkicon.shp","subicon.shp","subticon.shp","tanyicon.shp","tanyuico.shp","techicon.shp","tempicon.shp","teslaicon.shp","tickicon.shp","tnkdicon.shp","tnkduico.shp","towricon.shp","trkaicon.shp","trsticon.shp","trstuico.shp","tslaicon.shp","ttnkicon.shp","ttnkuico.shp","turbicon.shp","twr1icon.shp","twr2icon.shp","twr3icon.shp","v3icon.shp","v3uico.shp","wallicon.shp","weapicon.shp","weaticon.shp","weedicon.shp","wethicon.shp","xxicon.shp","yardicon.shp","yuriicon.shp","yuriuico.shp","yurpicon.shp","yurpuico.shp","zepicon.shp","zepuico.shp"]).set("theme.mix",["200meter.wav","blowitup.wav","burn.wav","destroy.wav","eaglehun.wav","fortific.wav","grinder.wav","hm2.wav","indeep.wav","industro.wav","jank.wav","motorize.wav","power.wav","ra2-opt.wav","ra2-sco.wav","tension.wav"]);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"];bt.set("sidec01.mix",s).set("sidec02.mix",s);var vt,St,s=["reportbug.shp"];bt.set("sidec01cd.mix",s).set("sidec02cd.mix",s),(s=vt=vt||{})[s.Archive=0]="Archive",s[s.Cdn=1]="Cdn",s[s.Local=2]="Local";class _t{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=St=St||{})[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 kt{constructor(e,t){this.modeIniLoader=t,this.entries=new Map,this.loadIni(e)}loadIni(e){e.getOrderedSections().forEach(r=>{let s=St[r.name]??St.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 _t).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 Ot{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 It{constructor(e){this.gameModes=e,this.manifests=[]}addFromIni(i){let e=i.getSection("MultiMaps");if(!e)throw new Error("Invalid map list. Missing [MultiMaps] section.");return this.manifests=this.manifests.concat([...e.entries.values()].map(e=>{var t=i.getSection(e);if(!t)throw new Error(`Invalid map list. Missing [${e}] section.`);return(new Ot).fromIni(t,this.gameModes.getAll())})),this.dedupeEntries(),this}add(e){this.manifests.push(e)}addFromMapFile(e){this.add((new Ot).fromMapFile(e,this.gameModes.getAll()))}getAll(){return this.manifests}getByName(t){return this.manifests.find(e=>e.fileName.toLowerCase()===t.toLowerCase())}sortByName(){this.manifests.sort((e,t)=>e.fileName.localeCompare(t.fileName))}clone(){let e=new It(this.gameModes);return e.manifests=[...this.manifests],e}mergeWith(e){return this.manifests.push(...e.manifests),this.dedupeEntries(),this}dedupeEntries(){this.manifests=[...new Map(this.manifests.map(e=>[e.fileName.toLowerCase(),e])).values()]}}class At{getMatrix(e){return this.matrices[e]}}var Ct,Bt,Et=__webpack_require__(949);class xt{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 At;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 Et.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.47.0".split(".").slice(0,2).join(".")}static getModHash(){if(!this.modHash)throw new Error("Rules must be loaded first");return this.modHash}static getActiveMod(){return this.activeMod}static setActiveMod(e){this.activeMod=e}static initGameResSource(e){this.gameResSource=e}static async initRfs(e){let t=this.rfs=new fe;return t.addRootDirectoryHandle(e),t}static async initVfs(e,t){return this.vfs=new de(e,t),Pt.iniFiles.setVfs(this.vfs),Pt.palettes.setVfs(this.vfs),Pt.images.setVfs(this.vfs),Pt.voxels.setVfs(this.vfs),Pt.voxelAnims.setVfs(this.vfs),Pt.tileData.setVfs(this.vfs),Pt.sounds.setVfs(this.vfs),Pt.themes.setDir(await this.rfs?.findDirectory(Pt.rfsSettings.musicDir)),Pt.taunts.setDir(await this.rfs?.findDirectory(Pt.rfsSettings.tauntsDir)),this.vfs}static supportsTheater(t){var e=this.getActiveEngine();return this.theaterSettings.get(e)?.some(e=>e.Type===t)||!1}static getTheaterSettings(e,t){if(!this.theaterSettings.has(e))throw new Error(`Unknown engineType "${e}`);e=this.theaterSettings.get(e).find(e=>e.Type===t);if(!e)throw new Error(`Unsupported theater "${I[t]}"`);return e}static async loadTheater(e){if(!Pt.rules||!Pt.art)throw new Error("Rules and art should be loaded first");if(void 0===Pt.gameResSource)throw new Error("No gameResSource is set");var t=Pt.getActiveEngine();let i;var r,s=Pt.getTheaterSettings(t,e);if(Pt.gameResSource!==vt.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=bt.get(e);if(!i)return void console.warn(`Mix "${e}" not found in mix database`);for(t of i)("pal"===t.split(".").pop()?Pt.palettes:Pt.images).clear(t)}}static getTheaterIni(e,t){t=Pt.getTheaterSettings(e,t).TheaterIni;return Pt.getIni(t)}static loadRules(){var e=this.getFileNameVariant("rules.ini"),t=this.getFileNameVariant("art.ini");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(D(this.getVersion())),n.get()}static getRules(){if(!Pt.rules)throw new Error("Rules must be loaded first");return Pt.rules}static getArt(){if(!Pt.art)throw new Error("Art must be loaded first");return Pt.art}static 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 kt(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 It(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 It(t);if(this.rfs)for await(var o of this.rfs.getEntries()){let t=o.toLowerCase();try{t.endsWith(".pkt")?(i=new c(await this.rfs.openFile(o,!0)),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 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 getMapDir(){return this.getOrCreateDir(Pt.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()}}Pt.UI_ANIM_SPEED=2,Pt.rfsSettings={menuVideoFileName:"ra2ts_l.webm",splashImgFileName:"glsl.png",mapDir:"maps",modDir:"mods",musicDir:"music",tauntsDir:"Taunts",cacheDir:"cache",replayDir:"replays"},Pt.supportedMapTypes=["mpr","map"],Pt.images=new ye(e=>new r(e)),Pt.voxels=new ye(e=>new S(e)),Pt.voxelAnims=new ye(e=>new xt(e)),Pt.sounds=new ye(e=>new yt(e)),Pt.themes=new wt(e=>new Tt(e),!1),Pt.taunts=new wt(async e=>new yt(new Uint8Array(await e.arrayBuffer()))),Pt.iniFiles=new ye(e=>new c(e)),Pt.tileData=new ye(e=>new x(e)),Pt.palettes=new ye(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=Bt=Bt||{})[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 Nt{constructor(e){this.type=e}isStructure(){return this.type===Bt.Building}isVehicle(){return this.type===Bt.Vehicle}isInfantry(){return this.type===Bt.Infantry}isAircraft(){return this.type===Bt.Aircraft}isTerrain(){return this.type===Bt.Terrain}isSmudge(){return this.type===Bt.Smudge}isOverlay(){return this.type===Bt.Overlay}isNamed(){return"name"in this}isTechno(){return"health"in this}}class Rt extends Nt{}class Dt extends Rt{}class Mt extends Dt{constructor(){super(Bt.Building)}}class Lt extends Dt{constructor(){super(Bt.Vehicle)}}class Ft extends Dt{constructor(){super(Bt.Infantry)}}class jt extends Dt{constructor(){super(Bt.Aircraft)}}class Wt extends Rt{constructor(){super(Bt.Terrain)}}class Ut extends Rt{constructor(){super(Bt.Smudge)}}class Vt extends Nt{constructor(){super(Bt.Overlay)}}class zt{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 Ht,Gt,$t,qt,Zt,Qt,Xt,Yt,Kt,Jt,ei,ti,ii,ri,si,ai,ni,oi,hi,li,ci=__webpack_require__(251).default;class ui{static decompress(e,t){e={inputBuffer:e,outputBuffer:null},t=ci.decompress(e,{outputSize:t});if(0!==t)throw new Error(`MiniLzo decode failed with code ${t}`);return e.outputBuffer}}class di{static decode(e,t,i=5){t=new Uint8Array(t);return this.decodeInto(e,t,i),t}static decodeInto(e,i,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?zt.decode(e.subarray(s,s+n),o):ui.decompress(e.subarray(s,s+n),o);for(let e=0;e<o;++e)i[a+e]=t[e];s+=n,a+=o}}}function pi(e){switch(e){case Ht.Indexed:return 1;case Ht.Rgb:return 3;case Ht.Rgba:return 4;default:throw new Error(`Unsupported pixel format ${e}`)}}(s=Ht=Ht||{})[s.Rgb=1]="Rgb",s[s.Rgba=2]="Rgba",s[s.Indexed=3]="Indexed";class gi{constructor(e,t,i,r=Ht.Rgba){var s=pi(r);this.data=i||new Uint8Array(s*e*t),this.pixelFormat=r,this.width=e,this.height=t}drawIndexedImage(t,e,i){var r=pi(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 mi extends gi{constructor(e,t,i){super(e,t,i,Ht.Rgb)}}(s=Gt=Gt||{})[s.OnceAny=0]="OnceAny",s[s.OnceAll=1]="OnceAll",s[s.Repeat=2]="Repeat";class fi{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!==Gt[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=$t=$t||{})[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=qt=qt||{})[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 yi{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!==$t[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!==qt[o]?(h={triggerId:a,index:e,type:o,params:[Number(h[0]||"0"),h[1]||"0",h[2]||"0",h[3]||"0",h[4]||"0",h[5]||"0",h[6]?this.readAZActionParam(h[6]):0]},t.push(h)):(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 wi{constructor(){this.level=0,this.ambient=1,this.red=1,this.green=1,this.blue=1,this.ground=0,this.forceTint=!1}read(e,t=""){return this.level=e.getNumber(t+"Level",.032),this.ambient=e.getNumber(t+"Ambient",1),this.red=e.getNumber(t+"Red",1),this.green=e.getNumber(t+"Green",1),this.blue=e.getNumber(t+"Blue",1),this.ground=e.getNumber(t+"Ground",0),this}copy(e){return this.level=e.level,this.ambient=e.ambient,this.red=e.red,this.green=e.green,this.blue=e.blue,this.ground=e.ground,this.forceTint=e.forceTint,this}}class Ti{read(e,t){let i=[];for(var[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 bi{constructor(e,t){this.name=e,this.value=t}clone(){return new bi(this.name,this.value)}}class vi{read(e){return this.initialVeteran=e.getBool("InitialVeteran"),this}}class Si extends c{fromString(e){super.fromString(e);let t=this.getSection("Map");if(!t)throw new Error("[Map] section not found");e=t.getNumberArray("Size");if(this.fullSize={x:e[0],y:e[1],width:e[2],height:e[3]},e=t.getNumberArray("LocalSize"),this.localSize={x:e[0],y:e[1],width:e[2],height:e[3]},this.theaterType=t.getEnum("Theater",I,I.None,!0),this.theaterType===I.None)throw new Error(`Unsupported theater type "${t.getString("Theater")}"`);let i=this.getSection("Basic");e=this.iniFormat=i?.getNumber("NewINIFormat")??0;return this.readTiles(),i?.getBool("MultiplayerOnly")&&this.readWaypoints(this.getOrCreateSection("Waypoints")),this.readStructures(this.getOrCreateSection("Structures")),this.readVehicles(),this.readInfantries(),this.readAircrafts(),this.readTerrains(this.getOrCreateSection("Terrain")),this.readOverlays(),this.readSmudges(),this.readLighting(),this.readTagsAndTriggers(),this.readCellTags(e),this.readVariableNames(),this.startingLocations=this.readStartingLocations(this.waypoints),this.specialFlags=(new vi).read(this.getOrCreateSection("SpecialFlags")),this}readStartingLocations(e){let t=[];var i;for(i of e.filter(e=>e.number<8).sort((e,t)=>e.number<t.number?-1:1))t.push({x:i.rx,y:i.ry});return t}readLighting(){var e=this.getOrCreateSection("Lighting");this.lighting=(new wi).read(e),this.ionLighting=(new wi).read(e,"Ion"),this.ionLighting.forceTint=!0}readTagsAndTriggers(){this.tags=(new fi).read(this.getOrCreateSection("Tags"));var e=this.getOrCreateSection("Triggers"),t=this.getOrCreateSection("Events"),i=this.getOrCreateSection("Actions"),{triggers:e,unknownEventTypes:t,unknownActionTypes:i}=(new yi).read(e,t,i,this.tags);this.triggers=e,this.unknownEventTypes=t,this.unknownActionTypes=i}readCellTags(e){this.cellTags=(new Ti).read(this.getOrCreateSection("CellTags"),e)}readVariableNames(){var e,t,i=this.getOrCreateSection("VariableNames");let 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 bi(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);di.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 Mt;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),e.tag=this.readTagId(t[6]),e.poweredOn=Boolean(Number(t[9])),this.structures.push(e)}}}readTagId(e){return"none"!==e.toLowerCase()?e:void 0}readVehicles(){this.vehicles=[];let e=this.getSection("Units");if(e)for(var t of e.entries.values()){var i=t.split(",");if(i.length<=11)console.warn(`Invalid Vehicle entry: "${t}"`);else{let e=new Lt;e.owner=i[0],e.name=i[1],e.health=Number(i[2]),e.rx=Number(i[3]),e.ry=Number(i[4]),e.direction=Number(i[5]),e.tag=this.readTagId(i[7]),e.veterancy=Number(i[8]),e.onBridge="1"===i[10],this.vehicles.push(e)}}}readInfantries(){this.infantries=[];let e=this.getSection("Infantry");if(e)for(var t of e.entries.values()){var i=t.split(",");let e=new Ft;i.length<=8?console.warn(`Invalid Infantry entry: "${t}"`):(e.owner=i[0],e.name=i[1],e.health=Number(i[2]),e.rx=Number(i[3]),e.ry=Number(i[4]),e.subCell=Number(i[5]),e.direction=Number(i[7]),e.tag=this.readTagId(i[8]),e.veterancy=Number(i[9]),e.onBridge="1"===i[11],this.infantries.push(e))}}readAircrafts(){this.aircrafts=[];let e=this.getSection("Aircraft");if(e)for(var t of e.entries.values()){t=t.split(",");let e=new jt;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),e.direction=Number(t[5]),e.tag=this.readTagId(t[7]),e.veterancy=Number(t[8]),e.onBridge="1"===t[t.length-4],this.aircrafts.push(e)}}readTerrains(e){this.terrains=[];for(var[t,i]of e.entries){t=Number(t);if(!isNaN(t)){let e=new Wt;e.name=i,e.rx=t%1e3,e.ry=Math.floor(t/1e3),this.terrains.push(e)}}}readOverlays(){this.overlays=[],this.maxOverlayId=0;let t=this.getSection("OverlayPack");if(t){var i=M(t.getConcatenatedValues()),r=new Uint8Array(1<<18);di.decodeInto(i,r,80);let e=this.getSection("OverlayDataPack");if(e){var i=M(e.getConcatenatedValues()),s=new Uint8Array(1<<18);di.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 Vt;e.id=n,e.value=a,e.rx=o,e.ry=h,this.overlays.push(e),this.maxOverlayId=Math.max(this.maxOverlayId,n)}}}else console.warn("[OverlayDataPack] section not found. Skipping.")}else console.warn("[Overlay] section not found. Skipping.")}readSmudges(){this.smudges=[];let e=this.getSection("Smudge");if(e)for(var t of e.entries.values()){t=t.split(",");if(t.length<=2)console.warn(`Invalid Smudge entry: "${t}"`);else{let e=new 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=M(t.getConcatenatedValues()),r=new mi(i,r);return di.decodeInto(s,r.data),r}}}(s=Zt=Zt||{})[s.GDI=0]="GDI",s[s.Nod=1]="Nod",s[s.Civilian=2]="Civilian",s[s.Mutant=3]="Mutant";const _i=(new Map).set("GDI",Zt.GDI).set("Nod",Zt.Nod).set("Civilian",Zt.Civilian).set("Mutant",Zt.Mutant),ki=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 Oi{constructor(e){this.id=e}readIni(e){this.name=e.name,this.uiName=e.getString("UIName"),this.uiTooltip=e.get("UITooltip")||ki.get(this.name);var t=e.getString("Side");if(!t)throw new Error(`Missing Side for country "${this.name}"`);var i=_i.get(t);if(void 0===i)throw new Error(`Unknown side "${t}" for country "${this.name}"`);this.side=i,this.multiplay=e.getBool("Multiplay"),this.multiplayPassive=e.getBool("MultiplayPassive"),this.veteranAircraft=e.getArray("VeteranAircraft"),this.veteranInfantry=e.getArray("VeteranInfantry"),this.veteranUnits=e.getArray("VeteranUnits")}}class Ii{constructor(e,t,i=-1){this.type=e,this.ini=t,this.index=i,this.parse()}static iniSpeedToLeptonsPerTick(e){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===Bt.Infantry),this.crushSound=this.ini.getString("CrushSound")||void 0,this.dontScore=this.ini.getBool("DontScore"),this.insignificant=this.ini.getBool("Insignificant"),this.legalTarget=this.ini.getBool("LegalTarget",!0),this.noShadow=this.ini.getBool("NoShadow"),this.uiName=this.ini.getString("UIName")}get name(){return this.ini.name}get imageName(){let e=this.ini.getString("Image");return e&&"null"!==e||(e=this.name),e}}Ii.IMAGE_NONE="none";class Ai{constructor(e){this.rules=e,this.parse()}parse(){this.ambientDamage=this.rules.getNumber("AmbientDamage"),this.anim=this.rules.getArray("Anim"),this.areaFire=this.rules.getBool("AreaFire"),this.burst=this.rules.getNumber("Burst",1),this.cellRangefinding=this.rules.getBool("CellRangefinding"),this.damage=this.rules.getNumber("Damage"),this.decloakToFire=this.rules.getBool("DecloakToFire",!0),this.fireOnce=this.rules.getBool("FireOnce"),this.isAlternateColor=this.rules.getBool("IsAlternateColor"),this.isElectricBolt=this.rules.getBool("IsElectricBolt"),this.isHouseColor=this.rules.getBool("IsHouseColor"),this.isLaser=this.rules.getBool("IsLaser"),this.isRadBeam=this.rules.getBool("IsRadBeam"),this.isSonic=this.rules.getBool("IsSonic"),this.laserDuration=this.rules.getNumber("LaserDuration"),this.limboLaunch=this.rules.getBool("LimboLaunch"),this.minimumRange=this.rules.getNumber("MinimumRange"),this.name=this.rules.name,this.neverUse=this.rules.getBool("NeverUse"),this.omniFire=this.rules.getBool("OmniFire"),this.projectile=this.rules.getString("Projectile"),this.radLevel=this.rules.getNumber("RadLevel"),this.range=this.rules.getNumber("Range"),-2===this.range&&(this.range=Number.POSITIVE_INFINITY),this.report=this.rules.getArray("Report"),this.revealOnFire=this.rules.getBool("RevealOnFire",!0),this.rof=this.rules.getNumber("ROF"),this.sabotageCursor=this.rules.getBool("SabotageCursor"),this.spawner=this.rules.getBool("Spawner");var e=this.rules.getNumber("Speed");this.iniSpeed=e,this.speed=Ii.iniSpeedToLeptonsPerTick(e),this.suicide=this.rules.getBool("Suicide"),this.useSparkParticles=this.rules.getBool("UseSparkParticles"),this.warhead=this.rules.getString("Warhead")}}class Ci{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=Qt=Qt||{})[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 Bi{readIni(e){return this.eventSuppressionDistances=e.getNumberArray("RadarEventSuppressionDistances"),this.eventVisibilityDurations=e.getNumberArray("RadarEventVisibilityDurations"),this.eventDurations=e.getNumberArray("RadarEventDurations"),this.flashFrameTime=e.getNumber("FlashFrameTime"),this.combatFlashTime=e.getNumber("RadarCombatFlashTime"),this.eventMinRadius=e.getNumber("RadarEventMinRadius"),this.eventSpeed=e.getNumber("RadarEventSpeed"),this.eventRotationSpeed=e.getNumber("RadarEventRotationSpeed"),this.eventColorSpeed=e.getNumber("RadarEventColorSpeed"),this}getEventSuppresionDistance(e){if(e>this.eventSuppressionDistances.length-1)throw new RangeError(`No event suppression distance is defined for type ${Qt[e]}`);return this.eventSuppressionDistances[e]}getEventVisibilityDuration(e){if(e>this.eventVisibilityDurations.length-1)throw new RangeError(`No event visibility duration is defined for type ${Qt[e]}`);return this.eventVisibilityDurations[e]}getEventDuration(e){if(e>this.eventDurations.length-1)throw new RangeError(`No event duration is defined for type ${Qt[e]}`);return this.eventDurations[e]}}class Ei{readIni(e){return this.reloadRate=e.getNumber("ReloadRate"),this.repairPercent=e.getNumber("RepairPercent"),this.repairRate=e.getNumber("RepairRate"),this.repairStep=e.getNumber("RepairStep"),this.uRepairRate=e.getNumber("URepairRate"),this.iRepairRate=e.getNumber("IRepairRate"),this.iRepairStep=e.getNumber("IRepairStep"),this}}class xi{readIni(e){return this.veteranRatio=e.getNumber("VeteranRatio",3),this.veteranCombat=e.getNumber("VeteranCombat",1),this.veteranSpeed=e.getNumber("VeteranSpeed",1),this.veteranSight=Math.max(1,e.getNumber("VeteranSight",1)),this.veteranArmor=e.getNumber("VeteranArmor",1),this.veteranROF=e.getNumber("VeteranROF",1),this.veteranCap=e.getNumber("VeteranCap",2),this.initialVeteran=e.getBool("InitialVeteran"),this}}class Pi{readIni(e){return this.alliedCrew=e.getString("AlliedCrew"),this.alliedSurvivorDivisor=e.getNumber("AlliedSurvivorDivisor"),this.crewEscape=e.getNumber("CrewEscape"),this.sovietCrew=e.getString("SovietCrew"),this.sovietSurvivorDivisor=e.getNumber("SovietSurvivorDivisor"),this.survivorRate=e.getNumber("SurvivorRate"),this}}class Ni{readIni(e){return this.type=e.getString("PrismType"),this.supportHeight=e.getNumber("PrismSupportHeight"),this.supportMax=e.getNumber("PrismSupportMax"),this.supportModifier=e.getNumber("PrismSupportModifier",1),this}}class Ri{readIni(e){return this.myEffectivenessCoefficientDefault=e.getNumber("MyEffectivenessCoefficientDefault"),this.targetEffectivenessCoefficientDefault=e.getNumber("TargetEffectivenessCoefficientDefault"),this.targetSpecialThreatCoefficientDefault=e.getNumber("TargetSpecialThreatCoefficientDefault"),this.targetStrengthCoefficientDefault=e.getNumber("TargetStrengthCoefficientDefault"),this.targetDistanceCoefficientDefault=e.getNumber("TargetDistanceCoefficientDefault"),this}}class Di{readIni(e){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 Zt.GDI:return this.allyParaDrop;case Zt.Nod:return this.sovParaDrop;default:throw new Error(`Unhandled side type "${e}"`)}}}class Mi{readIni(e){return this.deferment=e.getNumber("LightningDeferment"),this.damage=e.getNumber("LightningDamage"),this.duration=e.getNumber("LightningStormDuration"),this.warhead=e.getString("LightningWarhead"),this.hitDelay=e.getNumber("LightningHitDelay"),this.scatterDelay=e.getNumber("LightningScatterDelay"),this.cellSpread=e.getNumber("LightningCellSpread"),this.separation=e.getNumber("LightningSeparation"),this}}class Li{}class Fi extends Li{readIni(e){return this.pauseFrames=e.getNumber("V3RocketPauseFrames"),this.tiltFrames=e.getNumber("V3RocketTiltFrames"),this.pitchInitial=e.getNumber("V3RocketPitchInitial"),this.pitchFinal=e.getNumber("V3RocketPitchFinal"),this.turnRate=e.getNumber("V3RocketTurnRate"),this.acceleration=e.getNumber("V3RocketAcceleration"),this.altitude=e.getNumber("V3RocketAltitude"),this.damage=e.getNumber("V3RocketDamage"),this.eliteDamage=e.getNumber("V3RocketEliteDamage"),this.bodyLength=e.getNumber("V3RocketBodyLength"),this.lazyCurve=e.getBool("V3RocketLazyCurve"),this.type=e.getString("V3RocketType"),this}}class ji extends Li{readIni(e){return this.pauseFrames=e.getNumber("DMislPauseFrames"),this.tiltFrames=e.getNumber("DMislTiltFrames"),this.pitchInitial=e.getNumber("DMislPitchInitial"),this.pitchFinal=e.getNumber("DMislPitchFinal"),this.turnRate=e.getNumber("DMislTurnRate"),this.acceleration=e.getNumber("DMislAcceleration"),this.altitude=e.getNumber("DMislAltitude"),this.damage=e.getNumber("DMislDamage"),this.eliteDamage=e.getNumber("DMislEliteDamage"),this.bodyLength=e.getNumber("DMislBodyLength"),this.lazyCurve=e.getBool("DMislLazyCurve"),this.type=e.getString("DMislType"),this}}class Wi{readIni(e){return this.height=e.getNumber("HoverHeight"),this.dampen=e.getNumber("HoverDampen"),this.bob=e.getNumber("HoverBob"),this.boost=e.getNumber("HoverBoost"),this.acceleration=e.getNumber("HoverAcceleration"),this.brake=e.getNumber("HoverBrake"),this}}(s=Xt=Xt||{})[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 Ui=(new Map).set(Xt.Power,"PrerequisitePower").set(Xt.Factory,"PrerequisiteFactory").set(Xt.Barracks,"PrerequisiteBarracks").set(Xt.Radar,"PrerequisiteRadar").set(Xt.Tech,"PrerequisiteTech").set(Xt.Proc,"PrerequisiteProc");class Vi{constructor(){this.prereqCategories=new Map}readIni(e){this.aircraftFogReveal=e.getNumber("AircraftFogReveal"),this.alliedDisguise=e.getString("AlliedDisguise"),this.baseUnit=e.getArray("BaseUnit"),this.bridgeVoxelMax=e.getNumber("BridgeVoxelMax"),this.buildSpeed=e.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 Pi).readIni(e),this.defaultMirageDisguises=e.getArray("DefaultMirageDisguises"),this.dMisl=(new ji).readIni(e),this.dropPodWeapon=e.getString("DropPodWeapon"),this.engineer=e.getString("Engineer"),this.flightLevel=e.getNumber("FlightLevel"),this.guardAreaTargetingDelay=e.getNumber("GuardAreaTargetingDelay"),this.harvesterTooFarDistance=e.getNumber("HarvesterTooFarDistance"),this.harvesterUnit=e.getArray("HarvesterUnit"),this.hover=(new Wi).readIni(e),this.infantryBlinkDisguiseTime=e.getNumber("InfantryBlinkDisguiseTime"),this.lightningStorm=(new Mi).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 Di).readIni(e),this.prism=(new Ni).readIni(e),this.purifierBonus=e.getNumber("PurifierBonus"),this.radar=(new Bi).readIni(e),this.refundPercent=e.getNumber("RefundPercent"),this.repair=(new Ei).readIni(e),this.revealTriggerRadius=Math.min(10,e.getNumber("RevealTriggerRadius")),this.shipSinkingWeight=e.getNumber("ShipSinkingWeight"),this.sovietDisguise=e.getString("SovietDisguise"),this.spyMoneyStealPercent=e.getNumber("SpyMoneyStealPercent"),this.spyPowerBlackout=e.getNumber("SpyPowerBlackout"),this.technician=e.getString("Technician"),this.threat=(new Ri).readIni(e),this.treeStrength=e.getNumber("TreeStrength"),this.v3Rocket=(new Fi).readIni(e),this.veteran=(new xi).readIni(e),this.wallBuildSpeedCoefficient=e.getNumber("WallBuildSpeedCoefficient"),this.readPrereqCategories(e)}readPrereqCategories(e){for(var[t,i]of Ui){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=Yt=Yt||{})[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=Kt=Kt||{})[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.Weeds=6]="Weeds",s[s.Water=7]="Water",s[s.Wall=8]="Wall",s[s.Tiberium=9]="Tiberium",s[s.Cliff=10]="Cliff";const zi=new Map([[Yt.Default,Kt.Clear],[Yt.Clear,Kt.Clear],[Yt.Tunnel,Kt.Cliff],[Yt.Railroad,Kt.Railroad],[Yt.Rock1,Kt.Rock],[Yt.Rock2,Kt.Rock],[Yt.Water,Kt.Water],[Yt.Shore,Kt.Beach],[Yt.Pavement,Kt.Road],[Yt.Dirt,Kt.Road],[Yt.Rough,Kt.Rough],[Yt.Cliff,Kt.Cliff]]);function Hi(e){if(!zi.has(e))throw new Error(`Unknown terrain type ${e}`);return zi.get(e)}(s=Jt=Jt||{})[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 Gi{constructor(){this.speedModifiers=new Map}readIni(t){return this.buildable=t.getBool("Buildable",!1),[...t.entries.keys()].forEach(e=>{void 0!==Jt[e]&&this.speedModifiers.set(Jt[e],t.getNumber(e))}),this}getSpeedModifier(e){if(e===Jt.Foot&&0===this.speedModifiers.get(Jt.Track))return 0;let t=this.speedModifiers.get(e);return void 0===t&&(t=1),t}}(s=ei=ei||{})[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 $i{constructor(e){this.rules=e,this.verses=new Map,this.parse()}get name(){return this.rules.name}parse(){this.animList=this.rules.getArray("AnimList"),this.bombDisarm=this.rules.getBool("BombDisarm"),this.bullets=this.rules.getBool("Bullets"),this.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.getEnumNumeric("InfDeath",ei,ei.None),this.ivanBomb=this.rules.getBool("IvanBomb"),this.makesDisguise=this.rules.getBool("MakesDisguise"),this.mindControl=this.rules.getBool("MindControl"),this.nukeMaker=this.rules.getBool("NukeMaker"),this.paralyzes=this.rules.getNumber("Paralyzes"),this.parasite=this.rules.getBool("Parasite"),this.percentAtMax=this.rules.getNumber("PercentAtMax",1),this.proneDamage=this.rules.getNumber("ProneDamage",1),this.psychicDamage=this.rules.getBool("PsychicDamage"),this.radiation=this.rules.getBool("Radiation"),this.rocker=this.rules.getBool("Rocker"),this.sonic=this.rules.getBool("Sonic"),this.temporal=this.rules.getBool("Temporal");let e=this.rules.getFixedArray("Verses");e.forEach((e,t)=>this.verses.set(t,e)),this.wallAbsoluteDestroyer=this.rules.getBool("WallAbsoluteDestroyer"),this.wall=this.rules.getBool("Wall"),this.wood=this.rules.getBool("Wood")}}class qi extends Ii{parse(){super.parse();var e=this.ini.getNumber("ROT",0);let t=this.ini.getNumber("Acceleration");1!==e||t||(t=Number.POSITIVE_INFINITY),t=t||3,this.acceleration=t,this.arcing=this.ini.getBool("Arcing"),this.courseLockDuration=this.ini.getNumber("CourseLockDuration"),this.detonationAltitude=this.ini.getNumber("DetonationAltitude"),this.firersPalette=this.ini.getBool("FirersPalette"),this.flakScatter=this.ini.getBool("FlakScatter"),this.inaccurate=this.ini.getBool("Inaccurate"),this.inviso=this.ini.getBool("Inviso"),this.isAntiAir=this.ini.getBool("AA"),this.isAntiGround=this.ini.getBool("AG",!0),this.level=this.ini.getBool("Level"),this.rot=Ii.iniRotToDegsPerTick(e),this.iniRot=e,this.shadow=this.ini.getBool("Shadow",!0),this.shrapnelWeapon=this.ini.getString("ShrapnelWeapon")||void 0,this.shrapnelCount=this.ini.getNumber("ShrapnelCount"),this.subjectToCliffs=this.ini.getBool("SubjectToCliffs"),this.subjectToElevation=this.ini.getBool("SubjectToElevation"),this.subjectToWalls=this.ini.getBool("SubjectToWalls"),this.vertical=this.ini.getBool("Vertical")}}(s=ti=ti||{})[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=ii=ii||{})[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 Zi=new Map([["{4A582746-9839-11d1-B709-00A024DDAFD1}",ii.Aircraft],["{4A582747-9839-11d1-B709-00A024DDAFD1}",ii.Chrono],["{4A582742-9839-11d1-B709-00A024DDAFD1}",ii.Hover],["{4A582744-9839-11d1-B709-00A024DDAFD1}",ii.Infantry],["{92612C46-F71F-11d1-AC9F-006008055BB5}",ii.Jumpjet],["{B7B49766-E576-11d3-9BD9-00104B972FE8}",ii.Missile],["{2BEA74E1-7CCA-11d3-BE14-00104B62A16C}",ii.Ship],["{4A582741-9839-11d1-B709-00A024DDAFD1}",ii.Vehicle]]),Qi=new Map([[ii.Infantry,Jt.Foot],[ii.Ship,Jt.Float],[ii.Hover,Jt.Hover],[ii.Jumpjet,Jt.Winged],[ii.Aircraft,Jt.Winged],[ii.Missile,Jt.Winged]]);(s=ri=ri||{})[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=si=si||{})[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=ai=ai||{})[s.LandOk=0]="LandOk",s[s.LandNotOk=1]="LandNotOk",s[s.LandSecondary=2]="LandSecondary",(s=ni=ni||{})[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",(s=oi=oi||{})[s.Primary=0]="Primary",s[s.Secondary=1]="Secondary",s[s.DeathWeapon=2]="DeathWeapon",(s=hi=hi||{})[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=li=li||{})[s.None=0]="None",s[s.Normal=1]="Normal",s[s.Strong=2]="Strong";var Xi,Yi,Ki,Ji,er,tr=__webpack_require__(949);(s=Xi=Xi||{})[s.Combat=0]="Combat",s[s.Tech=1]="Tech",s[s.Resource=2]="Resource",s[s.Power=3]="Power",(s=Yi=Yi||{})[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 ir extends Ii{parse(){super.parse(),this.owner=this.ini.getArray("Owner");var e=this.ini.getNumber("AIBasePlanningSide");this.aiBasePlanningSide=-1!==e&&void 0!==Zt[e]?e:void 0,this.requiredHouses=this.ini.getArray("RequiredHouses"),this.forbiddenHouses=this.ini.getArray("ForbiddenHouses"),this.requiresStolenAlliedTech=this.ini.getBool("RequiresStolenAlliedTech"),this.requiresStolenSovietTech=this.ini.getBool("RequiresStolenSovietTech"),this.techLevel=this.ini.getNumber("TechLevel",-1),this.cost=this.ini.getNumber("Cost"),this.points=this.ini.getNumber("Points"),this.power=this.ini.getNumber("Power"),this.powered=this.ini.getBool("Powered"),this.prerequisite=this.ini.getArray("Prerequisite"),this.soylent=this.ini.getNumber("Soylent"),this.crateGoodie=this.ini.getBool("CrateGoodie"),this.buildCat=this.ini.getEnum("BuildCat",Xi,Xi.Combat),this.adjacent=this.ini.getNumber("Adjacent",1),this.baseNormal=this.ini.getBool("BaseNormal",!0),this.buildLimit=this.ini.getNumber("BuildLimit",Number.POSITIVE_INFINITY),this.airRangeBonus=this.ini.getNumber("AirRangeBonus"),this.guardRange=this.ini.getNumber("GuardRange"),this.defaultToGuardArea=this.ini.getBool("DefaultToGuardArea"),this.eligibileForAllyBuilding=this.ini.getBool("EligibileForAllyBuilding"),this.numberImpassableRows=this.ini.getNumber("NumberImpassableRows"),this.bridgeRepairHut=this.ini.getBool("BridgeRepairHut"),this.constructionYard=this.ini.getBool("ConstructionYard"),this.refinery=this.ini.getBool("Refinery"),this.unitRepair=this.ini.getBool("UnitRepair"),this.unitReload=this.ini.getBool("UnitReload"),this.isBaseDefense=this.ini.getBool("IsBaseDefense"),this.superWeapon=this.parseWeaponName(this.ini.getString("SuperWeapon")),this.chargedAnimTime=this.ini.getNumber("ChargedAnimTime");var t=this.ini.getBool("Naval");this.naval=t,this.underwater=this.ini.getBool("Underwater"),this.waterBound=this.ini.getBool("WaterBound"),this.orePurifier=this.ini.getBool("OrePurifier"),this.cloning=this.ini.getBool("Cloning"),this.nukeSilo=this.ini.getBool("NukeSilo"),this.repairable=this.ini.getBool("Repairable",this.type===Bt.Building),this.clickRepairable=this.ini.getBool("ClickRepairable",this.type===Bt.Building),this.unsellable=this.ini.getBool("Unsellable"),this.gdiBarracks=this.ini.getBool("GDIBarracks"),this.nodBarracks=this.ini.getBool("NODBarracks"),this.numberOfDocks=this.ini.getNumber("NumberOfDocks"),this.unitRepair&&!this.numberOfDocks&&(this.numberOfDocks=1),this.factory=this.ini.getEnum("Factory",Yi,Yi.None),this.factory===Yi.UnitType&&t&&(this.factory=Yi.NavalUnitType),this.weaponsFactory=this.ini.getBool("WeaponsFactory"),this.helipad=this.ini.getBool("Helipad"),this.hospital=this.ini.getBool("Hospital"),this.landTargeting=this.ini.getEnumNumeric("LandTargeting",ai,ai.LandOk),this.navalTargeting=this.ini.getEnumNumeric("NavalTargeting",ni,ni.UnderwaterNever),this.tooBigToFitUnderBridge=this.ini.getBool("TooBigToFitUnderBridge",this.type===Bt.Building),this.canBeOccupied=this.ini.getBool("CanBeOccupied"),this.maxNumberOccupants=this.ini.getNumber("MaxNumberOccupants"),this.leaveRubble=this.ini.getBool("LeaveRubble"),this.undeploysInto=this.ini.getString("UndeploysInto"),this.deploysInto=this.ini.getString("DeploysInto"),this.capturable=this.ini.getBool("Capturable"),this.spyable=this.ini.getBool("Spyable"),this.needsEngineer=this.ini.getBool("NeedsEngineer"),this.c4=this.ini.getBool("C4"),this.canC4=this.ini.getBool("CanC4",!0),this.produceCashStartup=this.ini.getNumber("ProduceCashStartup"),this.produceCashAmount=this.ini.getNumber("ProduceCashAmount"),this.produceCashDelay=this.ini.getNumber("ProduceCashDelay"),this.explosion=this.ini.getArray("Explosion"),this.explodes=this.ini.getBool("Explodes"),this.ifvMode=this.ini.getNumber("IFVMode"),this.turretIndexesByIfvMode=this.parseTurretIndexes(),this.turret=this.ini.getBool("Turret"),this.turretCount=this.ini.getNumber("TurretCount",this.turret?1:0),this.turretAnim=this.ini.getString("TurretAnim"),this.turretAnimIsVoxel=this.ini.getBool("TurretAnimIsVoxel"),this.turretAnimX=this.ini.getNumber("TurretAnimX"),this.turretAnimY=this.ini.getNumber("TurretAnimY"),this.turretAnimZAdjust=this.ini.getNumber("TurretAnimZAdjust"),this.isChargeTurret=this.ini.getBool("IsChargeTurret"),this.overpowerable=this.ini.getBool("Overpowerable"),this.freeUnit=this.ini.getString("FreeUnit"),this.primary=this.parseWeaponName(this.ini.getString("Primary")),this.secondary=this.parseWeaponName(this.ini.getString("Secondary")),this.elitePrimary=this.parseWeaponName(this.ini.getString("ElitePrimary")),this.eliteSecondary=this.parseWeaponName(this.ini.getString("EliteSecondary")),this.weaponCount=this.ini.getNumber("WeaponCount"),this.deathWeapon=this.parseWeaponName(this.ini.getString("DeathWeapon")),this.deathWeaponDamageModifier=this.ini.getNumber("DeathWeaponDamageModifier",1),this.occupyWeapon=this.parseWeaponName(this.ini.getString("OccupyWeapon")),this.eliteOccupyWeapon=this.parseWeaponName(this.ini.getString("EliteOccupyWeapon")),this.veteranAbilities=new Set(this.ini.getEnumArray("VeteranAbilities",hi)),this.eliteAbilities=new Set([...this.veteranAbilities,...this.ini.getEnumArray("EliteAbilities",hi)]),this.selfHealing=this.ini.getBool("SelfHealing"),this.wall=this.ini.getBool("Wall"),this.gate=this.ini.getBool("Gate"),this.armor=this.ini.getEnum("Armor",si,si.None,!0),this.strength=Math.floor(this.ini.getNumber("Strength")),this.immune=this.ini.getBool("Immune"),this.immuneToRadiation=this.ini.getBool("ImmuneToRadiation"),this.immuneToPsionics=this.ini.getBool("ImmuneToPsionics"),this.typeImmune=this.ini.getBool("TypeImmune"),this.warpable=this.ini.getBool("Warpable",!0),this.isTilter=this.ini.getBool("IsTilter",!0),this.walkRate=this.ini.getNumber("WalkRate",1),this.idleRate=this.ini.getNumber("IdleRate",0),this.noSpawnAlt=this.ini.getBool("NoSpawnAlt"),this.crusher=this.ini.getBool("Crusher"),this.consideredAircraft=this.ini.getBool("ConsideredAircraft"),this.crashable=this.ini.getBool("Crashable");var i=this.ini.getBool("Landable");this.landable=i,this.airportBound=this.ini.getBool("AirportBound"),this.balloonHover=this.ini.getBool("BalloonHover"),this.hoverAttack=this.ini.getBool("HoverAttack"),this.omniFire=this.ini.getBool("OmniFire"),this.fighter=this.ini.getBool("Fighter"),this.flightLevel=this.ini.getNumber("FlightLevel")||void 0;e=this.ini.getString("Locomotor");if(e?(t=Zi.get(e))?this.locomotor=t:(console.warn(`Object rules "${this.name}" has invalid Locomotor "${e}"`),this.locomotor=ii.Statue):this.locomotor=ii.Statue,this.locomotor!==ii.Statue){let e=Qi.get(this.locomotor);void 0===e&&(this.type===Bt.Aircraft||this.consideredAircraft?e=Jt.Winged:this.type===Bt.Vehicle?e=this.crusher?Jt.Track:Jt.Wheel:this.type===Bt.Infantry&&(e=Jt.Foot)),this.speedType=this.ini.getEnum("SpeedType",Jt,e)}this.speed=Ii.iniSpeedToLeptonsPerTick(this.ini.getNumber("Speed")),this.movementZone=this.ini.getEnum("MovementZone",ri,ri.Normal),this.fearless=this.ini.getBool("Fearless"),this.deployer=this.ini.getBool("Deployer"),this.deployFire=this.ini.getBool("DeployFire"),this.deployFireWeapon=this.ini.getNumber("DeployFireWeapon",oi.Secondary),this.undeployDelay=this.ini.getNumber("UndeployDelay"),this.fraidycat=this.ini.getBool("Fraidycat",!1),this.isHuman=!this.ini.getBool("NotHuman"),this.organic=this.type===Bt.Infantry||this.ini.getBool("Organic"),this.occupier=this.ini.getBool("Occupier"),this.engineer=this.ini.getBool("Engineer"),this.ivan=this.ini.getBool("Ivan"),this.civilian=this.ini.getBool("Civilian"),this.agent=this.ini.getBool("Agent"),this.infiltrate=this.ini.getBool("Infiltrate"),this.threatPosed=this.ini.getNumber("ThreatPosed"),this.specialThreatValue=this.ini.getNumber("SpecialThreatValue"),this.canPassiveAquire=this.ini.getBool("CanPassiveAquire",!0),this.canRetaliate=this.ini.getBool("CanRetaliate",!0),this.preventAttackMove=this.ini.getBool("PreventAttackMove"),this.opportunityFire=this.ini.getBool("OpportunityFire"),this.distributedFire=this.ini.getBool("DistributedFire"),this.radialFireSegments=this.ini.getNumber("RadialFireSegments"),this.attackCursorOnFriendlies=this.ini.getBool("AttackCursorOnFriendlies"),this.bombable=this.ini.getBool("Bombable",!0),this.trainable=this.ini.getBool("Trainable",this.type!==Bt.Building),this.crewed=this.ini.getBool("Crewed"),this.parasiteable=this.ini.getBool("Parasiteable",this.type!==Bt.Building),this.suppressionThreshold=this.ini.getNumber("SuppressionThreshold"),this.reselectIfLimboed=this.ini.getBool("ReselectIfLimboed"),this.rejoinTeamIfLimboed=this.ini.getBool("RejoinTeamIfLimboed"),this.weight=this.ini.getNumber("Weight"),this.accelerates=this.ini.getBool("Accelerates",!0),this.accelerationFactor=this.ini.getNumber("AccelerationFactor",.03),this.teleporter=this.ini.getBool("Teleporter"),this.canDisguise=this.ini.getBool("CanDisguise"),this.disguiseWhenStill=this.ini.getBool("DisguiseWhenStill"),this.permaDisguise=this.ini.getBool("PermaDisguise"),this.detectDisguise=this.ini.getBool("DetectDisguise"),this.detectDisguiseRange=this.ini.getNumber("DetectDisguiseRange"),this.cloakable=this.ini.getBool("Cloakable"),this.sensors=this.ini.getBool("Sensors"),this.sensorArray=this.ini.getBool("SensorArray"),this.sensorsSight=this.ini.getNumber("SensorsSight"),this.burstDelay=this.parseBurstDelay(),this.vhpScan=this.ini.getEnum("VHPScan",li,li.None,!0),this.pip=this.ini.getEnum("Pip",ti,ti.Green,!0),this.passengers=this.ini.getNumber("Passengers"),this.gunner=this.ini.getBool("Gunner"),this.ammo=this.ini.getNumber("Ammo",-1),this.initialAmmo=this.ini.getNumber("InitialAmmo",-1),this.manualReload=this.ini.getBool("ManualReload",this.type===Bt.Aircraft),this.storage=this.ini.getNumber("Storage"),this.spawned=this.ini.getBool("Spawned"),this.spawns=this.ini.getString("Spawns"),this.spawnsNumber=this.ini.getNumber("SpawnsNumber"),this.spawnRegenRate=this.ini.getNumber("SpawnRegenRate"),this.spawnReloadRate=this.ini.getNumber("SpawnReloadRate"),this.missileSpawn=this.ini.getBool("MissileSpawn"),this.size=this.ini.getNumber("Size",1),this.sizeLimit=this.ini.getNumber("SizeLimit"),this.sight=Math.min(ir.MAX_SIGHT,this.ini.getNumber("Sight",1)),this.spySat=this.ini.getBool("SpySat"),this.gapGenerator=this.ini.getBool("GapGenerator"),this.gapRadiusInCells=this.ini.getNumber("GapRadiusInCells"),this.psychicDetectionRadius=this.ini.getNumber("PsychicDetectionRadius"),this.hasRadialIndicator=this.ini.getBool("HasRadialIndicator"),this.harvester=this.ini.getBool("Harvester"),this.unloadingClass=this.ini.getString("UnloadingClass"),this.dock=this.ini.getArray("Dock"),this.radar=this.ini.getBool("Radar"),this.radarInvisible=this.ini.getBool("RadarInvisible"),this.revealToAll=this.ini.getBool("RevealToAll"),this.selectable=!(this.type===Bt.Aircraft&&!i)&&this.ini.getBool("Selectable",!0),this.isSelectableCombatant=this.ini.getBool("IsSelectableCombatant"),this.invisibleInGame=this.ini.getBool("InvisibleInGame"),this.moveToShroud=this.ini.getBool("MoveToShroud",this.type!==Bt.Aircraft),this.leadershipRating=this.ini.getNumber("LeadershipRating",5),this.allowedToStartInMultiplayer=this.ini.getBool("AllowedToStartInMultiplayer",!0),this.rot=Ii.iniRotToDegsPerTick(this.ini.getNumber("ROT",0)),this.jumpjetAccel=this.ini.getNumber("JumpJetAccel",2),this.jumpjetClimb=this.ini.getNumber("JumpjetClimb",5),this.jumpjetCrash=this.ini.getNumber("JumpjetCrash",5),this.jumpjetDeviation=this.ini.getNumber("JumpjetDeviation",40),this.jumpjetHeight=this.ini.getNumber("JumpjetHeight",500),this.jumpjetNoWobbles=this.ini.getBool("JumpjetNoWobbles"),this.jumpjetSpeed=this.ini.getNumber("JumpjetSpeed",14),this.jumpjetTurnRate=Ii.iniRotToDegsPerTick(this.ini.getNumber("JumpJetTurnRate",4)),this.jumpjetWobbles=this.ini.getNumber("JumpjetWobbles",.15),this.pitchSpeed=this.ini.getNumber("PitchSpeed",.25),this.pitchAngle=1<=this.pitchSpeed?0:20,this.damageParticleSystems=this.ini.getArray("DamageParticleSystems");i=this.ini.getNumberArray("DamageSmokeOffset",void 0,[0,0,0]);this.damageSmokeOffset=new tr.Vector3(i[0],i[2]/Math.SQRT2,i[1]),this.minDebris=this.ini.getNumber("MinDebris"),this.maxDebris=this.ini.getNumber("MaxDebris"),this.debrisTypes=this.ini.getArray("DebrisTypes"),this.debrisAnims=this.ini.getArray("DebrisAnims"),this.isLightpost="GALITE"===this.imageName,this.lightVisibility=this.ini.getNumber("LightVisibility",5e3),this.lightIntensity=this.ini.getNumber("LightIntensity"),this.lightRedTint=this.ini.getNumber("LightRedTint",1),this.lightGreenTint=this.ini.getNumber("LightGreenTint",1),this.lightBlueTint=this.ini.getNumber("LightBlueTint",1),this.ambientSound=this.ini.getString("AmbientSound")||void 0,this.createSound=this.ini.getString("CreateSound")||void 0,this.deploySound=this.ini.getString("DeploySound")||void 0,this.undeploySound=this.ini.getString("UndeploySound")||void 0,this.voiceSelect=this.ini.getString("VoiceSelect")||void 0,this.voiceMove=this.ini.getString("VoiceMove")||void 0,this.voiceAttack=this.ini.getString("VoiceAttack")||void 0,this.voiceFeedback=this.ini.getString("VoiceFeedback")||void 0,this.voiceSpecialAttack=this.ini.getString("VoiceSpecialAttack")||void 0,this.voiceEnter=this.ini.getString("VoiceEnter")||void 0,this.voiceCapture=this.ini.getString("VoiceCapture")||void 0,this.voiceCrashing=this.ini.getString("VoiceCrashing")||void 0,this.crashingSound=this.ini.getString("CrashingSound")||void 0,this.impactLandSound=this.ini.getString("ImpactLandSound")||void 0,this.auxSound1=this.ini.getString("AuxSound1")||void 0,this.auxSound2=this.ini.getString("AuxSound2")||void 0,this.dieSound=this.ini.getString("DieSound")||void 0,this.moveSound=this.ini.getString("MoveSound")||void 0,this.enterWaterSound=this.ini.getString("EnterWaterSound")||void 0,this.leaveWaterSound=this.ini.getString("LeaveWaterSound")||void 0,this.turretRotateSound=this.ini.getString("TurretRotateSound")||void 0,this.workingSound=this.ini.getString("WorkingSound")||void 0,this.notWorkingSound=this.ini.getString("NotWorkingSound")||void 0,this.chronoInSound=this.ini.getString("ChronoInSound")||void 0,this.chronoOutSound=this.ini.getString("ChronoOutSound")||void 0,this.enterTransportSound=this.ini.getString("EnterTransportSound")||void 0,this.leaveTransportSound=this.ini.getString("LeaveTransportSound")||void 0}parseWeaponName(e){return e&&"none"!==e.toLowerCase()?e:void 0}parseTurretIndexes(){let i=new Map;return this.ini.getBool("Gunner")&&this.ini.entries.forEach((e,t)=>{t=t.match(/^(.*)TurretWeapon$/i);t&&(t=t[1]+"TurretIndex",this.ini.has(t)&&i.set(Number(e),this.ini.getNumber(t)))}),i}parseBurstDelay(){let t=[];for(let e=0;e<4;++e)t.push(this.ini.has(`BurstDelay${e}`)?this.ini.getNumber(`BurstDelay${e}`):void 0);return t}hasOwner(e){return!!this.owner.length&&-1!==this.owner.indexOf(e.name)}isAvailableTo(e){return(!this.requiredHouses.length||-1!==this.requiredHouses.indexOf(e.name))&&-1===this.forbiddenHouses.indexOf(e.name)}get proneWhenAttacked(){return!this.fearless&&this.isHuman}getWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`Weapon${e+1}`))}getEliteWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`EliteWeapon${e+1}`))}}ir.MAX_SIGHT=11,ir.MAGIC_SPEED_MULT=.65;class rr extends Ii{parse(){super.parse(),this.armor=this.ini.getEnum("Armor",si,si.None,!0),this.crate=this.ini.getBool("Crate");var e=this.ini.getBool("IsARock");this.isARock=e,this.isRubble=this.ini.getBool("IsRubble"),this.isVeinholeMonster=this.ini.getBool("IsVeinholeMonster"),this.isVeins=this.ini.getBool("IsVeins"),this.land=this.ini.getEnum("Land",Kt,Kt.Clear),this.noUseTileLandType=!!this.ini.getString("NoUseTileLandType"),this.strength=this.ini.getNumber("Strength"),this.tiberium=this.ini.getBool("Tiberium");var t=this.ini.getBool("Wall");this.wall=t,this.radarInvisible=this.ini.getBool("RadarInvisible",!t&&!e)}}(s=Ki=Ki||{})[s.All=7]="All",s[s.Right=1]="Right",s[s.Left=2]="Left",s[s.Bottom=4]="Bottom";class sr extends Ii{parse(){super.parse(),this.animationRate=this.ini.getNumber("AnimationRate"),this.animationProbability=this.ini.getNumber("AnimationProbability"),this.gate=this.ini.getBool("Gate"),this.immune=this.ini.getBool("Immune"),this.isAnimated=this.ini.getBool("IsAnimated"),this.snowOccupationBits=this.normalizeOccupationBits(this.ini.getNumber("SnowOccupationBits",Ki.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",Ki.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===Ki.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&Ki.Right);case 3:return 0!=(t&Ki.Left);case 4:return 0!=(t&Ki.Bottom);default:throw new Error(`Invalid subCell "${e}`)}}(t,i)||r.push(t);return r}}class ar extends Ii{parse(){super.parse(),this.burn=this.ini.getBool("Burn"),this.crater=this.ini.getBool("Crater"),this.width=this.ini.getNumber("Width",1),this.height=this.ini.getNumber("Height",1)}}class nr extends Ii{parse(){super.parse(),this.damage=this.ini.getNumber("Damage"),this.damageRadius=this.ini.getNumber("DamageRadius"),this.duration=this.ini.getNumber("Duration"),this.elasticity=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 or{create(e,t,i){switch(e){case Bt.Aircraft:case Bt.Building:case Bt.Infantry:case Bt.Vehicle:return new ir(e,t,i);case Bt.Overlay:return new rr(e,t,i);case Bt.Terrain:return new sr(e,t,i);case Bt.Smudge:return new ar(e,t,i);case Bt.VoxelAnim:return new nr(e,t,i);default:return new Ii(e,t,i)}}}class hr{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 lr{readIni(e){return this.value=e.getNumber("Value"),this}}class cr{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 ur{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 dr{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=Ji=Ji||{})[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 pr{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",Ji,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",Ji,void 0),this.uiName=e.getString("UIName"),this.weaponType=e.getString("WeaponType")||void 0,this}}class gr{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=er=er||{})[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 mr{constructor(e,t,i,r){this.target=e,this.player=t,this.source=i,this.tile=r,this.type=er.CratePickup}}var fr,yr=__webpack_require__(949);class wr{static init(e){wr.worldOrigin=e}static worldToScreen(e,t){if(!wr.worldOrigin)throw new Error("Coords not initialized with world origin");return{x:(e-=wr.worldOrigin.x)-(t-=wr.worldOrigin.y)-1,y:(e+t-1)/2}}static screenToWorld(e,t){if(!wr.worldOrigin)throw new Error("Coords not initialized with world origin");return{x:(e+2*t)/2+1+wr.worldOrigin.x,y:(2*t-e)/2+wr.worldOrigin.y}}static tileToWorld(e,t){return{x:e*wr.ISO_TILE_SIZE,y:t*wr.ISO_TILE_SIZE}}static worldToTile(e,t){return{x:Math.floor(e/wr.ISO_TILE_SIZE),y:Math.floor(t/wr.ISO_TILE_SIZE)}}static worldToLeptons(e){return e*wr.LEPTONS_PER_TILE/wr.ISO_TILE_SIZE}static leptonsToWorld(e){return e/wr.LEPTONS_PER_TILE*wr.ISO_TILE_SIZE}static vecWorldToLeptons(e){return e.clone().multiplyScalar(wr.LEPTONS_PER_TILE/wr.ISO_TILE_SIZE)}static vecLeptonsToWorld(e){return e.clone().multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE)}static vecWorldToScreen(e){let t=wr.worldToScreen(e.x,e.z);return t.y-=e.y/wr.zScale,t}static vecWorldToGround(e){return new yr.Vector2(e.x,e.z)}static vecGroundToWorld(e){return new yr.Vector3(e.x,0,e.y)}static tileHeightToWorld(e){return e*(wr.ISO_TILE_SIZE/2)*wr.zScale+1}static tileHeightToScreen(e){return e*(wr.ISO_TILE_SIZE/2)+1/wr.zScale}static worldToTileHeight(e){return(e-1)/wr.zScale/(wr.ISO_TILE_SIZE/2)}static tileToScreen(e,t){t=wr.tileToWorld(e,t);return wr.worldToScreen(t.x,t.y)}static tile3dToWorld(e,t,i){t=wr.tileToWorld(e,t),i=wr.tileHeightToWorld(i);return new yr.Vector3(t.x,i,t.y)}static tile3dToScreen(e,t,i){t=wr.tileToWorld(e,t);let r=wr.worldToScreen(t.x,t.y);return r.y-=i*(wr.ISO_TILE_SIZE/2)+1/wr.zScale,r}static screenTileToScreen(e,t){return{x:e*wr.ISO_TILE_SIZE,y:t*wr.ISO_TILE_SIZE/2}}static screenToScreenTile(e,t){return{x:e/wr.ISO_TILE_SIZE,y:t/(wr.ISO_TILE_SIZE/2)}}static screenTileToWorld(e,t){t=wr.screenTileToScreen(e,t);return wr.screenToWorld(t.x,t.y)}static getScreenTileSize(){return{width:wr.tileToScreen(1,0).x-wr.tileToScreen(0,1).x,height:wr.tileToScreen(1,1).y-wr.tileToScreen(0,0).y}}static screenDistanceToWorld(e,t){var i=wr.screenToWorld(0,0),t=wr.screenToWorld(e,t);return{x:t.x-i.x,y:t.y-i.y}}static screenDistanceToLeptons(e,t){var{x:e,y:t}=wr.screenDistanceToWorld(e,t);return{x:e/wr.ISO_TILE_SIZE*wr.LEPTONS_PER_TILE,y:t/wr.ISO_TILE_SIZE*wr.LEPTONS_PER_TILE}}static getWorldTileSize(){return wr.ISO_TILE_SIZE}}function Tr(e){return[Kt.Water,Kt.Beach].includes(e)?fr.Water:fr.Ground}wr.ISO_TILE_SIZE=30,wr.LEPTONS_PER_TILE=256,wr.ISO_CAMERA_ALPHA=Math.PI/6,wr.ISO_CAMERA_BETA=Math.PI/4,wr.COS_ISO_CAMERA_BETA=Math.cos(wr.ISO_CAMERA_BETA),wr.zScale=Math.cos(wr.ISO_CAMERA_BETA)/Math.cos(wr.ISO_CAMERA_ALPHA),(s=fr=fr||{})[s.Ground=0]="Ground",s[s.Air=1]="Air",s[s.Water=2]="Water";var br,vr=__webpack_require__(949);const Sr=e=>void 0!==e.position,_r=e=>void 0!==e.addScalar;class kr{constructor(e){this.tileOccupation=e}isInWeaponRange(e,t,i,r,s){var a=s??e;if(i.rules.limboLaunch&&2<Math.abs((Sr(a)?a.position.tileElevation+a.tile.z:a.z)-(Sr(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===ri.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!Sr(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&&!Sr(t)||(a=Sr(e)?e.tile.z+e.tileElevation:e.z,(n=Sr(t)?t.tile.z+t.tileElevation:t.z)<a&&(s+=r.elevationModel.getBonus(a,n))),i.projectileRules.isAntiAir&&Sr(e)&&e.isTechno()&&Sr(t)&&t.isUnit()&&t.zone===fr.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===ri.Fly?this.isInRange2(e,t,i,r):this.isInRange3(e,t,i,r)}isInRange3(e,t,i,r){return V(this.distance3(e,t)/wr.ISO_TILE_SIZE,i,r)}isInRange2(e,t,i,r){return V(this.distance2(e,t)/wr.ISO_TILE_SIZE,i,r)}distance3(e,t){let i=Sr(e)?e.position.worldPosition:_r(e)?e:wr.tile3dToWorld(e.rx+.5,e.ry+.5,e.z);t=Sr(t)?t.position.worldPosition:_r(t)?t:wr.tile3dToWorld(t.rx+.5,t.ry+.5,t.z);return i.distanceTo(t)}distance2(e,t){let i=Sr(e)?new vr.Vector2(e.position.worldPosition.x,e.position.worldPosition.z):_r(e)?new vr.Vector2(e.x,e.z):new vr.Vector2(e.rx+.5,e.ry+.5).multiplyScalar(wr.ISO_TILE_SIZE);t=Sr(t)?new vr.Vector2(t.position.worldPosition.x,t.position.worldPosition.z):_r(t)?new vr.Vector2(t.x,t.z):new vr.Vector2(t.rx+.5,t.ry+.5).multiplyScalar(wr.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=Sr(e)?this.tileOccupation.calculateTilesForGameObject(e.tile,e):Array.isArray(e)?e:[e],r=Sr(t)?this.tileOccupation.calculateTilesForGameObject(t.tile,t):Array.isArray(t)?t:[t];let s=new vr.Vector2,a=new vr.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 Or=e=>"name"in e;(s=br=br||{})[s.Brutal=0]="Brutal",s[s.Medium=1]="Medium",s[s.Easy=2]="Easy";var Ir,Ar,Cr,Br,Er,xr,Pr,Nr,Rr;(new Map).set(br.Easy,"GUI:AIDummy");class Dr{static computeGameSpeed(e){let t;return t=6===e?60:5===e?45:60/(6-e),t/Dr.BASE_TICKS_PER_SECOND}}Dr.BASE_TICKS_PER_SECOND=15;class Mr{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=Ir=Ir||{})[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",(Ar=Ar||{}).onTick=Symbol(),(Cr=Cr||{}).onChange=Symbol();class Lr{constructor(e){this.target=e,this.type=er.SuperWeaponReady}}(s=Br=Br||{})[s.Charging=0]="Charging",s[s.Paused=1]="Paused",s[s.Ready=2]="Ready";class Fr{constructor(e,t,i,r=!1){this.name=e,this.rules=t,this.owner=i,this.oneTimeOnly=r,this.status=Br.Charging,this.isGift=!1,this.rechargeTicks=60*t.rechargeTime*Dr.BASE_TICKS_PER_SECOND,this.chargeTicks=this.rechargeTicks,r&&(this.status=Br.Ready,this.chargeTicks=0)}update(e){0<this.chargeTicks&&this.status!==Br.Paused&&(this.chargeTicks--,0===this.chargeTicks&&(this.status=Br.Ready,e.events.dispatch(new Lr(this))))}pauseTimer(){this.status=Br.Paused}resumeTimer(){this.status=0<this.chargeTicks?Br.Charging:Br.Ready}resetTimer(){this.chargeTicks=this.rechargeTicks,this.status===Br.Ready&&(this.status=Br.Charging)}getTimerSeconds(){return this.chargeTicks/Dr.BASE_TICKS_PER_SECOND}getChargeProgress(){return(this.rechargeTicks-this.chargeTicks)/this.rechargeTicks}}(s=Er=Er||{})[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Finished=2]="Finished";class jr{constructor(e,t,i){this.type=e,this.owner=t,this.tile=i,this.status=Er.NotStarted}onStart(e){}onTick(e){return!0}}(s=xr=xr||{}).onPowerLow=Symbol(),s.onPowerRestore=Symbol(),s.onPowerChange=Symbol(),(Pr=Pr||{}).onActivate=Symbol();class Wr{constructor(e,t,i,r,s){this.target=e,this.owner=t,this.atTile=i,this.atTile2=r,this.noSfxWarning=s,this.type=er.SuperWeaponActivate}}(s=Nr=Nr||{})[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=Rr=Rr||{})[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 Ur{constructor(){this.status=Rr.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===Rr.Running}isCancelling(){return this.status===Rr.Cancelling}setCancellable(e){return this.cancellable=e,this}onStart(e){}onEnd(e){}cancel(){if(this.cancellable)if(this.status===Rr.Running)this.status=Rr.Cancelling,this.children.length&&this.children.forEach(e=>e.cancel());else if(this.status===Rr.NotStarted&&(this.status=Rr.Cancelled,this.children.length))throw new Error("Should't have any children before starting a task")}getTargetLinesConfig(e){}}function Vr(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return e;return-1}class zr extends Ur{constructor(e){super(),this.ticks=e}onTick(){return!!this.isCancelling()||!(0<this.ticks--)}}class Hr{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===ri.Fly&&!t.rules.balloonHover&&!this.map.terrain.getPassableSpeed(i,Jt.Amphibious,!!e)||t.rules.movementZone!==ri.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 Mr(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!==ri.Fly||c.rules.balloonHover||this.map.terrain.getPassableSpeed(l,Jt.Amphibious,!!u))&&(c.rules.movementZone===ri.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===ri.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 Gr=__webpack_require__(949);function $r(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 qr(e,t){let i=new Gr.Box2(new Gr.Vector2(e.x,e.y),new Gr.Vector2(e.x+e.width,e.y+e.height));return i.containsPoint(new Gr.Vector2(t.x,t.y))}function Zr(e,t){var i=Gr.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 Qr(e){let t=Gr.Math.radToDeg(e.angle());return Math.abs(Math.abs(t)-Math.floor(Math.abs(t))-.5)<.01&&(t+=.01),Math.round(t)}function Xr(e,t){t=2*Math.acos(Math.abs(Gr.Math.clamp(e.dot(t),-1,1)));let i=Gr.Math.radToDeg(t);return Math.abs(Math.abs(i)-Math.floor(Math.abs(i))-.5)<.01&&(i+=.01),Math.round(i)}function Yr(e,t){e=Qr(e),t=Qr(t);return Math.min((e-t+360)%360,(t-e+360)%360)}function Kr(e,t){return Xr(Jr(e),Jr(t))}function Jr(e){return(new Gr.Quaternion).setFromRotationMatrix((new Gr.Matrix4).lookAt(e,new Gr.Vector3(0,0,0),new Gr.Vector3(0,1,0)))}function es(e,t,i){var r,s=e.length(),a=Jr(t),n=Jr(e);r=i,0!==(a=Xr(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 ts extends Ur{constructor(e,t){super(),this.game=e,this.fromDirection=t,this.resolved=!1,this.chainPushIssued=!1}onEnd(e){e.moveTrait.collisionState=Qs.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 Hr(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=Zr(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===ri.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 Gs(this.game,a,!!n,{closeEnoughTiles:0,strictCloseEnough:!0})),!1);{if(this.chainPushIssued)return this.children.push(new zr(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===Nr.Paradrop)&&!(e.isAircraft()&&e.missileSpawnTrait));return e.find(e=>e.moveTrait.collisionState===Qs.Waiting||e.unitOrderTrait.hasTasks())?(this.children.push(new zr(5)),i.moveTrait.collisionState=Qs.Waiting,i.moveTrait.moveState=qs.PlanMove,!1):(e.forEach(e=>{e.unitOrderTrait.addTask(new ts(this.game,this.fromDirection))}),this.children.push(new zr(1)),i.moveTrait.collisionState=Qs.Waiting,i.moveTrait.moveState=qs.PlanMove,!(this.chainPushIssued=!0))}}}const is=__webpack_require__(163);var rs=__webpack_require__(949);class ss{constructor(e){this.game=e,this.ignoresTerrain=!0,this.distanceToWaypoint=new rs.Vector2}onNewWaypoint(e,t){}tick(e,t,i,r){if(r)return{distance:new rs.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 rs.Vector3(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!0,isTeleport:!0}}}var as=__webpack_require__(949);class ns{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(-Qr(e)-90+720)%360}static toMapCoords(e){return Zr(new as.Vector2(10,0),ns.toWorldDeg(e)).normalize()}static toWorldDeg(e){return-(e+90)}}class os extends Ur{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}=ns.tick(e.direction,this.direction,t);return e.direction=i,e.spinVelocity=t,!1}}var hs,ls=__webpack_require__(949);(s=hs=hs||{})[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 cs{constructor(e){this.game=e,this.hasMomentum=!1,this.moveOnCurve=!1,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=hs.None}selectNextWaypoint(i,r){if(this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==hs.End?hs.Normal:hs.Start,this.initialPosition=i.position.getMapPosition(),this.currentWaypointType!==hs.Start?i.moveTrait.speedPenalty=0:this.currentSpeed=0,1<r.length){var s=r[r.length-1],a=r[r.length-2],e=new ls.Vector2(s.tile.rx-i.tile.rx,s.tile.ry-i.tile.ry),n=Math.abs(Qr(e)-Qr(new ls.Vector2(a.tile.rx-s.tile.rx,a.tile.ry-s.tile.ry)));if(!Math.abs(ns.fromMapCoords(e)-i.direction)&&0<n&&n<90&&this.hasMomentum){this.moveOnCurve=!0,this.currentWaypointType=2===r.length?this.currentWaypointType===hs.Start?hs.Single:hs.End:hs.Normal;let e=this.initialPosition;i=new ls.Vector2(s.tile.rx+.5,s.tile.ry+.5).multiplyScalar(wr.LEPTONS_PER_TILE);let t=new ls.Vector2(a.tile.rx+.5,a.tile.ry+.5).multiplyScalar(wr.LEPTONS_PER_TILE);n=e.clone().lerp(i,.5),s=t.clone().lerp(i,.5);return this.steerCurve=new ls.CurvePath,this.steerCurve.add(new ls.LineCurve(e,n)),this.steerCurve.add(new ls.QuadraticBezierCurve(n,i,s)),this.steerCurve.add(new ls.LineCurve(s,t)),this.lastPosition=e,a}}else this.currentWaypointType=this.currentWaypointType===hs.Start?hs.Single:hs.End;return this.hasMomentum=!0,this.moveOnCurve=!1,r[r.length-1]}onNewWaypoint(e,t,i){let r=(new ls.Vector2).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=this.moveOnCurve?this.steerCurve.getLength():r.length();t=ns.fromMapCoords(r);if(t!==e.direction&&(this.pointTurretToTarget(e,i),!this.moveOnCurve))return e.moveTrait.velocity.set(0,0,0),[new os(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(wr.getWorldTileSize()/wr.LEPTONS_PER_TILE);var s=i.rules.rot,{facing:h,delta:s}=ns.tick(i.direction,ns.fromMapCoords(t),s);i.direction=h,i.spinVelocity=s;s=this.lastPosition;this.lastPosition=e.clone(),o=e.sub(s)}else{let e=(new ls.Vector2).copy(r).sub(n);n=Math.min(e.length(),a);o=e.clone().setLength(n);let t=o.clone();this.carryOverDistance&&t.add(wr.vecWorldToGround(wr.vecWorldToLeptons(i.moveTrait.velocity))),i.moveTrait.velocity.set(t.x,0,t.y).multiplyScalar(wr.getWorldTileSize()/wr.LEPTONS_PER_TILE),this.distanceTravelled+=n,this.carryOverDistance=Math.max(0,a-e.length())}return{distance:new ls.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 ls.Vector2).copy(i).sub(r);e.length()&&(r=ns.fromMapCoords(e),t.turretTrait.desiredFacing=r)}}applyAcceleration(e,t,i,r){if(this.currentWaypointType===hs.Single)return.3*i;if(this.currentWaypointType!==hs.End)return Math.min(t+e.rules.accelerationFactor*i,i);return this.moveOnCurve&&this.currentWaypointType===hs.End&&(r=r<=.5?0:2*(r-.5)),ls.Math.lerp(1,i,1-r)}}var us=__webpack_require__(949);class ds{constructor(e){this.game=e,this.currentMoveDirection=new us.Vector2,this.distanceToWaypoint=new us.Vector2,this.carryOverDistance=0}onNewWaypoint(e,t){this.currentMoveDirection.copy(t).sub(e.position.getMapPosition());t=ns.fromMapCoords(this.currentMoveDirection);t!==e.direction&&(e.direction=t)}onWaypointUpdate(e,t){this.onNewWaypoint(e,t)}tick(e,t){let i=e.moveTrait.baseSpeed*ir.MAGIC_SPEED_MULT;e.stance===Nr.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(wr.getWorldTileSize()/wr.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 us.Vector3(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!this.distanceToWaypoint.length()||!!this.carryOverDistance}}}var ps,gs=__webpack_require__(949);(s=ps=ps||{})[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 ms{constructor(e){this.hoverRules=e,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=ps.None,this.nextWaypointDir=new gs.Vector2}selectNextWaypoint(e,t){var i;return this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==ps.End?ps.Normal:ps.Start,this.initialPosition=e.position.getMapPosition(),this.currentWaypointType===ps.Start&&(this.currentSpeed=0),t.length<=1?(this.currentWaypointType=this.currentWaypointType===ps.Start?ps.Single:ps.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 gs.Vector2).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=r.length();t=this.maxSpeed=e.moveTrait.baseSpeed*ir.MAGIC_SPEED_MULT,e=60*this.hoverRules.acceleration*Dr.BASE_TICKS_PER_SECOND;this.acceleration=t/e;e=60*this.hoverRules.brake*Dr.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===ps.Single?this.currentSpeed=i/2:this.currentWaypointType===ps.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=ns.fromMapCoords(r),i=ns.fromMapCoords(this.nextWaypointDir);let a=s,n=e.rules.rot;this.currentWaypointType===ps.Normal&&s!==i&&(s=(o=Yr(this.nextWaypointDir,ns.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=ns.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(wr.vecWorldToGround(wr.vecWorldToLeptons(e.moveTrait.velocity))),e.moveTrait.velocity.set(c.x,0,c.y).multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE),this.distanceTravelled+=o,this.carryOverDistance=Math.max(0,h-t),{distance:new gs.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 fs=__webpack_require__(949);class ys{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 fs.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/=fs.Math.degToRad(Math.abs(i));let s=Zr(t.clone(),90*-Math.sign(i));return{center:isFinite(r)?s.setLength(r).add(e):e.clone(),radius:r}}}class ws{constructor(e){this.gameObject=e,this.type=er.ObjectLiftOff}}class Ts{constructor(e){this.gameObject=e,this.type=er.ObjectLand}}var bs=__webpack_require__(949);class vs{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.currentMoveDir=new bs.Vector2,this.currentHorizSpeed=0}static tickStationary(t,i){if(t.zone===fr.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)!==fr.Water&&0<i.map.terrain.getPassableSpeed(t.tile,Jt.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),wr.worldToLeptons(wr.tileHeightToWorld(a))):(n=t.tile.z+i.map.getGroundObjectsOnTile(t.tile).filter(e=>!(e.isInfantry()&&e.stance===Nr.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0),wr.worldToLeptons(wr.tileHeightToWorld(n))+t.rules.jumpjetHeight);var a,n,o=wr.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 bs.Vector3(0,n,0))):s&&(t.zone=fr.Ground,t.onBridge=!!r,i.events.dispatch(new Ts(t)))}}static tickCrash(e,t,i){var r=2*e.rules.jumpjetCrash;return e.direction=(e.direction-6+360)%360,new bs.Vector3(0,-r,0)}onNewWaypoint(e,t,i){this.currentMoveDir=ns.toMapCoords(e.direction),this.cancelDestLeptons=void 0}tick(t,e,i,r){if(t.zone!==fr.Air&&(t.onBridge=!1,t.zone=fr.Air,this.game.events.dispatch(new ws(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===Nr.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=wr.worldToLeptons(wr.tileHeightToWorld(o)),c=wr.worldToLeptons(wr.tileHeightToWorld(o+h)),u=wr.worldToLeptons(t.position.worldPosition.y),d=ns.fromMapCoords(a),p=a.length()<t.rules.jumpjetSpeed;let g=0;l<=u&&!p&&({facing:T,delta:r}=ns.tick(t.direction,d,t.rules.jumpjetTurnRate),g=r,t.direction=T,this.currentMoveDir.copy(ns.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?ys.computeTurnCircle(s,this.currentMoveDir,Math.sign(g)*t.rules.jumpjetTurnRate,T):void 0)&&$r(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 bs.Vector3(b.x,y,b.y);p=v.clone();return t.moveTrait.velocity.copy(p).multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE),{distance:v,done:f&&m}}findTilesToCheckForBlockers(e,t,i,r){r=i.clone().setLength(Math.min(r,wr.LEPTONS_PER_TILE)).add(t).multiplyScalar(1/wr.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/wr.LEPTONS_PER_TILE).floor().multiplyScalar(wr.LEPTONS_PER_TILE),i=t.clone().sub(i);return new bs.Vector2(e.rx,e.ry).multiplyScalar(wr.LEPTONS_PER_TILE).add(i)}}var Ss,_s,ks=__webpack_require__(949);(s=Ss=Ss||{})[s.Boost=0]="Boost",s[s.Midcourse=1]="Midcourse",s[s.Terminal=2]="Terminal";class Os{constructor(e,t){this.game=e,this.missileRules=t,this.flightPhase=Ss.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=wr.vecWorldToLeptons(wr.tile3dToWorld(i.tile.rx+.5,i.tile.ry+.5,t)),this.cruiseAltitude=wr.worldToLeptons(wr.tileHeightToWorld(t))+this.missileRules.altitude,i}onNewWaypoint(e,t,i){}tick(i,e,t){let r=wr.vecWorldToLeptons(i.position.worldPosition),s=this.targetPosition.clone().sub(r);i.zone!==fr.Air&&(i.onBridge=!1,i.zone=fr.Air,this.game.events.dispatch(new ws(i)));let a;var n;a=this.currentVelocity?(n=i.rules.speed*ir.MAGIC_SPEED_MULT,Math.min(this.currentVelocity.length()+this.missileRules.acceleration,n)):(p=this.missileRules.acceleration,this.missileRules.lazyCurve?this.currentVelocity=new ks.Vector3(s.x,0,s.z):this.currentVelocity=wr.vecGroundToWorld(ns.toMapCoords(i.direction)),es(this.currentVelocity,new ks.Vector3(this.currentVelocity.x,1e8,this.currentVelocity.z),i.pitch),p),this.currentVelocity.setLength(a);let o=!1;switch(this.flightPhase){case Ss.Boost:if(!(wr.worldToLeptons(i.position.worldPosition.y)>=this.cruiseAltitude)){o=!1;break}this.flightPhase=Ss.Midcourse;case Ss.Midcourse:var h,l=new ks.Vector2(s.x,s.z).length();if(!this.missileRules.lazyCurve){es(this.currentVelocity,new ks.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)),es(this.currentVelocity,new ks.Vector3(s.x,this.currentVelocity.y,s.z),i.rules.rot),i.direction=ns.fromMapCoords(wr.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*Kr(this.currentVelocity,new ks.Vector3(this.currentVelocity.x,0,this.currentVelocity.z)),l/(r.y-this.targetPosition.y)<1&&(this.flightPhase=Ss.Terminal);break}this.flightPhase=Ss.Terminal;var c=r.clone().add(this.currentVelocity.clone().setLength(l/3/z(Math.cos(ks.Math.degToRad(i.pitch)),10))),u=this.targetPosition.clone().lerp(r,.15).setY(c.y);this.descentCurve=new ks.CubicBezierCurve3(r,c,u,this.targetPosition);case Ss.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)*Kr(u,t),o=1<=(this.descentTravelled+c)/d}else{es(this.currentVelocity,s,i.rules.rot),i.direction=ns.fromMapCoords(wr.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*Kr(this.currentVelocity,new ks.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=wr.vecLeptonsToWorld(r.clone().add(this.currentVelocity));return this.game.map.isWithinHardBounds(p)?(i.moveTrait.velocity.copy(this.currentVelocity).multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE),{distance:this.currentVelocity,done:o}):(this.game.destroyObject(i),{done:!0,distance:new ks.Vector3})}}class Is extends zr{constructor(e){super(Math.floor(Dr.BASE_TICKS_PER_SECOND*e*60))}}class As extends Ur{constructor(e){super(),this.cb=e}onTick(e){return this.cb(e),!0}}(_s=_s||{}).onTick=Symbol();var Cs,Bs=__webpack_require__(949);(s=Cs=Cs||{})[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 Es extends Ur{constructor(e,t){super(),this.game=e,this.target=t,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.dockingStatus=Cs.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=Cs.MoveToDock:void 0!==(t=this.target.dockTrait.getFirstAvailableDockNumber())?(this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=Cs.MoveToDock):this.target.helipadTrait?this.cancel():this.dockingStatus=Cs.MoveToQueueingTile}onEnd(e){this.dockingStatus!==Cs.Docked&&this.target.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),this.dockingStatus=Cs.Idle}onTick(e){if(this.isCancelling())return!0;if(!this.isValidTarget(this.target,e))return!0;if(this.dockingStatus===Cs.MoveToQueueingTile){var t=this.findReachableQueueingTile(e);if(!t)return!0;if(e.tile!==t)return this.children.push(new Gs(this.game,t,!1,{closeEnoughTiles:5}),new As(()=>{e.moveTrait.lastMoveResult===Zs.Fail?this.cancel():e.moveTrait.lastMoveResult===Zs.CloseEnough&&(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)||(this.dockingStatus=Cs.WaitForTurn))})),!1;this.dockingStatus=Cs.WaitForTurn}if(this.dockingStatus===Cs.WaitForTurn){var i=this.target.dockTrait.getFirstAvailableDockNumber();if(void 0===i)return this.children.push(new Is(1/60)),!1;this.target.dockTrait.reserveDockAt(e,i),this.dockingStatus=Cs.MoveToDock}if(this.dockingStatus===Cs.MoveToDock){var r=this.target.dockTrait.getReservedDockForUnit(e),i=this.target.dockTrait.getDockTile(r),r=wr.vecWorldToGround(this.target.dockTrait.getDockOffset(r)).add(this.target.position.getMapPosition()).sub(new Bs.Vector2(i.rx,i.ry).multiplyScalar(wr.LEPTONS_PER_TILE));if(e.tile!==i)return this.children.push(new Gs(this.game,i,!1,{targetOffset:e.isAircraft()?r:void 0,closeEnoughTiles:0,strictCloseEnough:!0}),new As(()=>{e.moveTrait.lastMoveResult===Zs.Fail&&this.cancel()})),this.game.afterTick(()=>e.unitOrderTrait[_s.onTick](e,this.game)),!1;this.dockingStatus=Cs.Docking}if(this.dockingStatus!==Cs.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=Cs.Docked,!0}isValidTarget(e,t){return e.isSpawned&&this.game.areFriendly(e,t)}findReachableQueueingTile(t){var e=this.target.getFoundation(),e=new Bs.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 Mr(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>this.isValidQueueingTile(e,t)).getNextTile()}isValidQueueingTile(e,t){return(t.rules.movementZone===ri.Fly||0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-this.target.tile.z)<2&&!e.onBridgeLandType&&!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length)&&!this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)}}var xs,Ps,Ns=__webpack_require__(949);(s=xs=xs||{})[s.None=0]="None",s[s.CircleStrafe=1]="CircleStrafe",s[s.HoverStrafe=2]="HoverStrafe";class Rs{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.lastDestLeptons=new Ns.Vector2,this.currentMoveDir=new Ns.Vector2,this.currentHorizSpeed=0,this.maneuverType=xs.None,this.deceleratingToTurn=!1}static tickStationary(s,a){if(s.zone===fr.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)!==fr.Water&&0<a.map.terrain.getPassableSpeed(s.tile,Jt.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=ns.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 Es(a,e)),s.unitOrderTrait[_s.onTick](s,a)):s.crashableTrait.crash(void 0))}let t;t=i?i.tile.z+i.tileElevation:s.tile.z+(n?.tileElevation??0),r=wr.worldToLeptons(wr.tileHeightToWorld(t))}else{var t=s.tile.z+(n?.tileElevation??0),l=s.rules.flightLevel??a.rules.general.flightLevel;r=wr.worldToLeptons(wr.tileHeightToWorld(t))+l}t=wr.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 Ns.Vector3(0,l,0))):e&&(s.zone=fr.Ground,i?i.airSpawnTrait.storeAircraft(s,a):s.onBridge=!!n,a.events.dispatch(new Ts(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=wr.vecWorldToGround(wr.vecWorldToLeptons(e.moveTrait.velocity));return new Ns.Vector3(e.x,-30,e.y)}onNewWaypoint(e,t,i){this.currentHorizSpeed=wr.worldToLeptons(wr.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=xs.HoverStrafe:t.zone===fr.Air&&this.currentHorizSpeed<5?this.maneuverType=n>wr.LEPTONS_PER_TILE?xs.CircleStrafe:xs.HoverStrafe:this.maneuverType=xs.None,this.deceleratingToTurn=!1),t.zone!==fr.Air&&(t.onBridge=!1,t.zone=fr.Air,this.game.events.dispatch(new ws(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=wr.worldToLeptons(wr.tileHeightToWorld(h))+l,o=wr.worldToLeptons(t.position.worldPosition.y),c=ns.fromMapCoords(a);t.direction===c&&this.maneuverType===xs.None&&n<=wr.LEPTONS_PER_TILE?this.maneuverType=xs.HoverStrafe:t.direction===c&&this.maneuverType===xs.CircleStrafe&&(this.maneuverType=xs.None);let u;switch(this.maneuverType){case xs.HoverStrafe:if(t.attackTrait?.currentTarget){let e=wr.vecWorldToGround(wr.vecWorldToLeptons(t.attackTrait.currentTarget.getWorldCoords()));u=ns.fromMapCoords(e.sub(s))}else u=t.airportBoundTrait?.preferredAirport?.dockTrait?.hasReservedDockForUnit(t)?0:270;break;case xs.CircleStrafe:case xs.None:u=c;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}var{facing:d,delta:p}=ns.tick(t.direction,u,t.rules.rot);t.direction=d,t.roll=Math.sign(p)*t.rules.pitchAngle;let g;switch(this.maneuverType){case xs.HoverStrafe:g=c;break;case xs.CircleStrafe:g=(d-90*Math.sign(p)+360)%360;break;case xs.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}=ns.tick(this.thrustFacing,g,h);this.thrustFacing=l,this.currentMoveDir.copy(ns.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*ir.MAGIC_SPEED_MULT;n<=wr.LEPTONS_PER_TILE&&this.maneuverType!==xs.CircleStrafe&&(T=Ns.Math.lerp(1,T/2,Math.sqrt(n/wr.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?ys.computeTurnCircle(s,this.currentMoveDir,Math.sign(h)*t.rules.rot,b):void 0,0!==b&&!$r(h,i)||(this.maneuverType===xs.HoverStrafe||n>wr.LEPTONS_PER_TILE?this.deceleratingToTurn=!0:this.maneuverType===xs.None&&(this.maneuverType=xs.HoverStrafe)),y=b,!1):(y=Math.min(b,n),n<=b);let v;v=n<1?(m=!0,a):m?a:this.currentMoveDir.clone().setLength(y);let S=new Ns.Vector3(v.x,f,v.y);n=S.clone();return t.moveTrait.velocity.copy(n).multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE),{distance:S,done:m&&w}}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/wr.LEPTONS_PER_TILE).floor().multiplyScalar(wr.LEPTONS_PER_TILE),i=t.clone().sub(i);return new Ns.Vector2(e.rx,e.ry).multiplyScalar(wr.LEPTONS_PER_TILE).add(i)}}class Ds{constructor(e){this.game=e}create(e){var t=e.rules.locomotor;switch(t){case ii.Infantry:return new ds(this.game);case ii.Jumpjet:return new vs(this.game);case ii.Vehicle:case ii.Ship:return new cs(this.game);case ii.Chrono:return e.isVehicle()&&e.harvesterTrait&&e.rules.teleporter?new cs(this.game):new ss(this.game);case ii.Aircraft:return new Rs(this.game);case ii.Missile:return new Os(this.game,this.game.rules.general.getMissileRules(e.name));case ii.Hover:return new ms(this.game.rules.general.hover);default:throw new Error(`Unhandled locomotor type ${t}`)}}}class Ms{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 Ls{constructor(e,t,i){this.target=e,this.isChronoshift=t,this.prevTile=i,this.type=er.ObjectTeleport}}(Ps=Ps||{}).onBeforeTeleport=Symbol();class Fs{constructor(e){this.game=e,this.movePositionHelper=new Hr(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 Ms(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 js extends Ur{constructor(e,t,i){super(),this.game=e,this.target=t,this.options=i}onStart(i){if(!i.moveTrait.isDisabled()&&i.rules.movementZone!==ri.Fly){let e,t;if(this.target)({tile:e,toBridge:t}=this.target);else{i=new Fs(this.game).findPositions([i],this.options).get(i);if(!i)return;e=i.tile,t=!!i.onBridge}this.children.push(new Gs(this.game,e,t,{closeEnoughTiles:0,ignoredBlockers:this.options?.ignoredBlockers}))}}onTick(e){return!0}}var Ws,Us,Vs,zs,Hs=__webpack_require__(949);class Gs extends Ur{constructor(e,t,i,r){super(),this.game=e,this.targetTile=t,this.toBridge=i,this.options=r,this.preventOpportunityFire=!1,this.logger=is.get("move"),this.destinationLeptons=new Hs.Vector2,this.currentWaypointLeptons=new Hs.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 Ds(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=qs.ReachedNextWaypoint,e.moveTrait.lastMoveResult=void 0,e.moveTrait.lastTargetOffset=void 0,e.moveTrait.lastVelocity=void 0}computeTargetOffset(e){return this.options?.targetOffset??(e.isInfantry()?e.position.getTileOffset():e.position.computeSubCellOffset(0))}computePath(e,t){let i;i=this.options?.allowOutOfBoundsTarget||this.game.map.mapBounds.isWithinBounds(this.targetTile)?e.rules.movementZone===ri.Fly?this.computeAirPath(e):t.ignoresTerrain?this.computeDirectJumpPath(e):(this.blockedPathNodes=this.blockedPathNodes.filter(e=>e.obj.isSpawned&&e.node.tile===e.obj.tile),this.computeGroundPath(e)):[],e.rules.movementZone===ri.Fly?(this.targetLinesConfig.pathNodes=i.map(({tile:e,onBridge:t})=>({tile:e,onBridge:t})),i.length&&(this.targetLinesConfig.pathNodes[0].onBridge=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0)):this.targetLinesConfig.pathNodes=i,this.path=i}computeAirPath(e){return[{tile:this.targetTile,onBridge:void 0},{tile:e.tile,onBridge:void 0}]}computeDirectJumpPath(t){let i=this.game.map;var e=t.onBridge?i.tileOccupation.getBridgeOnTile(t.tile):void 0;let r=this.targetTile,s=this.toBridge?i.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.options?.ignoredBlockers;var n=new Mr(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===qs.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 Hr(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*wr.LEPTONS_PER_TILE,e.ry*wr.LEPTONS_PER_TILE).add(t)}canStopAtTile(t,i,r){if(t.zone===fr.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!==qs.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!==qs.Moving&&e!==t);if(2<e.length||e.find(e=>e.position.subCell===t.position.subCell))return!1}return!(t.zone!==fr.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 kr(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=Qs.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!==Rr.Running&&this.status!==Rr.Cancelling||(e.moveTrait.unreservePathNodes(),e.moveTrait.lastMoveResult=Zs.Cancel,this.onEnd(e),e.moveTrait.lastTargetOffset=this.targetOffset,e.moveTrait.lastVelocity=e.moveTrait.velocity.clone()),this.status=Rr.Cancelled,!0))}onTick(s){if(s.moveTrait.isDisabled()&&s.moveTrait.moveState===qs.ReachedNextWaypoint)return!!this.isCancelling()&&(s.moveTrait.lastMoveResult=Zs.Cancel,!0);this.needsPathUpdate&&(s.moveTrait.moveState===qs.PlanMove&&(this.inPlanningForTicks=void 0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.collisionState=Qs.Resolved,s.moveTrait.moveState=qs.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===qs.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()?Zs.Cancel:Zs.Success,!0;{if(5<this.unreachableTargets.length)return s.moveTrait.lastMoveResult=Zs.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?Zs.Fail:Zs.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=Zs.Cancel,!0;this.cancelProcessed=!1,s.moveTrait.moveState=qs.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(wr.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===qs.PlanMove){if(this.isCancelling()&&!this.cancelRepositionPending)return s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=qs.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!==ri.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=qs.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)===Ir.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=qs.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=qs.ReachedNextWaypoint,this.onTick(s);if(e.obj.rules.crushable){if(!(s.rules.speedType!==Jt.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=qs.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=qs.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!==fr.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===qs.Idle||m.moveTrait.collisionState!==Qs.Resolved){if(!o&&s.moveTrait.collisionState!==Qs.Resolved&&m.isUnit()&&m.moveTrait.collisionState!==Qs.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===Qs.Resolved){var u=this.findFreeSubCell(s,r);if(void 0!==u)return this.relocateToSubCell(s,u),this.onTick(s)}l=Vr(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=Zs.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=qs.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 zr(40)),this.inPlanningForTicks=0,s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Qs.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===Qs.Waiting||d||m.isAircraft()&&m.missileSpawnTrait)return!this.options?.forceWaitOnPathBlocked&&(m.isBuilding()||d&&m.moveTrait.moveState===qs.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 zr(40)),this.options?.forceWaitOnPathBlocked?this.inPlanningForTicks=0:this.inPlanningForTicks+=40,s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Qs.Waiting),!1;var d,d=new Hs.Vector2(m.tile.rx-s.tile.rx,m.tile.ry-s.tile.ry);return this.pushTried=!0,m.unitOrderTrait.addTask(new ts(this.game,d)),this.children.push(new zr(1)),s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Qs.Waiting,this.log(s,"push "+m.id),!1}}if(!o)return 40<this.inPlanningForTicks&&(s.moveTrait.collisionState=Qs.Waiting),!1;if(180===Math.abs(s.direction-m.direction))return s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Qs.Waiting,!1;if(Math.abs(s.direction-m.direction)<=45&&1.5*c<o){c=this.path.indexOf(r);if(5<=c){let e=Vr(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=qs.ReachedNextWaypoint,this.onTick(s)}}return s.moveTrait.collisionState=Qs.Waiting,s.moveTrait.velocity.set(0,0,0),!1}return s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Qs.Waiting,!1}}}if(s.rules.speedType===Jt.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(hi.SCATTER)&&!this.game.areFriendly(e,s)))p.unitOrderTrait.hasTasks()||p.unitOrderTrait.addTask(new js(this.game))}}s.moveTrait.reservedPathNodes.length||(s.moveTrait.reservedPathNodes.push(...t),t.forEach(e=>{i.tileOccupation.occupySingleTile(e.tile,s)}))}s.moveTrait.moveState=qs.Moving,this.inPlanningForTicks=void 0,this.unreachableTargets.length=0,this.pushTried=!1,s.moveTrait.collisionState===Qs.Waiting&&(s.moveTrait.collisionState=Qs.Resolved)}if(s.moveTrait.moveState===qs.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(Ps).forEach(e=>{e[Ps.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 Ls(s,!0,a))),s.isDestroyed)return!0}}if(i)return s.moveTrait.moveState=qs.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===ri.Fly){let e=new Ms(n.tiles,n.mapBounds,r,1,this.game,e=>!0);i=e.getNextTile()}else{let e=new Hr(n),t=new Mr(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===fr.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 ga.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(wr.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 Ds(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}`)}}(Ws=Ws||{}).onDestroy=Symbol(),(s=Us=Us||{})[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",(Vs=Vs||{}).onTileChange=Symbol(),(zs=zs||{}).onTileChange=Symbol();class $s{constructor(e,t){this.target=e,this.source=t,this.type=er.EnterTile}}var qs,Zs,Qs,Xs,Ys,Ks,Js,ea,ta,ia=__webpack_require__(949);(s=qs=qs||{})[s.Idle=0]="Idle",s[s.ReachedNextWaypoint=1]="ReachedNextWaypoint",s[s.PlanMove=2]="PlanMove",s[s.Moving=3]="Moving",(s=Zs=Zs||{})[s.Success=0]="Success",s[s.Cancel=1]="Cancel",s[s.CloseEnough=2]="CloseEnough",s[s.Fail=3]="Fail",(s=Qs=Qs||{})[s.Waiting=0]="Waiting",s[s.Resolved=1]="Resolved";const ra=e=>e instanceof Gs||e.children[0]&&ra(e.children[0]);class sa{constructor(e,t){this.gameObject=e,this.tileOccupation=t,this.disabled=!1,this.speedPenalty=0,this.velocity=new ia.Vector3,this.reservedPathNodes=[],this.moveState=qs.Idle,this.collisionState=Qs.Resolved}get baseSpeed(){return this.gameObject.rules.speed*(this.gameObject.veteranTrait?.getVeteranSpeedMultiplier()??1)*this.gameObject.crateBonuses.speed*(this.gameObject.isVehicle()&&this.gameObject.healthTrait.health<=50&&this.gameObject.rules.locomotor!==ii.Hover?.75:1)*(1-this.speedPenalty)}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isMoving(){return this.moveState===qs.Moving}isIdle(){return this.moveState===qs.Idle}isWaiting(){return this.collisionState===Qs.Waiting}[_s.onTick](e,t){var i;this.moveState!==qs.Idle&&this.collisionState===Qs.Resolved&&((i=e.unitOrderTrait.getCurrentTask())&&ra(i)||(this.velocity.set(0,0,0),this.moveState=qs.Idle,this.locomotor=void 0,!i&&!e.attackTrait?.currentTarget&&e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction))),this.moveState===qs.Idle&&(e.rules.locomotor===ii.Jumpjet?vs.tickStationary(e,t):e.isAircraft()&&e.rules.locomotor===ii.Aircraft&&Rs.tickStationary(e,t))}[Ws.onDestroy](e,t){this.unreservePathNodes()}teleportUnitToTile(e,t,i,r,s){let a=this.gameObject;var n=a.tile;a.traits.filter(Ps).forEach(e=>{e[Ps.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=qs.Idle,this.collisionState=Qs.Resolved,this.locomotor=void 0,this.currentWaypoint=void 0,this.lastTargetOffset=void 0,this.lastVelocity=void 0,this.lastMoveResult=Zs.Cancel,a.isVehicle()&&(a.spinVelocity=0,a.turretTrait&&(a.turretTrait.desiredFacing=a.direction))),this.lastTeleportTick=s.currentTick,s.events.dispatch(new Ls(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!==fr.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===Jt.Amphibious||s)&&(a.zone=Tr(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===Nr.Paradrop)&&(!(e.isTechno()&&!i)||!r.areFriendly(e,a))))l.isDestroyed||(l.isInfantry()&&(l.infDeathType=ei.None),a.isVehicle()&&l.isOverlay()&&l.rules.wall&&a.applyRocking(0,.5),l.deathType=Us.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(Vs).forEach(e=>{e[Vs.onTileChange](a,r,t,s)}),a.traits.filter(zs).forEach(e=>{e[zs.onTileChange](a,r,t,s)}),r.events.dispatch(new $s(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 aa{constructor(){this.suppressionTicks=0,this.enabled=!0}disable(){this.enabled=!1}isSuppressed(){return this.enabled&&0<this.suppressionTicks}supress(){this.enabled&&(this.suppressionTicks=30)}[_s.onTick](){0<this.suppressionTicks&&this.suppressionTicks--}}class na{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()}}(Xs=Xs||{}).onChange=Symbol(),(Ys=Ys||{}).onSpawn=Symbol(),(Ks=Ks||{}).onUnspawn=Symbol(),(Js=Js||{}).onAttack=Symbol();class oa{constructor(e,t,i,r){this.traits=new na,this.cachedTraits={tick:[]},this.isCrashing=!1,this.isDestroyed=!1,this.deathType=Us.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===Bt.Smudge}isOverlay(){return this.type===Bt.Overlay}isTerrain(){return this.type===Bt.Terrain}isProjectile(){return this.type===Bt.Projectile}isDebris(){return this.type===Bt.Debris}isBuilding(){return!1}isInfantry(){return!1}isVehicle(){return!1}isAircraft(){return!1}isUnit(){return!1}isTechno(){return!1}update(e){for(var t of this.cachedTraits.tick)t[_s.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(Ks).forEach(e=>{e[Ks.onUnspawn](this,t)})}onDestroy(t,i,r){this.traits.filter(Ws).forEach(e=>{e[Ws.onDestroy](this,t,i,r)})}onOwnerChange(t,i){this.traits.filter(Xs).forEach(e=>{e[Xs.onChange](this,t,i)})}onAttack(t,i){this.traits.filter(Js).forEach(e=>{e[Js.onAttack](this,i,t)})}addTrait(e){this.traits.add(e),e[_s.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=ea=ea||{})[s.None=0]="None",s[s.Veteran=1]="Veteran",s[s.Elite=2]="Elite";class ha extends oa{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(ir.MAX_SIGHT,this.rules.sight*(this.veteranTrait?.getVeteranSightMultiplier()??1))}get veteranLevel(){return this.veteranTrait?.veteranLevel??ea.None}resetGuardModeToIdle(){this.guardMode=this.defaultToGuardArea,this.guardArea=void 0}update(e){if(this.warpedOutTrait.isActive())for(var t of this.cachedTraits.tick)t.ticksWhenWarpedOut&&t[_s.onTick](this,e);else super.update(e)}isTechno(){return!0}}class la{constructor(){this.cooldownTicks=Number.POSITIVE_INFINITY,this._actionDueThisTick=!1}[_s.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 js(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*Dr.BASE_TICKS_PER_SECOND)}}class ca{constructor(e){this.gameObject=e,this.type=er.ObjectCrashing}}(ta=ta||{}).onCrash=Symbol();class ua{constructor(e){this.gameObject=e,this.crashingEvtSent=!1,this.crashState={}}[_s.onTick](i,r){if(i.isCrashing){if(this.crashingEvtSent||(this.crashingEvtSent=!0,i.traits.filter(ta).forEach(e=>e[ta.onCrash](i,r)),r.events.dispatch(new ca(i))),i.rules.locomotor!==ii.Jumpjet&&i.rules.locomotor!==ii.Aircraft)throw new Error(`Crashing logic not implemented for locomotor ${ii[i.rules.locomotor]}`);{let e;if(i.rules.locomotor===ii.Jumpjet)e=vs.tickCrash(i,r,this.crashState);else{if(i.rules.locomotor!==ii.Aircraft)throw new Error(`Unhandled locomotor type "${i.rules.locomotor}"`);if(!i.isAircraft())throw new Error(`Obj "${i.name}#${i.id} is not an aircraft`);e=Rs.tickCrash(i,r,this.crashState)}let t=!1;var s,a=wr.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 da{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),[Yi.InfantryType,Yi.UnitType].includes(t.factoryTrait?.type)&&e.owner.production?.addVeteranType(t.factoryTrait.type)}}class pa{constructor(){this.firepower=1,this.armor=1,this.speed=1}}class ga extends ha{constructor(e,t,i){super(Bt.Infantry,e,t,i),this.direction=0,this.onBridge=!1,this.zone=fr.Ground,this._stance=Nr.None,this.isFiring=!1,this.isPanicked=!1,this.infDeathType=ei.Gunfire,this.crateBonuses=new pa}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r){let s=new this(e,t,i);return s.moveTrait=new sa(s,r),s.traits.add(s.moveTrait),s.rules.crashable&&(s.crashableTrait=new ua(s),s.traits.add(s.crashableTrait)),s.rules.proneWhenAttacked&&(s.suppressionTrait=new aa,s.traits.add(s.suppressionTrait)),s.rules.agent&&(s.agentTrait=new da,s.traits.add(s.agentTrait)),s.idleActionTrait=new la,s.traits.add(s.idleActionTrait),s}get stance(){return this._stance===Nr.None&&this.suppressionTrait?.isSuppressed()?Nr.Prone:this._stance}set stance(e){this._stance=e,this.moveTrait.setDisabled([Nr.Deployed,Nr.Cheer].includes(e)),this.attackTrait?.setDisabled([Nr.Paradrop,Nr.Cheer].includes(e))}isUnit(){return!0}isInfantry(){return!0}}ga.SUB_CELLS=[2,4,3];var ma=__webpack_require__(949);class fa extends Ur{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=wr.worldToLeptons(wr.tileHeightToWorld(i)),s=wr.worldToLeptons(wr.tileHeightToScreen(e.tileElevation));return r<Math.max(r,s-t)?(e.position.moveByLeptons3(new ma.Vector3(0,-t,0)),!1):(e.position.tileElevation=i,e.stance=Nr.None,this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge)||(e.infDeathType=ei.None,this.game.destroyObject(e,void 0,!0)),!0)}}function ya(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 wa(e){return null!=e}class Ta extends Ur{constructor(...e){super(),this.children.push(...e)}onTick(e){return!0}}var ba=__webpack_require__(949);class va{constructor(){this.enabled=!0}setEnabled(e){this.enabled=e}[_s.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 Ta(new Gs(t,i,!1,{allowOutOfBoundsTarget:!0}),new As(e=>t.unspawnObject(e))).setCancellable(!1)))}chooseExitTile(e,t){var i=t.map.tiles.getMapSize(),i=.5<t.generateRandom()?new ba.Vector2(Math.floor(i.width/2),0):new ba.Vector2(0,Math.floor(i.height/2)),e=new ba.Vector2(e.rx,e.ry),i=ya(e.x,e.y,i.x,i.y).map(e=>t.map.tiles.getByMapCoords(e.x,e.y)).filter(wa);if(!i.length)throw new Error("No valid exit tile found");return i[i.length-1]}}var Sa,_a,ka,Oa,Ia,Aa,Ca,Ba=__webpack_require__(949);(s=Sa=Sa||{})[s.Spawning=0]="Spawning",s[s.EnRoute=1]="EnRoute",s[s.Dropping=2]="Dropping",s[s.TurningAround=3]="TurningAround";const Ea=5*Dr.BASE_TICKS_PER_SECOND;class xa extends jr{constructor(e,t,i,r,s){super(e,t,i),this.paradropSquad=r,this.state=Sa.Spawning,this.spawnDelay=s*Ea}onStart(e){this.passengerRules=e.rules.getObject(this.paradropSquad.inf,Bt.Infantry),this.passengerCount=this.paradropSquad.num}computeFlightPath(e,t,i){if(t.equals(e))throw new Error("Source and destination must be different");let r=e.clone().sub(t);e=i.rules.general.paradrop.paradropRadius/wr.LEPTONS_PER_TILE,e=t.clone().add(r.clone().setLength(r.length()+2*e)).floor();let s=ya(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=wr.tileToWorld(a.rx+.5,a.ry+.5);if(i.map.isWithinHardBounds(new Ba.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===Sa.Spawning){if(0<this.spawnDelay)return this.spawnDelay--,!1;var a=s.map.tiles.getMapSize(),n=[new Ba.Vector2(0,0),new Ba.Vector2(Math.floor(a.width/2),0),new Ba.Vector2(0,Math.floor(a.height/2))][s.generateRandomInt(0,2)];let t=this.passengerRules.speedType,e=new Mr(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 Ba.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,Bt.Aircraft);let r=this.pdPlane=s.createUnitForPlayer(n,this.owner);s.spawnObject(r,h),r.direction=ns.fromMapCoords(i.clone().sub(new Ba.Vector2(h.rx,h.ry))),r.position.tileElevation=wr.worldToTileHeight(wr.leptonsToWorld(r.rules.flightLevel??s.rules.general.flightLevel)),r.zone=fr.Air,r.onBridge=!1,r.unitOrderTrait.addTask(new Gs(s,a,!1,{allowOutOfBoundsTarget:!0})),r.traits.get(va).setEnabled(!1),this.state=Sa.EnRoute}if(!this.pdPlane||this.pdPlane.isDestroyed||this.pdPlane.isCrashing)return!0;o=this.targetTile;if(!this.pdPlane.unitOrderTrait.hasTasks())return this.state=Sa.TurningAround,this.pdPlane.unitOrderTrait.addTask(new Gs(s,o,!1,{allowOutOfBoundsTarget:!0})),!1;n=s.rules.general.paradrop.paradropRadius/wr.LEPTONS_PER_TILE;let e=new kr(s.map.tileOccupation);h=e.isInTileRange(this.pdPlane.tile,o,0,n);if(this.state===Sa.EnRoute&&h&&(this.state=Sa.Dropping),this.state===Sa.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===Nr.Paradrop))return!1;n=this.findFreeSubCell(s,a);if(!n)return!1;this.passengerCount--;let i=s.createUnitForPlayer(this.passengerRules,this.owner);i.stance=Nr.Paradrop,i.position.tileElevation=this.pdPlane.tileElevation,i.position.subCell=n,i.onBridge=t,i.rules.trainable&&this.owner.canProduceVeteran(i.rules)&&i.veteranTrait?.setVeteranLevel(ea.Veteran),s.spawnObject(i,a),i.unitOrderTrait.addTask(new fa(s).setCancellable(!1))}else{if(!(0<this.passengerCount))return this.pdPlane.unitOrderTrait.getCurrentTask().forceCancel(this.pdPlane),this.pdPlane.traits.get(va).setEnabled(!0),!0;this.state=Sa.TurningAround,this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!!o.onBridgeLandType)}return this.state===Sa.TurningAround&&h&&(o=this.computeFlightPath(new Ba.Vector2(o.rx,o.ry),new Ba.Vector2(this.pdPlane.tile.rx,this.pdPlane.tile.ry),s)["toTile"],this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!1),this.state=Sa.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=ga.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=_a=_a||{})[s.NotBridge=0]="NotBridge",s[s.Concrete=1]="Concrete",s[s.Wood=2]="Wood";class Pa{static getOverlayBridgeType(e){return V(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)||V(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)?_a.Concrete:V(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||V(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)?_a.Wood:_a.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===_a.Concrete)i=this.minLowBridgeConcreteId;else{if(e!==_a.Wood)throw new Error("Not implemented");i=this.minLowBridgeWoodId}return i+(t?0:9)}static calculateHighBridgeOverlayId(e,t){let i;if(e===_a.Concrete)i=this.minHighBridgeConcreteId;else{if(e!==_a.Wood)throw new Error("Not implemented");i=this.minHighBridgeWoodId}return i+(t?0:1)}}Pa.minLowBridgeWoodId=74,Pa.maxLowBridgeWoodId=99,Pa.minLowBridgeConcreteId=205,Pa.maxLowBridgeConcreteId=230,Pa.minHighBridgeConcreteId=24,Pa.maxHighBridgeConcreteId=25,Pa.minHighBridgeWoodId=237,Pa.maxHighBridgeWoodId=238,Pa.bridgePlaceholderIds=[100,101,231,232],(ka=ka||{}).onAttack=Symbol(),(s=Oa=Oa||{})[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 Na{constructor(e,t,i,r){this.target=e,this.position=t,this.explodeAnim=i,this.isLightningStrike=r,this.type=er.WarheadDetonate}}(s=Ia=Ia||{})[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 Ra{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(Yt));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:Hi(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!==Yt.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===Yt.Cliff&&t.z===s.z})||(s.landType=Kt.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(wa)}getNeighbourTile(e,t){var i=e.rx,r=e.ry;switch(t){case Ia.Bottom:return this.getByMapCoords(i+1,r+1);case Ia.Top:return this.getByMapCoords(i-1,r-1);case Ia.Left:return this.getByMapCoords(i-1,r+1);case Ia.Right:return this.getByMapCoords(i+1,r-1);case Ia.BottomLeft:return this.getByMapCoords(i,r+1);case Ia.BottomRight:return this.getByMapCoords(i+1,r);case Ia.TopLeft:return this.getByMapCoords(i-1,r);case Ia.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:Kt.Rock,terrainType:Yt.Rock1,rampType:0,subTile:0,tileNum:0,occluded:!1,onBridgeLandType:void 0}}}(s=Aa=Aa||{})[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 Da{static getOverlayTibType(e){return this.isRiparius(e)?Aa.Riparius:this.isCruentus(e)?Aa.Cruentus:this.isVinifera(e)?Aa.Vinifera:this.isAboreus(e)?Aa.Aboreus:Aa.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}}Da.minIdRiparius=102,Da.maxIdRiparius=127,Da.minIdCruentus=27,Da.maxIdCruentus=38,Da.minIdVinifera=127,Da.maxIdVinifera=146,Da.minIdAboreus=147,Da.maxIdAboreus=166,(s=Ca=Ca||{})[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 Ma{constructor(e){this.gameObject=e}static canBePlacedOn(e,t){return[Kt.Clear,Kt.Road,Kt.Rough].includes(e.landType)&&!t.getGroundObjectsOnTile(e).find(e=>!e.isSmudge()&&!e.isUnit())}getTiberiumType(){var e=Da.getOverlayTibType(this.gameObject.overlayId);switch(e){case Aa.Ore:return Ca.Ore;case Aa.Gems:return Ca.Gems;case Aa.Vinifera:return Ca.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(Ma.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}}Ma.maxBails=11;class La{destroyOre(i,r,s){if(r.landType===Kt.Tiberium&&(s.art.hasObject(i,Bt.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(Ma.maxBails/2),r=i.startsWith("S_CLSN")?r:s.generateRandomInt(1,r);let e=t.traits.get(Ma);e.removeBails(r),e.getBailCount()||s.unspawnObject(t)}}}spawnSmudges(e,s,a){if(s.landType===Kt.Clear&&0===s.rampType&&a.map.mapBounds.isWithinBounds(s)&&!a.map.getObjectsOnTile(s).find(e=>!e.isUnit())){e=a.art.hasObject(e,Bt.Animation)?a.art.getAnimation(e):void 0;if(e?.crater){let t=e?.forceBigCraters?2:1,i=e?.scorch,r=[Ia.Bottom,Ia.BottomLeft,Ia.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(Bt.Smudge,e),a.spawnObject(e,s))}}}}class Fa{constructor(e,t,i){this.target=e,this.attacker=t,this.incidental=i,this.type=er.ObjectAttacked}}var ja=__webpack_require__(949);class Wa{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!==fr.Air||i===fr.Air)&&(!(!e.isUnit()&&i===fr.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()||!Pa.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!==fr.Air)return 0;if(this.rules.radiation||this.rules.temporal||!i.isInfantry()||i.stance!==Nr.Prone||(s*=this.rules.proneDamage),i.isTechno()||i.isOverlay()||i.isTerrain()){let e=i.isTerrain()?si.Wood:i.rules.armor;i.isOverlay()&&i.isBridge()&&((t=Pa.getOverlayBridgeType(i.overlayId))===_a.Wood?e=si.Wood:t===_a.Concrete&&(e=si.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===si.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(ka).forEach(e=>{e[ka.onAttack](t,i?.obj,r)}),t.onAttack(r,i),r.events.dispatch(new Fa(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=Us.Temporal),t.isUnit()&&t.crashableTrait&&t.zone===fr.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 js(t)),e.isInfantry()&&e.unitOrderTrait.addTask(new As(()=>e.isPanicked=!1).setCancellable(!1))):e.isInfantry()&&e.suppressionTrait?.supress()}createDummyWeaponInfo(){return{minRange:0,range:0,speed:Number.POSITIVE_INFINITY,type:oi.Primary,rules:new Ai(new h("Dummy")),projectileRules:new qi(Bt.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/wr.LEPTONS_PER_TILE:this.rules.cellSpread,v=this.rules.percentAtMax;let S=new Set,_=new Map,k=new kr(i.map.tileOccupation),O=new Mr(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!==Oa.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===Oa.OnBridge&&!m.isBridge()))){var I=z(I=m.isBuilding()?g===t?0:k.distance3(g,s)/wr.ISO_TILE_SIZE:m.isTerrain()||m.isOverlay()?k.distance3(g,t)/wr.ISO_TILE_SIZE:k.distance3(m,s)/wr.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=ja.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=ns.fromMapCoords(f.position.getMapPosition().clone().sub(wr.vecWorldToGround(wr.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===fr.Ground){let e=new La;p&&e.destroyOre(p,t,i),u&&e.spawnSmudges(u,t,i),p&&e.spawnSmudges(p,t,i)}i.events.dispatch(new Na(this,s,p,c))}pickExplodeAnim(t,i,r,s,a){if(t){if(a)return s.rules.audioVisual.weatherConBoltExplosion;if(this.rules.conventional&&r===fr.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}}}Wa.SPECIAL_WARHEAD_NAME="Special",Wa.HE_WARHEAD_NAME="HE";class Ua{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 Ua([this.forward,this.lateral,this.vertical])}}class Va{constructor(e,t){this.weapon=e,this.gameObject=t,this.type=er.WeaponFire}}class za{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===oi.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===Nr.Paradrop)return this.projectileRules.isAntiAir&&(this.projectileRules.isAntiGround||this.weaponType===oi.Secondary);if(e.zone===fr.Air)return this.projectileRules.isAntiAir;if(this.weaponType===oi.Secondary&&this.projectileRules.isAntiAir)return!1;i=e.zone}else i=t.landType===Kt.Water?fr.Water:fr.Ground;return i===fr.Water?this.canTargetNaval(this.gameObject.rules.navalTargeting,this.gameObject,e,this.weaponType):this.canTargetLand(this.gameObject.rules.landTargeting,this.weaponType)}canTargetLand(e,t){switch(e){case ai.LandOk:return!0;case ai.LandNotOk:return!1;case ai.LandSecondary:return t===oi.Secondary;default:throw new Error(`Unhandled LandTargeting value "${e}"`)}}canTargetNaval(e,t,i,r){switch(e){case ni.UnderwaterNever:return!i||!(i.isVehicle()&&i.submergibleTrait?.isSubmerged());case ni.UnderwaterSecondary:return i&&i.isVehicle()&&i.submergibleTrait&&!t.rules.spawned?r===oi.Secondary:r===oi.Primary;case ni.UnderwaterOnly:return!!(i&&i.isVehicle()&&i.submergibleTrait);case ni.OrganicSecondary:return i?.isTechno()&&i.rules.organic?r===oi.Secondary:r===oi.Primary;case ni.SealSpecial:return i?.isTechno()&&i.rules.naval&&!i.rules.organic&&(i.isBuilding()||i.rules.speedType===Jt.Float)?r===oi.Secondary:r===oi.Primary;case ni.NavalAll:return!0;case ni.NavalNone:return!1;default:throw new Error(`Unhandled NavalTargeting value "${e}"`)}}}var Ha=__webpack_require__(949);class Ga{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===Wa.SPECIAL_WARHEAD_NAME&&(n=Ga.findSpecialWarheadName(a,i,r));var o=new Wa(r.getWarhead(n)),e=r.getProjectile(a.projectile),r=new za(t,e,a,o.rules,i,r.general);return new this(t,i,a,o,e,s||new Ua,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,Bt.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*Ii.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===oi.Secondary&&this.gameObject.primaryWeapon?Math.min(this.gameObject.primaryWeapon.rules.range,this.rules.range):this.rules.range}get speed(){return Ga.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(wr.vecLeptonsToWorld(h))){t.position.moveToLeptons(h),t.position.tileElevation=n.position.tileElevation;let e=new Ha.Vector2(i.lateral,i.forward);a=this.getMuzzleFacing()+this.distributedFireAngle;e=Zr(e,a);var h=Zr(h=new Ha.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=wr.screenDistanceToLeptons(n.rules.turretAnimX,n.rules.turretAnimY),l=n.getFoundationCenterOffset(),t.position.moveByLeptons(-l.x+c.x,-l.y+c.y));var l=new Ha.Vector3(e.x,i.vertical,-e.y),c=wr.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 Va(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}}Ga.NUKE_PAYLOAD_NAME="NukePayload";var $a,qa,Za,Qa=__webpack_require__(949);class Xa extends jr{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(Bt.Building).find(e=>e.rules.nukeSilo);if(s){let e=Ga.factory(i.name,oi.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(wr.ISO_TILE_SIZE);if(r.map.isWithinHardBounds(s)){let e=r.createLooseProjectile(t.name,this.owner,i);e.position.moveToLeptons(wr.vecWorldToLeptons(s)),e.position.tileElevation=wr.worldToTileHeight(wr.leptonsToWorld(e.rules.detonationAltitude)),r.spawnObject(e,e.position.tile)}}onTick(e){return!0}}class Ya{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*Ya.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)}}Ya.defaultRate=Dr.BASE_TICKS_PER_SECOND;class Ka{constructor(e){this.position=e,this.type=er.LightningStormCloud}}class Ja{constructor(e){this.target=e,this.type=er.LightningStormManifest}}(s=$a=$a||{})[s.Approaching=0]="Approaching",s[s.Manifesting=1]="Manifesting";class en extends jr{constructor(){super(...arguments),this.state=$a.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===$a.Approaching&&(0<this.manifestStartTimer?this.manifestStartTimer--:(this.state=$a.Manifesting,t.events.dispatch(new Ja(this.tile)))),this.state===$a.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 kr(t.map.tileOccupation),e=new Ms(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 Wa(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,wr.tile3dToWorld(n.rx+.5,n.ry+.5,n.z+h),r,o?Oa.OnBridge:Oa.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 Ya(i.art,60),i=Math.floor(Dr.BASE_TICKS_PER_SECOND/i.rate*60);this.clouds.push({tile:e,durationTicks:i,ticksLeft:i});i=(t.map.tileOccupation.getBridgeOnTile(e)?.tileElevation??0)+wr.worldToTileHeight(wr.leptonsToWorld(t.rules.general.flightLevel)),i=wr.tile3dToWorld(e.rx+.5,e.ry+.5,e.z+i);t.events.dispatch(new Ka(i))}}class tn extends jr{onStart(e){var t,i,r=e.rules.combatDamage.ironCurtainDuration,s={player:this.owner};let a=new Mr(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 rn extends jr{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===Nr.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===ri.Fly&&(n=Jt.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 Mr(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)===fr.Water&&(o.deathType=Us.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!==Nr.Paradrop&&(t.deathType=Us.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}}(qa=qa||{}).onDeactivate=Symbol();class sn{constructor(){this.effects=[]}[Ar.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===Er.NotStarted&&(t.onStart(i),t.status=Er.Running),t.onTick(i)&&(t.status=Er.Finished,i.traits.filter(qa).forEach(e=>{e[qa.onDeactivate](t.type,t.owner,i)}));this.effects=this.effects.filter(e=>e.status!==Er.Finished)}[xr.onPowerLow](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!1)})}[xr.onPowerRestore](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!0)})}[xr.onPowerChange](e,t){}[Cr.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===Br.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 Ji.AmerParaDrop:for(var[h,l]of r.rules.general.paradrop.amerParaDrop.entries())t.push(new xa(o,i,s,l,h));break;case Ji.ParaDrop:{let e=r.rules.general.paradrop.getParadropSquads(i.country.side);for(var[c,u]of e.entries())t.push(new xa(o,i,s,u,c));break}case Ji.MultiMissile:if(!e.weaponType)throw new Error("Missing WeaponType in super weapon rules");t.push(new Xa(o,i,s,e.weaponType));break;case Ji.LightningStorm:t.push(new en(o,i,s));break;case Ji.IronCurtain:t.push(new tn(o,i,s));break;case Ji.ChronoSphere:if(!a)throw new Error("Missing tile2 action param");t.push(new rn(o,i,s,a))}for(var d of t)this.addEffect(d);r.traits.filter(Pr).forEach(e=>{e[Pr.onActivate](o,i,r,s,a)}),r.events.dispatch(new Wr(o,i,s,a,n))}}}class an{constructor(e){this.target=e,this.type=er.ObjectCloakChange}}(Za=Za||{}).onDamage=Symbol();class nn{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 an(this.gameObject)))}resetCloakCooldown(){this.cooldownTicks=Math.floor(60*this.cloakDelayMinutes*Dr.BASE_TICKS_PER_SECOND)}[Ys.onSpawn](e,t){this.resetCloakCooldown()}[_s.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 an(this.gameObject)))}[Za.onDamage](e,t){this.uncloak(t)}dispose(){this.gameObject=void 0}}class on{static calculateOverlayId(e,t,i){let r;if("number"!=typeof e?(r=Da.getOverlayTibType(e.id),t=e.rx,i=e.ry):r=e,r!==Aa.NotSpecial){var t=wr.tileToScreen(t,i),{x:i,y:t}=wr.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===Aa.Ore?Da.minIdRiparius+i:r===Aa.Gems?Da.minIdCruentus+i:r===Aa.Vinifera?Da.minIdVinifera+i:r===Aa.Aboreus?Da.minIdAboreus+i:void 0}}}var hn,ln,cn=__webpack_require__(949);const un=[Ir.IonStorm,Ir.Gas,Ir.Pod,Ir.Squad];class dn{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)===fr.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}[Ar.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)===fr.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)===fr.Water,a=r.rules.crateRules,s=s?a.waterCrateImg:a.crateImg;let e=r.createObject(Bt.Overlay,s);e.overlayId=r.rules.getOverlayId(s),e.value=0,r.spawnObject(e,t);r=60*a.crateRegen*Dr.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,Jt.Amphibious,!1)&&t.terrainType!==Yt.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 mr(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===Ir.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,Bt.Vehicle);return t.isAvailableTo(a.country)&&t.hasOwner(a.country)});if(!o)throw new Error(`No suitable MCV found for player country ${a.country}`);e=s.rules.getObject(o,Bt.Vehicle)}}if(e||(h=(h=s.rules.crateRules.unitCrateType)?s.rules.hasObject(h,Bt.Vehicle)?[s.rules.getObject(h,Bt.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 Mr(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===Ir.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===Ir.HealBase){var e;for(e of a.getOwnedObjects(!0))e.isDestroyed||e.healthTrait.healToFull(void 0,s);n=!0}else if(i.type===Ir.Reveal)s.mapShroudTrait.revealMap(a,s),n=!0;else if(i.type===Ir.Darkness)s.mapShroudTrait.resetShroud(a,s),n=!0;else if(i.type===Ir.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===Ir.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===Ir.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===Ir.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===Ir.Cloak){if(!t.cloakableTrait){n=!0;for(var y of this.getUnitsInCrateRadius(s,r,a))y.cloakableTrait||(y.cloakableTrait=new nn(y,s.rules.general.cloakDelay),s.addObjectTrait(y,y.cloakableTrait))}}else if(i.type===Ir.ICBM){var w=[...s.rules.superWeaponRules.values()].find(e=>e.type===Ji.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===Ir.Invulnerability){var T=[...s.rules.superWeaponRules.values()].find(e=>e.type===Ji.IronCurtain);T&&(s.traits.get(sn).activateEffect(T,a,s,r,void 0,!0),n=!0)}else if(i.type===Ir.Explosion||i.type===Ir.Napalm){n=!0;w=Number(i.data),T=i.type===Ir.Napalm?s.rules.combatDamage.flameDamage:s.rules.combatDamage.c4Warhead;let e=new Wa(s.rules.getWarhead(T));e.detonate(s,w,t.tile,t.tileElevation,t.position.worldPosition,t.zone,Oa.None,s.createTarget(t,t.tile),{player:t.owner,weapon:void 0},!1,!1,void 0,0)}else{if(i.type!==Ir.Tiberium)return void console.warn(`Unhandled powerup type "${Ir[i.type]}"`);{let e=new Ms(s.map.tiles,s.map.mapBounds,r,2,s,e=>Ma.canBePlacedOn(e,s.map)),t,i=0;for(;i++<6&&(t=e.getNextTile());){var b=on.calculateOverlayId(Aa.Ore,t.rx,t.ry);if(void 0===b)throw new Error("Expected an overlayId");let e=s.createObject(Bt.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===Ir.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 kr(e.map.tileOccupation);return e.map.technosByTile.queryRange((new cn.Box2).setFromCenterAndSize(new cn.Vector2(t.rx,t.ry),new cn.Vector2(r,r))).filter(e=>e.owner===i&&e.isUnit()&&s.tileDistance(e,t)<=r)}}class pn{constructor(){this.powerups=[]}readIni(e){for(var[s,a]of e.entries){let[e,t,i,r]=a.split(",");var n=Number(e),a=Ir[s];void 0!==a?un.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 gn=["Gold","DarkRed","DarkBlue","DarkGreen","Orange","DarkSky","Purple","Magenta"];class mn{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 pn,this.colors=new Map,this.general=new Vi,this.ai=new cr,this.crateRules=new gr,this.elevationModel=new ur,this.mpDialogSettings=new _t,this.audioVisual=new Ci,this.combatDamage=new hr,this.radiation=new dr,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 Ai(i),this.cachedWeaponRules.set(e,t)}return t}getWeaponByInternalId(e){var t=this.weaponTypes.get(e);if(!t)throw new RangeError(`Weapon with internal ID "${e}" not found`);return this.getWeapon(t)}getWarhead(e){let t=this.warheadRules.get(e.toLowerCase());var i;if(t||(i=this.ini.getSection(e))&&(t=new $i(i),this.warheadRules.set(e.toLowerCase(),t)),!t)throw new Error(`Unknown warhead ${e}`);return t}getProjectile(e){let t=this.cachedProjectileRules.get(e);if(!t){var i=this.ini.getSection(e);if(!i)throw new Error(`Projectile ${e} is missing ini section`);t=new qi(Bt.Projectile,i),this.cachedProjectileRules.set(e,t)}return t}getOverlayName(e){var t=this.overlayTypes.get(e);if(!t)throw new Error(`Invalid overlay id ${e}`);return t}hasOverlayId(e){return this.overlayTypes.has(e)}getOverlayId(e){var t=this.overlayIdsByType.get(e);if(void 0===t)throw new Error(`Invalid overlay name ${e}`);return t}getOverlay(e){var t=this.overlayRules.get(e);if(!t)throw new Error(`Missing rules for overlay "${e}"`);return t}getAnimationName(e){return this.animationTypes.get(e)}getCountry(e){if(!this.countryRules.has(e))throw new Error(`Unknown country ${e}`);return this.countryRules.get(e)}getMultiplayerCountries(){return[...this.countryRules.values()].filter(e=>e.multiplay)}getMultiplayerColors(){let t=new Map;return gn.forEach(e=>{if(!this.colors.has(e))throw new Error(`Multiplayer color "${e}" does not exist in the rules [Colors] section.`);t.set(e,this.colors.get(e))}),t}getLandRules(e){let t=this.landRules.get(e);var i;return t||(i=e===Kt.Cliff?"Rock":Kt[e],t=(new Gi).readIni(this.ini.getOrCreateSection(i)),this.landRules.set(e,t)),t}getTiberium(e){var t=this.tiberiumTypes.get(e);if(!t)throw new Error(`Unknown tiberium type ${e}`);return this.tiberiumRules.get(t)}getSuperWeapon(e){if(!this.superWeaponRules.has(e))throw new Error(`Unknown superweapon type "${e}"`);return this.superWeaponRules.get(e)}getIni(){return this.ini}applySpecialFlags(e){e.initialVeteran&&(this.general.veteran.initialVeteran=!0)}init(){this.readAudioVisual(),this.readCombatDamage(),this.readRadiation(),this.readGeneral(),this.readAi(),this.readCrateRules(),this.readElevationModel(),this.readMpDialogSettings(),this.readObjectTypes("BuildingTypes",this.buildingTypes),this.readObjectTypes("InfantryTypes",this.infantryTypes),this.readObjectTypes("VehicleTypes",this.vehicleTypes),this.readObjectTypes("AircraftTypes",this.aircraftTypes),this.readObjectTypes("TerrainTypes",this.terrainTypes),this.readObjectTypes("SmudgeTypes",this.smudgeTypes),this.readObjectTypes("Animations",this.animationTypes),this.animationNames=new Set(this.animationTypes.values()),this.readObjectTypes("VoxelAnims",this.voxelAnimTypes),this.readObjectTypes("OverlayTypes",this.overlayTypes),this.overlayTypes.forEach((e,t)=>this.overlayIdsByType.set(e,t)),this.readColors(),this.readObjectTypes("Countries",this.countryTypes),this.readObjectTypes("Warheads",this.warheadTypes),this.readObjectTypes("Tiberiums",this.tiberiumTypes),this.readObjectTypes("SuperWeaponTypes",this.superWeaponTypes),this.allObjectRules.set(Bt.Building,this.buildingRules).set(Bt.Infantry,this.infantryRules).set(Bt.Vehicle,this.vehicleRules).set(Bt.Aircraft,this.aircraftRules).set(Bt.Terrain,this.terrainRules).set(Bt.Overlay,this.overlayRules).set(Bt.Smudge,this.smudgeRules).set(Bt.VoxelAnim,this.voxelAnimRules),this.readObjects(Bt.Building,this.buildingTypes,this.buildingRules),this.readObjects(Bt.Infantry,this.infantryTypes,this.infantryRules),this.readObjects(Bt.Vehicle,this.vehicleTypes,this.vehicleRules),this.readObjects(Bt.Aircraft,this.aircraftTypes,this.aircraftRules),this.readObjects(Bt.Terrain,this.terrainTypes,this.terrainRules),this.readObjects(Bt.Overlay,this.overlayTypes,this.overlayRules),this.readObjects(Bt.Smudge,this.smudgeTypes,this.smudgeRules),this.readObjects(Bt.VoxelAnim,this.voxelAnimTypes,this.voxelAnimRules),this.readCountries(),this.readWarheads(),this.readPowerups(),this.readTiberiums(),this.readSuperWeapons(),this.buildWeaponsList()}readAudioVisual(){var e=this.ini.getSection("AudioVisual");if(!e)throw new Error("Missing [AudioVisual] section");this.audioVisual.readIni(e)}readCombatDamage(){var e=this.ini.getSection("CombatDamage");if(!e)throw new Error("Missing [CombatDamage] section");this.combatDamage.readIni(e)}readRadiation(){var e=this.ini.getSection("Radiation");if(!e)throw new Error("Missing [Radiation] section");this.radiation.readIni(e)}readGeneral(){var e=this.ini.getSection("General");if(!e)throw new Error("Missing [General] section");this.general.readIni(e)}readAi(){var e=this.ini.getSection("AI");if(!e)throw new Error("Missing [AI] section");this.ai.readIni(e)}readCrateRules(){var e=this.ini.getSection("CrateRules");if(!e)throw new Error("Missing [CrateRules] section");this.crateRules.readIni(e)}readElevationModel(){var e=this.ini.getSection("ElevationModel");if(!e)throw new Error("Missing [ElevationModel] section");this.elevationModel.readIni(e)}readMpDialogSettings(){var e=this.ini.getSection("MultiplayerDialogSettings");if(!e)throw new Error("Missing [MultiplayerDialogSettings] section");this.mpDialogSettings.readIni(e)}readObjectTypes(i,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 or).create(r,i,t),s.set(e,t)):this.logger?.debug(`${Bt[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 Oi(t);r.readIni(i),this.countryRules.set(e,r)})}readWarheads(){this.warheadTypes.forEach(e=>{var t=this.ini.getSection(e);t?(t=new $i(t),this.warheadRules.set(e.toLowerCase(),t)):this.logger?.debug(`Warhead "${e}" has no rules section`)})}readPowerups(){var e=this.ini.getSection("Powerups");if(!e)throw new Error("Missing [Powerups] section");this.powerups.readIni(e)}readTiberiums(){this.tiberiumTypes.forEach(e=>{var t=this.ini.getSection(e);if(!t)throw new Error(`Missing rules section for tiberium type ${e}`);this.tiberiumRules.set(e,(new lr).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 pr(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(Ga.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(wa).filter(e=>""!==e))e.add(r);let s=0;for(i of e)this.weaponTypes.set(s++,i)}}(s=hn=hn||{})[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 fn=new Map([["E",5],["S",3],["W",1],["N",7]]);class yn{readIni(e){let t=new Map;for(var[i,r]of e.entries){i=hn[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]?fn.get(r[3]):void 0},t.set(i,r))}return t}}(s=ln=ln||{})[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 wn,Tn,bn,vn=__webpack_require__(949);class Sn{constructor(e,t,i){this.sequences=new Map,this.dockingOffsets=[],this.type=e,this.rules=t,this.art=i,this.init()}static getDefaultPalette(e){switch(e){case Bt.Building:case Bt.Aircraft:case Bt.Infantry:case Bt.Vehicle:case Bt.Projectile:case Bt.VoxelAnim:return O.Unit;case Bt.Overlay:return O.Overlay;case Bt.Smudge:case Bt.Terrain:return O.Iso;default:Bt.Animation;return O.Anim}}static getDefaultLighting(e){switch(e){case Bt.Animation:return ln.None;case Bt.Aircraft:case Bt.Building:case Bt.Infantry:case Bt.Vehicle:return ln.Ambient;case Bt.Projectile:case Bt.VoxelAnim:return ln.Global;case Bt.Overlay:case Bt.Smudge:case Bt.Terrain:default:return ln.Full}}static getDefaultRemapability(e){switch(e){case Bt.Aircraft:case Bt.Building:case Bt.Infantry:case Bt.Vehicle:return!0;case Bt.Overlay:case Bt.Smudge:case Bt.Terrain:case Bt.Animation:case Bt.Projectile:case Bt.VoxelAnim:return!1;default:throw new Error(`Unknown object type ${e}`)}}static getDefaultDrawOffset(e){switch(e){case Bt.Animation:case Bt.Building:case Bt.Vehicle:case Bt.Infantry:case Bt.Overlay:case Bt.Smudge:case Bt.Projectile:case Bt.VoxelAnim:return new vn.Vector2(0,0);case Bt.Terrain:case Bt.Aircraft:return new vn.Vector2(0,(wr.ISO_TILE_SIZE+1)/2);default:throw new Error(`Unknown object type ${e}`)}}static getDefaultShadow(e){switch(e){case Bt.Overlay:case Bt.Building:case Bt.Infantry:case Bt.Terrain:case Bt.Vehicle:case Bt.Aircraft:return!0;default:case Bt.Smudge:case Bt.Animation:case Bt.Projectile:case Bt.VoxelAnim:return!1}}static getDefaultHeight(e){switch(e){case Bt.Building:return 2;case Bt.Infantry:case Bt.Vehicle:case Bt.Aircraft:return 1;default:return 0}}static factory(e,t,i,r){var s=t.imageName;let a=i.getSection(s);a||(r?.debug(`Image ${s} (${Bt[e]}: ${t.name}) has no section in art.ini`),a=new h(s));let n=new this(e,t,a);return e===Bt.Infantry&&(!(e=a.getString("Sequence"))||(e=i.getSection(e))&&(n.sequences=(new yn).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 vn.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",Sn.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",Sn.getDefaultHeight(this.type)),this.isVoxel=this.art.getBool("Voxel"),this.occupyHeight=this.art.getNumber("OccupyHeight",this.height),this.type===Bt.Building?this.canHideThings=this.art.getBool("CanHideThings",!0):this.canHideThings=!1,this.canBeHidden=this.art.getBool("CanBeHidden",!0),this.addOccupy=this.readAddRemoveOccupy("AddOccupy"),this.removeOccupy=this.readAddRemoveOccupy("RemoveOccupy"),this.rotates=this.art.getBool("Rotates")}get imageName(){return(this.image||this.rules.imageName)+(this.rules.alternateArcticArt?"A":"")}get cameo(){let e=this.art.getString("Cameo")||Sn.MISSING_CAMEO;return e.toLowerCase()}get altCameo(){let e=this.art.getString("AltCameo")||Sn.MISSING_CAMEO;return e.toLowerCase()}get useTheaterExtension(){return this.art.getBool("Theater")}readPaletteAndLightingTypes(){this.paletteType=O.Default,this.lightingType=ln.Default,(this.rules instanceof rr?this.rules.noUseTileLandType:void 0)&&(this.paletteType=O.Iso,this.lightingType=ln.Full),this.art.getBool("TerrainPalette")||this.art.getBool("ShouldUseCellDrawer")?this.paletteType=O.Iso:this.art.getBool("AnimPalette")?(this.paletteType=O.Anim,this.lightingType=ln.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 rr||this.rules instanceof ir)&&this.rules.wall&&(this.paletteType=O.Unit,this.lightingType=ln.Ambient),(this.rules instanceof sr||this.rules instanceof ir)&&this.rules.gate&&(this.paletteType=O.Unit),this.rules instanceof sr&&this.rules.spawnsTiberium&&(this.paletteType=O.Unit,this.lightingType=ln.None),this.rules instanceof rr&&(this.rules.isVeins&&(this.paletteType=O.Unit,this.lightingType=ln.None),this.rules.isVeinholeMonster&&(this.paletteType=O.Unit,this.lightingType=ln.None),this.rules.tiberium&&(this.lightingType=ln.None),this.rules.land===Kt.Railroad&&(this.paletteType=O.Iso,this.lightingType=ln.Full),this.rules.crate&&(this.paletteType=O.Iso,this.lightingType=ln.Full)),this.paletteType===O.Default&&(this.paletteType=Sn.getDefaultPalette(this.type)),this.lightingType===ln.Default&&(this.lightingType=Sn.getDefaultLighting(this.type))}readRemapability(){this.remapable=Sn.getDefaultRemapability(this.type),this.art.getBool("TerrainPalette")||this.art.getBool("AnimPalette")?this.remapable=!1:this.rules instanceof qi&&this.rules.firersPalette&&(this.remapable=!0)}readFlatness(){let e=!1;this.type===Bt.Building||this.type===Bt.Animation?e=this.art.getBool("Flat"):this.type===Bt.Smudge&&(e=!0),this.rules instanceof rr&&(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 vn.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===Bt.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 vn.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 vn.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 sr&&this.rules.spawnsTiberium)return new vn.Vector2(0,0);let e=Sn.getDefaultDrawOffset(this.type);return this.rules instanceof rr&&this.rules.isARock&&(e.y+=(wr.ISO_TILE_SIZE+1)/2),e}get hasShadow(){return this.art.getBool("Shadow",Sn.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 Ua(this.art.getNumberArray("PrimaryFireFLH"))}get elitePrimaryFireFlh(){var e=this.art.getNumberArray("ElitePrimaryFireFLH");return e.length?new Ua(e):this.primaryFireFlh}get primaryFirePixelOffset(){return this.art.getNumberArray("PrimaryFirePixelOffset")}get secondaryFirePixelOffset(){return this.art.getNumberArray("SecondaryFirePixelOffset")}get secondaryFireFlh(){return new Ua(this.art.getNumberArray("SecondaryFireFLH"))}get eliteSecondaryFireFlh(){var e=this.art.getNumberArray("EliteSecondaryFireFLH");return e.length?new Ua(e):this.secondaryFireFlh}getSpecialWeaponFlh(e){return new Ua(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}}Sn.DEFAULT_LINE_TRAIL_DEC=16,Sn.MISSING_CAMEO="xxicon";class _n{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){if(!e)throw new Error(`Must specify an art name for type "${Bt[t]}"`);var i=this.objectArt.get(t)?.get(e);return i||(this.logger?.debug(`Missing art for object "${e}"`),new Sn(t,this.rules.hasObject(e,t)?this.rules.getObject(e,t):new Ii(t,new h(e)),new h(e)))}getAnimation(e){return this.getObject(e,Bt.Animation)}getProjectile(e){e=this.rules.getProjectile(e);return Sn.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=Sn.factory(e.type,e,this.artIni),i.set(e.name,t)):this.logger?.debug(`${Bt[e.type]} "${e.name}" has no art section`)})});let e=[[Bt.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 Ii(r,new h(e)),i=new Sn(r,t,i),s.set(e,i)):this.logger?.debug(`${Bt[r]} "${e}" has no art section`)})})}}class kn{constructor(e){this.rules=e}static factory(e,t){return new this(t.getCountry(e))}get id(){return this.rules.id}get side(){return this.rules.side}get name(){return this.rules.name}isPlayable(){return this.rules.multiplay&&!this.rules.multiplayPassive}hasVeteranUnit(e,t){let i=[];switch(e){case Bt.Aircraft:i=this.rules.veteranAircraft;break;case Bt.Infantry:i=this.rules.veteranInfantry;break;case Bt.Vehicle:i=this.rules.veteranUnits;break;default:throw new Error(`Unsupported object type "${Bt[e]}"`)}return i.includes(t)}}class On{constructor(e,t){this.target=e,this.player=t,this.type=er.BuildingEvacuate}}class In{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}[Za.onDamage](e,t){e.healthTrait.health<=100*this.evacThreshold&&this.evacuate(t)}[Ws.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 Mr(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 js(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 On(a,i))}}}class An{constructor(){this.facing=0,this.desiredFacing=0}isRotating(){return this.facing!==this.desiredFacing}[_s.onTick](e){this.desiredFacing!==this.facing&&(e=e.rules.rot,this.facing=ns.tick(this.facing,this.desiredFacing,e||Number.POSITIVE_INFINITY).facing)}}class Cn{constructor(e,t){this.target=e,this.status=t,this.type=er.BuildStatusChange}}class Bn{constructor(e){this.target=e,this.type=er.PowerLow}}class En{constructor(e){this.target=e,this.type=er.PowerRestore}}class xn{constructor(e,t,i){this.target=e,this.power=t,this.drain=i,this.type=er.PowerChange}}(s=wn=wn||{})[s.Low=0]="Low",s[s.Normal=1]="Normal";class Pn{constructor(e){this.player=e,this.power=0,this.drain=0,this.level=wn.Normal,this.blackoutFrames=0,this.powerByObject=new Map}isLowPower(){return this.level===wn.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(xr).forEach(e=>{e[xr.onPowerChange](this.player,r)}),r.events.dispatch(new xn(this.player,this.power,this.drain))}}updateLevel(t){var e=this.level;this.level=this.power>=this.drain&&!this.blackoutFrames?wn.Normal:wn.Low,this.level!==e&&(e===wn.Normal&&this.level===wn.Low&&(t.traits.filter(xr).forEach(e=>{e[xr.onPowerLow](this.player,t)}),t.events.dispatch(new Bn(this.player))),e===wn.Low&&this.level===wn.Normal&&(t.traits.filter(xr).forEach(e=>{e[xr.onPowerRestore](this.player,t)}),t.events.dispatch(new En(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 Nn{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!==wn.Low))}dispose(){this.obj=void 0}}class Rn{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=Tn=Tn||{})[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=bn=bn||{})[s.Idle=0]="Idle",s[s.Active=1]="Active",s[s.OnHold=2]="OnHold",s[s.Ready=3]="Ready";class Dn{constructor(e,t,i){this.type=e,this._maxSize=t,this.maxItemQuantity=i,this.items=[],this.size=0,this._status=bn.Idle,this._onUpdate=new Rn}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=bn.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===bn.Idle&&(this._status=bn.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 ${Tn[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=bn.Active),a-=e.quantity):(e.quantity-=a,a=0)}this.size-=t,t&&(this.size||(this._status=bn.Idle),this._onUpdate.dispatch(this))}notifyUpdated(){this._onUpdate.dispatch(this)}}class Mn extends Gs{constructor(e,t,i,r){super(e,i,!1,{ignoredBlockers:[t],closeEnoughTiles:0,strictCloseEnough:!0,forceWaitOnPathBlocked:t.factoryTrait?.type!==Yi.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===qs.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 Ln,Fn,jn,Wn,Un=__webpack_require__(949);class Vn{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 Un.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 Un.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}}}(Ln=Ln||{}).onSell=Symbol();class zn{[Ks.onUnspawn](e){this.undock(e),this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Xs.onChange](e){e.owner!==this.dock?.owner&&this.undock(e),e.owner!==this.reservedDock?.owner&&this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Ps.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 Hn{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}}[Ks.onUnspawn](){for(let e=0;e<this.numberOfDocks;e++)this.unreserveDockAt(e)}[_s.onTick](){for(let e=0;e<this.numberOfDocks;e++){var t=this.unitsByDockNumber[e];t&&t.tile!==this.getDockTile(e)&&this.undockUnit(t)}}[Ws.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))}[Ln.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 Es(s,n)):e.unitOrderTrait.addTask(new Ta(new Gs(s,e.tile,!1),new As(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))}}[Xs.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)/wr.LEPTONS_PER_TILE),Math.floor((t.y+e.z)/wr.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}`);let i=e.traits.find(zn);if(!i)throw new Error(`Unit "${e.name}" cannot be docked to ${this.building.name}`);this.unitsByDockNumber[t]=e,i.dock=this.building}undockUnitAt(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);let t=this.unitsByDockNumber[e];t&&(this.unitsByDockNumber[e]=void 0,t.traits.get(zn).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(wa)}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(zn).reservedDock?.dockTrait.unreserveDockForUnit(e),e.traits.get(zn).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(zn).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 Gn{constructor(e){this.target=e,this.type=er.FactoryProduceUnit}}(s=Fn=Fn||{})[s.All=0]="All",s[s.Ground=1]="Ground",s[s.Air=2]="Air";class $n{constructor(e){this.tiles=e,this.tileOccupation=[],this.emptyTiles=new Set,this._onChange=new Rn;let t=this.tileOccupation;for(var i of e.getAll())t[i.rx]=t[i.rx]||[],t[i.rx][i.ry]=new Set,this.emptyTiles.add(i)}get onChange(){return this._onChange.asEvent()}occupyTileRange(e,t){let i=this.calculateTilesForGameObject(e,t);i.forEach(e=>this.occupyTile(e,t)),this._onChange.dispatch(this,{tiles:i,object:t,type:"added"})}unoccupyTileRange(e,t){let i=this.calculateTilesForGameObject(e,t);i.forEach(e=>this.unoccupyTile(e,t)),this._onChange.dispatch(this,{tiles:i,object:t,type:"removed"})}occupySingleTile(e,t){this.occupyTile(e,t),this._onChange.dispatch(this,{tiles:[e],object:t,type:"added"})}unoccupySingleTile(e,t){this.unoccupyTile(e,t),this._onChange.dispatch(this,{tiles:[e],object:t,type:"removed"})}calculateTilesForGameObject(e,t){return this.tiles.getInRectangle(e,t.getFoundation())}occupyTile(e,t){let i=this.tileOccupation[e.rx]?.[e.ry];i&&(i.add(t),this.emptyTiles.delete(e),e.landType=this.computeTileLandType(e),e.onBridgeLandType=this.computeOnBridgeLandType(e))}unoccupyTile(e,t){let i=this.tileOccupation[e.rx]?.[e.ry];i&&(i.delete(t),i.size||this.emptyTiles.add(e),e.landType=this.computeTileLandType(e),e.onBridgeLandType=this.computeOnBridgeLandType(e))}isTileOccupiedBy(e,t){return!!this.tileOccupation[e.rx]?.[e.ry]?.has(t)}computeTileLandType(e){if(e.landType===Kt.Rock)return Kt.Rock;var t,i=Hi(e.terrainType);for(t of this.tileOccupation[e.rx]?.[e.ry]??[]){if((t.isOverlay()||t.isBuilding())&&t.rules.wall)return Kt.Wall;if(t.isOverlay()&&t.isTiberium())return Kt.Tiberium;if(t.isOverlay()&&t.rules.land!==Kt.Clear&&!t.isBridge()&&!t.isBridgePlaceholder())return t.rules.land}return i}computeOnBridgeLandType(e){for(var t of this.tileOccupation[e.rx]?.[e.ry]??[])if(t.isOverlay()&&t.isBridge())return t.isHighBridge()?Kt.Road:t.rules.land}getTileZone(e,t=!1){return Tr(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===fr.Air||t.push(i);return t}getAirObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isUnit()&&i.zone===fr.Air&&t.push(i);return t}getObjectsOnTileByLayer(e,t){if(t===Fn.Ground)return this.getGroundObjectsOnTile(e);if(t===Fn.Air)return this.getAirObjectsOnTile(e);if(t===Fn.All)return this.getObjectsOnTile(e);throw new Error(`Unhandled layer type "${t}"`)}getEmptyTiles(){return[...this.emptyTiles]}}(jn=jn||{}).onChange=Symbol(),(Wn=Wn||{}).onProduce=Symbol();var qn,Zn=__webpack_require__(949);(s=qn=qn||{})[s.Idle=0]="Idle",s[s.Delivering=1]="Delivering";class Qn{constructor(e,t=!1){this.type=e,this.isCloningVats=t,this.status=qn.Idle}[Ys.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;[Yi.BuildingType,Yi.AircraftType].includes(this.type)||(i=this.computeDefaultRallyPoint(e,this.type,t.map),e.rallyTrait?.changeRallyPoint(i,e,t))}[jn.onChange](t,e,i){if(t.owner.production){let e=[];e=this.type===Yi.BuildingType?[Tn.Structures,Tn.Armory]:[t.owner.production.getQueueTypeForFactory(this.type)];for(var r of e)t.owner.production.getQueue(r).notifyUpdated()}}[_s.onTick](i,r){if(this.status===qn.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=qn.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===Yi.UnitType)&&this.type!==Yi.BuildingType){let e=i.owner.production.getQueueForFactory(this.type);if(e&&e.status===bn.Ready){let t=e.getFirst();if(this.type===Yi.AircraftType){let e=this.produceAircraftAt(i,t,r);var s;if(!e)for(s of[...i.owner.buildings].filter(e=>e.factoryTrait?.type===Yi.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===Yi.InfantryType){let e=[...i.owner.buildings].find(e=>e.factoryTrait&&e.rules.cloning);e?.factoryTrait.status===qn.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=bn.Active)}}}}produceGroundUnitAt(e,t,i){let r=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(r.rules)&&r.veteranTrait?.setVeteranLevel(ea.Veteran),r.isInfantry()&&(r.position.subCell=ga.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===Yi.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?Fn.Air:Fn.Ground).filter(e=>e.isInfantry()&&e.moveTrait.moveState!==qs.Moving).map(e=>e.position.subCell);r.position.subCell=ga.SUB_CELLS.find(e=>!t.includes(e))??ga.SUB_CELLS[0]}r.direction=270,i.spawnObject(r,a),i.traits.filter(Wn).forEach(e=>{e[Wn.onProduce](r,i)}),i.events.dispatch(new Gn(r)),r.rules.consideredAircraft?(n=o??{tile:s,onBridge:void 0},r.unitOrderTrait.addTask(new Gs(i,n.tile,!!n.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))):r.unitOrderTrait.addTask(new Mn(i,e,s,o)),this.status=qn.Delivering,this.deliveringUnit=r}produceAircraftAt(e,t,i){let r=e.traits.find(Hn);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(ea.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(Wn).forEach(e=>{e[Wn.onProduce](a,i)}),i.events.dispatch(new Gn(a)),!0}computeExitCoords(e,t){if(t===Yi.InfantryType)return this.computeBarracksDefaultExitCoords(e);if(t===Yi.UnitType)return this.computeWarFactoryExitCoords(e);throw new Error(`Unsupported factory type ${Yi[t]}`)}computeInternalRallyPoint(e,t,i,r){let s,a;if(t===Yi.NavalUnitType)a=this.computeNavalInternalRallyPoint(e,i,r);else{if(t===Yi.InfantryType)s=this.computeBarracksInternalRallyCoords(e);else{if(t!==Yi.UnitType)throw new Error(`Unsupported factory type ${Yi[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===Yi.NavalUnitType)s=this.computeNavalDefaultRallyPoint(e,i);else{if(t===Yi.InfantryType)r=this.computeBarracksInternalRallyCoords(e);else{if(t!==Yi.UnitType)throw new Error(`Unsupported factory type ${Yi[t]}`);r=this.computeWarFactoryDefaultRallyCoords(e)}s=i.tiles.getByMapCoords(r.rx,r.ry)}return s??this.findTileAdjacentToBuilding(e,i)}findTileAdjacentToBuilding(e,t){return new Mr(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 Vn(t.tiles,t.mapBounds,e.centerTile,5,5,e=>e.terrainType===Yt.Water&&!t.getObjectsOnTile(e).find(e=>e.isBuilding()||e.isOverlay()&&e.isBridge()));return i.diagonal=!1,i.getNextTile()??t.tiles.getByMapCoords(e.tile.rx+e.getFoundation().width,e.tile.ry+e.getFoundation().height)}computeNavalInternalRallyPoint(e,t,i){t=new Zn.Vector2(t.rx,t.ry).sub(new Zn.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 Xn{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 Yn{[Ys.onSpawn](i,r){let e;if(r.rules.hasObject(i.rules.freeUnit,Bt.Vehicle))e=r.rules.getObject(i.rules.freeUnit,Bt.Vehicle);else{if(!r.rules.hasObject(i.rules.freeUnit,Bt.Infantry))return void console.warn(`Free unit "${i.rules.freeUnit}" is not a vehicle or infantry type.`);e=r.rules.getObject(i.rules.freeUnit,Bt.Infantry)}let s=r.createUnitForPlayer(e,i.owner),a;var t=new Xn(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 Kn{[Ln.onSell](e,t){this.spawnSurvivors(e,t)}[Ws.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===Zt.GDI)i=t.alliedSurvivorDivisor,a=t.alliedCrew;else{if(e!==Zt.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,Bt.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=ga.SUB_CELLS[0]),e.veteranTrait&&r.owner.canProduceVeteran(e.rules)&&e.veteranTrait.setVeteranLevel(ea.Veteran),s.spawnObject(e,t),r.isBuilding()&&e.unitOrderTrait.addTask(new js(s,void 0,{ignoredBlockers:r.isDestroyed?void 0:[r]}))}}}}}class Jn{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?Pa.calculateHighBridgeOverlayId(r.type,s):Pa.calculateLowBridgeOverlayId(r.type,s);var n,o,h=t.rules.getOverlayName(a);for(n of e){let e=t.createObject(Bt.Overlay,h);e.overlayId=a,e.value=0,e.position.tileElevation=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 js(r)))}else for(a of r.map.getGroundObjectsOnTile(t))a.isUnit()&&(r.map.terrain.getPassableSpeed(t,a.rules.speedType,!0)?(a.zone=fr.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)!==fr.Water||r.obj.isDestroyed||(r.obj.deathType=Us.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 eo{constructor(){this.isActive=!1,this.produceCashCooldown=0}[Ys.onSpawn](e){e.owner.isNeutral||(this.isActive=!0)}[Xs.onChange](e,t){t.isNeutral&&!e.owner.isNeutral&&(e.owner.credits+=e.rules.produceCashStartup,this.isActive=!0,this.produceCashCooldown=e.rules.produceCashDelay)}[_s.onTick](e){this.isActive&&(this.produceCashCooldown--,this.produceCashCooldown<=0&&(this.produceCashCooldown=e.rules.produceCashDelay,e.owner.credits+=e.rules.produceCashAmount))}}class to{constructor(){this.linkedDamageHandled=!1}[Za.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===Kt.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 io=e=>void 0!==e.position;class ro{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=io(e)?e.tile:e,t=io(t)?t.tile:t;for({x:h,y:l}of ya(c.rx,c.ry,t.rx,t.ry)){var u=this.tiles.getByMapCoords(h,l);if(!u)return!1;if(!r&&u.landType===Kt.Wall)return!1;if(s)if(u.landType===Kt.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 so=__webpack_require__(949);class ao extends Gs{constructor(e,t,i,r){super(e,t instanceof oa?t.isBuilding()?t.centerTile:t.tile:t,i,{pathFinderIgnoredBlockers:t instanceof oa&&0<r.range?[t]:void 0}),this.target=t,this.weapon=r,this.recalcMinRange=!0,this.cancelRequested=!1,this.bomberInitialLock=!1,this.rangeHelper=new kr(e.map.tileOccupation),this.losHelper=new ro(e.map.tiles,e.map.tileOccupation)}onStart(i){let e=this.target,r=this.game.map;if(e instanceof oa&&e.isBuilding()&&i.rules.movementZone!==ri.Fly){let t=e.tile;var s=e instanceof oa?e.getFoundation():{width:1,height:1},s=new Mr(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===ri.Fly&&e.rules.locomotor===ii.Aircraft&&e.rules.fighter&&1<this.weapon.projectileRules.iniRot}isBombingRun(e){return e.rules.movementZone===ri.Fly&&e.rules.locomotor===ii.Aircraft&&this.weapon.projectileRules.iniRot<=1}isAirStrafeCloseEnough(e){return this.rangeHelper.tileDistance(e,this.targetTile)<Math.min(this.weapon.range,2)}bomberCanReturn(e){return!this.bomberManeuverTile||this.rangeHelper.tileDistance(e,this.bomberManeuverTile)<=1}findStrafeDestination(t,i){let e=new Ms(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!==fr.Air&&this.target instanceof oa&&this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)&&(!this.target.isUnit()||this.target.tile===e&&this.target.moveTrait.moveState!==qs.Moving))return!1;if(t.zone!==fr.Air){if(!super.canStopAtTile(t,e,i))return!1}else if(this.game.map.tileOccupation.getAirObjectsOnTile(e).filter(e=>e.isUnit()&&e.moveTrait.moveState!==qs.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===fr.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=wr.tile3dToWorld(t.rx+i.x/wr.LEPTONS_PER_TILE,t.ry+i.y/wr.LEPTONS_PER_TILE,t.z+e.position.tileElevation);return(e.isUnit()&&e.rules.movementZone===ri.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!==ri.Fly)return super.findRelocationTile(t,i,r);{i=this.game.map;let e=new Ms(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 oa?e.isBuilding()?e.centerTile:e.tile:e;this.bomberManeuverTile?this.bomberQueuedTargetTile=i:(this.updateTarget(i,t),this.recalcMinRange=!0),this.target=e,this.options?.ignoredBlockers&&(this.options.ignoredBlockers=e instanceof oa?[e]:void 0),this.options??(this.options={}),this.options.pathFinderIgnoredBlockers=e instanceof oa?[e]:void 0}onTick(s){if(this.recalcMinRange){this.recalcMinRange=!1;var e=this.findMinRangeRelocationTile(s,this.targetTile);if(e!==this.targetTile){if(!e)return this.cancel(),!1;this.updateTarget(e,!!e.onBridgeLandType)}}if(this.shouldAirStrafe(s)&&!this.isCancelling()&&(this.updateTarget(this.target instanceof oa?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target,!1),!this.isAirStrafeCloseEnough(s)||(a=this.findStrafeDestination(s,this.targetTile))&&this.updateTarget(a,!1)),this.isBombingRun(s)&&!this.isCancelling()&&(!s.ammo||this.weapon.getBurstsFired()||this.bomberInitialLock)&&!this.bomberManeuverTile){this.bomberInitialLock=!1;let e=s.position.getMapPosition();var a=this.target instanceof oa?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target;let t=new so.Vector2(a.rx+.5,a.ry+.5).clone().multiplyScalar(wr.LEPTONS_PER_TILE).sub(e),i=t.length();i||(t.copy(ns.toMapCoords(s.direction)),i=Number.EPSILON);let r=e.clone().add(t.setLength(i+7*wr.LEPTONS_PER_TILE));a=r.multiplyScalar(1/wr.LEPTONS_PER_TILE).floor(),a=ya(a.x,a.y,s.tile.rx,s.tile.ry);if(!a.length)throw new Error("Bresenham returned no tiles");a=a[0];this.bomberManeuverTile=this.game.map.tiles.getByMapCoords(a.x,a.y)??this.game.map.tiles.getPlaceholderTile(a.x,a.y),this.options.allowOutOfBoundsTarget=!0,this.updateTarget(this.bomberManeuverTile,!1)}return this.bomberManeuverTile&&this.bomberCanReturn(s.tile)&&(this.bomberManeuverTile=void 0,this.bomberQueuedTargetTile&&(this.updateTarget(this.bomberQueuedTargetTile,!1),this.recalcMinRange=!0,this.bomberQueuedTargetTile=void 0)),this.cancelRequested&&(this.bomberManeuverTile||(this.cancelRequested=!1,this.cancel())),!!(this.isBombingRun(s)&&this.isCancelling()&&this.forceCancel(s))||super.onTick(s)}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===ii.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 so.Vector2(t.tile.rx-e.rx,t.tile.ry-e.ry).setLength(i).floor().add(new so.Vector2(e.rx,e.ry));let n;for(a of ya(i.x,i.y,e.rx,e.ry))if(n=s.tiles.getByMapCoords(a.x,a.y),n)break;if(n){let e=new Mr(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 no{tick(e,t){this.tickChildren(e,t)}startTask(e,t){if(e.status!==Rr.NotStarted)throw new Error(`Attempted to start a task with status ${e.status}`);e.status=Rr.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===Rr.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===Rr.Cancelled||e.status===Rr.Finished),e.waitingForChildrenToFinish=!i);a=a&&i;return a&&(e.onEnd(t),e.status=s?Rr.Cancelled:Rr.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===Rr.NotStarted&&this.startTask(i,s),i.status===Rr.Running||i.status===Rr.Cancelling)e=!0===this.tickTask(i,s);else{if(i.status!==Rr.Cancelled)throw new Error(`Unhandled task status ${Rr[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 oo{constructor(e,t,i){this.tileOccupation=i,this.isOre=!1,e?e.isOverlay()&&e.isBridge()?(this.bridge=e,this.tile=t):e.isOverlay()&&e.isTiberium()?(this.isOre=!0,this.tile=e.tile):(this.obj=e,this.tile=e.isBuilding()?e.centerTile:e.tile):(t.landType===Kt.Tiberium&&(this.isOre=!0),this.tile=t)}equals(e){return this.obj===e.obj&&this.tile===e.tile&&this.bridge===e.bridge&&this.isOre===e.isOre}getWorldCoords(){return this.obj?this.obj.position.worldPosition:wr.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 ho,lo=__webpack_require__(949);(s=ho=ho||{})[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 co{constructor(e,t){this.disabled=!1,this.attackState=ho.Idle,this.passiveScanCooldownTicks=0,this.taskRunner=new no,this.distributedFireHistory=new Map,this.rangeHelper=new kr(t),this.losHelper=new ro(e,t)}isIdle(){return this.attackState===ho.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===Zt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon:void 0:e.isBuilding()&&e.overpoweredTrait?e.overpoweredTrait.getWeapon():e.primaryWeapon;return i}selectWeaponVersus(e,t,i,r=!1,s=!1){var a=t.tile;const n=t instanceof oo?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!==fr.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===Zt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon]:[]:e.isBuilding()&&e.overpoweredTrait?[e.overpoweredTrait.getWeapon()]:i||t?[e.primaryWeapon,!i&&t&&e.secondaryWeapon&&(e.secondaryWeapon.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||e.nukeMaker?1:e.verses.get(t);return void 0===r?(console.warn(`Unhandled ArmorType ${si[t]} in warhead ${e.name} verses`),!1):!(100*r<=(i?1:0))}createAttackTask(e,t,i,r,s){return new po(e,e.createTarget(t,i),r,s)}[_s.onTick](a,n){if(!this.isDisabled()){var e;if(this.opportunityFireTask&&(!a.unitOrderTrait.hasTasks()||a.isUnit()&&!a.unitOrderTrait.getTasks()[0].preventOpportunityFire||(a.unitOrderTrait.getTasks()[0]instanceof po?this.opportunityFireTask=void 0:this.opportunityFireTask.cancel()),this.opportunityFireTask&&(e=[this.opportunityFireTask],this.taskRunner.tick(e,a),e.length||(this.opportunityFireTask=void 0))),!this.opportunityFireTask&&this.retaliateTarget){var o=this.retaliateTarget;this.retaliateTarget=void 0;let e;!a.unitOrderTrait.hasTasks()&&n.isValidTarget(o)&&(e=this.selectWeaponVersus(a,o,n,!1))&&a.unitOrderTrait.addTask(this.createAttackTask(n,o,o.tile,e,{holdGround:a.rules.movementZone===ri.Fly}))}if(!this.opportunityFireTask&&this.shouldPassiveAcquire(a))if(0<this.passiveScanCooldownTicks)this.passiveScanCooldownTicks--;else{this.passiveScanCooldownTicks=a.guardMode?n.rules.general.guardAreaTargetingDelay:n.rules.general.normalTargetingDelay;let e=this.selectDefaultWeapon(a);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===ri.Fly&&!a.guardMode||a.rules.movementZone!==ri.Fly&&e.isUnit()&&e.zone===fr.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 Gs(n,a.guardArea.tile,a.guardArea.onBridge),new As(()=>{[Zs.Success,Zs.CloseEnough].includes(a.moveTrait.lastMoveResult)||a.resetGuardModeToIdle(),a.guardArea=void 0}))}}}[Za.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)}[Ps.onBeforeTeleport](e,t,i,r){r||(this.attackState=ho.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)/wr.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)/wr.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 lo.Vector2(e.tile.rx,e.tile.ry),a=new lo.Vector2(e.tile.rx+r.width-1,e.tile.ry+r.height-1);s.addScalar(-t),a.addScalar(t);t=new lo.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(wa).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===li.Strong&&e.healthTrait.getProjectedHitPoints()<=0&&(a-=1e6),a}updateDistributedFireHistory(e){if(50!==this.distributedFireHistory.get(e.target)){for(var[t,i]of this.distributedFireHistory)i--,i<=0?this.distributedFireHistory.delete(t):this.distributedFireHistory.set(t,i);this.distributedFireHistory.set(e.target,50)}}dispose(){this.distributedFireHistory.clear()}}var uo=__webpack_require__(949);class po extends Ur{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 uo.Vector3,this.lastInRangeSelfPosition=new uo.Vector3,this.initialIndirectTarget=!1,this.forceDropTarget=!1,this.rangeHelper=new kr(e.map.tileOccupation),this.losHelper=new ro(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=ho.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===ri.Fly&&t.zone!==fr.Air&&(t.rules.hoverAttack||t.isAircraft())&&this.children.push(new Gs(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 Hr(i),h=s.rules.movementZone===ri.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 Mr(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=ho.Idle,e.attackTrait.currentTarget=void 0;var t=this.game.rules.general.prism.type;e.isBuilding()&&e.name===t&&this.weapon.type!==oi.Secondary&&this.countSupportBeamsAndFireDownTowers(e,t),this.weapon.rules.limboLaunch&&e.attackTrait.expirePassiveScanCooldown(),(e.isInfantry()||e.isVehicle())&&(e.isFiring=!1),this.weapon.hasBurstsLeft()&&this.weapon.resetBursts()}forceCancel(t){if(t.rules.movementZone!==ri.Fly)return!1;if(!this.cancellable||this.children.some(e=>!e.cancellable))return!1;if(this.status===Rr.Running||this.status===Rr.Cancelling){if(this.children.filter(e=>e instanceof Gs).some(e=>!e.forceCancel(t)))return!1;this.onEnd(t),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!1)}return this.status=Rr.Cancelled,!0}onTick(i){let r=i.attackTrait;(i.isInfantry()||i.isVehicle())&&r.attackState!==ho.Firing&&(i.isFiring=!1);let s=this.target.obj,a=this.children.find(e=>e instanceof ao);if(this.isCancelling()&&r.attackState!==ho.FireUp)return!i.airSpawnTrait?.isLaunchingMissiles()&&(a?.cancel(),!0);let n=!1;if(r.attackState===ho.FireUp){if(r.isDisabled())return!0;r.attackState=ho.Firing,n=!0}if(r.attackState===ho.Firing){if(this.initialIndirectTarget&&!this.game.map.getObjectsOnTile(this.target.tile).find(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()))return this.cancel(),this.onTick(i);if(n){var o=this.target.obj||this.target.tile;if(!this.game.isValidTarget(this.target.obj)||this.shouldDropTarget(this.target.obj)||!this.weapon.targeting.canTarget(this.target.obj,this.target.tile,this.game,!!this.options.force,!!this.options.passive)||!this.rangeHelper.isInWeaponRange(i,o,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,o,this.weapon))return r.attackState=ho.CheckRange,this.onTick(i)}if(this.weapon.rules.limboLaunch){if((s?.isVehicle()||s?.isAircraft())&&s.parasiteableTrait?.isInfested())return!0;if(i.rules.movementZone!==ri.Fly&&s?.isUnit()&&s.zone===fr.Air)return!0}if(this.target.tile.onBridgeLandType&&i.tile.onBridgeLandType&&i.isUnit()&&(this.game.map.tileOccupation.getBridgeOnTile(this.target.tile)?.isHighBridge()||this.game.map.tileOccupation.getBridgeOnTile(i.tile)?.isHighBridge()))if((s?s.isUnit()&&(s.zone===fr.Air||s.onBridge):this.target.isBridge())!==(i.zone===fr.Air||i.onBridge)&&this.game.map.bridges.findHighBridgeBoundary(i.tile)?.tile===this.game.map.bridges.findHighBridgeBoundary(this.target.tile)?.tile)return!0;let e=1;o=this.game.rules.general.prism.type;if(i.isBuilding()&&i.name===o&&this.weapon.type!==oi.Secondary&&(o=this.countSupportBeamsAndFireDownTowers(i,o),e=1+o*this.game.rules.general.prism.supportModifier),this.weapon.rules.spawner&&(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isParalyzed())return!0;if(0===i.ammo)return i.isAircraft()&&(i.rules.fighter||i.rules.spawned)&&a?.cancel(),!0;let t=!1;if(this.weapon.rules.limboLaunch&&a){if(!a.forceCancel(i))return!1;i.moveTrait.lastTargetOffset=void 0,i.moveTrait.lastVelocity=void 0,t=!0}return(this.weapon.fire(this.target,this.game,e),t)?!0:!!this.weapon.rules.fireOnce||(!(!this.options.passive||!i.rules.distributedFire)||(r.attackState=ho.JustFired,!1))}if(r.attackState===ho.JustFired)return r.attackState=ho.PrepareToFire,this.onTick(i);this.needsTargetUpdate&&(this.target=this.needsTargetUpdate,s=this.target.obj,this.needsTargetUpdate=void 0,this.onTargetChange(i),s||a?.retarget(this.target.tile,!!this.target.getBridge())),s?.isTechno()&&s.replacedBy&&(h=this.game.createTarget(s.replacedBy,s.replacedBy.tile),this.target=h,s=s.replacedBy,this.onTargetChange(i));let t=this.game.isValidTarget(s)&&!this.shouldDropTarget(s);if(t){let e=this.weapon.targeting.canTarget(s,this.target.tile,this.game,!!this.options.force,!!this.options.passive);if(!e||!i.armedTrait.isEquippedWithWeapon(this.weapon)){var h=r.selectWeaponVersus(i,this.target,this.game,this.options.force,this.options.passive);if(h){if(this.setWeapon(h),r.attackState!==ho.CheckRange)return r.attackState=ho.CheckRange,this.onTick(i);e=!0}else e=!1}t=e}if(t&&(l=this.lastTargetTpCheck,s?.isUnit()&&l&&s.moveTrait.lastTeleportTick>=l?(t=!1,this.rangeCheckCooldown=0):this.lastTargetTpCheck=this.game.currentTick),t&&s&&(this.lastValidTargetPosition={tile:s.tile,onBridge:this.target.getBridge()}),t||(this.targetLinesConfig.isAttack=!1),r.attackState===ho.CheckRange){if(0<this.rangeCheckCooldown)return this.rangeCheckCooldown--,!1;let e=this.target.obj?t?this.target.obj:this.lastValidTargetPosition.tile:this.target.tile;var l=this.target.obj?t?this.target.obj.isBuilding()?this.target.obj.centerTile:this.target.obj.tile:this.lastValidTargetPosition.tile:this.target.tile;if(!this.rangeHelper.isInWeaponRange(i,e,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,e,this.weapon)||i.isUnit()&&i.rules.balloonHover&&!i.rules.hoverAttack&&!a&&i.tile!==l||i.isAircraft()&&this.weapon.projectileRules.iniRot<=1&&!a){if(i.isUnit()&&!this.options.holdGround&&this.game.map.isWithinBounds(l)){if(a){if(a.target!==this.target.obj||t)if(t&&this.target.obj&&this.rangeHelper.tileDistance(this.target.obj,this.lastSelfMoveTargetTile)>this.weapon.range)a.retarget(this.target.obj,!!this.target.getBridge()),this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=this.target.obj?.tile??this.target.tile;else{if(void 0!==this.options.leashTiles&&this.rangeHelper.tileDistance(this.initialSelfPosition.tile,i.tile)>this.options.leashTiles)return a.cancel(),!0;var c=e instanceof oa&&e.isUnit()?e.moveTrait.baseSpeed:0,u=Math.ceil((this.rangeHelper.tileDistance(i,e)-(this.weapon.range+1))/((i.moveTrait.baseSpeed+c)/wr.LEPTONS_PER_TILE));0<u&&(this.rangeCheckCooldown=Math.min(Dr.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),r.currentTarget=e,a.retarget(e.tile,e.isBridge()),this.updateTargetLines(e,!1)}return!1}if(!i.moveTrait||i.moveTrait.isDisabled())return!0;if(this.isCancelling())return!0;if(i.tile===this.lastSelfTileBeforeMove||this.moveExecuted&&i.moveTrait.lastMoveResult===Zs.Fail?this.moveAttempts++:this.moveAttempts=0,this.weapon.rules.limboLaunch&&i.defaultToGuardArea&&s&&this.moveExecuted&&i.moveTrait.lastMoveResult===Zs.Fail&&this.rangeHelper.isInRange(i,s,0,i.armedTrait.computeGuardScanRange(this.weapon),!0))return!0;if(3<this.moveAttempts)return!0;0<this.moveAttempts&&this.children.push(new Is(1/60));c=e,u=s&&!t?this.lastValidTargetPosition.onBridge:this.target.getBridge();return a=new ao(this.game,c,!!u,this.weapon),a.blocking=!1,this.children.push(a),this.moveExecuted=!0,this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=c instanceof oa?c.tile:c,this.onTick(i)}return!0}if(this.moveExecuted=!1,this.moveAttempts=0,a&&(i.rules.balloonHover&&!i.rules.hoverAttack||i.rules.fighter||i.rules.spawned||i.rules.movementZone===ri.Fly&&!this.rangeHelper.isInRange2(i,this.target.obj??this.target.tile,this.weapon.minRange,this.weapon.range-1)||a.cancel()),a&&(i.isInfantry()&&!i.rules.balloonHover||this.weapon.rules.spawner))return!1;if(a?.children.some(e=>!e.cancellable)&&this.weapon.rules.limboLaunch)return!1;if(a&&a.shouldAirStrafe(i)&&this.target.obj?.isUnit()&&this.target.obj.moveTrait.isMoving()&&1<this.weapon.range&&!this.rangeHelper.isInRange2(i,this.target.obj,this.weapon.minRange,this.weapon.range-1))return!1;r.attackState=ho.PrepareToFire}if(r.attackState!==ho.PrepareToFire)return!1;if(!t||r.isDisabled())return a?.cancel(),!0;u=this.target.getWorldCoords(),c=i.position.worldPosition;if(!(this.lastInRangeTargetPosition.length()&&this.lastInRangeTargetPosition.equals(u)&&this.lastInRangeSelfPosition.length()&&this.lastInRangeSelfPosition.equals(c)))return this.lastInRangeTargetPosition.copy(u),this.lastInRangeSelfPosition.copy(c),r.attackState=ho.CheckRange,this.onTick(i);if(!(this.weapon.rules.omniFire||i.rules.omniFire&&i.rules.fighter)){var c=(new uo.Vector3).copy(u).sub(c),e=ns.fromMapCoords(new uo.Vector2(c.x,c.z)),c=this.weapon.projectileRules.rot?45:11.25;if((i.isVehicle()||i.isBuilding())&&i.turretTrait){if(i.turretTrait.desiredFacing=e,Math.abs(e-i.turretTrait.facing)>=c)return!1}else if(Math.abs(e-i.direction)>=c){if(i.isAircraft())return i.direction=ns.tick(i.direction,e,i.rules.rot).facing,!1;if(a)return!1;if(i.isVehicle())return!!this.options.disallowTurning||(this.children.push(new os(e)),!1);i.direction=e}}if(!this.losHelper.hasLineOfSight(i,this.target.obj||this.target.tile,this.weapon))return r.attackState=ho.CheckRange,this.onTick(i);if(r.isOnCooldown(i))return!1;if(this.weapon.warhead.rules.temporal&&i.temporalTrait.getTarget()===this.target.obj)return!1;if(this.weapon.rules.suicide&&this.weapon.type!==oi.DeathWeapon)return this.game.destroyObject(i,{player:i.owner,obj:i,weapon:this.weapon}),!0;e=this.game.rules.general.prism.type;return i.isBuilding()&&i.name===e&&this.weapon.type!==oi.Secondary&&this.fireUpPrismSupportTowers(i,e),(i.isInfantry()||i.isVehicle())&&(i.isFiring=!0),i.art.fireUp?(this.children.push(new zr(i.art.fireUp).setCancellable(!1)),r.attackState=ho.FireUp,!1):(r.attackState=ho.Firing,this.onTick(i))}shouldDropTarget(e){return this.forceDropTarget||e?.isTechno()&&(this.weapon.rules.limboLaunch&&((e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested()||e.invulnerableTrait.isActive())||e.warpedOutTrait.isInvulnerable()&&!this.weapon.warhead.rules.temporal||this.initialTargetOwner!==e.owner)}fireUpPrismSupportTowers(t,i){var e;for(e of t.owner.getOwnedObjectsByType(Bt.Building).filter(e=>e.name===i&&e.secondaryWeapon&&!e.unitOrderTrait.hasTasks()&&e.attackTrait&&!e.attackTrait.isDisabled()&&!e.attackTrait.isOnCooldown(e)).filter(e=>this.rangeHelper.isInWeaponRange(e,t,e.secondaryWeapon,this.game.rules)).slice(0,this.game.rules.general.prism.supportMax))e.unitOrderTrait.addTask(e.attackTrait.createAttackTask(this.game,t,t.centerTile,e.secondaryWeapon,{passive:!0}))}countSupportBeamsAndFireDownTowers(t,i){var e,r=t.owner.getOwnedObjectsByType(Bt.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 go{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()}[_s.onTick](i){if(0<this.chargers.size){let t=!1;this.chargers.forEach(e=>{(e.isDestroyed||e.isCrashing||e.owner!==i.owner||e.attackTrait?.currentTarget?.obj!==i)&&(this.chargers.delete(e),t=!0)}),t&&this.swapAttackTaskWeapon()}}swapAttackTaskWeapon(){let e=this.obj?.unitOrderTrait.getCurrentTask();var t;e instanceof po&&((t=this.getWeapon())?e.setWeapon(t):e.cancel())}getWeapon(){return this.isOverpowered()?this.obj?.secondaryWeapon:this.obj?.primaryWeapon}dispose(){this.obj=void 0,this.chargers.clear()}}class mo{constructor(e,t){this.target=e,this.from=t,this.type=er.UnitRepairFinish}}class fo{constructor(e){this.target=e,this.type=er.UnitRepairStart}}var yo,wo,To,bo=__webpack_require__(949);(s=yo=yo||{})[s.Idle=0]="Idle",s[s.Repairing=1]="Repairing";class vo{constructor(){this.status=yo.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))}[_s.onTick](t,i){if(t.dockTrait&&(!t.rules.needsEngineer||!t.owner.isNeutral))if(!t.dockTrait.hasDockedUnits()||t.dockTrait.getDockedUnits().some(e=>e.zone===fr.Air)||t.poweredTrait&&!t.poweredTrait.isPoweredOn())this.status=yo.Idle;else if(this.cooldownTicks<=0){var r,s,a=i.rules.general.repair,a=t.rules.unitReload?a.reloadRate:a.uRepairRate;this.cooldownTicks+=Dr.BASE_TICKS_PER_SECOND*a*60;let e=!1;for(r of t.dockTrait.getDockedUnits())r.zone!==fr.Air&&(r.healthTrait.health<100&&i.areFriendly(r,t)?(this.tickRepair(r,i,t)&&(e=!0),!e||this.status!==yo.Idle&&this.lastRepairTickSuccessful||t.helipadTrait||i.events.dispatch(new fo(r))):((s=t.rallyTrait.findRallyNodeForUnit(r,i.map))&&(t.dockTrait.undockUnit(r),r.unitOrderTrait.addTask(new Gs(i,s.tile,!!s.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))),t.helipadTrait||i.events.dispatch(new mo(r,t))));this.lastRepairTickSuccessful=e,this.status=e?yo.Repairing:yo.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 bo.Vector2(e.tile.rx,e.tile.ry+i.height);return t.tiles.getByMapCoords(i.x,i.y)??e.tile}}class So{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 Mr(r.tiles,r.mapBounds,e,{width:1,height:1},0,20,e=>i.rules.naval===(e.terrainType===Yt.Water)&&!r.tileOccupation.isTileOccupiedBy(e,i)),s=t.getNextTile();if(!s&&i.factoryTrait?.type===Yi.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,Jt.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===ri.Fly,t=new Mr(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 _o{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 ko{constructor(){this.timer=new _o}hasCharge(){return this.timer.isActive()}setCharge(e,t){this.hasCharge()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[_s.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=Us.Demolish,t.destroyObject(e,this.attackerInfo,!0))))}}class Oo{[Xs.onChange](e,t,i){this.checkAircraftsForPlayer(t,i)}[Ks.onUnspawn](e,t){this.checkAircraftsForPlayer(e.owner,t)}checkAircraftsForPlayer(e,t){let i=t.rules.general.padAircraft;var r;for(r of e.getOwnedObjectsByType(Bt.Aircraft).filter(e=>i.includes(e.name)))r.airportBoundTrait&&(r.airportBoundTrait.preferredAirport=void 0)}}class Io{[_s.onTick](t,i){if(t.dockTrait&&t.dockTrait.hasDockedUnits()&&!t.dockTrait.getDockedUnits().every(e=>!this.canReloadUnit(e)))if(void 0===this.cooldownTicks&&(this.cooldownTicks=Dr.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60),this.cooldownTicks<=0){this.cooldownTicks=Dr.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===fr.Air)}}class Ao extends Ta{constructor(e){super(new Is(e),new As(e=>e.buildStatus=Do.Ready)),this.cancellable=!1}}class Co{constructor(e){this.name=e}getSuperWeapon(e){return e.owner.superWeaponsTrait?.get(this.name)}[Ys.onSpawn](e,t){this.addSuperWeaponToPlayerIfNeeded(e.owner,t)}[Ks.onUnspawn](e,t){this.removeSuperWeaponFromPlayerIfNeeded(e.owner)}[Xs.onChange](e,t,i){this.removeSuperWeaponFromPlayerIfNeeded(t),this.addSuperWeaponToPlayerIfNeeded(e.owner,i)}addSuperWeaponToPlayerIfNeeded(t,i){if(t.superWeaponsTrait&&!t.superWeaponsTrait.has(this.name)){let e=i.createSuperWeapon(this.name,t);t.superWeaponsTrait.add(e),e.rules.isPowered&&t.powerTrait?.isLowPower()&&e.pauseTimer()}}removeSuperWeaponFromPlayerIfNeeded(e){let t=e.superWeaponsTrait;t&&(e.getOwnedObjectsByType(Bt.Building).some(e=>e.superWeaponTrait?.name===this.name)||(e=t.get(this.name))&&!e.isGift&&t.remove(this.name))}}(s=wo=wo||{})[s.Unexplored=0]="Unexplored",s[s.TemporaryReveal=1]="TemporaryReveal",s[s.Explored=2]="Explored",To=To||{},To[To.Darken=8]="Darken";class Bo{constructor(){this.invalidations=new Map,this.temporaryReveals=new Map,this.fullInvalidation=!1,this._onChange=new Rn}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(wo.Unexplored),this.tileElevation=new Uint8Array(i.width*i.height);for(t of e.getAll())this.tileElevation[t.rx+t.ry*i.width]=t.terrainType===Yt.Cliff&&0<t.z?t.z-1:t.z;return this}clone(){let e=new Bo;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)===wo.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,wo.Unexplored,wo.Explored),this._onChange.dispatch(this,{type:"incremental",tiles:i})}revealTemporarily(e){this.temporaryReveals.set(e.tile,5*Dr.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,wo.Explored,[wo.Unexplored,wo.TemporaryReveal]);this.invalidations.clear()}this.temporaryReveals.size&&this.temporaryReveals.forEach((e,t)=>{e<=0?(this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,wo.Unexplored,wo.TemporaryReveal),this.temporaryReveals.delete(t)):(e===5*Dr.BASE_TICKS_PER_SECOND&&this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,wo.TemporaryReveal,wo.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(wo.Explored),this._onChange.dispatch(this,{type:"clear"})}reset(){this.tiles.fill(wo.Unexplored),this._onChange.dispatch(this,{type:"cover"})}}var Eo=__webpack_require__(949);class xo{constructor(e){this.radiusTiles=e,this.refreshTicks=0}[_s.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)}[Ks.onUnspawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!1),this.update(e,t)}[Xs.onChange](e,t,i){this.markGapTilesForFriendlies(e,t,i,!1),this.markGapTilesForFriendlies(e,e.owner,i,!0),this.update(e,i)}[jn.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,To.Darken,t),!t)){if(!a){let t=new kr(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,To.Darken,!0)}}}update(t,i){this.refreshTicks=5*Dr.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+ir.MAX_SIGHT,a=new Eo.Vector2(t.tile.rx,t.tile.ry).addScalar(-n),n=new Eo.Vector2(t.tile.rx,t.tile.ry).addScalar(n),r=i.map.technosByTile.queryRange(new Eo.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 Po=Dr.BASE_TICKS_PER_SECOND;class No{constructor(e){this.radiusTiles=e,this.detectionLines=[],this.nextScan=Po}[_s.onTick](e,t){e.owner.powerTrait?.isLowPower()?this.disable():(0<this.nextScan&&this.nextScan--,this.nextScan<=0&&(this.nextScan=Po,this.detectionLines=this.scan(e,t)))}[jn.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 kr(i.map.tileOccupation);var a,n,o,h=e=>s.distance2(e,t)/wr.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 Ro{constructor(){this.healQueue=[]}addToHealQueue(e){return this.healQueue.push(e),this.healQueue.length-1}unitIsFirstInHealQueue(e){return this.healQueue[0]===e}removeFromHealQueue(e){e=this.healQueue.indexOf(e);-1!==e&&this.healQueue.splice(e,1)}startHealing(e){if(this.unit)throw new Error(`Already busy healing unit ${Bt[this.unit.type]}#${this.unit.id}}`);this.unit=e,this.healTicks=5*Dr.BASE_TICKS_PER_SECOND}[_s.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 mo(i,e))))}[Ws.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 Mr(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 js(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 Do,Mo=__webpack_require__(949);(s=Do=Do||{})[s.BuildUp=0]="BuildUp",s[s.Ready=1]="Ready",s[s.BuildDown=2]="BuildDown";class Lo extends ha{constructor(e,t,i){super(Bt.Building,e,t,i),this.showWeaponRange=!1,this.wallType=[0,0,0,0],this.direction=0,this.buildStatus=Do.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 In(n,i.audioVisual.conditionRed,t.maxNumberOccupants),n.traits.add(n.garrisonTrait)),t.canC4&&!t.wall&&(n.c4ChargeTrait=new ko,n.traits.add(n.c4ChargeTrait)),t.bridgeRepairHut&&(n.cabHutTrait=new Jn(n,a),n.traits.add(n.cabHutTrait)),t.crewed&&(n.crewedTrait=new Kn,n.traits.add(n.crewedTrait)),t.turret&&(n.turretTrait=new An,n.traits.add(n.turretTrait)),t.overpowerable&&(n.overpoweredTrait=new go(n),n.traits.add(n.overpoweredTrait)),(t.powered&&0!==t.power||t.needsEngineer)&&(n.poweredTrait=new Nn(n),n.traits.add(n.poweredTrait)),(t.factory||t.cloning)&&(n.factoryTrait=new Qn(t.cloning?Yi.InfantryType:t.factory,t.cloning),n.traits.add(n.factoryTrait)),t.superWeapon&&(n.superWeaponTrait=new Co(t.superWeapon),n.traits.add(n.superWeaponTrait)),t.numberOfDocks&&(n.dockTrait=new Hn(n,s,t.numberOfDocks,r.dockingOffsets),n.traits.add(n.dockTrait),t.helipad&&(n.helipadTrait=new Oo,n.traits.add(n.helipadTrait)),(t.unitRepair||t.unitReload)&&(n.unitRepairTrait=new vo,n.traits.add(n.unitRepairTrait)),t.unitReload&&(n.unitReloadTrait=new Io,n.traits.add(n.unitReloadTrait))),t.hospital&&(n.hospitalTrait=new Ro,n.traits.add(n.hospitalTrait)),(t.factory||t.cloning||t.numberOfDocks)&&(n.rallyTrait=new So,n.traits.add(n.rallyTrait)),t.freeUnit&&n.traits.add(new Yn),t.produceCashStartup&&n.traits.add(new eo),t.wall&&(n.wallTrait=new to,n.traits.add(n.wallTrait)),t.gapGenerator&&(n.gapGeneratorTrait=new xo(t.gapRadiusInCells),n.traits.add(n.gapGeneratorTrait)),t.psychicDetectionRadius&&(n.psychicDetectorTrait=new No(t.psychicDetectionRadius),n.traits.add(n.psychicDetectorTrait)),n}isBuilding(){return!0}getFoundation(){return this.art.foundation}getFoundationCenterOffset(){var e=this.getFoundation();return new Mo.Vector2(e.width/2*wr.LEPTONS_PER_TILE,e.height/2*wr.LEPTONS_PER_TILE)}update(e){this.buildStatus!==Do.BuildUp||this.unitOrderTrait.hasTasks()||this.unitOrderTrait.addTask(new Ao(e.rules.general.buildupTime)),this.buildStatus!==this.lastBuildStatus&&(this.lastBuildStatus=this.buildStatus,e.events.dispatch(new Cn(this,this.buildStatus))),this.attackTrait?.setDisabled(this.buildStatus!==Do.Ready||!!this.poweredTrait&&!this.poweredTrait.isPoweredOn()),super.update(e)}}class Fo extends oa{constructor(e,t,i){super(Bt.Terrain,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){return new this(e,t,i)}}class jo extends oa{constructor(e,t,i){super(Bt.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 to,r.traits.add(r.wallTrait)),r}isTiberium(){return Da.getOverlayTibType(this.overlayId)!==Aa.NotSpecial}isBridge(){return Pa.isBridge(this.overlayId)}isXBridge(){return Pa.isXBridge(this.overlayId)}isHighBridge(){return Pa.isHighBridge(this.overlayId)}isLowBridge(){return Pa.isLowBridge(this.overlayId)}isBridgePlaceholder(){return Pa.isBridgePlaceholder(this.overlayId)}getFoundation(){let e={width:1,height:1};return this.isBridge()&&(this.isXBridge()?e.height+=2:e.width+=2),e}}class Wo extends oa{constructor(e,t,i){super(Bt.Smudge,e,t,i)}static factory(e,t,i){return new this(e,t,i)}getFoundation(){return{width:this.rules.width,height:this.rules.height}}}class Uo extends Gs{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!==ii.Chrono)throw new Error(`Vehicle ${e.name} is not a chrono miner`)}onTick(e){return!e.moveTrait.isDisabled()&&(!(this.isCancelling()||e.moveTrait.moveState!==qs.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===fr.Air&&(e.zone=fr.Ground,e.position.tileElevation=0),!0))}}class Vo extends Ur{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 kr(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=Go.MovingToOreSite,e.harvesterTrait.lastGatherExplicit=this.explicitOrder}onEnd(e){e.harvesterTrait.status!==Go.LookingForOreSite&&(e.harvesterTrait.status=Go.Idle)}onTick(i){if(this.isCancelling())return!0;let r=i.harvesterTrait;if(r.status===Go.MovingToOreSite){if(this.target=this.initialTarget?.landType===Kt.Tiberium?this.initialTarget:this.findClosestReachableOreSite(i,r.lastOreSite??i.tile,!0),r.lastOreSite=this.target,!this.target){r.status=Go.LookingForOreSite;let e=this.getRefineryOnTile(i.tile);if(e&&1===i.unitOrderTrait.getTasks().length){let t=i.rules.movementZone===ri.Fly;var s=new Mr(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 Gs(this.game,s,!1),new As(()=>{[Zs.Success,Zs.CloseEnough,Zs.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new Is(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!==Kt.Tiberium||!s||this.strictTarget)){if(i.tile!==this.target&&s&&i.tile.landType!==Kt.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 Gs(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=Go.LookingForOreSite,!0;this.target=s,r.lastOreSite=this.target}}return this.children.push(new Gs(this.game,this.target,!1,{closeEnoughTiles:a}),new As(()=>{[Zs.Success,Zs.CloseEnough,Zs.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new Is(5/60))})),!1}this.target=i.tile,r.lastOreSite=this.target,r.status=Go.Harvesting,this.forceMoveTried=!1,this.strictTarget=!1}if(r.status!==Go.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=Go.MovingToOreSite,this.onTick(i)):(this.returnOreIfPossible(i),!0);let t=e.traits.get(Ma);a=t.collectBail();if(t.getBailCount()||this.game.unspawnObject(e),a===Ca.Ore)r.ore++;else{if(a!==Ca.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 Is(1/60)),!1):!0}}findClosestReachableOreSite(t,i,e,r=!1){let s=t.rules.movementZone===ri.Fly;var a=e=>e.landType===Kt.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 Ms(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 Mr(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 Zo(this.game))}getTargetLinesConfig(e){return{pathNodes:this.initialTarget?[{tile:this.initialTarget,onBridge:void 0}]:[]}}}var zo,Ho,Go,$o,qo=__webpack_require__(949);class Zo extends Ur{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 kr(e.map.tileOccupation)}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=Go.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!==Go.LookingForRefinery&&(e.harvesterTrait.status=Go.Idle)}onTick(r){if(this.isCancelling())return!0;let s=r.harvesterTrait;if(s.status===Go.LookingForRefinery)return!0;if(s.status===Go.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=Go.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 Uo(this.game,i,o,()=>this.chronoMinerCanTeleport(r,i,this.target)):new Gs(this.game,o,!1),new As(()=>{r.moveTrait.lastMoveResult===Zs.Fail?s.status=Go.LookingForRefinery:r.moveTrait.lastMoveResult===Zs.CloseEnough&&this.children.push(new Is(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 Uo(this.game,i,void 0,()=>this.chronoMinerCanTeleport(r,i,this.target)):new Gs(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new As(()=>{r.moveTrait.lastMoveResult===Zs.Fail&&(s.status=Go.LookingForRefinery)})),!1;s.status=Go.Docking}if(!this.isValidTargetRefinery(this.target,r))return s.status=Go.MovingToRefinery,this.forceTarget=void 0,this.onTick(r);if(s.status===Go.Docking){if(270!==r.direction)return this.children.push(new os(270)),!1;this.target.dockTrait.dockUnitAt(r,this.reservedDockNumber),this.reservedDockNumber=void 0,s.status=Go.PreparingToUnload}if(s.status===Go.PreparingToUnload)return this.preventOpportunityFire=!0,this.children.push(new Is(2/60)),s.status=Go.Unloading,!1;if(s.status!==Go.Unloading)return!1;a=s.ore*this.game.rules.getTiberium(Ca.Ore).value+s.gems*this.game.rules.getTiberium(Ca.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 Vo(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 qo.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 Mr(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===fr.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))))}}(zo=zo||{}).onPush=Symbol(),(s=Ho=Ho||{})[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=Go=Go||{})[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=Go.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 Vo(t))})}[Xs.onChange](e,t,i){!t.isCombatant()&&e.owner.isCombatant()&&i.afterTick(()=>{e.unitOrderTrait.addTask(new Vo(i))})}[_s.onTick](e,t){this.status===Go.LookingForRefinery?this.ticksSinceLastRefineryCheck++>5*Dr.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastRefineryCheck=0,e.unitOrderTrait.hasTasks()?this.ticksSinceLastRefineryCheck=-25*Dr.BASE_TICKS_PER_SECOND:[...e.owner.buildings].some(e=>e.rules.refinery)||this.lastGatherExplicit?e.unitOrderTrait.addTask(new Zo(t)):this.status=Go.Idle):this.status===Go.LookingForOreSite?this.ticksSinceLastOreCheck++>20*Dr.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastOreCheck=0,e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Vo(t))):this.status===Go.Idle&&this.autoGatherOnNextIdle&&e.unitOrderTrait.isIdle()&&e.tile.landType===Kt.Tiberium&&(this.autoGatherOnNextIdle=!1,e.unitOrderTrait.addTask(new Vo(t,e.tile,!0)))}[Ps.onBeforeTeleport](e,t,i,r){!r&&e.owner.isCombatant()&&(this.status=Go.Idle,this.lastOreSite=void 0,i&&e.rules.teleporter&&t.afterTick(()=>{e.unitOrderTrait.addTask(new(this.isFull()?Zo:Vo)(t))}))}[zo.onPush](e,t){this.autoGatherOnNextIdle=[Ho.AttackMove,Ho.Move,Ho.ForceMove,Ho.Scatter].includes(t),[Go.LookingForRefinery,Go.LookingForOreSite].includes(this.status)&&(this.status=Go.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 Xo{constructor(e){this.target=e,this.type=er.LeaveTransport}}class Yo{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)}[_s.onTick](e,t){this.loadQueue=this.loadQueue.filter(e=>!e.isDestroyed&&!e.isCrashing)}[Ws.onDestroy](e,t,i,r){var s=!!e.armedTrait?.deathWeapon,a=i?.weapon?.warhead.rules.parasite;if(r||s||e.zone===fr.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 js(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 Xo(t))}}getHash(){return H(this.units.map(e=>e.getHash()))}debugGetState(){return this.units.map(e=>e.debugGetState())}dispose(){this.obj=void 0}}class Ko{[_s.onTick](e){var t,i;!!e.transportTrait.units.length!==this.lastHadGunner&&(this.lastHadGunner=!!e.transportTrait.units.length,i=t=e.transportTrait.units[0]?.rules.ifvMode??0,(t=e.rules.turretIndexesByIfvMode.get(t)??0)<e.rules.turretCount&&(e.turretNo=t,e.armedTrait?.selectSpecialWeapon(i,e.veteranLevel===ea.Elite)))}getUiNameForIfvMode(e,t){switch(e){case 0:return"tip:rocket";case 1:return"tip:repair";case 2:case 4:case 5:return"tip:machinegun";default:return t?"name:"+t.toLowerCase():void 0}}}($o=$o||{}).onHeal=Symbol();class Jo{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=sh+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}[_s.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?sh+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!==fr.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}[$o.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=Us.None,t.destroyObject(this.parasite,r?{player:r.owner,obj:r}:void 0),this.uninfest()))}[Za.onDamage](e,t,i,r){r?.obj!==this.parasite&&(this.lastExternalDamageInflicted=i,this.lastExternalDamageTick=t.currentTick)}[Js.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 po&&t.getWeapon().warhead.rules.sonic&&t.cancel()}}[Ws.onDestroy](e,t,i,r){this.parasite&&!this.parasite.isDestroyed&&(r||!this.parasite.invulnerableTrait.isActive()&&this.shouldSupressParasite(t,this.parasite,i)?(this.parasite.deathType=Us.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}[Ps.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 Is(10/60).setCancellable(!1)),e.isVehicle()&&e.submergibleTrait&&(e.submergibleTrait.emerge(e,t),e.cloakableTrait?.uncloak(t),e.submergibleTrait.setCooldown(10*Dr.BASE_TICKS_PER_SECOND))}evictOrDestroyParasite(r,s,a=!1){if(this.parasite&&!this.parasite.isDestroyed){var e=r.zone===fr.Air;if(e&&this.parasite.rules.movementZone!==ri.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=Us.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 Mr(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=Us.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=Us.None,t.destroyObject(this.parasite,e),this.uninfest())}dispose(){this.gameObject=void 0}}class eh{constructor(e){this.target=e,this.type=er.ShipSubmergeChange}}class th{constructor(){this.isActive=!1}isSubmerged(){return this.isActive}setCooldown(e){this.cooldownTicks=e}[_s.onTick](e,t){this.isActive||e.parasiteableTrait?.isInfested()||(e.attackTrait&&e.attackTrait.attackState!==ho.Idle&&!e.moveTrait.isMoving()?this.cooldownTicks=Math.max(this.cooldownTicks??0,5*Dr.BASE_TICKS_PER_SECOND):this.cooldownTicks??(this.cooldownTicks=Math.floor(60*t.rules.general.cloakDelay*Dr.BASE_TICKS_PER_SECOND)),0<this.cooldownTicks&&this.cooldownTicks--,this.cooldownTicks<=0&&(this.isActive=!0,t.events.dispatch(new eh(e))))}[Za.onDamage](e,t){this.emerge(e,t)}emerge(e,t){this.isActive&&(this.isActive=!1,this.cooldownTicks=void 0,t.events.dispatch(new eh(e)))}}class ih{constructor(){this.prevHoverBobLeptons=0}[Ys.onSpawn](e,t){this.setBaseElevation(e,t)}[zs.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)+wr.worldToTileHeight(wr.leptonsToWorld(t.rules.general.hover.height))}[_s.onTick](e,t){var i=this.computeHoverBobLeptons(t.currentTick,t.rules.general.hover),t=i-this.prevHoverBobLeptons;this.prevHoverBobLeptons=i;i=wr.tileHeightToWorld(e.position.tileElevation);e.position.tileElevation=wr.worldToTileHeight(i+wr.leptonsToWorld(t))}computeHoverBobLeptons(e,t){e=e/Dr.BASE_TICKS_PER_SECOND/(60*t.bob);return.1*t.height*z(Math.sin(2*e*Math.PI),10)}}class rh{constructor(){this.tilt={pitch:0,yaw:0}}[Ys.onSpawn](e){this.tilt=this.computeTilt(e.tile.rampType)}[zs.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 sh=34;class ah extends ha{constructor(e,t,i){super(Bt.Vehicle,e,t,i),this.direction=0,this.spinVelocity=0,this.crateBonuses=new pa,this.turretNo=0,this.onBridge=!1,this.isSinker=!1,this.isFiring=!1,this.zone=t.naval?fr.Water:fr.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 sa(a,s),a.traits.add(a.moveTrait),t.crashable&&(a.crashableTrait=new ua(a),a.traits.add(a.crashableTrait)),t.crewed&&(a.crewedTrait=new Kn,a.traits.add(a.crewedTrait)),t.harvester&&(a.harvesterTrait=new Qo(t.storage),a.traits.add(a.harvesterTrait)),t.passengers&&(a.transportTrait=new Yo(a),a.traits.add(a.transportTrait),t.gunner&&(a.gunnerTrait=new Ko,a.traits.add(a.gunnerTrait))),t.turret&&(a.turretTrait=new An,a.traits.add(a.turretTrait)),t.consideredAircraft&&!t.landable||a.traits.add(new zn),t.parasiteable&&(a.parasiteableTrait=new Jo(a),a.traits.add(a.parasiteableTrait)),t.naval&&t.underwater&&(a.submergibleTrait=new th,a.traits.add(a.submergibleTrait)),t.locomotor===ii.Hover&&a.traits.add(new ih),t.isTilter&&!t.consideredAircraft&&(a.tilterTrait=new rh,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??sh,facing:e,factor:t}}}class nh{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 oh{setParent(e){this.parent=e}getParent(){return this.parent}[_s.onTick](r,s){if(this.parent&&r.attackTrait&&r.primaryWeapon){let e=this.parent.attackTrait?.currentTarget,t=r.unitOrderTrait.getCurrentTask(),i=new kr(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 Gs||this.parent.unitOrderTrait.getCurrentTask()instanceof po))&&(!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 Gs?(r.unitOrderTrait.cancelAllTasks(),r.unitOrderTrait.addTask(r.attackTrait.createAttackTask(s,e.obj,e.tile,r.primaryWeapon,{force:!0}))):r.attackTrait.attackState!==ho.Idle&&t.requestTargetUpdate(e):t?t instanceof Gs||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 Gs&&e.updateTarget(i.tile,!!i.isUnit()&&i.onBridge):t.unitOrderTrait.addTask(new Gs(r,i.tile,!!i.isUnit()&&i.onBridge,{closeEnoughTiles:0,strictCloseEnough:!0}))}}}class hh{setWarhead(e){return this.warhead=e,this}setDamage(e){return this.damage=e,this}setLauncher(e){return this.launcher=e,this}[Ws.onDestroy](e,t){this.warhead&&this.damage&&this.launcher&&this.warhead.detonate(t,this.damage,e.tile,e.tileElevation,e.position.worldPosition,e.zone,Oa.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 lh extends ha{constructor(e,t,i,r){super(Bt.Aircraft,e,t,i),this.pitch=0,this.yaw=0,this.roll=0,this.onBridge=!1,this.zone=fr.Ground,this.crateBonuses=new pa,this.generalRules=r}get sight(){return this.rules.spawned?super.sight:super.sight+(this.zone===fr.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 nh(a.rules.dock),a.traits.add(a.airportBoundTrait)),a.rules.missileSpawn||(a.crashableTrait=new ua(a),a.traits.add(a.crashableTrait)),a.rules.spawned&&(a.rules.missileSpawn?(a.missileSpawnTrait=new hh,a.traits.add(a.missileSpawnTrait)):(a.spawnLinkTrait=new oh,a.traits.add(a.spawnLinkTrait))),a.moveTrait=new sa(a,s),a.traits.add(a.moveTrait),t.dock.length&&a.traits.add(new zn),t.landable&&e!==r.general.paradrop.paradropPlane||a.traits.add(new va),t.parasiteable&&(a.parasiteableTrait=new Jo(a),a.traits.add(a.parasiteableTrait)),a}isUnit(){return!0}isAircraft(){return!0}}class ch{constructor(e){this.gameObject=e,this.orders=[],this.queuedOrders=new Set,this.tasks=[],this.taskRunner=new no}[_s.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 zr(5)),this.tasks.push(new As(()=>{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))}}[Xs.onChange](){this.clearOrders(),this.cancelAllTasks()}[Ps.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!==Rr.NotStarted),this.tasks.forEach(e=>e.cancel())),this.orders.push(t),e&&this.queuedOrders.add(t),this.gameObject.traits.filter(zo).forEach(e=>{e[zo.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 uh=[[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 dh=__webpack_require__(949);class ph{constructor(e){this.tiles=e,this._worldPosition=new dh.Vector3,this._tileOffset=new dh.Vector2,this._centerOffset=new dh.Vector2,this.desiredSubCell=0,this._tileElevation=0,this._onPositionChange=new Rn}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/wr.LEPTONS_PER_TILE-.5),t=Math.sign(this._tileOffset.y/wr.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 dh.Vector2(this._tile.rx*wr.LEPTONS_PER_TILE+this._tileOffset.x+this._centerOffset.x,this._tile.ry*wr.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)*wr.LEPTONS_PER_TILE,(t-s)*wr.LEPTONS_PER_TILE),this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:a})}moveToLeptons(e,t=!1){this.moveToTileCoords(e.x/wr.LEPTONS_PER_TILE,e.y/wr.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)/wr.LEPTONS_PER_TILE,this._tile.ry+(this._tileOffset.y+t)/wr.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/wr.LEPTONS_PER_TILE*wr.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*wr.LEPTONS_PER_TILE/4,height:r*wr.LEPTONS_PER_TILE/4});var r=wr.LEPTONS_PER_TILE/2;return new dh.Vector2(r+t.width,r+t.height)}interpolateRampHeight(e,t,i){var r=uh[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)/wr.LEPTONS_PER_TILE,r=(e.y+this._centerOffset.y)/wr.LEPTONS_PER_TILE,e=wr.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=wr.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=wr.worldToTileHeight(this._worldPosition.y),t=(this._tileOffset.x+this._centerOffset.x)/wr.LEPTONS_PER_TILE,i=(this._tileOffset.y+this._centerOffset.y)/wr.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 ph(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 gh{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===Kt.Wall)return Oa.Wall;if(i.buildings&&n?.tile===s&&e.tileElevation<=1.1&&i.buildings(n.owner))return Oa.Wall}if(i.shore&&s.landType!==Kt.Water)return Oa.Shore;if(i.ground&&e.tileElevation<0)return Oa.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?Oa.UnderBridge:Oa.OnBridge}else if(a?.isLowBridge()&&i.shore)return Oa.UnderBridge;if(i.cliffs){t=s.z-t.tile.z;if(e.tileElevation<0&&4<=t)return Oa.Cliff}return Oa.None}computeDetonationZone(e,t,i){let r=this.tileOccupation.getBridgeOnTile(e);return i===Oa.None&&t>1.5+(r?.tileElevation??0)?fr.Air:r&&1.5<t||e.terrainType!==Yt.Water||r?.isLowBridge()?fr.Ground:fr.Water}}var mh,fh,yh,wh,Th,bh,vh,Sh=__webpack_require__(949);(s=mh=mh||{})[s.Travel=0]="Travel",s[s.Impact=1]="Impact",s[s.Detonation=2]="Detonation";class _h extends oa{constructor(e,t,i,r){super(Bt.Projectile,e,t,i),this.tileOccupation=r,this.state=mh.Travel,this.detonationTimer=0,this.collisionType=Oa.None,this.direction=0,this.zone=fr.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 Sh.Vector3,this.sonicVisitedObjects=new Map,this.collisionHelper=new gh(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?Ii.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===oi.DeathWeapon||this.fromWeapon.rules.limboLaunch||!this.isHoming()&&this.fromWeapon.speed===Number.POSITIVE_INFINITY||this.rules.inaccurate||this.rules.arcing||this.rules.flakScatter||0<(e=this.computeBaseDamage(a))&&(e=this.fromWeapon.warhead.computeDamage(e,this.target.obj),this.target.obj.healthTrait?.projectDamage(e)),a.afterTick(()=>{let e=new kr(this.tileOccupation);var t=e.distance2(this.target.getWorldCoords(),this)/wr.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!==ea.Elite||e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new js(a))}}else if(this.rules.vertical){let e=this.position.clone();e.tileElevation=this.fromWeapon.warhead.rules.nukeMaker?wr.worldToTileHeight(wr.leptonsToWorld(this.fromWeapon.projectileRules.detonationAltitude)):0,this.aimPoint=wr.vecWorldToLeptons(e.worldPosition)}else{let s=this.target.getWorldCoords();a.afterTick(()=>{let e=wr.vecWorldToLeptons(this.target.getWorldCoords().clone().sub(s));var t=e.length()>wr.LEPTONS_PER_TILE;let i=t?wr.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):wr.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(wr.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*wr.LEPTONS_PER_TILE;this.rules.flakScatter&&(n=t.clone().sub(wr.vecWorldToLeptons(this.initialSelfPosition)).length(),s*=n/(this.fromWeapon.range*wr.LEPTONS_PER_TILE));var a=Zr(new Sh.Vector2(s,0),e.generateRandomInt(0,360)),n=wr.vecWorldToGround(t).add(a).multiplyScalar(1/wr.LEPTONS_PER_TILE).floor();e.map.tiles.getByMapCoords(n.x,n.y)&&t.add(new Sh.Vector3(a.x,0,a.y))}calculateBallisticOvershootVsMoving(e,t){let i=wr.vecWorldToLeptons(this.target.getWorldCoords()).sub(wr.vecWorldToLeptons(this.initialSelfPosition));var r=Yr(wr.vecWorldToGround(i),wr.vecWorldToGround(t.moveTrait.velocity)),t=(90<r?180-r:r)/90,r=i.length()/wr.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!==mh.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()>=wr.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*wr.LEPTONS_PER_TILE))return void this.detonate(n);if(this.homingMoveDir||(c=ns.toMapCoords(this.direction),this.homingMoveDir=new Sh.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 kr(this.tileOccupation);var l=Math.floor(e.distance2(a,this)/wr.ISO_TILE_SIZE),c=2<l&&1<this.iniRot;let t=wr.vecWorldToLeptons(a.clone().sub(this.position.worldPosition)),i=0;this.homingTravelTicks<this.rules.courseLockDuration||(c?(es(this.homingMoveDir,new Sh.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=wr.tileHeightToWorld(Math.sign(u)*Math.min(Math.abs(u),p))/wr.ISO_TILE_SIZE*wr.LEPTONS_PER_TILE)):es(this.homingMoveDir,t,this.rot)),this.direction=ns.fromMapCoords(new Sh.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=Oa.None;if(1<=u){let e=this.homingMoveDir.clone().setLength(u);i&&(e.y+=i),u===h&&this.velocity.copy(e).multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE);var d=wr.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(wr.vecWorldToLeptons(this.position.worldPosition));this.rules.vertical||(this.direction=ns.fromMapCoords(new Sh.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=wr.vecWorldToGround(wr.vecWorldToLeptons(this.position.worldPosition.clone().sub(this.initialSelfPosition)).add(t));var l=this.aimPoint.clone().sub(wr.vecWorldToLeptons(this.initialSelfPosition)),s=e.length(),d=wr.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+wr.worldToLeptons(this.initialSelfPosition.y)-wr.worldToLeptons(this.position.worldPosition.y)}let e=!1;s=wr.vecLeptonsToWorld(t).add(this.position.worldPosition);n.map.isWithinHardBounds(s)?this.position.moveByLeptons3(t):e=!0;let i=Oa.None;if(1<=p?(p!==h&&!this.overshootTiles||this.velocity.copy(t).multiplyScalar(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE),i=this.checkObstacles(o,n),(i||p<h)&&(e=!0)):e=!0,e){if(!i)if(this.overshootTiles){var g=wr.vecWorldToGround(r).setLength(this.overshootTiles*wr.LEPTONS_PER_TILE);if(Zr(g,n.generateRandomInt(-45,45)),s=wr.vecLeptonsToWorld(wr.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(wr.vecWorldToLeptons(a.clone().sub(this.position.worldPosition)))}this.collisionType=i,this.isNuke?(this.state=mh.Impact,this.detonationTimer=2.5*Dr.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=wr.vecWorldToGround(g).multiplyScalar(1/wr.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)&&t.isSpawned&&(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 kr(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=wr.worldToLeptons(s.moveTrait.velocity.length()))&&(this.fromObject.rules.movementZone===ri.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*ir.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*wr.LEPTONS_PER_TILE/21)),r}checkObstacles(e,t){return this.fromWeapon.rules.limboLaunch?Oa.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===oi.DeathWeapon&&i.rules.ivanBomb&&(r=e.rules.combatDamage.ivanDamage);let s=r*this.baseDamageMultiplier;return t.type===oi.DeathWeapon&&this.fromObject&&(s*=this.fromObject.rules.deathWeaponDamageModifier),s*=this.veteranDamageMult,s}detonate(n,e=Oa.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===oi.DeathWeapon&&r.rules.ivanBomb&&(r=new Wa(n.rules.getWarhead(n.rules.combatDamage.ivanWarhead)));let a=this.computeBaseDamage(n);n.destroyObject(this),this.state=mh.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 Ga))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=Ga.factory(Ga.NUKE_PAYLOAD_NAME,oi.Primary,this.fromObject,n.rules),n.createProjectile(u.projectileRules.name,this.fromObject,u,this.target,!1)):n.createLooseProjectile(Ga.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 kr(n.map.tileOccupation),e=new Mr(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?Fn.Air:Fn.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===Nr.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 Ms(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===ri.Fly;if(i)t=o,a=!1;else{let i=this.target.obj.isUnit()&&this.target.obj.tile.onBridgeLandType&&!this.target.obj.onBridge?void 0:n.map.tileOccupation.getBridgeOnTile(o),r=new Hr(n.map),e=new Mr(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=wr.leptonsToWorld(i);if(i<3*t.moveTrait.velocity.length())return wr.vecWorldToLeptons(a);let o=ys.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!==fr.Air){o.multiplyScalar(1/wr.ISO_TILE_SIZE);let e=t.position.clone();e.moveToTileCoords(o.x,o.z),n=e.worldPosition}else n=o;else n=a}return wr.vecWorldToLeptons(n)}}(s=fh=fh||{})[s.None=0]="None",s[s.PreparingToFire=1]="PreparingToFire",s[s.FiringUp=2]="FiringUp",s[s.Firing=3]="Firing";class kh{constructor(e){this.gameObject=e,this.deployed=!1,this.deployFireDelay=0,this.deployFireState=fh.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?Nr.Deployed:Nr.None),t?(this.deployFireState=fh.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===fh.FiringUp&&(e.isFiring=!1),this.deployFireState=fh.None,this.deployWeapon=void 0)}}toggleDeployed(){this.setDeployed(!this.isDeployed())}[_s.onTick](e,t){if(void 0!==this.undeployDelay&&(0<this.undeployDelay&&this.undeployDelay--,this.undeployDelay<=0&&[fh.None,fh.PreparingToFire].includes(this.deployFireState)))return this.undeployDelay=void 0,void this.setDeployed(!1);if(this.deployWeapon&&this.deployFireState!==fh.None){if(this.deployFireState===fh.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=fh.FiringUp}if(this.deployFireState===fh.FiringUp){if(e.isFiring=!0,0<this.fireUpDelay--)return;this.deployFireState=fh.Firing}var i;this.deployFireState===fh.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=fh.None,this.deployWeapon=void 0):this.deployFireState=fh.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}}(yh=yh||{}).onChange=Symbol();class Oh{constructor(e,t,i,r,s){this.target=e,this.attacker=t,this.damageHitPoints=i,this.currentHealth=r,this.prevHealth=s,this.type=er.InflictDamage}}(wh=wh||{}).onChange=Symbol(),(s=Th=Th||{})[s.Green=0]="Green",s[s.Yellow=1]="Yellow",s[s.Red=2]="Red";class Ih{constructor(e,t,i){this.target=e,this.currentHealth=t,this.prevHealth=i,this.type=er.HealthChange}}class Ah{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?Th.Green:this.health>100*this.conditionRed?Th.Yellow:Th.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(Za).forEach(e=>{e[Za.onDamage](this.gameObject,r,t,i)}),r.events.dispatch(new Oh(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($o).forEach(e=>{e[$o.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($o).forEach(e=>{e[$o.onHeal]?.(this.gameObject,r,t,i)})}}applyHitPoints(e,t){let i=this.health;this.setHitPoints(e),i!==this.health&&(t.traits.filter(yh).forEach(e=>{e[yh.onChange](this.gameObject,t,i)}),this.gameObject.traits.filter(wh).forEach(e=>{e[wh.onChange](this.gameObject,t,i)}),t.events.dispatch(new Ih(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)}[_s.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 Ch{constructor(e){this.bridges=e,this.needsImageUpdate=!1,this.dominoHandled=!1}[Za.onDamage](){this.needsImageUpdate=!0}[_s.onTick](e){this.needsImageUpdate&&(this.needsImageUpdate=!1,this.bridges.handlePieceHealthChange(this.bridges.getPieceAtTile(e.tile)))}[Ws.onDestroy](r,s,a){var e=this.bridges.getPieceAtTile(r.tile);this.dominoHandled||this.bridges.findDominoPieces(e).filter(e=>!e.obj.isDestroyed).forEach(e=>{e.obj.traits.get(Ch).dominoHandled=!0,s.destroyObject(e.obj,a)});let t=s.map.tileOccupation.calculateTilesForGameObject(r.tile,r);t.forEach(e=>{let t=Hi(e.terrainType),i=s.rules.getLandRules(t);s.map.getGroundObjectsOnTile(e).forEach(e=>{e.isUnit()&&e.onBridge&&!e.isDestroyed&&(r.isLowBridge()&&0<i.getSpeedModifier(e.rules.speedType)||e.isInfantry()&&e.stance===Nr.Paradrop?(e.onBridge=!1,e.zone=Tr(t)):(e.isInfantry()&&(e.infDeathType=ei.None),s.destroyObject(e,a,!0)))})})}}(s=bh=bh||{})[s.Idle=0]="Idle",s[s.Spawning=1]="Spawning";class Bh{constructor(e){this.rules=e,this.ticksSinceLastSpawn=0,this.cooldownTicks=Math.floor(1/this.rules.animationProbability),this.status=bh.Idle}[_s.onTick](e,t){this.status=bh.Idle,this.ticksSinceLastSpawn++>this.cooldownTicks&&(this.ticksSinceLastSpawn=0,this.status=bh.Spawning,this.spawnTiberium(e.tile,t))}spawnTiberium(r,s){for(let i=1;i<=2;i++){let e=new Mr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},i,i,e=>Ma.canBePlacedOn(e,s.map));var a=e.getNextTile();if(a){var n=on.calculateOverlayId(Aa.Ore,a.rx,a.ry);if(void 0===n)throw new Error("Expected an overlayId");let e=s.createObject(Bt.Overlay,s.rules.getOverlayName(n));return e.overlayId=n,e.value=3,void s.spawnObject(e,a)}e=new Mr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},i,i,e=>e.landType===Kt.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(Ma).getBailCount()+1<=Ma.maxBails)}if(t)return void t.traits.get(Ma).spawnBails(1)}}}class Eh{constructor(e=!1){this.freeRepair=e,this.disabled=!0,this.cooldownTicks=0,this.healLeftover=0}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}[_s.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+=Dr.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--}[Xs.onChange](){this.setDisabled(!0)}}(vh=vh||{}).onDestroy=Symbol();class xh{constructor(e){this.target=e,this.type=er.UnitPromote}}class Ph{constructor(){this.cooldownTicks=0}[_s.onTick](e,t){100!==e.healthTrait.health&&(this.cooldownTicks<=0?(this.cooldownTicks+=Dr.BASE_TICKS_PER_SECOND*t.rules.general.repair.repairRate*60,e.healthTrait.healBy(1,e,t)):this.cooldownTicks--)}}class Nh{constructor(e,t){this.gameObject=e,this.rules=t,this.specialWeaponIndex=0;t=e.veteranLevel===ea.Elite;e.rules.weaponCount?(this.selectSpecialWeapon(0,t),this.guardWeaponRangeOverride=this.primaryWeapon?.range):this.selectStandardWeapons(t)}selectStandardWeapons(e=!1){var t=this.gameObject,i=e&&t.rules.elitePrimary||t.rules.primary;i?(s=e?t.art.elitePrimaryFireFlh:t.art.primaryFireFlh,this.primaryWeapon=Ga.factory(i,oi.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=Ga.factory(s,oi.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=Ga.factory(r,oi.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=Ga.factory(r,oi.Primary,i,this.rules,t),this.secondaryWeapon=void 0,this.specialWeaponIndex=e,this.deathWeapon=this.primaryWeapon.rules.suicide?Ga.factory(i.rules.deathWeapon||this.primaryWeapon.name,oi.DeathWeapon,i,this.rules):void 0}toggleEliteWeapons(e){this.gameObject.rules.weaponCount?this.selectSpecialWeapon(this.specialWeaponIndex,e):this.selectStandardWeapons(e)}getSpecialWeaponIndex(){return this.specialWeaponIndex}computeGuardScanRange(t){var e=this.guardWeaponRangeOverride??[this.primaryWeapon,this.secondaryWeapon].filter(e=>e===t||e?.rules.neverUse).reduce((e,t)=>Math.max(e,t.range),0),e=Math.max(e,this.gameObject.rules.guardRange);return Math.min(15,2*e-1)}getDeployFireWeapon(){if(this.gameObject.rules.deployFire)return this.gameObject.rules.deployFireWeapon===oi.Primary?this.primaryWeapon:this.secondaryWeapon}isEquippedWithWeapon(e){return[this.primaryWeapon,this.secondaryWeapon].includes(e)}getWeapons(){return[this.primaryWeapon,this.secondaryWeapon].filter(wa)}[_s.onTick](){this.primaryWeapon&&this.primaryWeapon.tick(),this.secondaryWeapon&&this.secondaryWeapon.tick()}[Ws.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 Rh{}class Dh{constructor(e,t){this.gameObject=e,this.veteranRules=t,this.veteranLevel=ea.None,this.xp=0,this.promotionThresh=e.rules.cost*t.veteranRatio+1}[vh.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===ea.Elite}setVeteranLevel(e){this.veteranLevel=e,this.veteranLevel===ea.Elite&&this.gameObject.armedTrait?.toggleEliteWeapons(!0)}handlePromotion(e,t){this.hasVeteranAbility(hi.SELF_HEAL)&&(e.traits.find(Ph)||t.addObjectTrait(e,new Ph)),this.hasVeteranAbility(hi.CLOAK)&&(e.cloakableTrait||(e.cloakableTrait=new nn(e,t.rules.general.cloakDelay),t.addObjectTrait(e,e.cloakableTrait))),this.hasVeteranAbility(hi.EXPLODES)&&(e.explodes||(e.explodes=!0,e.armedTrait||(e.armedTrait=new Nh(e,t.rules),t.addObjectTrait(e,e.armedTrait)))),this.hasVeteranAbility(hi.RADAR_INVISIBLE)&&(e.radarInvisible||(e.radarInvisible=!0)),this.hasVeteranAbility(hi.SENSORS)&&(e.sensorsTrait||(e.sensorsTrait=new Rh,t.addObjectTrait(e,e.sensorsTrait))),e.isInfantry()&&this.hasVeteranAbility(hi.FEARLESS)&&e.suppressionTrait?.disable(),this.hasVeteranAbility(hi.C4)&&(e.c4||(e.c4=!0)),this.hasVeteranAbility(hi.GUARD_AREA)&&(e.defaultToGuardArea||(e.defaultToGuardArea=!0,e.unitOrderTrait.isIdle()&&e.resetGuardModeToIdle())),this.hasVeteranAbility(hi.CRUSHER)&&(e.crusher||(e.crusher=!0)),t.events.dispatch(new xh(e))}getVeteranSightMultiplier(){return this.getVeteranAbilityMultiplier(hi.SIGHT)}getVeteranSpeedMultiplier(){return this.getVeteranAbilityMultiplier(hi.FASTER)}getVeteranArmorMultiplier(){return this.getVeteranAbilityMultiplier(hi.STRONGER)}getVeteranDamageMultiplier(){return this.getVeteranAbilityMultiplier(hi.FIREPOWER)}getVeteranRofMultiplier(){return this.getVeteranAbilityMultiplier(hi.ROF)}hasVeteranAbility(e){return this.veteranLevel===ea.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=ea.Elite&&this.gameObject.rules.eliteAbilities.has(e)}getVeteranAbilityMultiplier(e){let t=1;return(this.veteranLevel===ea.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=ea.Elite&&this.gameObject.rules.eliteAbilities.has(e))&&(t=this.getVeteranRulesMultiplier(e)),t}getVeteranRulesMultiplier(e){switch(e){case hi.FASTER:return this.veteranRules.veteranSpeed;case hi.STRONGER:return this.veteranRules.veteranArmor;case hi.FIREPOWER:return this.veteranRules.veteranCombat;case hi.ROF:return this.veteranRules.veteranROF;case hi.SIGHT:return this.veteranRules.veteranSight;default:throw new Error(`Unhandled VeteranAbility ${e}`)}}dispose(){this.gameObject=void 0}}class Mh{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 Lh{constructor(e){this.target=e,this.type=er.ObjectDisguiseChange}}class Fh{constructor(){this.isActive=!1,this.cooldownTicks=0}isDisguised(){return this.isActive}getDisguise(){return this.isActive?this.disguisedAs:void 0}hasTerrainDisguise(){return this.getDisguise()?.rules.type===Bt.Terrain}disguiseAs(e,t,i){this.disguisedAs={rules:e.rules,owner:e.owner},this.isActive=!0,i.events.dispatch(new Lh(t))}revealDisguise(e,t){this.cooldownTicks=t.rules.general.infantryBlinkDisguiseTime,this.isActive=!1,t.events.dispatch(new Lh(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,Bt.Infantry),this.disguisedAs={rules:i,owner:e.owner},this.isActive=!0))}getDefaultInfantryDisguise(e,t){switch(e){case Zt.GDI:return t.alliedDisguise;case Zt.Nod:return t.sovietDisguise;default:return}}[_s.onTick](e,t){e.rules.permaDisguise||(e.attackTrait?.attackState===ho.JustFired||e.moveTrait.moveState!==qs.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 Lh(e))))}[Za.onDamage](e,t){this.revealDisguise(e,t)}selectRandomMirageDisguise(e){var t=e.rules.general.defaultMirageDisguises;if(!t.length)throw new Error("No default mirage disguises are defined");t=t[e.generateRandomInt(0,t.length-1)];return e.rules.getObject(t,Bt.Terrain)}}class jh{constructor(){this.timer=new _o}isActive(){return this.timer.isActive()}setActiveFor(e,t){this.timer.setActiveFor(e,t)}[_s.onTick](e,t){this.timer.tick(t.currentTick)}}class Wh{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(Cr).forEach(e=>{e[Cr.onChange](this.gameObject,i,t)}),this.gameObject.traits.filter(jn).forEach(e=>{e[jn.onChange](this.gameObject,i,t)})}expire(e){this.remainingTicks=0,this.notifyChange(!1,e)}isInvulnerable(){return this.isActive()&&this.invulnerable}[_s.onTick](e,t){0<this.remainingTicks&&(this.remainingTicks--,this.remainingTicks<=0&&this.notifyChange(!1,t))}dispose(){this.gameObject=void 0}}class Uh{constructor(){this.timer=new _o}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()}[_s.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))}[Ws.onDestroy](e,t,i){this.timer.isActive()&&!i?.weapon?.warhead.rules.ivanBomb&&e.deathType!==Us.None&&e.deathType!==Us.Temporal&&(this.timer.reset(),this.detonateIvanWarhead(t,e))}detonateIvanWarhead(e,t){var i=e.rules.combatDamage.ivanDamage;let r=new Wa(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()?wr.tile3dToWorld(s.rx+.5,s.ry+.5,s.z+a):t.position.worldPosition,n,o?Oa.OnBridge:Oa.None,e.createTarget(t,s),{...this.attackerInfo,weapon:void 0},!1,!1,void 0)}}class Vh{constructor(e){this.gameObject=e}getOriginalOwner(){return this.prevOwner}isActive(){return!!this.controller}getController(){return this.controller}controlBy(e,t){if(this.controller)throw new Error(`Object "${this.gameObject?.name}" is already mind controlled by "${e.name}"`);this.controller=e,this.prevOwner=this.gameObject.owner,t.changeObjectOwner(this.gameObject,e.owner)}restore(e){this.prevOwner&&(e.changeObjectOwner(this.gameObject,this.prevOwner),this.prevOwner=void 0,this.controller=void 0)}[Ks.onUnspawn](e,t){this.controller&&(this.controller.mindControllerTrait.cleanTarget(e),!e.isDestroyed&&e.limboData&&this.restore(t))}dispose(){this.gameObject=void 0}}class zh{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)}[Ks.onUnspawn](e,t){for(var i of this.targets)i.mindControllableTrait.restore(t);this.targets.length=0}dispose(){this.gameObject=void 0}}class Hh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.attackers=new Set}[_s.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=Us.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 po||e instanceof Gs)&&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}}[Ws.onDestroy](e,t){this.releaseCurrentTarget(t)}dispose(){this.gameObject=void 0,this.attackers.clear()}}class Gh{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,Bt.Aircraft);for(let e=0;e<t.rules.spawnsNumber;e++)this.pushNewSpawn(r,i,t)}[Ks.onUnspawn](e,t){this.destroySpawns(e,t)}[Ws.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:fr.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}[_s.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,Bt.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 Ta(new Gs(a,r.targetTile,!!r.targetBridge),new As(()=>{var e,t;i.isDestroyed||(a.unspawnObject(i),i.dispose(),t=wr.vecGroundToWorld(ns.toMapCoords(i.direction).multiplyScalar(wr.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?Oa.OnBridge:Oa.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)}}}}[Xs.onChange](e,t,i){for(var r of this.spawns)r.isDestroyed||i.changeObjectOwner(r,e.owner)}[jn.onChange](e,t,i){i&&this.removeMissileLaunches(t)}[Ps.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 Wa(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 $h{[ta.onCrash](e,t){this.handleDestroy(e,t)}[Ws.onDestroy](e,t,i){i?.weapon?.warhead.rules.temporal||e.isCrashing||e.deathType!==Us.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(wr.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,Bt.VoxelAnim)||i.art.hasObject(e,Bt.Animation)),new Array(r).fill(0).map(()=>e[i.generateRandomInt(0,e.length-1)]).map(e=>i.createObject(Bt.Debris,e)).forEach(e=>{e.position.moveToLeptons(s),e.position.tileElevation=t.position.tileElevation,i.spawnObject(e,e.position.tile)})}}}var qh=__webpack_require__(949);class Zh extends oa{constructor(e,t,i,r){super(Bt.Debris,e,t,i),this.age=0,this.direction=0,this.rotationAxis=new qh.Vector3,this.angularVelocity=0,this.zone=fr.Air,this.velocity=new qh.Vector3,this.collisionHelper=new gh(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=qh.Math.lerp(0,this.rules.maxXYVel,e.generateRandom()),this.zSpeed=qh.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=qh.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=ns.toMapCoords(this.direction).setLength(this.xySpeed),i=new qh.Vector3(e.x,this.zSpeed,e.y),r=this.position.clone(),e=wr.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&&(!([Oa.Ground,Oa.OnBridge].includes(r)&&0<this.rules.elasticity&&t.map.getTileZone(this.tile)!==fr.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(wr.ISO_TILE_SIZE/wr.LEPTONS_PER_TILE)}else t.unspawnObject(this)}detonate(t,i=Oa.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===fr.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 La;if(a&&n.spawnSmudges(a,this.tile,t),t.destroyObject(this),r){let e=new Wa(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===Bt.Debris?s=i.hasObject(t,Bt.VoxelAnim)?(a=r.getObject(t,Bt.VoxelAnim),i.getObject(t,Bt.VoxelAnim)):(a=r.getAnimation(t),new nr(Bt.Debris,r.getIni().getOrCreateSection(t))):a=e===Bt.Projectile?(s=i.getProjectile(t),s.inviso?new Sn(Bt.Projectile,s,new h(t)):r.getProjectile(t)):(s=i.getObject(t,e),r.getObject(t,e));let n;switch(e){case Bt.Building:n=Lo.factory(t,s,i,a,this.tiles,this.bridges);break;case Bt.Infantry:n=ga.factory(t,s,a,this.tileOccupation);break;case Bt.Vehicle:n=ah.factory(t,s,a,i,this.tileOccupation);break;case Bt.Aircraft:n=lh.factory(t,s,a,i,this.tileOccupation);break;case Bt.Terrain:n=Fo.factory(t,s,a);break;case Bt.Overlay:n=jo.factory(t,s,a);break;case Bt.Smudge:n=Wo.factory(t,s,a);break;case Bt.Projectile:n=_h.factory(t,s,a,this.tileOccupation);break;case Bt.Debris:n=Zh.factory(t,s,a,this.tileOccupation);break;default:throw new Error("Not implemented")}if(n.id=this.nextObjectId.value++,n.position=new ph(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 Nh(n,i),n.traits.add(n.armedTrait)),-1!==n.rules.ammo&&(o=n.rules.initialAmmo,n.ammoTrait=new Mh(n.rules.ammo,-1!==o?o:void 0),n.traits.add(n.ammoTrait)),n.unitOrderTrait=new ch(n),n.traits.addToFront(n.unitOrderTrait),(n.primaryWeapon||n.secondaryWeapon)&&(n.attackTrait=new co(this.tiles,this.tileOccupation),n.traits.add(n.attackTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.deployer&&(n.deployerTrait=new kh(n),n.traits.add(n.deployerTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.canDisguise&&(n.disguiseTrait=new Fh,n.traits.add(n.disguiseTrait)),n.rules.cloakable&&(n.cloakableTrait=new nn(n,i.general.cloakDelay),n.traits.add(n.cloakableTrait)),n.rules.sensors&&(n.sensorsTrait=new Rh,n.traits.add(n.sensorsTrait)),n.autoRepairTrait=new Eh(!n.isBuilding()),n.traits.add(n.autoRepairTrait),n.rules.trainable&&(n.veteranTrait=new Dh(n,i.general.veteran),n.traits.add(n.veteranTrait)),n.rules.selfHealing&&n.traits.add(new Ph),n.invulnerableTrait=new jh,n.traits.add(n.invulnerableTrait),n.warpedOutTrait=new Wh(n),n.traits.add(n.warpedOutTrait),n.temporalTrait=new Hh(n),n.traits.add(n.temporalTrait),n.rules.bombable&&(n.tntChargeTrait=new Uh,n.traits.add(n.tntChargeTrait)),n.rules.immuneToPsionics||n.isBuilding()||(n.mindControllableTrait=new Vh(n),n.traits.add(n.mindControllableTrait)),[n.primaryWeapon,n.secondaryWeapon].some(e=>e?.warhead.rules.mindControl)&&(n.mindControllerTrait=new zh(n),n.traits.add(n.mindControllerTrait)),n.rules.spawns&&(n.airSpawnTrait=new Gh,n.traits.add(n.airSpawnTrait)),n.rules.maxDebris&&n.traits.add(new $h)),n.isTechno()||n.isOverlay()||n.isTerrain()){var o=n.isOverlay()&&Pa.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 Ah(e,n,i.audioVisual.conditionYellow,i.audioVisual.conditionRed),n.traits.add(n.healthTrait)),n.isOverlay()&&o&&(n.bridgeTrait=new Ch(this.bridges),n.traits.add(n.bridgeTrait),Pa.getOverlayBridgeType(i.getOverlayId(n.name))===_a.Concrete&&n.traits.add(new $h))}return n.isOverlay()&&n.isOverlay()&&Da.getOverlayTibType(i.getOverlayId(n.name))!==Aa.NotSpecial&&n.traits.add(new Ma(n)),n.isTerrain()&&n.rules.spawnsTiberium&&n.traits.add(new Bh(n.rules)),n.cachedTraits.tick.push(...n.traits.filter(_s)),n}}class Xh{constructor(){this.allObjects=new Map,this._onObjectSpawned=new Rn,this._onObjectRemoved=new Rn}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),Yh=__webpack_require__.n(s),Kh=__webpack_require__(45);class Jh{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=Jt.Foot;return i.isTerrain()&&i.rules.getOccupationBits(this.theaterType)!==Ki.All&&(t=Jt.Wheel),i.isOverlay()&&(i.isBridge()||i.isTiberium())||this.isBlockerObject(i,e,!1,t)||this.isBlockerObject(i,e,!0,t)||i.isBuilding()&&i.rules.leaveRubble});e.length&&this.invalidateTiles(e)},this.handleMapBoundsResize=()=>{this.passabilityGraphs.clear()},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 Mr(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,Kh.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(Jt).forEach(e=>{e=Number(e);isNaN(e)||e===Jt.Winged||this.computePassabilityGraph(e)})}computePassabilityGraph(t){let i=this.passabilityGraphs.get(t);if(i){let e=this.invalidatedTiles.get(t);e?.size&&(this.updatePassability([...e],t,i),e.clear())}else i=Yh()({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,Ia.Right),this.tiles.getNeighbourTile(e,Ia.BottomRight),this.tiles.getNeighbourTile(e,Ia.Bottom),this.tiles.getNeighbourTile(e,Ia.BottomLeft)].filter(wa).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=[Ia.Left,Ia.TopLeft,Ia.Top,Ia.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===Kt.Wall&&t===Jt.Track&&(a=Hi(e.terrainType));let n=this.rules.getLandRules(a);var o,h=n.getSpeedModifier(t);if(!h)return 0;if(!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===Jt.Foot&&t.rules.getOccupationBits(this.theaterType)!==Ki.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===Jt.Foot?e=s.width:t.rules.weaponsFactory&&!e&&(e=s.width-1),qr({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===Jt.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===Jt.Track&&i.rules.crushable||s===Jt.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 el{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 Rn}get onLocalResize(){return this._onLocalResize.asEvent()}fromMapFile(e,t){this.fullSize={width:2*e.fullSize.width,height:2*e.fullSize.height},this.clampedFullSize={x:1,y:2,width:2*(e.fullSize.width-1)-1/wr.ISO_TILE_SIZE,height:2*(e.fullSize.height-1)-1/wr.ISO_TILE_SIZE},this.mapCutoffHeight=t.getCutoffTileHeight();t=Math.max(2,e.localSize.x),e={x:t,y:e.localSize.y,width:Math.min(e.fullSize.width-2-t,e.localSize.width),height:e.localSize.height};return this.updateRawLocalSize(e),this}updateRawLocalSize(e){var t,i;this.rawLocalSize.width&&this.rawLocalSize.height&&!function(e,t){let i=new Gr.Box2(new Gr.Vector2(e.x,e.y),new Gr.Vector2(e.x+e.width,e.y+e.height));return t=new Gr.Box2(new Gr.Vector2(t.x,t.y),new Gr.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=wr.screenTileToScreen(e.x,e.y),e=wr.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 qr(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z})}clampWithinBounds(e){let{x:t,y:i}=function(e,t){let i=new Gr.Box2(new Gr.Vector2(e.x,e.y),new Gr.Vector2(e.x+e.width,e.y+e.height));return i.clampPoint(new Gr.Vector2(t.x,t.y),new Gr.Vector2)}(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z});return i+=t%2-i%2,i>this.mapBuildableSize.y+this.mapBuildableSize.height&&(i-=2),{dx:t,dy:i}}isWithinHardBounds(e){var t=e.x/wr.ISO_TILE_SIZE,i=(e.z??e.y)/wr.ISO_TILE_SIZE,e=t-i+this.fullSize.width/2-1,i=t+i-this.fullSize.width/2-1;return qr(this.clampedFullSize,{x:++e,y:++i})}}class tl{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 il,rl=__webpack_require__(949);(s=il=il||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.End=2]="End";class sl{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===il.None||e)for(;e;){if(i.push(e),e.headType!==il.None){r=!0;break}e=e.next}else r=!0;if(r){r=!1,i.length=0;let e=t.prev;if(t.headType===il.None||e)for(;e;){if(i.push(e),e.headType!==il.None){r=!0;break}e=e.prev}else r=!0;if(r)return[]}return i}findBridgeAdjacentTiles(e){var t=e.isXBridge(),t=new rl.Vector2(Number(t),Number(!t));let i=new rl.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?il.Start:i?.z===r?il.End:il.None}return Pa.isLowBridgeHead(e.overlayId)?Pa.isLowBridgeHeadStart(e.overlayId)?il.Start:il.End:il.None}updateOverlayData(t){let i=t.obj,r=t.prev,s=t.next,a=!1;var n=i.isXBridge(),o=Pa.getOverlayBridgeType(i.overlayId);if(Pa.isLowBridgeHead(i.overlayId)){let e=0;Pa.isLowBridgeHeadStart(i.overlayId)?(e=n?20:22,s||e++):(e=n?18:24,r||e++),i.overlayId=(o===_a.Wood?Pa.minLowBridgeWoodId:Pa.minLowBridgeConcreteId)+e,i.value=e,a=!0}else{let e;var h,l=(i.healthTrait?.health??100)<=50;e=t.headType!==il.None?t.headType===il.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===_a.Wood?Pa.minLowBridgeWoodId:Pa.minLowBridgeConcreteId)+e,i.value=e,a=!0)}a&&(i.name=this.rules.getOverlayName(i.overlayId))}findClosestBridgeSpec(i){let e=new Mr(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===il.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=_a.Concrete,this.tileSets.getSetNum(o.tileNum)===this.tileSets.getGeneralValue("WoodBridgeSet")&&(t=_a.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=Pa.getOverlayBridgeType(e.obj.overlayId);if(c===_a.NotBridge)throw new Error("Expected a bridge type");t=c,s=e.obj.isXBridge(),a=e.headType===il.Start}var u=Number(s)*(a?1:-1),d=Number(!s)*(a?1:-1);let n;if(h){o=new tl(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?il.End:il.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 Mr(this.tiles,this.mapBounds,s,{width:1,height:1},0,5,e=>e.terrainType===Yt.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?Ia.BottomLeft:Ia.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()?Ia.BottomLeft:Ia.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?Ia.BottomLeft:Ia.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 tl(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 al=new(__webpack_require__(949).Vector2);class nl{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 nl(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(al);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 ol=__webpack_require__(949);class hl{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 ol.Vector2(e-t,-t));for(let t=1;t<=i;t++)for(let e=1;e<s.height;e++)r.push(new ol.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 ll{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,Ia.TopRight),s=u.getNeighbourTile(t,Ia.BottomRight),a=u.getNeighbourTile(t,Ia.BottomLeft),n=u.getNeighbourTile(t,Ia.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,Ia.TopRight),h=u.getNeighbourTile(t,Ia.BottomRight),l=u.getNeighbourTile(t,Ia.BottomLeft),c=u.getNeighbourTile(t,Ia.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 cl,ul,dl,pl,gl,ml,fl,yl,wl,Tl=__webpack_require__(949);class bl{constructor(e,t,i){this.mapFile=e,this.tiles=new Ra(this.mapFile.tiles,t,i.general),this.mapBounds=(new el).fromMapFile(this.mapFile,this.tiles),this.tileOccupation=new $n(this.tiles),this.tileOcclusion=new hl(this.tiles),this.terrain=new Jh(this.tiles,this.mapFile.theaterType,this.mapBounds,this.tileOccupation,i),this.bridges=new sl(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 nl(new Tl.Box2(new Tl.Vector2(0,0),new Tl.Vector2(i.width,i.height)),{getKey:e=>{e=e.isBuilding()?e.centerTile:e.tile;return new Tl.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&&ll.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){var t=this.mapBounds.clampWithinBounds(e);let i=this.tiles.getByDisplayCoords(t.dx,t.dy);if(i&&this.mapBounds.isWithinBounds(i)){let e=i;for(;e&&this.mapBounds.isWithinBounds(e);)i=e,e=this.tiles.getByDisplayCoords(e.dx,e.dy+2)}else{let e=0;for(;!i||!this.mapBounds.isWithinBounds(i);){if(30<e)throw new Error("Exceeded max elevation while trying to clamp tile to map bounds");i=this.tiles.getByDisplayCoords(t.dx,t.dy+e),e+=2}}return i}isWithinHardBounds(e){return this.mapBounds.isWithinHardBounds(e)}getInitialMapObjects(){return{terrains:this.mapFile.terrains,overlays:this.mapFile.overlays,smudges:this.mapFile.smudges,technos:[...this.mapFile.structures,...this.mapFile.infantries,...this.mapFile.vehicles,...this.mapFile.aircrafts]}}getObjectsOnTile(e){return this.tileOccupation.getObjectsOnTile(e)}getGroundObjectsOnTile(e){return this.tileOccupation.getGroundObjectsOnTile(e)}getTileZone(e,t=!1){return this.tileOccupation.getTileZone(e,t)}dispose(){this.terrain.dispose(),this.bridges.dispose()}}class vl{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=cl=cl||{})[s.Requested=0]="Requested",s[s.Formed=1]="Formed";class Sl{constructor(e){this.playerList=e,this.alliances=[]}findByPlayers(e,t){let i=new vl(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,cl.Requested)}}cancelRequest(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==cl.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!==cl.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=cl.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 vl(e,t),status:i},this.alliances.push(r),r}breakAlliance(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==cl.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===cl.Formed}getAllies(t){return this.filterByPlayer(t).filter(e=>e.status===cl.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 vl(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 vl(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 _l{constructor(){this.players=[]}addPlayer(e){this.players.push(e)}getPlayerAt(e){if(e>=this.players.length)throw new RangeError(`Player #${e} out of bounds`);return this.players[e]}getPlayerByName(t){var e=this.players.find(e=>e.name===t);if(!e)throw new Error(`Player with name "${t}" not found`);return e}getPlayerNumber(e){var t=this.players.indexOf(e);if(-1===t)throw new Error(`Player ${e.name} not found`);return t}getCombatants(){return this.players.filter(e=>e.isCombatant())}getNonNeutral(){return this.players.filter(e=>!e.isNeutral)}getCivilian(){return this.players.find(e=>e.country?.side===Zt.Civilian)}getAll(){return this.players}}(s=ul=ul||{})[s.None=0]="None",s[s.Hover=1]="Hover",s[s.Selected=2]="Selected",s[s.SelectedHover=3]="SelectedHover";class kl{constructor(e){this.selectionLevel=ul.None,e.isBuilding()&&e.rules.wall?this.maxSelectionLevel=ul.None:this.maxSelectionLevel=e.rules.selectable?ul.Selected|ul.Hover:ul.Hover}getSelectionLevel(){return this.selectionLevel}setSelectionLevel(e){this.selectionLevel=Math.min(this.maxSelectionLevel,e)}setHover(e){this.setSelectionLevel(e?this.selectionLevel|ul.Hover:this.selectionLevel&~ul.Hover)}setSelected(e){this.setSelectionLevel(e?this.selectionLevel|ul.Selected:this.selectionLevel&~ul.Selected)}isHovered(){return this.selectionLevel>>ul.Hover&1}isSelected(){return this.selectionLevel>=ul.Selected}getControlGroupNumber(){return this.controlGroupNumber}setControlGroupNumber(e){this.controlGroupNumber=e}}class Ol{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 kl(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 Il{constructor(e){this._onChange=new Rn,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 Al{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 na,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(Bt.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 Cl{constructor(){this.disabled=!0,this.activeEvents=[]}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}}const Bl=(new Map).set("POWER",Xt.Power).set("FACTORY",Xt.Factory).set("BARRACKS",Xt.Barracks).set("RADAR",Xt.Radar).set("TECH",Xt.Tech).set("PROC",Xt.Proc);class El{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 Rn,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 El(e,t.mpDialogSettings.techLevel,i,t,r);t=t.general.maximumQueuedObjects+1;return s.addQueue(Tn.Structures,new Dn(Tn.Structures,1,1)),s.addQueue(Tn.Armory,new Dn(Tn.Armory,1,1)),s.addQueue(Tn.Infantry,new Dn(Tn.Infantry,t,t)),s.addQueue(Tn.Vehicles,new Dn(Tn.Vehicles,t,t)),s.addQueue(Tn.Ships,new Dn(Tn.Ships,t,t)),s.addQueue(Tn.Aircrafts,new Dn(Tn.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 ${Tn[e]}`);return t}getAllQueues(){return[...this.queues.values()]}getQueueTypeForObject(e){if(e.type===Bt.Building)return e.buildCat===Xi.Combat?Tn.Armory:Tn.Structures;if(e.type===Bt.Infantry)return Tn.Infantry;if(e.type===Bt.Vehicle)return e.naval?Tn.Ships:Tn.Vehicles;if(e.type===Bt.Aircraft)return Tn.Aircrafts;throw new Error(`Unsupported object type ${Bt[e.type]}`)}getQueueForObject(e){return this.getQueue(this.getQueueTypeForObject(e))}getQueueTypeForFactory(e){if(e===Yi.InfantryType)return Tn.Infantry;if(e===Yi.UnitType)return Tn.Vehicles;if(e===Yi.AircraftType)return Tn.Aircrafts;if(e===Yi.NavalUnitType)return Tn.Ships;throw new Error(`Unsupported factory type ${Yi[e]}`)}getFactoryTypeForQueueType(e){if(e===Tn.Structures||e===Tn.Armory)return Yi.BuildingType;if(e===Tn.Infantry)return Yi.InfantryType;if(e===Tn.Vehicles)return Yi.UnitType;if(e===Tn.Aircrafts)return Yi.AircraftType;if(e===Tn.Ships)return Yi.NavalUnitType;throw new Error(`Unsupported queue type ${Tn[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!==Yi.UnitType||e.rules.naval===i.naval)&&!!e.rules.owner.find(e=>i.owner.includes(e)))}return!0}meetsStolenTech(e){return e.requiresStolenAlliedTech?this.stolenTech.has(Zt.GDI):!e.requiresStolenSovietTech||this.stolenTech.has(Zt.Nod)}getFactoryTypeFor(e){return e.type===Bt.Building?Yi.BuildingType:e.type===Bt.Infantry?Yi.InfantryType:e.type===Bt.Aircraft?Yi.AircraftType:e.naval?Yi.NavalUnitType:Yi.UnitType}meetsPrerequisites(e){let t=[...this.player.buildings].map(e=>e.name);var i;for(i of e.prerequisite)if(i=i.toUpperCase(),Bl.has(i)){var r=Bl.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 ${Yi[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 xl{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 Pl{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 Nl{constructor(e,t,i){this.rules=e,this.gameOpts=t,this.allAvailableObjects=i}createCombatant(e,t,i,r,s,a){let n=new Al(e,t,i,r);return n.isAi=s,n.aiDifficulty=a,n.powerTrait=new Pn(n),n.traits.add(n.powerTrait),n.radarTrait=new Cl,n.traits.add(n.radarTrait),n.superWeaponsTrait=new xl,n.traits.add(n.superWeaponsTrait),n.production=El.factory(n,this.rules,this.gameOpts,this.allAvailableObjects),n.sharedDetectDisguiseTrait=new Pl,n}createObserver(e,t){let i=new Al(e,void 0,void 0,t.colors.get("LightGrey"));return i.radarTrait=new Cl,i.traits.add(i.radarTrait),i.radarTrait.setDisabled(!1),i}createNeutral(e,t){var i=[...e.countryRules.values()].find(e=>e.side===Zt.Civilian);if(!i)throw new Error("Missing neutral country. No country found in rules with Civilian side");i=new kn(i);let r=new Al(t,i,void 0,e.colors.get("LightGrey"));return r.powerTrait=new Pn(r),r.traits.add(r.powerTrait),r}}(dl=dl||{}).onSpawn=Symbol(),(pl=pl||{}).onUnspawn=Symbol(),(gl=gl||{}).onChange=Symbol();class Rl{[dl.onSpawn](e,t){e.isTechno()&&e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"add",t)}[pl.onUnspawn](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"remove",t)}[yh.onChange](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"update",t)}[gl.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))}[Cr.onChange](e,t,i){e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,i?"remove":"add",t)}[Ar.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 Dl{constructor(e){this.target=e,this.type=er.BuildingSell}}class Ml{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(Ln).forEach(e=>{e[Ln.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 Dl(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 Ll{constructor(e,t){this.target=e,this.radarEnabled=t,this.type=er.RadarOnOff}}class Fl{constructor(e,t,i){this.target=e,this.radarEventType=t,this.tile=i,this.type=er.RadarEvent}}class jl{constructor(){this.activeLightningStrikes=new Map}[dl.onSpawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[pl.onUnspawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[xr.onPowerLow](e,t){this.updateRadarForPlayer(e,t)}[xr.onPowerRestore](e,t){this.updateRadarForPlayer(e,t)}[xr.onPowerChange](){}[gl.onChange](e,t,i){e.rules.radar&&(this.updateRadarForPlayer(t,i),this.updateRadarForPlayer(e.owner,i))}[Cr.onChange](e,t){e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Pr.onActivate](e,t,i){if(e===Ji.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)}}[qa.onDeactivate](e,t,i){if(e===Ji.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===wn.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 Ll(i,!t)))}[ka.onAttack](e,t,i){e.isTechno()&&(!e.isBuilding()||e.rules.canBeOccupied||e.rules.needsEngineer?e.isVehicle()&&e.harvesterTrait&&this.addEventForPlayer(Qt.HarvesterUnderAttack,e.owner,e.tile,i):this.addEventForPlayer(Qt.BaseUnderAttack,e.owner,e.tile,i))}addEventForPlayer(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 kr(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 Fl(e,r,s)))}}}class Wl{constructor(e){this.target=e,this.type=er.InsufficientFunds}}class Ul{constructor(e,t){this.rules=e,this.speedCheat=t,this.availableObjectRules=new Set;t=60*e.general.buildSpeed*Dr.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)})}[Ar.onTick](e){for(var t of e.getCombatants())for(var i of t.production.getAllQueues())this.tickQueue(i,t,e)}[dl.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===Yi.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t)):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[pl.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===Yi.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t))):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[gl.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===Yi.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))}[xr.onPowerLow](e){e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}[xr.onPowerRestore](e){e.production&&(e.production.buildSpeedModifier=1)}[xr.onPowerChange](e){e.powerTrait?.level===wn.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(Bt.Aircraft,!0).filter(e=>r.rules.general.padAircraft.includes(e.name)).length;i.production.getQueueForFactory(Yi.AircraftType).maxSize=Math.max(0,e-t)})}tickQueue(r,s,a){if(r.status===bn.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*Dr.BASE_TICKS_PER_SECOND,n=t.creditsEach?t.creditsEach/i:h;n/(60*Dr.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=bn.Ready),0<o&&!s.credits&&a.events.dispatch(new Wl(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]}}(ml=ml||{}).onChange=Symbol();class Vl{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 Bo).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()}}[Ar.onTick](e){for(var[t,i]of this.shroudByPlayer)t.defeated&&!t.isObserver?this.shroudByPlayer.delete(t):i.update()}[gl.onChange](e,t,i){if(e.isBuilding()&&e.rules.spySat&&(this.revealMap(e.owner,i),t.getOwnedObjectsByType(Bt.Building).find(e=>e.rules.spySat)||this.resetShroud(t,i)),e.isSpawned)for(var r of[e.owner,...i.alliances.getAllies(e.owner)])this.shroudByPlayer.get(r)?.revealFrom(e)}[ml.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(wa);for(r of t)e.merge(r);e.invalidateFull();for(s of t)s.copy(e),s.invalidateFull()}}[dl.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(jl).addEventForPlayer(Qt.EnemyObjectSensed,i,e.centerTile,t))}e.gapGeneratorTrait&&this.gapGenerators.add(e)}}[pl.onUnspawn](e,t){e.isBuilding()&&(e.rules.spySat&&(e.owner.getOwnedObjectsByType(Bt.Building).find(e=>e.rules.spySat)||this.resetShroud(e.owner,t)),e.rules.revealToAll&&this.revealedToAll.delete(e),e.gapGeneratorTrait&&this.gapGenerators.delete(e))}[xr.onPowerLow](e,t){this.updateGaps(t,e)}[xr.onPowerRestore](e,t){this.updateGaps(t,e)}[xr.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,To.Darken,!0)}dispose(){this.map.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class zl extends Ur{onTick(e){return!(e.buildStatus!==Do.BuildDown&&(e.buildStatus=Do.BuildDown,!e.rules.wall))||(this.children.push(new Is(.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,Bt.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,Bt.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,Bt.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 Ta(new zl,new As(()=>{this.game.unspawnObject(e),e.rules.wall&&this.updateAdjacentWalls(e),t()})).setCancellable(!1))}executePlacement(e,t){let i=this.game.createObject(Bt.Building,t.name);return this.game.changeObjectOwner(i,this.player),i.purchaseValue=this.game.sellTrait.computePurchaseValue(t,this.player),this.game.spawnObject(i,e),i}getWallConnectingTiles(i,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 Vn(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(Jt.Float):0===e.rampType&&this.rules.getLandRules(e.landType).buildable)}}class Gl{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:Bt.Vehicle,count:l})}var c,i=i.filter(e=>!h.includes(e)),u=o/i.length;for(c of i){if(o<=0)break;var d=Math.ceil(u/c.cost);o-=d*c.cost,n.push({name:c.name,type:Bt.Infantry,count:d})}return n}}class $l{constructor(){this.dispatcher=new Rn,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 Rn,this.dispatchersByType.set(e,i)),i.subscribe(t),()=>this.unsubscribeType(e,t)}unsubscribeType(e,t){this.dispatchersByType.get(e)?.unsubscribe(t)}}class ql{constructor(e,t,i){this.target=e,this.attackerInfo=t,this.incidental=i,this.type=er.ObjectDestroy}}class Zl{constructor(e){this.target=e,this.type=er.PlayerDefeated}}(fl=fl||{}).onDestroy=Symbol();class Ql{constructor(e,t){this.target=e,this.prevOwner=t,this.type=er.ObjectOwnerChange}}class Xl{constructor(e){this.gameObject=e,this.type=er.ObjectUnspawn}}class Yl{constructor(e){this.gameObject=e,this.type=er.ObjectSpawn}}class Kl{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=yl=yl||{})[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 Jl{constructor(e){this.actionType=e}unserialize(e){}serialize(){return[]}print(){return""}}(s=wl=wl||{})[s.Add=0]="Add",s[s.Cancel=1]="Cancel",s[s.Pause=2]="Pause",s[s.Resume=3]="Resume";class ec extends Jl{constructor(e){super(yl.UpdateQueue),this.game=e}unserialize(e){this.queueType=Number(e[0]),this.updateType=Number(e[1]),this.updateType!==wl.Add&&this.updateType!==wl.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!==wl.Add&&this.updateType!==wl.Cancel||e.push(""+this.item.name,""+this.item.type,""+this.quantity),e}print(){return this.updateType===wl.Resume?`Resume queue ${Tn[this.queueType]}`:this.updateType===wl.Add?`Add to queue ${this.item.name} x ${this.quantity}`:this.updateType===wl.Pause?`Put queue ${Tn[this.queueType]} on hold.`:this.updateType===wl.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===wl.Resume)r.status===bn.OnHold&&(r.status=bn.Active);else if(this.updateType===wl.Add){let e=r.find(i);var s;(r.status===bn.Active||r.status===bn.Idle||r.status===bn.OnHold&&e[0]!==r.getFirst()||r.status===bn.Ready&&i.type!==Bt.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===wl.Cancel){if([bn.Ready,bn.OnHold,bn.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===wl.Pause&&r.status===bn.Active&&(r.status=bn.OnHold)}}var tc=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},ic=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 rc{constructor(e,t,i,r){lc.add(this),ac.set(this,void 0),nc.set(this,void 0),oc.set(this,void 0),hc.set(this,void 0),tc(this,ac,t,"f"),tc(this,nc,i,"f"),tc(this,oc,e,"f"),tc(this,hc,r,"f")}placeBuilding(t,i,r){ic(this,lc,"m",cc).call(this,yl.PlaceBuilding,e=>{e.name=t,e.tile={x:i,y:r}})}sellBuilding(t){ic(this,lc,"m",cc).call(this,yl.SellBuilding,e=>{e.buildingId=t})}toggleRepairWrench(t){ic(this,lc,"m",cc).call(this,yl.ToggleRepair,e=>{e.buildingId=t})}toggleAlliance(t,i){ic(this,lc,"m",cc).call(this,yl.ToggleAlliance,e=>{e.toPlayerName=t,e.toggle=i})}pauseProduction(t){ic(this,lc,"m",cc).call(this,yl.UpdateQueue,e=>{e.queueType=t,e.updateType=wl.Pause})}resumeProduction(t){ic(this,lc,"m",cc).call(this,yl.UpdateQueue,e=>{e.queueType=t,e.updateType=wl.Resume})}queueForProduction(t,e,i,r){let s=ic(this,oc,"f").rules.getObject(e,i);ic(this,lc,"m",cc).call(this,yl.UpdateQueue,e=>{e.queueType=t,e.updateType=wl.Add,e.item=s,e.quantity=r})}unqueueFromProduction(t,e,i,r){let s=ic(this,oc,"f").rules.getObject(e,i);ic(this,lc,"m",cc).call(this,yl.UpdateQueue,e=>{e.queueType=t,e.updateType=wl.Cancel,e.item=s,e.quantity=r})}activateSuperWeapon(t,i,r){ic(this,lc,"m",cc).call(this,yl.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){ic(this,lc,"m",cc).call(this,yl.SelectUnits,e=>{e.unitIds=t});let n;if(r){let e,t;if(s){e=void 0;var o=ic(this,oc,"f").map.tiles.getByMapCoords(r,s);if(!o)throw new Error(`No tile found at rx,ry=${r},${s}`);t=o,a&&(e=ic(this,oc,"f").map.tileOccupation.getBridgeOnTile(o))}else e=ic(this,oc,"f").getObjectById(r),t=e.tile;n=ic(this,oc,"f").createTarget(e,t)}ic(this,lc,"m",cc).call(this,yl.OrderUnits,e=>{e.orderType=i,e.target=n})}quitGame(){ic(this,lc,"m",cc).call(this,yl.QuitGame)}}var sc,ac=new WeakMap,nc=new WeakMap,oc=new WeakMap,hc=new WeakMap,lc=new WeakSet,cc=function(e,t){if(!ic(this,hc,"f"))throw new Error("Player name must be set before issuing any actions");let i=ic(this,ac,"f").create(e);i.playerName=ic(this,hc,"f"),t?.(i),ic(this,nc,"f").push(i)},uc=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},dc=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=sc=sc||{})[s.ObjectOwnerChange=0]="ObjectOwnerChange",s[s.ObjectSpawn=1]="ObjectSpawn",s[s.ObjectUnspawn=2]="ObjectUnspawn",s[s.ObjectDestroy=3]="ObjectDestroy";class pc{constructor(e){fc.add(this),gc.set(this,void 0),mc.set(this,[]),uc(this,gc,e,"f")}subscribe(e,t){let i=void 0,r;r="function"==typeof e?e:(i=e,t);t=dc(this,gc,"f").subscribe(e=>{e=dc(this,fc,"m",yc).call(this,e);!e||void 0!==i&&i!==e.type||r(e)});return dc(this,mc,"f").push(t),t}dispose(){for(var e of dc(this,mc,"f"))e();dc(this,mc,"f").length=0}}var gc=new WeakMap,mc=new WeakMap,fc=new WeakSet,yc=function(t){switch(t.type){case er.ObjectOwnerChange:return{type:sc.ObjectOwnerChange,prevOwnerName:t.prevOwner.name,newOwnerName:t.target.owner.name,target:t.target.id};case er.ObjectSpawn:return{type:sc.ObjectSpawn,target:t.gameObject.id};case er.ObjectUnspawn:return{type:sc.ObjectUnspawn,target:t.gameObject.id};case er.ObjectDestroy:{let e=t;return e.target.isProjectile()?void 0:{type:sc.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}},wc=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},Tc=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){_c.add(this),vc.set(this,void 0),Sc.set(this,void 0),wc(this,vc,e,"f"),wc(this,Sc,e.map,"f")}getStartingLocations(){return Tc(this,Sc,"f").startingLocations}getTheaterType(){return Tc(this,Sc,"f").getTheaterType()}getTile(e,t){t=Tc(this,Sc,"f").tiles.getByMapCoords(e,t);if(t&&Tc(this,Sc,"f").mapBounds.isWithinBounds(t))return t}getTilesInRect(e,t){return Tc(this,Sc,"f").tiles.getInRectangle(e,t).filter(e=>Tc(this,Sc,"f").mapBounds.isWithinBounds(e))}getObjectsOnTile(e){return Tc(this,Sc,"f").getObjectsOnTile(e).map(e=>e.id)}hasBridgeOnTile(e){return!!e.onBridgeLandType}hasHighBridgeOnTile(e){return!!Tc(this,Sc,"f").tileOccupation.getBridgeOnTile(e)?.isHighBridge()}isPassableTile(e,t,i){return 0<Tc(this,Sc,"f").terrain.getPassableSpeed(e,t,i)}isVisibleTile(e,t){var i=Tc(this,vc,"f").getPlayerByName(t);if(!i)throw new Error(`Player "${t}" doesn't exist`);return!Tc(this,vc,"f").mapShroudTrait.getPlayerShroud(i)?.isShrouded(e)}getTileResourceData(e){e=Tc(this,Sc,"f").getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium()||e.isTerrain()&&e.rules.spawnsTiberium);return e?Tc(this,_c,"m",kc).call(this,e):void 0}getAllTilesResourceData(){var e;let t=[];for(e of Tc(this,vc,"f").getWorld().getAllObjects()){var i=Tc(this,_c,"m",kc).call(this,e);i&&t.push(i)}return t}}var vc=new WeakMap,Sc=new WeakMap,_c=new WeakSet,kc=function(t){let i;if(t.isOverlay()&&t.isTiberium()){let e=t.traits.get(Ma);var r=e.getTiberiumType(),s=e.getBailCount();i={tile:t.tile,ore:r===Ca.Ore?s:0,gems:r===Ca.Gems?s:0,spawnsOre:!1}}else t.isTerrain()&&t.rules.spawnsTiberium&&(i={tile:t.tile,ore:0,gems:0,spawnsOre:!0});return i},Oc=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},Ic=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){Cc.set(this,void 0),Oc(this,Cc,e,"f")}get allObjectRules(){return Ic(this,Cc,"f").allObjectRules}get buildingRules(){return Ic(this,Cc,"f").buildingRules}get infantryRules(){return Ic(this,Cc,"f").infantryRules}get vehicleRules(){return Ic(this,Cc,"f").vehicleRules}get aircraftRules(){return Ic(this,Cc,"f").aircraftRules}get terrainRules(){return Ic(this,Cc,"f").terrainRules}get overlayRules(){return Ic(this,Cc,"f").overlayRules}get countryRules(){return Ic(this,Cc,"f").countryRules}get general(){return Ic(this,Cc,"f").general}get ai(){return Ic(this,Cc,"f").ai}get crateRules(){return Ic(this,Cc,"f").crateRules}get combatDamage(){return Ic(this,Cc,"f").combatDamage}get radiation(){return Ic(this,Cc,"f").radiation}hasObject(e,t){return Ic(this,Cc,"f").hasObject(e,t)}getObject(e,t){return Ic(this,Cc,"f").getObject(e,t)}getBuilding(e){return Ic(this,Cc,"f").getBuilding(e)}getWeapon(e){return Ic(this,Cc,"f").getWeapon(e)}getWarhead(e){return Ic(this,Cc,"f").getWarhead(e)}getProjectile(e){return Ic(this,Cc,"f").getProjectile(e)}getOverlayName(e){return Ic(this,Cc,"f").getOverlayName(e)}getOverlayId(e){return Ic(this,Cc,"f").getOverlayId(e)}getOverlay(e){return Ic(this,Cc,"f").getOverlay(e)}getCountry(e){return Ic(this,Cc,"f").getCountry(e)}getMultiplayerCountries(){return Ic(this,Cc,"f").getMultiplayerCountries()}getIni(){return Ic(this,Cc,"f").getIni()}}var Cc=new WeakMap,Bc=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 xc{constructor(e,t){Lc.add(this),Dc.set(this,void 0),Mc.set(this,void 0),Bc(this,Dc,e,"f"),Bc(this,Mc,t,"f"),this.mapApi=new bc(e),this.rulesApi=new Ac(e.rules)}isPlayerDefeated(e){return Ec(this,Dc,"f").getPlayerByName(e).defeated}areAlliedPlayers(e,t){var i=Ec(this,Dc,"f").getPlayerByName(e);if(!i)throw new Error(`Player "${e}" doesn't exist`);e=Ec(this,Dc,"f").getPlayerByName(t);if(!e)throw new Error(`Player "${t}" doesn't exist`);return Ec(this,Dc,"f").alliances.areAllied(i,e)}canPlaceBuilding(e,t,i){var r=Ec(this,Dc,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);let s=Ec(this,Dc,"f").getConstructionWorker(r).canBuildAt(t,i,void 0,!0);return!s.some(e=>!e.buildable)}getBuildingPlacementData(e){e=Ec(this,Dc,"f").art.getObject(e,Bt.Building);return{foundation:e.foundation,foundationCenter:e.foundationCenter}}getPlayers(){return Ec(this,Dc,"f").getNonNeutralPlayers().map(e=>e.name)}getPlayerData(e){let t=Ec(this,Dc,"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===wn.Low},radarDisabled:!!t.radarTrait?.isDisabled()}}getAllTerrainObjects(){return Ec(this,Dc,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}getAllUnits(){return Ec(this,Dc,"f").getWorld().getAllObjects().filter(e=>e.isTechno()).map(e=>e.id)}getVisibleUnits(e,t,i=()=>!0){const r=Ec(this,Dc,"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||Ec(this,Dc,"f").alliances.areAllied(e.owner,r);else{if("hostile"!==t)throw new Error(`Unexpected type ${t}`);{let t=Ec(this,Dc,"f").mapShroudTrait.getPlayerShroud(r);s=e=>!t?.isShrouded(e.tile)&&e.owner!==r&&!Ec(this,Dc,"f").alliances.areAllied(e.owner,r)}}return Ec(this,Dc,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&s(e)&&i(e.rules)).map(e=>e.id)}getGameObjectData(t){if(Ec(this,Dc,"f").getWorld().hasObjectId(t)){let e=Ec(this,Dc,"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=Ec(this,Dc,"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?Ec(this,Lc,"m",Fc).call(this,e.primaryWeapon):void 0,secondaryWeapon:e.secondaryWeapon?Ec(this,Lc,"m",Fc).call(this,e.secondaryWeapon):void 0,deathWeapon:e.armedTrait?.deathWeapon?Ec(this,Lc,"m",Fc).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 Ec(this,Dc,"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 Ec(this,Dc,"f").rules.general}getRulesIni(){return Ec(this,Dc,"f").rules.getIni()}getArtIni(){return Ec(this,Dc,"f").art.getIni()}generateRandomInt(e,t){if(Ec(this,Mc,"f"))return Ec(this,Dc,"f").generateRandomInt(e,t);var i=this.generateRandom();return Math.round(i*(t-e))+e}generateRandom(){return Ec(this,Mc,"f")?Ec(this,Dc,"f").generateRandom():Math.random()}getTickRate(){return Ec(this,Dc,"f").speed.value*Dr.BASE_TICKS_PER_SECOND}getCurrentTick(){return Ec(this,Dc,"f").currentTick}}var Pc,Nc,Rc,Dc=new WeakMap,Mc=new WeakMap,Lc=new WeakSet,Fc=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()}},jc=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},Wc=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 Uc{constructor(e){Pc.set(this,void 0),jc(this,Pc,e,"f")}isAvailableForProduction(e){return Wc(this,Pc,"f").isAvailableForProduction(e)}getAvailableObjects(t){let e=Wc(this,Pc,"f").getAvailableObjects();return void 0!==t&&(e=e.filter(e=>this.getQueueTypeForObject(e)===t)),e}getQueueTypeForObject(e){return Wc(this,Pc,"f").getQueueTypeForObject(e)}getQueueData(e){let t=Wc(this,Pc,"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}))}}}Pc=new WeakMap;class Vc{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=Nc=Nc||{})[s.Initial=0]="Initial",s[s.Deployed=1]="Deployed",s[s.Attacking=2]="Attacking",s[s.Defeated=3]="Defeated";class zc extends Vc{constructor(){super(...arguments),this.botState=Nc.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 Nc.Initial:{const i=e.getGeneralRules().baseUnit;if(e.getVisibleUnits(this.name,"self",e=>e.constructionYard).length){this.botState=Nc.Deployed;break}var t=e.getVisibleUnits(this.name,"self",e=>i.includes(e.name));t.length&&this.actionsApi.orderUnits([t[0]],Ho.DeploySelected);break}case Nc.Deployed:break;case Nc.Attacking:e.getVisibleUnits(this.name,"self",e=>e.isSelectableCombatant).length||(this.botState=Nc.Defeated,this.actionsApi.quitGame())}}}(s=Rc=Rc||{})[s.Requested=0]="Requested",s[s.Formed=1]="Formed",s[s.Broken=2]="Broken";class Hc{constructor(e,t,i){this.alliance=e,this.changeType=t,this.from=i,this.type=er.AllianceChange}}var Gc,$c,s=__webpack_require__(948),qc=__webpack_require__.n(s);class Zc{constructor(e){this.prng=new(qc())(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 Xc 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 Yc 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(Wa.HE_WARHEAD_NAME);let e=new Wa(r);var s=t.map.tileOccupation.getBridgeOnTile(i),a=s?.tileElevation??0,r=t.map.getTileZone(i);e.detonate(t,this.damage,i,a,wr.tile3dToWorld(i.rx+.5,i.ry+.5,i.z+a),r,s?Oa.OnBridge:Oa.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 Kc 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 Jc 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 oa&&r.isSpawned&&e.changeObjectOwner(r,i)}}class eu extends Ur{constructor(){super(),this.executed=!1,this.cancellable=!1}onTick(e){return this.executed?(e.stance=Nr.None,!0):!e.isInfantry()||!e.art.sequences.has(hn.Cheer)||(e.stance!==Nr.None&&e.stance!==Nr.Guard||(e.stance=Nr.Cheer,this.children.push(new Is(1/60).setCancellable(!1)),!(this.executed=!0)))}}class tu 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(Bt.Infantry))i.unitOrderTrait.isIdle()&&i.unitOrderTrait.addTask(new eu)}}const iu=new Map([[0,e=>{e=e.rules.powerups.powerups.find(e=>e.type===Ir.Money);return e?{...e,data:"5000"}:void 0}],[1,Ir.Unit],[2,Ir.HealBase],[3,Ir.Cloak],[4,Ir.Explosion],[5,Ir.Napalm],[6,Ir.Money],[7,Ir.Darkness],[8,Ir.Reveal],[9,Ir.Armor],[10,Ir.Speed],[11,Ir.Firepower],[12,Ir.ICBM],[13,void 0],[14,Ir.Veteran],[15,void 0],[16,Ir.Gas],[17,Ir.Tiberium],[18,void 0]]);class ru extends Qc{execute(e){var t=Number(this.action.params[1]),i=this.action.params[6],r=e.map.getTileAtWaypoint(i);if(r)if(iu.has(t)){const s=iu.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 su extends Qc{execute(e){var t=Number(this.action.params[1])-1;if(Object.values(Qt).includes(t)){var i=this.action.params[6],r=e.map.getTileAtWaypoint(i);if(r)for(var s of e.getCombatants())e.traits.get(jl).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 au extends Qc{execute(e,t){for(var i of t)i instanceof oa&&i.isSpawned&&e.destroyObject(i)}}class nu extends Qc{execute(e){var t=this.action.params[1];e.triggers.destroyTag(t)}}class ou extends Qc{execute(e){var t=this.action.params[1];e.triggers.destroyTrigger(t)}}class hu 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 Wa(e);var n=r.map.tileOccupation.getBridgeOnTile(a),o=n?.tileElevation??0,s=r.map.getTileZone(a);i.detonate(r,t.damage,a,o,wr.tile3dToWorld(a.rx+.5,a.ry+.5,a.z+o),s,n?Oa.OnBridge:Oa.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 lu extends Qc{execute(e,t){for(var i of t)i instanceof oa&&i.isBuilding()&&i.garrisonTrait&&!i.isDestroyed&&i.garrisonTrait.evacuate(e)}}class cu 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 uu extends Qc{execute(e){var t=this.action.params[1];e.triggers.forceTrigger(t,e)}}class du 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 pu 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===Ji.IronCurtain))&&e.traits.get(sn).activateEffect(i,t,e,s,void 0,!0):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class gu 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===Ji.LightningStorm))&&e.traits.get(sn).activateEffect(i,t,e,s,void 0,!0):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class mu 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 fu extends Qc{execute(){}}class yu 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===Ji.MultiMissile))&&e.traits.get(sn).activateEffect(i,t,e,s,void 0,!0):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class wu{constructor(e,t){this.name=e,this.tile=t,this.type=er.TriggerAnim}}class Tu 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 wu(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 bu{constructor(e,t){this.soundId=e,this.tile=t,this.type=er.TriggerSoundFx}}class vu 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 bu(i,t)):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class Su extends Qc{execute(e){e.events.dispatch(new bu(this.action.params[1]))}}class _u{constructor(e){this.soundId=e,this.type=er.TriggerEva}}class ku extends Qc{execute(e){e.events.dispatch(new _u(this.action.params[1]))}}class Ou extends Qc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.resetShroud(t,e)}}class Iu 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 Au 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 Cu extends Qc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.revealMap(t,e)}}class Bu extends Qc{execute(e,t){for(var i of t)i instanceof oa&&i.isBuilding()&&!i.isDestroyed&&e.sellTrait.sell(i)}}class Eu extends Qc{execute(e){var t=Number(this.action.params[1])/100;e.mapLightingTrait.setTargetAmbientIntensity(t)}}function xu(e){let t=new DataView(new ArrayBuffer(4));return t.setInt32(0,e),t.getFloat32(0)}class Pu extends Qc{execute(e){var t=xu(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeRate(t)}}class Nu extends Qc{execute(e){var t=xu(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeStep(t)}}class Ru{constructor(e){this.tile=e,this.type=er.TriggerStopSoundFx}}class Du extends Qc{execute(e){var t=this.action.params[6],i=e.map.getTileAtWaypoint(t);i?e.events.dispatch(new Ru(i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Mu{constructor(e){this.label=e,this.type=er.TriggerText}}class Lu extends Qc{execute(e){e.events.dispatch(new Mu(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.setSeconds(Number(this.action.params[1]))}}class Wu extends Qc{execute(e){e.countdownTimer.addSeconds(-Number(this.action.params[1]))}}class Uu extends Qc{execute(e){e.countdownTimer.start()}}class Vu extends Qc{execute(e){e.countdownTimer.stop()}}class zu extends Qc{execute(e){e.countdownTimer.text=this.action.params[1]}}class Hu 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 Gu extends Qc{constructor(e,t,i){super(e,t),this.turnOn=i}execute(e,t){for(var i of t)i instanceof oa&&i.isBuilding()&&i.poweredTrait?.setTurnedOn(this.turnOn)}}class $u 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 qu{create(e,t){switch(e.type){case qt.NoAction:return new fu(e,t);case qt.FireSale:return new cu(e,t);case qt.TextTrigger:return new Lu(e,t);case qt.DestroyTrigger:return new ou(e,t);case qt.ChangeHouse:return new Jc(e,t);case qt.RevealMap:return new Cu(e,t);case qt.RevealAroundWaypoint:return new Au(e,t);case qt.PlaySoundFx:return new Su(e,t);case qt.PlaySpeech:return new ku(e,t);case qt.ForceTrigger:return new uu(e,t);case qt.TimerStart:return new Uu(e,t);case qt.TimerStop:return new Vu(e,t);case qt.TimerExtend:return new Fu(e,t);case qt.TimerShorten:return new Wu(e,t);case qt.TimerSet:return new ju(e,t);case qt.GlobalSet:return new du(e,t,!0);case qt.GlobalClear:return new du(e,t,!1);case qt.DestroyObject:return new au(e,t);case qt.AddOneTimeSuperWeapon:return new Xc(e,t,!0);case qt.AddRepeatingSuperWeapon:return new Xc(e,t,!1);case qt.AllChangeHouse:return new Kc(e,t);case qt.ResizePlayerView:return new Iu(e,t);case qt.PlayAnimAt:return new Tu(e,t);case qt.DetonateWarhead:return new hu(e,t);case qt.ReshroudMap:return new Ou(e,t);case qt.EnableTrigger:return new Hu(e,t,!0);case qt.DisableTrigger:return new Hu(e,t,!1);case qt.CreateRadarEvent:return new su(e,t);case qt.LocalSet:return new mu(e,t,!0);case qt.LocalClear:return new mu(e,t,!1);case qt.SellBuilding:return new Bu(e,t);case qt.TurnOffBuilding:return new Gu(e,t,!1);case qt.TurnOnBuilding:return new Gu(e,t,!0);case qt.ApplyOneHundredDamage:return new Yc(e,t,100);case qt.DestroyTag:return new nu(e,t);case qt.SetAmbientStep:return new Nu(e,t);case qt.SetAmbientRate:return new Pu(e,t);case qt.SetAmbientLight:return new Eu(e,t);case qt.NukeStrike:return new yu(e,t);case qt.PlaySoundFxAt:return new vu(e,t);case qt.UnrevealAroundWaypoint:return new $u(e,t);case qt.LightningStrike:return new gu(e,t);case qt.TimerText:return new zu(e,t);case qt.CreateCrate:return new ru(e,t);case qt.IronCurtainAt:return new pu(e,t);case qt.EvictOccupiers:return new lu(e,t);case qt.Cheer:return new tu(e,t);case qt.StopSoundsAt:return new Du(e,t);default:throw new Error(`Unhandled action type "${qt[e.type]}"`)}}}class Zu{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 Zu{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 Xu extends Zu{check(e){return!0}}class Yu extends Zu{check(r,e){return e.filter(e=>{if(e.type!==er.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 Ku extends Zu{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==er.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 Ju extends Zu{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 ed extends Zu{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===er.ObjectSpawn&&e.gameObject.type===this.objectType&&e.gameObject.rules.index===this.objectIndex)}}class td extends Zu{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===er.EnterTile&&i.source.owner===this.player){let e=new kr(t.map.tileOccupation);if(e.tileDistance(i.target,this.waypointTile)<2)return!0}return!1}}class id extends Zu{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits<this.threshold}}class rd extends Zu{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits>this.threshold}}class sd extends Zu{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!==er.ObjectDestroy)return!1;let t=e.target;return!(!t.isBuilding()||t.owner.country?.id!==this.houseId)&&!t.owner.buildings.size})&&(this.allDestroyed=!0)}}class ad extends Zu{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!==er.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 nd extends Zu{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!==er.ObjectDestroy)return!1;let t=e.target;return!(!t.isUnit()||t.owner.country?.id!==this.houseId)&&!this.hasUnitsLeft(t.owner)})&&(this.allDestroyed=!0)}hasUnitsLeft(e){var t;for(t of[Bt.Aircraft,Bt.Vehicle,Bt.Infantry])if(e.getOwnedObjectsByType(t,!0).length)return!0;return!1}}class od extends Zu{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!==er.ObjectDestroy)return!1;let t=e.target;return!(!t.isUnit()||t.owner.country?.id!==this.houseId)&&!this.hasLandUnitsLeft(t.owner)})&&(this.allDestroyed=!0)}hasLandUnitsLeft(e){var t;for(t of[Bt.Vehicle,Bt.Infantry])if(e.getOwnedObjectsByType(t,!0).filter(e=>!e.rules.naval).length)return!0;return!1}}class hd extends Zu{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!==er.ObjectDestroy)return!1;let t=e.target;return!(!t.isVehicle()||t.owner.country?.id!==this.houseId)&&!t.owner.getOwnedObjectsByType(Bt.Vehicle,!0).filter(e=>e.rules.naval).length})&&(this.allDestroyed=!0)}}class ld extends Zu{check(r,e){return e.filter(e=>{if(e.type!==er.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 cd extends Zu{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===er.ObjectDestroy){let e=i.target;e.isBuilding()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class ud extends Zu{check(r,e){return e.filter(e=>{if(e.type!==er.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 dd extends Zu{check(e,t){return t.filter(e=>{if(e.type!==er.ObjectDestroy&&e.type!==er.ObjectOwnerChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class pd extends Zu{constructor(){super(...arguments),this.eventsFilter=[er.ObjectDestroy,er.ObjectOwnerChange,er.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 gd extends Zu{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===er.ObjectDestroy){let e=i.target;e.isUnit()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class md extends Zu{constructor(e,t){super(e,t),this.timerTicks=Number(this.event.params[1])*Dr.BASE_TICKS_PER_SECOND}check(e){return e.currentTick>this.timerTicks}}class fd extends Zu{constructor(e,t){super(e,t),this.elapsedTicks=0,this.timerTicks=Number(this.event.params[1])*Dr.BASE_TICKS_PER_SECOND}check(e){return this.elapsedTicks++>this.timerTicks}reset(){this.elapsedTicks=0}}class yd extends Zu{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>(e.type===er.EnterObject||e.type===er.EnterTile)&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class wd extends Zu{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 Td extends Zu{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==er.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 bd extends Zu{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==er.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 vd extends Zu{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 Sd extends Zu{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 _d extends Zu{check(e){return!1}}class kd extends Zu{check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.factoryTrait)return!1;return!0}}class Od extends Zu{check(e,t){return t.some(e=>e.type===er.CratePickup)}}class Id extends Zu{check(e,t){return t.filter(e=>e.type===er.CratePickup&&this.targets.includes(e.source)).map(e=>e.source)}}class Ad extends Zu{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]))*Dr.BASE_TICKS_PER_SECOND),this.elapsedTicks++>this.timerTicks}reset(){this.timerTicks=void 0,this.elapsedTicks=0}}class Cd extends Zu{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>e.type===er.BuildingInfiltration&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class Bd extends Zu{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==er.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 Ed extends Zu{constructor(e,t){super(e,t),this.infantryIdx=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==er.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 xd extends Zu{check(e,t){return t.some(e=>e.type===er.TimerExpire)}}class Pd{create(e,t){switch(e.type){case $t.NoEvent:return new _d(e,t);case $t.EnteredBy:return new yd(e,t);case $t.SpiedBy:return new Cd(e,t);case $t.AttackedByAny:return new Yu(e,t);case $t.DestroyedByAny:return new ud(e,t);case $t.AnyEvent:return new Xu(e,t);case $t.DestroyedAllUnits:return new nd(e,t);case $t.DestroyedAllBuildings:return new sd(e,t);case $t.DestroyedAll:return new ad(e,t);case $t.CreditsExceed:return new rd(e,t);case $t.ElapsedTime:return new fd(e,t);case $t.MissionTimerExpired:return new xd(e,t);case $t.DestroyedBuildings:return new cd(e,t);case $t.DestroyedUnits:return new gd(e,t);case $t.NoFactoriesLeft:return new kd(e,t);case $t.BuildBuilding:return new ed(e,t,Bt.Building);case $t.BuildUnit:return new ed(e,t,Bt.Vehicle);case $t.BuildInfantry:return new ed(e,t,Bt.Infantry);case $t.BuildAircraft:return new ed(e,t,Bt.Aircraft);case $t.GlobalIsSet:return new wd(e,t,!0);case $t.GlobalIsCleared:return new wd(e,t,!1);case $t.DestroyedOrCaptured:return new dd(e,t);case $t.LowPower:return new Sd(e,t);case $t.DestroyedBridge:return new ld(e,t);case $t.BuildingExists:return new Ju(e,t);case $t.ComesNearWaypoint:return new td(e,t);case $t.LocalIsSet:return new vd(e,t,!0);case $t.LocalIsCleared:return new vd(e,t,!1);case $t.FirstDamagedCombat:return new bd(e,t,100);case $t.HalfHealthCombat:return new bd(e,t,50);case $t.QuarterHealthCombat:return new bd(e,t,25);case $t.FirstDamagedAny:return new Td(e,t,100);case $t.HalfHealthAny:return new Td(e,t,50);case $t.QuarterHealthAny:return new Td(e,t,25);case $t.AttackedByHouse:return new Ku(e,t);case $t.AmbientLightBelow:return new Qu(e,t,"below");case $t.AmbientLightAbove:return new Qu(e,t,"above");case $t.ElapsedScenarioTime:return new md(e,t);case $t.DestroyedOrCapturedOrInfiltrated:return new pd(e,t);case $t.PickupCrate:return new Id(e,t);case $t.PickupCrateAny:return new Od(e,t);case $t.RandomDelay:return new Ad(e,t);case $t.CreditsBelow:return new id(e,t);case $t.SpyEnteringAsHouse:return new Bd(e,t);case $t.SpyEnteringAsInfantry:return new Ed(e,t);case $t.DestroyedAllUnitsNaval:return new hd(e,t);case $t.DestroyedAllUnitsLand:return new od(e,t);case $t.BuildingNotExists:return new Ju(e,t,!0);default:throw new Error(`Unhandled trigger event type "${$t[e.type]}"`)}}}class Nd{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 Rd{constructor(){this.disposables=new Nd,this.triggerInstances=new Map,this.targetsByTag=new Map,this.conditionFactory=new Pd,this.executorFactory=new qu,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===Gt.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===Gt.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!==Gt.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 bi("No name",t)):i.value=t}getLocalVariable(e){return!!this.localVariables.get(e)?.value}toggleLocalVariable(e,t){let i=this.localVariables.get(e);void 0===i?this.localVariables.set(e,new bi("No name",t)):i.value=t}dispose(){this.disposables.dispose()}}class Dd{constructor(e){this.target=e,this.type=er.TimerExpire}}class Md{constructor(){this.ticks=0,this.running=!1}getSeconds(){return Math.floor(this.ticks/Dr.BASE_TICKS_PER_SECOND)}setSeconds(e){this.ticks=Math.max(0,Math.floor(Dr.BASE_TICKS_PER_SECOND*e))}addSeconds(e){this.ticks=Math.max(0,this.ticks+Math.floor(Dr.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 Dd(this))))}}(Gc=Gc||{}).onAdd=Symbol(),(s=$c=$c||{})[s.NotStarted=0]="NotStarted",s[s.Started=1]="Started",s[s.Ended=2]="Ended";class Ld{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 Md,this._onEnd=new Rn,this.afterTickCallbacks=[],this.events=new $l,this.traits=new na,this.world=e,this.map=t,this.rules=i,this.art=r,this.id=s,this.startTimestamp=a,this.prng=new Zc(Number(s+""+a)),this.gameOpts=n,this.gameModeType=o,this.playerList=h,this.unitSelection=l,this.alliances=c,this.desiredSpeed=new Il(Dr.computeGameSpeed(n.gameSpeed)),this.speed=new Il(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 Kl,new xc(e,!0),new pc(e.events))}init(){var e,t;for(e of this.game.getCombatants().filter(e=>e.isAi))this.bots.set(e,new zc(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 rc(this.game,this.actionFactory,this.actionQueue,t.name)),t.setProductionApi(new Uc(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 Rd}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 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.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=$c.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=>Or(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,cl.Formed);this.onAllianceChange(s,r,!0)}}}createMapObjects(){var e=this.rules.general.harvesterUnit.every(e=>!V(this.rules.getObject(e,Bt.Vehicle).techLevel,0,this.rules.mpDialogSettings.techLevel)),t=this.map.getInitialMapObjects();this.createInitialMapTerrains(t.terrains,e),this.createInitialMapOverlays(t.overlays,e),this.createInitialMapSmudges(t.smudges),this.createInitialMapTechnos(t.technos)}createInitialMapTerrains(e,t){for(var i of e){var r,s,a=i.name;this.validateMapObjectRulesAndArt(a,Bt.Terrain)&&((r=this.map.tiles.getByMapCoords(i.rx,i.ry))?(s=this.rules.getObject(a,Bt.Terrain),t&&s.spawnsTiberium||(a=this.createObject(Bt.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,Bt.Overlay)){let e=this.createObject(Bt.Overlay,h),t=o.id;!e.rules.tiberium||void 0!==(l=on.calculateOverlayId(o))&&l!==o.id&&(e=this.createObject(Bt.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(Pa.isLowBridge(o.id))Pa.isBridgePlaceholder(o.id)||(a.set(l,o.value),1===o.value?n.set(l,e):e.dispose());else{if(e.isTiberium()){if(![Aa.Ore,Aa.Gems,Aa.Vinifera].includes(Da.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!==il.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=Pa.bridgePlaceholderIds[0],y=this.rules.getOverlayName(f);for(m of e){let e=this.createObject(Bt.Overlay,y);e.overlayId=f,this.spawnObject(e,m)}}createInitialMapSmudges(e){for(var t of e){var i=t.name,r=this.map.tiles.getByMapCoords(t.rx,t.ry);r?(i=this.createObject(Bt.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){if(n.isNeutral){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=Tr(e?a.onBridgeLandType:a.landType),e&&(t.position.tileElevation+=this.map.tileOccupation.getBridgeOnTile(a)?.tileElevation??0),i.veterancy&&t.veteranTrait?.setRelativeXP(i.veterancy)}else t.poweredTrait?.setTurnedOn(i.poweredOn);this.changeObjectOwner(t,n),this.spawnObject(t,a),e&&this.destroyObject(t,void 0,!0)}}else console.warn(`Invalid owner "${i.owner}" for map object`,i)}else console.warn(`Invalid map object location (${i.rx},${i.ry})`,i)}}}validateMapObjectRulesAndArt(e,t){return this.rules.hasObject(e,t)?!!this.art.hasObject(e,t)||(console.warn(`Map object '${e}' has no art section. Skipping.`),!1):(console.warn(`Map object '${e}' has no rules section. Skipping.`),!1)}createPlayerInitialUnits(){let e=this.playerList.getCombatants().map(e=>e.country);var i=[...this.rules.infantryRules.values(),...this.rules.vehicleRules.values()].filter(t=>t.allowedToStartInMultiplayer&&!t.naval&&-1!==t.techLevel&&t.techLevel<=this.rules.mpDialogSettings.techLevel&&!this.rules.general.baseUnit.includes(t.name)&&e.some(e=>t.isAvailableTo(e)&&t.hasOwner(e)));for(let h of this.playerList.getCombatants()){var l=this.map.startingLocations[h.startLocation],c=this.map.tiles.getByMapCoords(l.x,l.y);let t=this.rules.general.baseUnit.find(e=>{let t=this.rules.getObject(e,Bt.Vehicle);return t.isAvailableTo(h.country)&&t.hasOwner(h.country)});if(!t)throw new Error(`No suitable MCV found for player country ${h.country}`);l=this.rules.getObject(t,Bt.Vehicle),l=this.createUnitForPlayer(l,h);this.spawnObject(l,c);let e=Gl.generate(this.gameOpts.unitCount,[...this.rules.vehicleRules.keys()],i,h.country);this.gameModeType===St.Unholy&&e.push(...this.rules.general.baseUnit.filter(e=>e!==t).map(e=>({name:e,type:Bt.Vehicle,count:1})));var u,d,p;let r=[],s=!1,a=new Vn(this.map.tiles,this.map.mapBounds,c,4,4,e=>!this.map.getGroundObjectsOnTile(e).find(e=>!(e.isSmudge()||e.isOverlay()&&e.isTiberium()))&&0<this.map.terrain.getPassableSpeed(e,Jt.Foot,!1)),n=new Map,o=0;for({name:u,type:d,count:p}of e){let i=p;for(;0<i;){let t;if(s||(t=a.getNextTile(),t?r.push(t):s=!0),s&&r.length){var g=r[o];let e=n.get(g);e||(e=new Vn(this.map.tiles,this.map.mapBounds,g,1,0,e=>!this.map.getGroundObjectsOnTile(e).find(e=>!(e.isSmudge()||e.isOverlay()&&e.isTiberium()))&&0<this.map.terrain.getPassableSpeed(e,Jt.Foot,!1)),n.set(g,e)),o=(o+1)%r.length,t=e.getNextTile()}if(t){var m,f=this.rules.getObject(u,d);if(d===Bt.Vehicle){g=this.createUnitForPlayer(f,h);this.applyInitialVeteran(g,h),this.spawnObject(g,t),i--}else{if(d!==Bt.Infantry)throw new Error("Should not reach this line");for(m of ga.SUB_CELLS.slice(0,i)){let e=this.createUnitForPlayer(f,h);e.position.subCell=m,this.applyInitialVeteran(e,h),this.spawnObject(e,t),i--}}}else i--}}}}applyInitialVeteran(e,t){e.veteranTrait&&(this.rules.general.veteran.initialVeteran?e.veteranTrait.setVeteranLevel(ea.Elite):t.country.hasVeteranUnit(e.type,e.name)&&e.veteranTrait.setVeteranLevel(ea.Veteran))}createObject(e,t){return this.objectFactory.create(e,t,this.rules,this.art)}createUnitForPlayer(e,t){if(![Bt.Aircraft,Bt.Vehicle,Bt.Infantry].includes(e.type))throw new Error(`Attempted to create an invalid unit type "${e.type}"`);let i=this.createObject(e.type,e.name);return this.changeObjectOwner(i,t),i.purchaseValue=this.sellTrait.computePurchaseValue(i.rules,t),i}createProjectile(e,t,i,r,s){let a=this.createObject(Bt.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:Ga.computeSpeed(r,a),type:oi.Primary,warhead:new Wa(e)};let n=this.createObject(Bt.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 Fr(e,r,t,i)}createTarget(e,t){return new oo(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(dl).forEach(e=>{e[dl.onSpawn](t,this)}),this.events.dispatch(new Yl(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(pl).forEach(e=>{e[pl.onUnspawn](t,this)}),this.events.dispatch(new Xl(t))}destroyObject(t,i,e=!1,r=!1){if(t.isDestroyed)throw new Error(`Object with ID "${t.id}" is already destroyed`);if(t.isTechno()){let e=t.mindControllableTrait?.getOriginalOwner()??t.owner;!i||t.isBuilding()&&!e.isCombatant()||(i.player.kills++,i.player===e||this.alliances.areAllied(i.player,e)||(i.player.score+=t.rules.points)),e.isNeutral||e.unitsLost++}if(t.isDestroyed=!0,t.healthTrait&&(t.healthTrait.health=0),t.onDestroy(this,i,e),this.traits.filter(fl).forEach(e=>{e[fl.onDestroy](t,this,i)}),i?.obj?.traits.filter(vh).forEach(e=>{e[vh.onDestroy](i.obj,t,i.weapon,this)}),this.events.dispatch(new ql(t,i,r)),t.isBuilding()&&t.rules.leaveRubble&&t.deathType!==Us.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(pl).forEach(e=>{e[pl.onUnspawn](t,this)}),this.events.dispatch(new Xl(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(gl).forEach(e=>{e[gl.onChange](t,i,this)}),t.onOwnerChange(i,this),this.events.dispatch(new Ql(t,i)))}addObjectTrait(t,i){t.addTrait(i),this.traits.filter(Gc).forEach(e=>{e[Gc.onAdd](t,i,this)})}onAllianceChange(t,e,i){this.events.dispatch(new Hc(t,i?Rc.Formed:Rc.Broken,e)),this.traits.filter(ml).forEach(e=>{e[ml.onChange](t,i,this)})}update(){if(this.status!==$c.NotStarted){this.botManager.update(),this.status!==$c.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(Ar).forEach(e=>{e[Ar.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/Dr.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=$c.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(Bt.Building,!0)].some(e=>!e.rules.insignificant),e||t.getOwnedObjects(!0).some(e=>this.rules.general.baseUnit.includes(e.name))):t.getOwnedObjects(!0).some(e=>!e.rules.insignificant&&!e.limboData?.inTransport),i=!e}i&&(t.defeated=!0,this.removeAllPlayerAssets(t),this.events.dispatch(new Zl(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 Fd,jd,Wd,Ud,Vd,zd,Hd=__webpack_require__(949);class Gd{constructor(e){this.map=e,this.radSites=new Map,this.radLevelByTile=new Map,this._onChange=new Rn}get onChange(){return this._onChange.asEvent()}getRadLevel(e){return this.radLevelByTile.get(e)}[Ar.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 Wa(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===Nr.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 kr(this.map.tileOccupation),s=new Mr(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(Hd.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 $d{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 qd{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 Zd{constructor(){this.unitSelectionByPlayer=new Map}getOrCreateSelection(e){let t=this.unitSelectionByPlayer.get(e);return t||(t=new qd(e),this.unitSelectionByPlayer.set(e,t)),t}}class Qd extends Jl{constructor(){super(yl.NoAction)}process(){}}class Xd{create(){return new Qd}}class Yd{constructor(e){this.target=e,this.type=er.BuildingPlace}}class Kd{constructor(e,t,i){this.name=e,this.player=t,this.tile=i,this.type=er.BuildingFailedPlace}}(Fd=Fd||{}).onPlace=Symbol();class Jd extends Jl{constructor(e){super(yl.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(Fd).forEach(e=>{e[Fd.onPlace](i,this.game)}),this.game.events.dispatch(new Yd(i))):this.game.events.dispatch(new Kd(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===bn.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(Yi.BuildingType);return e&&(e.factoryTrait.status=qn.Delivering),s[0]}}}}}}class ep{constructor(e){this.game=e}create(){return new Jd(this.game)}}class tp extends Jl{constructor(e){super(yl.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!==Do.Ready||e.warpedOutTrait.isActive()||this.game.sellTrait.sell(e))}}}class ip{constructor(e){this.game=e}create(){return new tp(this.game)}}class rp extends Jl{constructor(e,t){super(yl.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 sp{constructor(e,t){this.game=e,this.orderActionContext=t}create(){return new rp(this.game,this.orderActionContext)}}const ap=[Ho.Occupy,Ho.Dock,Ho.Attack,Ho.Capture,Ho.Repair,Ho.EnterTransport,Ho.PlaceBomb,Ho.Deploy,Ho.Gather];(s=jd=jd||{})[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=Wd=Wd||{})[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 np{constructor(e){this.orderType=e,this.targetOptional=!0,this.minimapAllowed=!0,this.singleSelectionRequired=!1,this.terminal=!1,this.feedbackType=Wd.None}getPointerType(e,t){return e?jd.Mini:jd.Default}set(e,t){return this.sourceObject=e,this.target=t,this}isValid(){return!0}isAllowed(){return!0}onAdd(e,t){return!0}}class op{constructor(e,t){this.from=e,this.to=t,this.type=er.ObjectMorph}}class hp extends Ur{constructor(e){super(),this.game=e}onStart(e){if(!this.morphInto)throw new Error("morphInto not set");e.isBuilding()&&e.buildStatus!==Do.BuildDown&&this.morphInto.type!==Bt.Building&&this.children.push(new zl),e.isVehicle()&&this.morphInto.type===Bt.Building&&this.children.push(new os(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===Bt.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 Gs);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 op(r,a)),!0}}class lp extends hp{onStart(e){var t=e.rules.undeploysInto;if(!t)throw new Error(`Object type "${e.name}" doesn't undeploy into anything`);this.morphInto=this.game.rules.getObject(t,Bt.Vehicle),super.onStart(e)}}class cp{constructor(e){this.target=e,this.type=er.RallyPointChange}}class up extends np{constructor(e,t,i,r=!1){super(r?Ho.ForceMove:Ho.Move),this.game=e,this.map=t,this.unitSelection=i,this.forceMove=r,this.targetOptional=!1,this.feedbackType=Wd.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===ri.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,Jt.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?jd.MoveMini:jd.NoActionMini:t?jd.Move:jd.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 lp(this.game),new Gs(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t})]:e.isUnit()?[new Gs(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===Do.BuildUp)return this.sourceObject.unitOrderTrait.getTasks().find(e=>e instanceof Ao)?.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 cp(this.sourceObject)),!1;if(!e&&this.isValid()&&this.isAllowed()){this.sourceObject.attackTrait?.cancelOpportunityFire();let e=t.find(e=>e.constructor===Gs&&!e.isCancelling());if(e)return e.updateTarget(this.target.tile,!!this.target.getBridge()),e.children.length&&e.children[0]instanceof po&&e.children[0].cancel(),t.splice(t.indexOf(e)+1),this.sourceObject.unitOrderTrait.clearOrders(),!1;if(this.sourceObject.isUnit()&&this.sourceObject.rules.movementZone===ri.Fly){let e=t.find(e=>e.constructor===po&&!e.isCancelling());e&&e.forceCancel(this.sourceObject)&&t.splice(t.indexOf(e))}}return!0}}class dp extends hp{onStart(e){var t=e.rules.deploysInto;if(!t)throw new Error(`Object type "${e.name}" doesn't deploy into anything`);this.morphInto=this.game.rules.getObject(t,Bt.Building),super.onStart(e)}onTick(e){return!!this.isCancelling()||super.onTick(e)}}class pp{constructor(e,t){this.unit=e,this.deployType=t,this.type=er.UnitDeployUndeploy}}class gp{constructor(e){this.target=e,this.type=er.PrimaryFactoryChange}}(s=Ud=Ud||{})[s.None=0]="None",s[s.OnlyPassengers=1]="OnlyPassengers",s[s.All=2]="All";class mp extends Ur{constructor(e,t){super(),this.game=e,this.soft=t,this.evacState=Ud.None,this.evacTries=0,this.turnPerformed=!1,this.preventLanding=!1}forceEvac(){this.evacState=Ud.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!==Ud.OnlyPassengers&&1!==t.units.length||!e.rules.gunner?Ud.OnlyPassengers:Ud.All)}onTick(e){if(this.isCancelling()||this.evacState===Ud.None)return!0;if(e.zone===fr.Air)return this.children.push(new As(()=>e.zone!==fr.Air)),!1;let t=e.transportTrait.units;if(!t.length||e.rules.gunner&&1===t.length&&this.evacState!==Ud.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 os(s)),!1}return this.evacuateUnit(i,e,r)?(t.pop(),this.children.push(new Is(1/60)),!1):!(++this.evacTries<=3)||(this.children.push(new Is(.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 Gs(this.game,i.tile,!!i.onBridge)):e.unitOrderTrait.addTask(new js(this.game)),this.game.events.dispatch(new Xo(t)),!0}findValidEvacTarget(a,n){let o=this.game.map,h=new Hr(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=ns.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 fp extends np{constructor(e,t){super(t?Ho.Deploy:Ho.DeploySelected),this.game=e,this.targeted=t,this.minimapAllowed=!1,this.getPointerType=()=>this.isAllowed()?jd.Deploy:jd.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&&![Nr.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,Jt.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 mp(this.game,!0)]:e.isBuilding()&&e.rules.factory?void 0:e.isVehicle()&&e.rules.deploysInto?[new dp(this.game)]:(e.isInfantry()||e.isVehicle())&&e.deployerTrait?[new As(()=>{e.deployerTrait.toggleDeployed(),this.game.events.dispatch(new pp(e,e.deployerTrait.isDeployed()?"undeploy":"deploy"))})]:e.isBuilding()&&e.garrisonTrait?.units.length?[new As(()=>{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 gp(i)),!1;if(i.isVehicle()&&i.transportTrait&&!e&&this.isValid()&&this.isAllowed()){let e=t.find(e=>e.constructor===mp&&!e.isCancelling());if(e)return e.forceEvac(),!1}return!0}}class yp{constructor(e){this.player=e,this.type=er.Cheer}}class wp{constructor(e){this.target=e,this.type=er.DeployNotAllowed}}class Tp extends Jl{constructor(e,t,i,r){super(yl.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?"":`${Ho[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 up?t:e.orderType===Ho.Scatter?r:e.orderType===Ho.DeploySelected?i:e.orderType===Ho.Cheer?s:a).push(e)}),t.length&&this.target){let r=this.target.getBridge();var o=t.map(e=>e.sourceObject);let s=new Hr(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 Fs(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 yp(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 fp&&t.isValid()&&!t.isAllowed()&&this.game.events.dispatch(new wp(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 ap){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!==Ho.Deploy){let e=this.orderFactory.create(Ho.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(wa))];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 bp extends Gs{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 vp extends Gs{constructor(e,t){super(e,vp.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 Sp{constructor(e){this.target=e,this.type=er.BuildingGarrison}}class _p{constructor(e,t){this.target=e,this.source=t,this.type=er.EnterObject}}class kp extends Ur{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 bp(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 Sp(this.target))),this.game.events.dispatch(new _p(this.target,e)),t.units.push(e),!0):!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Op{constructor(e){this.target=e,this.type=er.UnitRecycle}}class Ip extends Ur{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ri.Fly&&e.rules.locomotor!==ii.Chrono&&0<this.game.sellTrait.computeRefundValue(e)&&this.target.rules.cloning&&!this.target.isDestroyed&&this.target.buildStatus===Do.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 bp(this.game,this.target)),!(this.aborted=!0)):(this.game.sellTrait.sell(e),this.game.events.dispatch(new Op(e)),this.game.events.dispatch(new _p(this.target,e)),!0):!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Ap{constructor(e,t){this.target=e,this.source=t,this.type=er.BuildingInfiltration}}class Cp extends Ur{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!==Do.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 bp(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.agentTrait?.infiltrate(e,this.target,this.game),this.game.events.dispatch(new Ap(this.target,e)),this.game.events.dispatch(new _p(this.target,e)),!0):!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}(s=Vd=Vd||{})[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 Bp extends Ur{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ri.Fly&&e.healthTrait.health<100&&this.target.hospitalTrait&&!this.target.isDestroyed&&!this.target.warpedOutTrait.isActive()&&this.game.areFriendly(e,this.target)&&(!this.target.ammoTrait||0<this.target.ammoTrait.ammo)}onStart(e){if(!this.target.hospitalTrait)throw new Error(`Target ${this.target.name} is not a valid hospital`);0<this.target.hospitalTrait.addToHealQueue(e)?this.state=Vd.MoveToQueueingTile:this.state=Vd.MoveToTarget}onEnd(e){!this.target.isDestroyed&&e.isSpawned&&this.target.hospitalTrait.removeFromHealQueue(e)}onTick(i){if(this.isCancelling()&&this.state!==Vd.EnterTarget||this.state===Vd.ClearTarget||i.moveTrait.isDisabled())return!0;if(this.state===Vd.MoveToQueueingTile){let t=new Hr(this.game.map);var e=new Mr(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 Gs(this.game,e,!1,{closeEnoughTiles:5})),this.children.push(new As(()=>{[Zs.Success,Zs.CloseEnough].includes(i.moveTrait.lastMoveResult)||this.cancel()})),this.state=Vd.WaitForTurn,this.queueingTile=e,!1)}if(this.state===Vd.WaitForTurn){if(!this.target.hospitalTrait.unitIsFirstInHealQueue(i))return!1;this.queueingTile=void 0,this.state=Vd.MoveToTarget}if(this.state===Vd.MoveToTarget){if(!this.isAllowed(i))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(i.tile,this.target))return!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),!(this.movePerformed=!0));this.state=Vd.EnterTarget}return this.state===Vd.EnterTarget&&(!this.isAllowed(i)||this.isCancelling()?(this.children.push(new bp(this.game,this.target)),this.state=Vd.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 _p(this.target,i)),!0))}getTargetLinesConfig(e){return{target:this.queueingTile?void 0:this.target,pathNodes:this.queueingTile?[{tile:this.queueingTile,onBridge:void 0}]:[]}}}class Ep extends np{constructor(e){super(Ho.Occupy),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Wd.Capture}getPointerType(e){return e?this.isAllowed()?jd.OccupyMini:jd.NoActionMini:this.isAllowed()?jd.Occupy:jd.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!==ri.Fly&&t.rules.locomotor!==ii.Chrono&&0<this.game.sellTrait.computeRefundValue(t):e.hospitalTrait?t.healthTrait.health<100&&t.rules.movementZone!==ri.Fly:!e.garrisonTrait||e.garrisonTrait.units.length<e.rules.maxNumberOccupants}process(){var e=this.target.obj,t=this.sourceObject;return this.isInfantryRecycle(t,e)?[new Ip(this.game,e)]:e.hospitalTrait?[new Bp(this.game,e)]:e.garrisonTrait?[new kp(this.game,e)]:[new Cp(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof kp||e instanceof Cp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new kr(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class xp extends Ur{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 vp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));if(!this.isAllowed(e)||this.isCancelling())return this.children.push(new bp(this.game,this.target)),!(this.aborted=!0);var t=Math.floor(60*this.game.rules.combatDamage.c4Delay*Dr.BASE_TICKS_PER_SECOND);return this.target.c4ChargeTrait.setCharge(t,{player:e.owner,obj:e}),this.game.events.dispatch(new _p(this.target,e)),this.children.push(new bp(this.game,this.target)),!(this.aborted=!0)}getTargetLinesConfig(e){return{target:this.target,pathNodes:[],isAttack:!0}}}class Pp extends np{constructor(e,{forceAttack:t,noIvanBomb:i}={}){super(t?Ho.ForceAttack:Ho.Attack),this.game=e,this.isC4=!1,this.forceAttack=!!t,this.ivanBombAllowed=!i||!!t,this.targetOptional=!1,this.feedbackType=Wd.None,this.rangeHelper=new kr(this.game.map.tileOccupation),this.losHelper=new ro(this.game.map.tiles,e.map.tileOccupation)}getPointerType(e,t){if(!this.isAllowed())return e?jd.NoActionMini:jd.NoAction;if(this.isC4)return jd.C4;var i=this.sourceObject.attackTrait?.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);if(i?.rules.sabotageCursor)return jd.C4;if(this.ivanBombAllowed&&this.sourceObject.rules.ivan&&i?.warhead.rules.ivanBomb)return jd.Dynamite;if(i?.warhead.rules.bombDisarm)return jd.DefuseBomb;if(i&&i.rules.damage<0)return jd.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?jd.AttackMini:t?jd.AttackRange:jd.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=Wd.SpecialAttack,!0;if(this.isC4=!1,this.feedbackType=Wd.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===fr.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===si.Wood))||e.isTechno())))))))}isAllowed(){return!this.sourceObject.attackTrait.isDisabled()}process(){if(this.isC4)return[new xp(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return[new po(this.game,this.target,e,{force:this.forceAttack})]}onAdd(t,e){let i=this.sourceObject;if(!e&&i.isUnit()&&this.isValid()&&this.isAllowed())if(i.rules.movementZone===ri.Fly){let e=t.find(e=>(e.constructor===Gs||e.constructor===po)&&!e.isCancelling());e&&(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor===po)&&e.forceCancel(i)&&t.splice(t.indexOf(e))}else{t.length&&i.isUnit()&&(i.rules.locomotor===ii.Vehicle||i.rules.locomotor===ii.Ship)&&(i.moveTrait.speedPenalty=.5);let e=t.find(e=>e.constructor===po&&!e.isCancelling());if(e?.getWeapon().warhead.rules.temporal)return e.setForceAttack(this.forceAttack),e.requestTargetUpdate(this.target),!1}return!0}}class Np extends np{constructor(e){super(Ho.Stop),this.game=e,this.getPointerType=()=>jd.NoAction}isValid(){return this.sourceObject.isTechno()}isAllowed(){return!0}process(){return[new As(e=>{!e.isUnit()||e.rules.locomotor!==ii.Vehicle&&e.rules.locomotor!==ii.Ship||(e.moveTrait.speedPenalty=0)})]}onAdd(e,t){let i=this.sourceObject;return t||!e.length||!i.isUnit()||i.rules.locomotor!==ii.Vehicle&&i.rules.locomotor!==ii.Ship||(i.moveTrait.speedPenalty=.5),i.isBuilding()&&i.rallyTrait?.getRallyPoint()&&(i.unitRepairTrait?.resetRallyPoint(i,this.game),i.factoryTrait?.resetRallyPoint(i,this.game)),!0}}class Rp extends np{constructor(){super(Ho.Cheer),this.getPointerType=()=>jd.NoAction}isValid(){return this.sourceObject.isInfantry()&&[Nr.None,Nr.Guard].includes(this.sourceObject.stance)}isAllowed(){return!0}process(){return[new eu]}}class Dp extends np{constructor(e){super(Ho.Dock),this.game=e,this.targetOptional=!1,this.feedbackType=Wd.Move}getPointerType(e){return e?this.isAllowed()?jd.OccupyMini:jd.NoActionMini:this.isAllowed()?jd.Occupy:jd.NoOccupy}isValid(){if(!this.target.obj?.isBuilding()||this.target.obj.isDestroyed||!this.target.obj.dockTrait||this.target.obj.buildStatus!==Do.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 Zo(this.game,e,!0,!0)]:e.unitRepairTrait||this.sourceObject.rules.dock.includes(e.name)?[new Es(this.game,e)]:[]}}class Mp extends np{constructor(e){super(Ho.Gather),this.game=e,this.targetOptional=!1,this.feedbackType=Wd.Move}getPointerType(e){return e?jd.AttackMini:jd.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 Vo(this.game,this.target.tile,!0)]}}class Lp extends Gs{constructor(){super(...arguments),this.attackPerformed=!1,this.passedFirstWaypoint=!1}onTick(i){if(i.moveTrait.moveState===qs.Moving&&(this.passedFirstWaypoint=!0),i.moveTrait.moveState===qs.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=Qs.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=Qs.Resolved,this.updateTarget(this.targetTile,this.toBridge)}}return super.onTick(i)}}class Fp extends np{constructor(e,t){super(Ho.AttackMove),this.game=e,this.map=t,this.targetOptional=!1,this.feedbackType=Wd.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===ri.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?jd.AttackMini:jd.NoActionMini:t?jd.AttackMove:jd.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 Lp(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})]}}class jp{constructor(e,t){this.target=e,this.source=t,this.type=er.BuildingRepairFull}}class Wp{constructor(e,t){this.source=e,this.tile=t,this.type=er.BridgeRepair}}class Up extends Ur{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 bp(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 Wp(e.owner,this.target.centerTile))):(this.target.healthTrait.healToFull(e,this.game),this.game.events.dispatch(new jp(this.target,e.owner))),this.game.events.dispatch(new _p(this.target,e)),!0):!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Vp extends np{constructor(e){super(Ho.Repair),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Wd.Capture}getPointerType(e){return e?this.isAllowed()?jd.OccupyMini:jd.NoActionMini:this.isAllowed()?jd.RepairMove:jd.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 Up(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Up);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new kr(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class zp extends np{constructor(e,t){super(t?Ho.GuardArea:Ho.Guard),this.game=e,this.targeted=t,this.getPointerType=e=>e?this.isAllowed()?jd.GuardMini:jd.NoActionMini:this.isAllowed()?jd.Guard:jd.NoMove,this.terminal=!0,this.targetOptional=!t,this.minimapAllowed=t,this.feedbackType=t?Wd.Move:Wd.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 As(()=>e.harvesterTrait.lastOreSite=void 0),new Vo(this.game,void 0,!0)];let i=[];return t&&i.push(new Gs(this.game,t,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})),i.push(new As(e=>{t&&![Zs.Success,Zs.CloseEnough].includes(this.sourceObject.moveTrait?.lastMoveResult)||(this.sourceObject.guardMode=!0)})),i}}class Hp extends np{constructor(e){super(Ho.Scatter),this.game=e,this.getPointerType=()=>jd.NoAction}isValid(){return(this.sourceObject.isInfantry()||this.sourceObject.isVehicle())&&this.sourceObject.rules.movementZone!==ri.Fly&&!this.sourceObject.moveTrait.isDisabled()}isAllowed(){return!0}process(){if(!this.target)throw new Error("Target should be set for executing a scatter order. See OrderUnitsAction.");return[new js(this.game,{tile:this.target.tile,toBridge:!!this.target.getBridge()})]}}class Gp{constructor(e){this.target=e,this.type=er.EnterTransport}}(s=zd=zd||{})[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 $p extends Ur{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!==fr.Air&&this.target.zone!==fr.Air&&this.target.transportTrait.unitFitsInside(e)&&this.target.moveTrait.moveState===qs.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=zd.MoveToQueueingTile:this.state=zd.MoveToTransport}onEnd(e){this.target.isDestroyed||this.target.transportTrait?.removeFromLoadQueue(e)}onTick(n){if(this.isCancelling()&&this.state!==zd.EnterTransport||this.state===zd.ClearTransport||n.moveTrait.isDisabled())return!0;if(this.target.tile!==this.initialTargetTile||this.target.moveTrait.moveState!==qs.Idle)return!0;if(this.state===zd.MoveToQueueingTile){let r=new Hr(this.game.map),s=this.target.onBridge?this.game.map.tileOccupation.getBridgeOnTile(this.target.tile):void 0,a;var e=new Mr(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 Gs(this.game,e,!!a,{closeEnoughTiles:5})),this.children.push(new As(()=>{[Zs.Success,Zs.CloseEnough].includes(n.moveTrait.lastMoveResult)||this.cancel()})),this.queueingNode={tile:e,onBridge:a},this.state=zd.WaitForTurn,!1)}if(this.state===zd.WaitForTurn){if(!this.target.transportTrait.unitIsFirstInLoadQueue(n))return!1;this.queueingNode=void 0,this.state=zd.MoveToTransport}if(this.state===zd.MoveToTransport){if(!this.isAllowed(n))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(n.tile,this.target))return!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));this.state=zd.EnterTransport}return this.state===zd.EnterTransport&&(!this.isAllowed(n)||this.isCancelling()?(this.children.push(new bp(this.game,this.target)),this.state=zd.ClearTransport,!1):(this.game.limboObject(n,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(n).getControlGroupNumber(),inTransport:!0}),this.game.events.dispatch(new Gp(this.target)),this.game.events.dispatch(new _p(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 qp extends np{constructor(e){super(Ho.EnterTransport),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Wd.Enter}getPointerType(e){return e?this.isAllowed()?jd.OccupyMini:jd.NoActionMini:this.isAllowed()?jd.Occupy:jd.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!==fr.Air&&e.zone!==fr.Air&&e.transportTrait.unitFitsInside(t)&&e.moveTrait.moveState===qs.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 $p(this.game,t)]:[new As(()=>{t.unitOrderTrait.addTask(new Gs(this.game,e.tile,e.onBridge)),t.unitOrderTrait.addTask(new As(()=>{this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)&&e.unitOrderTrait.addTask(new $p(this.game,t))}))})]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof $p);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new kr(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Zp{constructor(e){this.target=e,this.type=er.BuildingCapture}}class Qp extends Ur{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!==Do.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 bp(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Zp(this.target)),this.game.events.dispatch(new _p(this.target,e)),!0):!!this.movePerformed||(this.children.push(new vp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Xp extends np{constructor(e){super(Ho.Capture),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Wd.Capture}getPointerType(e){return e?this.isAllowed()?jd.OccupyMini:jd.NoActionMini:this.isAllowed()?jd.Occupy:jd.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 kr(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Yp{constructor(e,t){this.game=e,this.map=t}create(e,t){switch(e){case Ho.Deploy:return new fp(this.game,!0);case Ho.DeploySelected:return new fp(this.game,!1);case Ho.ForceMove:return new up(this.game,this.map,t,!0);case Ho.Move:return new up(this.game,this.map,t);case Ho.ForceAttack:return new Pp(this.game,{forceAttack:!0});case Ho.Attack:return new Pp(this.game,{noIvanBomb:!0});case Ho.PlaceBomb:return new Pp(this.game);case Ho.AttackMove:return new Fp(this.game,this.map);case Ho.Capture:return new Xp(this.game);case Ho.Occupy:return new Ep(this.game);case Ho.Stop:return new Np(this.game);case Ho.Cheer:return new Rp;case Ho.Dock:return new Dp(this.game);case Ho.Gather:return new Mp(this.game);case Ho.Repair:return new Vp(this.game);case Ho.Guard:return new zp(this.game,!1);case Ho.GuardArea:return new zp(this.game,!0);case Ho.Scatter:return new Hp(this.game);case Ho.EnterTransport:return new qp(this.game);default:throw new Error(`Unhandled order type ${Ho[e]}`)}}}class Kp{constructor(e,t,i){this.game=e,this.map=t,this.orderActionContext=i}create(){return new Tp(this.game,this.map,this.orderActionContext,new Yp(this.game,this.map))}}class Jp{constructor(e){this.game=e}create(){return new ec(this.game)}}class eg{constructor(e){this.target=e,this.type=er.PlayerResigned}}class tg extends Jl{constructor(e,t){super(yl.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 eg(e)))}}}class ig{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new tg(this.game,this.localPlayerName)}}class rg{constructor(e){this.target=e,this.type=er.BuildingRepairStart}}class sg extends Jl{constructor(e){super(yl.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(Eh);e.setDisabled(!e.isDisabled()),e.isDisabled()||this.game.events.dispatch(new rg(t))}}}}class ag{constructor(e){this.game=e}create(){return new sg(this.game)}}class ng extends Jl{constructor(e){super(yl.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===cl.Formed?e||(s.breakAlliance(i,r),this.game.onAllianceChange(t,i,!1)):t.status===cl.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 Hc(t,Rc.Broken,i)),this.game.traits.filter(ml).forEach(e=>{e[ml.onChange](t,!1,this.game)}))):e&&s.canFormAlliance(i,r)&&((e=s.request(i,r))&&this.game.events.dispatch(new Hc(e,Rc.Requested,i)))}}}}class og{constructor(e){this.game=e}create(){return new ng(this.game)}}class hg extends Jl{constructor(e){super(yl.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 ${Ji[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(sn).activateSuperWeapon(this.superWeaponType,t,this.game,i,e)):console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class lg{constructor(e){this.game=e}create(){return new hg(this.game)}}class cg{constructor(e,t){this.tile=e,this.player=t,this.type=er.PingLocation}}class ug extends Jl{constructor(e){super(yl.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 cg(t,e));for(var i of[e,...this.game.alliances.getAllies(e)])this.game.events.dispatch(new Fl(i,Qt.GenericNonCombat,t))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class dg{constructor(e){this.game=e}create(){return new ug(this.game)}}class pg extends Jl{constructor(e){super(yl.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 eg(e)),this.game.events.dispatch(new Zl(e)),this.game.mapShroudTrait.getPlayerShroud(e)?.revealAll(),t=e.radarTrait.isDisabled(),e.radarTrait.setDisabled(!1),t&&this.game.events.dispatch(new Ll(e,!0)))}}class gg{constructor(e){this.game=e}create(){return new pg(this.game)}}class mg{register(e,t,i){var r=new Zd;e.registerFactory(yl.NoAction,new Xd),e.registerFactory(yl.PlaceBuilding,new ep(t)),e.registerFactory(yl.SellBuilding,new ip(t)),e.registerFactory(yl.ToggleRepair,new ag(t)),e.registerFactory(yl.SelectUnits,new sp(t,r)),e.registerFactory(yl.OrderUnits,new Kp(t,t.map,r)),e.registerFactory(yl.UpdateQueue,new Jp(t)),e.registerFactory(yl.ToggleAlliance,new og(t)),e.registerFactory(yl.ActivateSuperWeapon,new lg(t)),e.registerFactory(yl.PingLocation,new dg(t)),e.registerFactory(yl.QuitGame,new ig(t,i)),e.registerFactory(yl.ObserveGame,new gg(t))}}var fg=__webpack_require__(949);class yg{constructor(){this.detectors=new Set}[dl.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.detect(e,t)}[pl.onUnspawn](e,t){e.isTechno()&&(this.isGlobalDetector(e)&&(this.detectors.delete(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.undetect(e,t))}[gl.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isDisguisable(e)&&(this.undetect(e,i),this.detect(e,i))}[Vs.onTileChange](e,t,i){this.isGlobalDetector(e)&&(this.updateAroundDetector(e,t,i),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&(this.undetect(e,t),this.detect(e,t))}[xr.onPowerLow](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait&&!e.poweredTrait.isPoweredOn());this.updateAroundDetectors(i,e)}[xr.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[xr.onPowerChange](e,t){}updateAroundDetectors(e,t){let i=new Set;for(var r of e)for(var s of this.findTechnosAroundDetector(r,t,r.tile))i.add(s);for(var a of i)this.isDisguisable(a)&&(this.undetect(a,t),this.detect(a,t))}updateAroundDetector(e,t,i=e.tile){var r;for(r of this.findTechnosAroundDetector(e,t,i))this.isDisguisable(r)&&(this.undetect(r,t),this.detect(r,t))}findTechnosAroundDetector(e,t,i){var r=e.getFoundation(),r=Math.max(r.width,r.height),e=e.rules.detectDisguiseRange+r,r=new fg.Vector2(i.rx,i.ry).addScalar(-e),e=new fg.Vector2(i.rx,i.ry).addScalar(e);return t.map.technosByTile.queryRange(new fg.Box2(r,e))}detect(e,t){let i=new Set,r=new kr(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 wg=__webpack_require__(949);class Tg{constructor(){this.detectors=new Set}[dl.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isCloakable(e)&&this.detect(e,t)}[pl.onUnspawn](e,t){e.isTechno()&&this.isGlobalDetector(e)&&this.detectors.delete(e)}[gl.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isCloakable(e)&&this.detect(e,i)}[Vs.onTileChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,t),this.isCloakable(e)&&this.detect(e,t)}[Gc.onAdd](e,t,i){e.isTechno()&&(t instanceof nn?this.isCloakable(e)&&this.detect(e,i):t instanceof Rh&&this.isGlobalDetector(e)&&this.updateAroundDetector(e,i))}[xr.onPowerLow](e,t){}[xr.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[xr.onPowerChange](e,t){}[Ar.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 wg.Vector2(e.tile.rx,e.tile.ry).addScalar(-i),i=new wg.Vector2(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new wg.Box2(r,i))}detect(e,t){let i=new kr(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(jl).addEventForPlayer(Qt.GenericNonCombat,a,e.tile,t);break}}}isGlobalDetector(e){return!(!e.isTechno()||!e.sensorsTrait&&!e.rules.sensorArray||!e.rules.sensorsSight)}isCloakable(e){return e.isTechno()&&!!e.cloakableTrait}}class bg{constructor(){this.type=er.StalemateDetect}}class vg{constructor(){this.stale=!1,this.allPlayersCredits=new Map,this.resetCountdown()}isStale(){return this.stale}getCountdownTicks(){return this.countdownTicks}resetCountdown(){this.countdownTicks=Math.floor(60*vg.graceMinutes*Dr.BASE_TICKS_PER_SECOND)}clearStale(){this.stale=!1,this.resetCountdown()}[Ar.onTick](e){0<this.countdownTicks?this.countdownTicks--:this.stale||(this.stale=!0,this.resetCountdown(),e.events.dispatch(new bg));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())}}[Wn.onProduce](){this.clearStale()}[Fd.onPlace](e){e.wallTrait||this.clearStale()}[fl.onDestroy](e,t,i){!e.isBuilding()||e.owner.isNeutral||e.wallTrait||e.rules.insignificant||i?.obj&&t.areFriendly(e,i.obj)||this.clearStale()}[gl.onChange](e,t,i){e.isBuilding()&&!t.isNeutral&&(i.alliances.areAllied(e.owner,t)||this.clearStale())}}vg.graceMinutes=5;var Sg,_g,kg=__webpack_require__(949);class Og{constructor(e){this.prng=e}static factory(e,t){return new this(new Zc(Number(e+""+t)))}generateColors(e){let t=[...e.humanPlayers,...e.aiPlayers].filter(wa),i=t.map(e=>e.colorId).filter(e=>-2!==e);e=gn.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(wa),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(wa),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 kg.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 kg.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 Ig{constructor(e,t){this.mapLighting=new wi,this._onChange=new Rn,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}[Ar.onTick](){var e;void 0!==this.targetAmbient&&(this.ambientUpdateTicks??(this.ambientUpdateTicks=Math.floor(60*Dr.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 Ag{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*Dr.BASE_TICKS_PER_SECOND)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}getTurnMillis(){return this.gameTurnMillis}doGameTurn(){if(!this.errorState){if(this.game.status!==$c.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=Sg=Sg||{})[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 Cg{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 Bg{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 Eg{serializeOptions(e){let t=e.gameMode,i=(new Cg).encode(e.mapTitle),r=(new Bg).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,Number(e.hostTeams),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===Sg.Closed)return"@Closed@";if(e.type===Sg.Open)return"@Open@";if(e.type===Sg.OpenObserver)return"@OpenObserver@";if(e.type===Sg.Ai){if(e.difficulty===br.Easy)return"@EasyAI@";if(e.difficulty===br.Medium)return"@MediumAI@";if(e.difficulty===br.Brutal)return"@HardAI@"}else if(e.type===Sg.Player)return e.name;throw new Error(`Unexpected slot info with type ${Sg[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 xg{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()),i.hostTeams=Boolean(Number(a.shift())),i.mapTitle=(new Cg).decode(a.shift()),i.maxSlots=Number(a.shift()),i.mapOfficial=Boolean(Number(a.shift())),i.mapSizeBytes=Number(a.shift()),i.mapName=(new Bg).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=Sg.Closed;else if("@Open@"===i)t.type=Sg.Open;else if("@OpenObserver@"===i)t.type=Sg.OpenObserver;else if(-1!==["@EasyAI@","@MediumAI@","@HardAI@"].indexOf(i)){t.type=Sg.Ai;let e;if("@EasyAI@"===i)e=br.Easy;else if("@MediumAI@"===i)e=br.Medium;else{if("@HardAI@"!==i)throw new Error(`Couldn't parse gameopt: unknown slot type ${i}`);e=br.Brutal}t.difficulty=e}else t.type=Sg.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 Pg{constructor(e,t){this.type=e,this.tickNo=t}}(s=_g=_g||{})[s.TurnActions=0]="TurnActions",s[s.ChatMessage=1]="ChatMessage",s[s.Taunt=2]="Taunt";class Ng extends Pg{constructor(e){super(_g.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 Rg extends Pg{constructor(e){super(_g.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 Dg extends Pg{constructor(e,t,i){super(_g.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 Mg{constructor(e,t){this.gameOptsParser=e,this.gameOptsSerializer=t}create(e,t){switch(e){case _g.TurnActions:return new Dg(this.gameOptsParser,this.gameOptsSerializer,t);case _g.ChatMessage:return new Ng(t);case _g.Taunt:return new Rg(t);default:throw new Error(`Unsupported replay event type "${e}" at game tick "${t}"`)}}}const Lg=[3,4];class Fg{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=Fg.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 Eg,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(Fg.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(!Lg.includes(r))throw new Error("Unsupported replay version");let s=new xg,a=i.shift();if(!a||!a.match(Fg.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 Mg(s,new Eg).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"}}Fg.extension=".rpl",Fg.maxNameLength=128,Fg.engineLineRegex=/^ENGINE \d+\.\d+( \d+)?$/;class jg{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 Dg(new xg,new Eg,t);e.payload=[[this.playerId,i.map(e=>this.actionSerializer.getActionPayload(e))]],this.replay.writeEvent(e)}else if(this.hasActualActions(i)){let e=new Dg(new xg,new Eg,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 Ng(e);r.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),message:i},this.replay.writeEvent(r)}recordTaunt(e,t,i){let r=new Rg(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!==yl.NoAction))}}class Wg{getActionPayload(e){return{id:e.actionType,params:e.serialize()}}}class Ug{constructor(e,t){this.options=e,this.logger=t,this.timeout=5,this._onMessage=new Rn,this._onError=new Rn,this._onClose=new Rn}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 Ug.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 Ug.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 Ug.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 Ug.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 Ug.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}}Ug.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}(Ug=Ug||{});class Vg extends Error{constructor(e,t){super(e),this.code=t}}(s=(s=Vg=Vg||{}).Code||(s.Code={}))[s.InstanceNonExistent=0]="InstanceNonExistent",s[s.InstanceAlreadyExists=1]="InstanceAlreadyExists";var zg;(s=zg=zg||{})[s.Public=0]="Public",s[s.Private=1]="Private",s[s.Page=2]="Page";class Hg{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 Rn,this._onActionsSent=new Rn,this._onActionsProcessed=new Rn,this._onActionsReceived=new Rn,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*Dr.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(Hg.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!==$c.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===yl.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)}}Hg.PREFERRED_HASH_CHECK_MILLIS=1e3;const Gg=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");class $g{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=Gg.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 qg=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");var Zg,Qg,Xg,Yg,Kg,Jg,em,tm,im=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},rm=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 sm{constructor(e,t,i,r,s,a,n,o){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.set(this,void 0),tm.set(this,void 0),im(this,Zg,e,"f"),im(this,Qg,t,"f"),im(this,Xg,new xc(t,!1),"f"),im(this,Yg,new pc(t.events),"f"),im(this,Kg,i,"f"),im(this,Jg,a,"f"),im(this,em,n,"f"),im(this,tm,o,"f"),rm(this,Yg,"f").subscribe(t=>e.forEach(e=>e.onGameEvent(t,rm(this,Xg,"f")))),e.forEach(e=>{e.setGameApi(rm(this,Xg,"f")),e.setActionsApi(new rc(t,r,s,e.name)),e.setProductionApi(new Uc(t.getPlayerByName(e.name).production)),e.onGameStart(rm(this,Xg,"f"))})}isFinished(){return rm(this,Qg,"f").status===$c.Ended||rm(this,Jg,"f").getErrorState()}async update(){if(rm(this,em,"f"))await rm(this,em,"f").waitForTick();else{if(!(rm(this,Jg,"f")instanceof Ag))throw new Error("Missing animation loop or turn manager");rm(this,Jg,"f").doGameTurn()}rm(this,Zg,"f").forEach(e=>e.onGameTick(rm(this,Xg,"f")))}getCurrentTick(){return rm(this,Xg,"f").getCurrentTick()}getTickRate(){return rm(this,Xg,"f").getTickRate()}getPlayerStats(){return rm(this,Qg,"f").getNonNeutralPlayers().filter(e=>!e.isObserver).map(t=>({name:t.name,country:t.country,ai:t.isAi||rm(this,Zg,"f").some(e=>e.name===t.name),defeated:t.defeated,credits:t.credits,startLocation:t.startLocation}))}saveReplay(e){let t=rm(this,Kg,"f");t.finish(rm(this,Qg,"f").currentTick);var i=`${rm(this,Qg,"f").gameOpts.mapName}_${Date.now()}${Fg.extension}`,r=t.serialize(),i=a.resolve(e??process.cwd(),i);qg.writeFileSync(i,r,"utf-8"),process.stdout.write(`Replay saved to "${i}"\n`)}dispose(){rm(this,Yg,"f").dispose(),rm(this,Zg,"f").length=0,rm(this,tm,"f")?.call(this)}}Zg=new WeakMap,Qg=new WeakMap,Xg=new WeakMap,Yg=new WeakMap,Kg=new WeakMap,Jg=new WeakMap,em=new WeakMap,tm=new WeakMap;var am,nm,om,hm,lm,cm,um,dm,pm,gm,mm,fm,ym=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)},wm=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 Tm=a.resolve((0,e.default)(),"./res");class bm{constructor(){am.add(this),nm.set(this,void 0),om.set(this,void 0),hm.set(this,void 0),lm.set(this,void 0),cm.set(this,!1),um.set(this,void 0)}async init(e){ym(this,am,"m",dm).call(this);var t=await(0,n.getOriginPrivateDirectory)(o.default,a.resolve(e)),i=await(0,n.getOriginPrivateDirectory)(o.default,Tm),e=await(0,n.getOriginPrivateDirectory)(o.default,process.cwd());Pt.initGameResSource(vt.Local);let r=await Pt.initRfs(t);r.addDirectoryHandle(i),r.addDirectoryHandle(e);let s=await Pt.initVfs(r,is.get("vfs"));await s.loadStandaloneFiles(),await s.loadExtraMixFiles(Pt.getActiveEngine()),await s.addMixFile("ra2cd.mix"),await s.loadImplicitMixFiles(Pt.getActiveEngine()),Pt.loadRules(),wm(this,um,await Pt.loadMapList(),"f"),wm(this,nm,Pt.getMpModes(),"f"),wm(this,cm,!0,"f")}getAvailableMaps(){if(!ym(this,cm,"f"))throw new Error("API is not initialized. Call init() first.");return ym(this,um,"f").getAll().map(e=>e.fileName.toLowerCase())}getAvailableGameModes(e){if(!ym(this,cm,"f"))throw new Error("API is not initialized. Call init() first.");let t=ym(this,um,"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?ym(this,am,"m",gm):ym(this,am,"m",pm)).call(this,e)}}nm=new WeakMap,om=new WeakMap,hm=new WeakMap,lm=new WeakMap,cm=new WeakMap,um=new WeakMap,am=new WeakSet,dm=function(){is.useDefaults(),is.setLevel(is.ERROR);const e=process.env.DEBUG_LOGGING;var t;if(e)if(isNaN(e))for(t of e.split(","))is.get(t).setLevel(is.DEBUG);else is.setLevel(Boolean(Number(e))?is.DEBUG:is.ERROR);wm(this,om,is.get("ini"),"f"),wm(this,hm,is.get("action"),"f"),wm(this,lm,is.get("net"),"f")},pm=async function(e){if(!ym(this,cm,"f"))throw new Error("API is not initialized. Call init() first.");var t=ym(this,am,"m",fm).call(this,e),i=e.agents.filter(e=>e instanceof Vc),r=new Si(Pt.vfs.openFile(t.mapName)),s=await ym(this,am,"m",mm).call(this,0,0,t,r,void 0),a=new Kl,e=new $d;(new mg).register(e,s,void 0);let n=new Fg;n.init(s.id,s.startTimestamp,t,Pt.getVersion(),Pt.getModHash());r=new Wg,t=new jg(n,0,s.gameOpts.humanPlayers,r);let o=new Ag(s,a,t,r,e,ym(this,hm,"f"));return o.init(),new sm(i,s,n,e,a,o)},gm=async function(e){if(!ym(this,cm,"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 Vc&&t.push(i)}if(!(e.agents[0]instanceof Vc))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 Vc))throw new Error("Only the first player in the agents array can be a bot in online mode");var r=ym(this,am,"m",fm).call(this,e);let s=class{constructor(e){this._onLoadInfo=new Rn,this._onGameStart=new Rn,this._onGameActions=new Rn,this._onGameDesync=new Rn,this._onRateChange=new Rn,this._onChatMessage=new Rn,this._onTaunt=new Rn,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 Ug({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 Vg(`Create error: ${s}`,Vg.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 Vg(`Join error: ${i}`,Vg.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 Eg).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 xg).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:zg.Public,from:i,text:t}:e===this.currentUser&&(r={type:zg.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:zg.Page};this._onChatMessage.dispatch(this,e)}}.factory(ym(this,lm,"f"));await s.connect(e.serverUrl),await s.login(e.agents[0].name);let a=new Eg;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 xg;var c=l.parseOptions(await s.gameOpts());let u=Pt.vfs.openFile(r.mapName);var d=new Si(u);r.mapOfficial||s.sendMap(u.readAsString());n=e.agents[0].name;let p=await ym(this,am,"m",mm).call(this,h,0,c,d,n);r=new Wg,h=new Kl,d=new $d;(new mg).register(d,p,n);let g=new Fg;g.init(p.id,p.startTimestamp,c,Pt.getVersion(),Pt.getModHash());var m,c=new jg(g,0,p.gameOpts.humanPlayers,r);let f=new Hg(p,s,l,a,r,d,h,()=>{console.error("Desync detected."),process.exit(1)},ym(this,hm,"f"),void 0,c,!1);f.init();let y=new $g(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 sm(t,p,g,d,h,f,y,()=>{y.destroy(),ym(this,lm,"f").setLevel(is.OFF),s.close()})},mm=async function(e,t,i,r,s){if(!ym(this,cm,"f"))throw new Error("API is not initialized. Call init() first.");var a=Pt.getIni(ym(this,nm,"f").getById(i.gameMode).rulesOverride);await Pt.loadTheater(r.theaterType);var n=Pt.getActiveEngine(),o=Pt.getTheaterSettings(n,r.theaterType),n=Pt.getTheaterIni(n,r.theaterType);let h=new X(n);h.loadTileData(Pt.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 mn(d,c);var g=new _n(p,r,c);p.applySpecialFlags(e.specialFlags),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 mn(i),f=m.getMultiplayerCountries(),y=[...m.getMultiplayerColors().values()],w=new bl(e,t,p);s=new Xh,d=h.getById(o.gameMode).type,r=new _l,c=new Sl(r),i=new Ol,e=new Il(1),t=new Qh(w.tiles,w.tileOccupation,w.bridges,e),h=new $d;let T=new Ld(s,w,p,g,a,n,o,d,r,i,c,e,t,h);(new mg).register(h,T,void 0),T.traits.add(new Rl),T.sellTrait=new Ml(T,p.general),T.traits.add(T.sellTrait),T.traits.add(new jl);let b=new Ul(p,u);T.traits.add(b),T.mapShroudTrait=new Vl(w,c),T.traits.add(T.mapShroudTrait),T.mapRadiationTrait=new Gd(w),T.traits.add(T.mapRadiationTrait),T.mapLightingTrait=new Ig(p.audioVisual,w.getLighting()),T.traits.add(T.mapLightingTrait),T.traits.add(new sn),T.traits.add(new yg),T.traits.add(new Tg),T.crateGeneratorTrait=new dn(o.cratesAppear),T.traits.add(T.crateGeneratorTrait),l||(T.stalemateDetectTrait=new vg,T.traits.add(T.stalemateDetectTrait));let v=new Nl(p,o,b.getAvailableObjects()),S=Og.factory(a,n),_=S.generateColors(o),k=S.generateCountries(o,m),O=S.generateStartLocations(o,w.startingLocations),I=[...o.humanPlayers,...o.aiPlayers].filter(wa);return I.forEach(e=>{let t,i,r;if(Or(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=kn.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,Pt.getRules(),Pt.getArt(),a,e,t,i,ym(this,nm,"f"),!1,ym(this,om,"f"),new Il(!1));return wr.init({x:0,y:l.map.mapBounds.getFullSize().width*wr.getWorldTileSize()/2}),l.init(s?l.getPlayerByName(s):void 0),l.start(),l},fm=function(t){let e=ym(this,um,"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 mn(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,mapOfficial:e.official}};class vm{}const Sm=new bm})();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};
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:()=>s});const s=function(){"use strict";var i=new function(){this.blockSize=131072,this.minNewSize=this.blockSize,this.maxSize=0,this.OK=0,this.INPUT_OVERRUN=-4,this.OUTPUT_OVERRUN=-5,this.LOOKBEHIND_OVERRUN=-6,this.EOF_FOUND=-999,this.ret=0,this.buf=null,this.buf32=null,this.out=new Uint8Array(262144),this.cbl=0,this.ip_end=0,this.op_end=0,this.t=0,this.ip=0,this.op=0,this.m_pos=0,this.m_len=0,this.m_off=0,this.dv_hi=0,this.dv_lo=0,this.dindex=0,this.ii=0,this.jj=0,this.tt=0,this.v=0,this.dict=new Uint32Array(16384),this.emptyDict=new Uint32Array(16384),this.skipToFirstLiteralFun=!1,this.returnNewBuffers=!0,this.setBlockSize=function(e){return"number"==typeof e&&!isNaN(e)&&0<parseInt(e)&&(this.blockSize=parseInt(e),!0)},this.setOutputSize=function(e){return"number"==typeof e&&!isNaN(e)&&0<parseInt(e)&&(this.out=new Uint8Array(parseInt(e)),!0)},this.setReturnNewBuffers=function(e){this.returnNewBuffers=!!e},this.applyConfig=function(e){void 0!==e&&(void 0!==e.outputSize&&i.setOutputSize(e.outputSize),void 0!==e.blockSize&&i.setBlockSize(e.blockSize))},this.ctzl=function(e){var t;return 1&e?t=0:(t=1,0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),t-=1&e),t},this.extendBuffer=function(){var e=new Uint8Array(this.minNewSize+(this.blockSize-this.minNewSize%this.blockSize));e.set(this.out),this.out=e,this.cbl=this.out.length},this.match_next=function(){this.minNewSize=this.op+3,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.buf[this.ip++],1<this.t&&(this.out[this.op++]=this.buf[this.ip++],2<this.t&&(this.out[this.op++]=this.buf[this.ip++])),this.t=this.buf[this.ip++]},this.match_done=function(){return this.t=3&this.buf[this.ip-2],this.t},this.copy_match=function(){for(this.t+=2,this.minNewSize=this.op+this.t,this.minNewSize>this.cbl&&this.extendBuffer();this.out[this.op++]=this.out[this.m_pos++],0<--this.t;);},this.copy_from_buf=function(){for(this.minNewSize=this.op+this.t,this.minNewSize>this.cbl&&this.extendBuffer();this.out[this.op++]=this.buf[this.ip++],0<--this.t;);},this.match=function(){for(;;){if(64<=this.t)this.m_pos=this.op-1-(this.t>>2&7)-(this.buf[this.ip++]<<3),this.t=(this.t>>5)-1,this.copy_match();else if(32<=this.t){if(this.t&=31,0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=31+this.buf[this.ip++]}this.m_pos=this.op-1-(this.buf[this.ip]>>2)-(this.buf[this.ip+1]<<6),this.ip+=2,this.copy_match()}else if(16<=this.t){if(this.m_pos=this.op-((8&this.t)<<11),this.t&=7,0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=7+this.buf[this.ip++]}if(this.m_pos-=(this.buf[this.ip]>>2)+(this.buf[this.ip+1]<<6),this.ip+=2,this.m_pos===this.op)return this.state.outputBuffer=!0===this.returnNewBuffers?new Uint8Array(this.out.subarray(0,this.op)):this.out.subarray(0,this.op),this.EOF_FOUND;this.m_pos-=16384,this.copy_match()}else this.m_pos=this.op-1-(this.t>>2)-(this.buf[this.ip++]<<2),this.minNewSize=this.op+2,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos];if(0===this.match_done())return this.OK;this.match_next()}},this.decompress=function(e){if(this.state=e,this.buf=this.state.inputBuffer,this.cbl=this.out.length,this.ip_end=this.buf.length,this.t=0,this.ip=0,this.op=0,this.m_pos=0,this.skipToFirstLiteralFun=!1,17<this.buf[this.ip])if(this.t=this.buf[this.ip++]-17,this.t<4){if(this.match_next(),this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret}else this.copy_from_buf(),this.skipToFirstLiteralFun=!0;for(;;){if(this.skipToFirstLiteralFun)this.skipToFirstLiteralFun=!1;else{if(this.t=this.buf[this.ip++],16<=this.t){if(this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret;continue}if(0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=15+this.buf[this.ip++]}this.t+=3,this.copy_from_buf()}if(this.t=this.buf[this.ip++],this.t<16){if(this.m_pos=this.op-2049,this.m_pos-=this.t>>2,this.m_pos-=this.buf[this.ip++]<<2,this.minNewSize=this.op+3,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos],0===this.match_done())continue;this.match_next()}if(this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret}return this.OK},this._compressCore=function(){for(this.ip_start=this.ip,this.ip_end=this.ip+this.ll-20,this.jj=this.ip,this.ti=this.t,this.ip+=this.ti<4?4-this.ti:0,this.ip+=1+(this.ip-this.jj>>5);!(this.ip>=this.ip_end);)if(this.dv_lo=this.buf[this.ip]|this.buf[this.ip+1]<<8,this.dv_hi=this.buf[this.ip+2]|this.buf[this.ip+3]<<8,this.dindex=((17053*this.dv_lo>>>16)+17053*this.dv_hi+6180*this.dv_lo&65535)>>>2,this.m_pos=this.ip_start+this.dict[this.dindex],this.dict[this.dindex]=this.ip-this.ip_start,(this.dv_hi<<16)+this.dv_lo==(this.buf[this.m_pos]|this.buf[this.m_pos+1]<<8|this.buf[this.m_pos+2]<<16|this.buf[this.m_pos+3]<<24)){if(this.jj-=this.ti,this.ti=0,this.v=this.ip-this.jj,0!==this.v)if(this.v<=3)for(this.out[this.op-2]|=this.v;this.out[this.op++]=this.buf[this.jj++],0<--this.v;);else{if(this.v<=18)this.out[this.op++]=this.v-3;else{for(this.tt=this.v-18,this.out[this.op++]=0;255<this.tt;)this.tt-=255,this.out[this.op++]=0;this.out[this.op++]=this.tt}for(;this.out[this.op++]=this.buf[this.jj++],0<--this.v;);}if(this.m_len=4,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len])for(;this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&!(this.ip+this.m_len>=this.ip_end)&&this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]))))))););if(this.m_off=this.ip-this.m_pos,this.ip+=this.m_len,this.jj=this.ip,this.m_len<=8&&this.m_off<=2048)--this.m_off,this.out[this.op++]=this.m_len-1<<5|(7&this.m_off)<<2,this.out[this.op++]=this.m_off>>3;else if(this.m_off<=16384){if(--this.m_off,this.m_len<=33)this.out[this.op++]=32|this.m_len-2;else{for(this.m_len-=33,this.out[this.op++]=32;255<this.m_len;)this.m_len-=255,this.out[this.op++]=0;this.out[this.op++]=this.m_len}this.out[this.op++]=this.m_off<<2,this.out[this.op++]=this.m_off>>6}else{if(this.m_off-=16384,this.m_len<=9)this.out[this.op++]=16|this.m_off>>11&8|this.m_len-2;else{for(this.m_len-=9,this.out[this.op++]=16|this.m_off>>11&8;255<this.m_len;)this.m_len-=255,this.out[this.op++]=0;this.out[this.op++]=this.m_len}this.out[this.op++]=this.m_off<<2,this.out[this.op++]=this.m_off>>6}}else this.ip+=1+(this.ip-this.jj>>5);this.t=this.ll-(this.jj-this.ip_start-this.ti)},this.compress=function(e){for(this.state=e,this.ip=0,this.buf=this.state.inputBuffer,this.maxSize=this.buf.length+Math.ceil(this.buf.length/16)+64+3,this.maxSize>this.out.length&&(this.out=new Uint8Array(this.maxSize)),this.op=0,this.l=this.buf.length,this.t=0;20<this.l&&(this.ll=this.l<=49152?this.l:49152,!(this.t+this.ll>>5<=0));)this.dict.set(this.emptyDict),this.prev_ip=this.ip,this._compressCore(),this.ip=this.prev_ip+this.ll,this.l-=this.ll;if(this.t+=this.l,0<this.t){if(this.ii=this.buf.length-this.t,0===this.op&&this.t<=238)this.out[this.op++]=17+this.t;else if(this.t<=3)this.out[this.op-2]|=this.t;else if(this.t<=18)this.out[this.op++]=this.t-3;else{for(this.tt=this.t-18,this.out[this.op++]=0;255<this.tt;)this.tt-=255,this.out[this.op++]=0;this.out[this.op++]=this.tt}for(;this.out[this.op++]=this.buf[this.ii++],0<--this.t;);}return this.out[this.op++]=17,this.out[this.op++]=0,this.out[this.op++]=0,this.state.outputBuffer=!0===this.returnNewBuffers?new Uint8Array(this.out.subarray(0,this.op)):this.out.subarray(0,this.op),this.OK}};return{setBlockSize:function(e){return i.setBlockSize(e)},setOutputEstimate:function(e){return i.setOutputSize(e)},setReturnNewBuffers:function(e){i.setReturnNewBuffers(e)},compress:function(e,t){return void 0!==t&&i.applyConfig(t),i.compress(e)},decompress:function(e,t){return void 0!==t&&i.applyConfig(t),i.decompress(e)}}}()},163:function(h,l,c){var u;!function(){"use strict";function e(e,t){return function(){return t.apply(e,arguments)}}function i(){for(var e,t=arguments,i=t[0],s=1;s<t.length;s++)for(e in t[s])e in i||!t[s].hasOwnProperty(e)||(i[e]=t[s][e]);return i}var s,o={VERSION:"1.4.1"},r={},t=function(e,t){return{value:e,name:t}};o.DEBUG=t(1,"DEBUG"),o.INFO=t(2,"INFO"),o.TIME=t(3,"TIME"),o.WARN=t(4,"WARN"),o.ERROR=t(8,"ERROR"),o.OFF=t(99,"OFF");function a(e){this.context=e,this.setLevel(e.filterLevel),this.log=this.info}a.prototype={setLevel:function(e){e&&"value"in e&&(this.context.filterLevel=e)},getLevel:function(){return this.context.filterLevel},enabledFor:function(e){var t=this.context.filterLevel;return e.value>=t.value},debug:function(){this.invoke(o.DEBUG,arguments)},info:function(){this.invoke(o.INFO,arguments)},warn:function(){this.invoke(o.WARN,arguments)},error:function(){this.invoke(o.ERROR,arguments)},time:function(e){"string"==typeof e&&0<e.length&&this.invoke(o.TIME,[e,"start"])},timeEnd:function(e){"string"==typeof e&&0<e.length&&this.invoke(o.TIME,[e,"end"])},invoke:function(e,t){s&&this.enabledFor(e)&&s(t,i({level:e},this.context))}};var n=new a({filterLevel:o.OFF});(t=o).enabledFor=e(n,n.enabledFor),t.debug=e(n,n.debug),t.time=e(n,n.time),t.timeEnd=e(n,n.timeEnd),t.info=e(n,n.info),t.warn=e(n,n.warn),t.error=e(n,n.error),t.log=t.info,o.setHandler=function(e){s=e},o.setLevel=function(e){for(var t in n.setLevel(e),r)r.hasOwnProperty(t)&&r[t].setLevel(e)},o.getLevel=function(){return n.getLevel()},o.get=function(e){return r[e]||(r[e]=new a(i({name:e},n.context)))},o.createDefaultHandler=function(r){(r=r||{}).formatter=r.formatter||function(e,t){t.name&&e.unshift("["+t.name+"]")};function a(e,t){Function.prototype.apply.call(e,console,t)}var n={};return"undefined"==typeof console?function(){}:function(e,t){e=Array.prototype.slice.call(e);var i,s=console.log;t.level===o.TIME?(i=(t.name?"["+t.name+"] ":"")+e[0],"start"===e[1]?console.time?console.time(i):n[i]=(new Date).getTime():console.timeEnd?console.timeEnd(i):a(s,[i+": "+((new Date).getTime()-n[i])+"ms"])):(t.level===o.WARN&&console.warn?s=console.warn:t.level===o.ERROR&&console.error?s=console.error:t.level===o.INFO&&console.info?s=console.info:t.level===o.DEBUG&&console.debug&&(s=console.debug),r.formatter(e,t),a(s,e))}},o.useDefaults=function(e){o.setLevel(e&&e.defaultLevel||o.DEBUG),o.setHandler(o.createDefaultHandler(e))},void 0===(u="function"==typeof(u=o)?u.call(l,c,l,h):u)||(h.exports=u)}()},948:e=>{function t(e){null==e&&(e=(new Date).getTime()),this.N=624,this.M=397,this.MATRIX_A=2567483615,this.UPPER_MASK=2147483648,this.LOWER_MASK=2147483647,this.mt=new Array(this.N),this.mti=this.N+1,e.constructor==Array?this.init_by_array(e,e.length):this.init_seed(e)}t.prototype.init_seed=function(e){for(this.mt[0]=e>>>0,this.mti=1;this.mti<this.N;this.mti++){e=this.mt[this.mti-1]^this.mt[this.mti-1]>>>30;this.mt[this.mti]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+this.mti,this.mt[this.mti]>>>=0}},t.prototype.init_by_array=function(e,t){var i,s,r;for(this.init_seed(19650218),i=1,s=0,r=this.N>t?this.N:t;r;r--){var a=this.mt[i-1]^this.mt[i-1]>>>30;this.mt[i]=(this.mt[i]^(1664525*((4294901760&a)>>>16)<<16)+1664525*(65535&a))+e[s]+s,this.mt[i]>>>=0,s++,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1),t<=s&&(s=0)}for(r=this.N-1;r;r--){a=this.mt[i-1]^this.mt[i-1]>>>30;this.mt[i]=(this.mt[i]^(1566083941*((4294901760&a)>>>16)<<16)+1566083941*(65535&a))-i,this.mt[i]>>>=0,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1)}this.mt[0]=2147483648},t.prototype.random_int=function(){var e,t,i=new Array(0,this.MATRIX_A);if(this.mti>=this.N){for(this.mti==this.N+1&&this.init_seed(5489),t=0;t<this.N-this.M;t++)e=this.mt[t]&this.UPPER_MASK|this.mt[t+1]&this.LOWER_MASK,this.mt[t]=this.mt[t+this.M]^e>>>1^i[1&e];for(;t<this.N-1;t++)e=this.mt[t]&this.UPPER_MASK|this.mt[t+1]&this.LOWER_MASK,this.mt[t]=this.mt[t+(this.M-this.N)]^e>>>1^i[1&e];e=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK,this.mt[this.N-1]=this.mt[this.M-1]^e>>>1^i[1&e],this.mti=0}return e=this.mt[this.mti++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,(e^=e>>>18)>>>0},t.prototype.random_int31=function(){return this.random_int()>>>1},t.prototype.random_incl=function(){return this.random_int()*(1/4294967295)},t.prototype.random=function(){return this.random_int()*(1/4294967296)},t.prototype.random_excl=function(){return(this.random_int()+.5)*(1/4294967296)},t.prototype.random_long=function(){return 1/9007199254740992*(67108864*(this.random_int()>>>5)+(this.random_int()>>>6))},e.exports=t},367:e=>{e.exports=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");for(var t=["on","fire","off"],i=0;i<t.length;++i)if(e.hasOwnProperty(t[i]))throw new Error("Subject cannot be eventified, since it already has property '"+t[i]+"'")}(e);var a,n,t=(a=e,n=Object.create(null),{on:function(e,t,i){if("function"!=typeof t)throw new Error("callback is expected to be a function");return(n[e]||(n[e]=[])).push({callback:t,ctx:i}),a},off:function(e,t){if(void 0===e)return n=Object.create(null),a;if(n[e])if("function"!=typeof t)delete n[e];else for(var i=n[e],s=0;s<i.length;++s)i[s].callback===t&&i.splice(s,1);return a},fire:function(e){var t,i=n[e];if(!i)return a;1<arguments.length&&(t=Array.prototype.splice.call(arguments,1));for(var s=0;s<i.length;++s){var r=i[s];r.callback.apply(r.ctx,t)}return a}});return e.on=t.on,e.off=t.off,e.fire=t.fire,e}},495:(e,t,i)=>{e.exports=function(e){"uniqueLinkId"in(e=e||{})&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n","\n","Note: there is also change in default behavior: From now on each graph\nis considered to be not a multigraph by default (each edge is unique)."),e.multigraph=e.uniqueLinkId);void 0===e.multigraph&&(e.multigraph=!1);if("function"!=typeof Map)throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var n=new Map,a=[],o={},t=0,h=e.multigraph?function(e,t,i){var s=x(e,t),r=o.hasOwnProperty(s);(r||b(e,t))&&(r||(o[s]=0),r="@"+ ++o[s],s=x(e+r,t+r));return new B(e,t,i,s)}:function(e,t,i){var s=x(e,t);return new B(e,t,i,s)},i=[],l=v,r=v,c=v,u=v,s={addNode:g,addLink:function(e,t,i){c();var s=m(e)||g(e),r=m(t)||g(t),i=h(e,t,i);a.push(i),C(s,i),e!==t&&C(r,i);return l(i,"add"),u(),i},removeLink:T,removeNode:f,getNode:m,getNodeCount:y,getLinkCount:w,getLinksCount:w,getNodesCount:y,getLinks:function(e){e=m(e);return e?e.links:null},forEachNode:k,forEachLinkedNode:function(e,t,i){var s=m(e);if(s&&s.links&&"function"==typeof t)return(i?function(e,t,i){for(var s=0;s<e.length;++s){var r=e[s];if(r.fromId===t&&i(n.get(r.toId),r))return!0}}:function(e,t,i){for(var s=0;s<e.length;++s){var r=e[s],a=r.fromId===t?r.toId:r.fromId;if(i(n.get(a),r))return!0}})(s.links,e,t)},forEachLink:function(e){var t,i;if("function"==typeof e)for(t=0,i=a.length;t<i;++t)e(a[t])},beginUpdate:c,endUpdate:u,clear:function(){c(),k(function(e){f(e.id)}),u()},hasLink:b,hasNode:m,getLink:b};return O(s),function(){var e=s.on;s.on=function(){return s.beginUpdate=c=S,s.endUpdate=u=_,l=d,r=p,(s.on=e).apply(s,arguments)}}(),s;function d(e,t){i.push({link:e,changeType:t})}function p(e,t){i.push({node:e,changeType:t})}function g(e,t){if(void 0===e)throw new Error("Invalid node identifier");c();var i=m(e);return i?(i.data=t,r(i,"update")):(i=new A(e,t),r(i,"add")),n.set(e,i),u(),i}function m(e){return n.get(e)}function f(e){var t=m(e);if(!t)return!1;c();var i=t.links;if(i){t.links=null;for(var s=0;s<i.length;++s)T(i[s])}return n.delete(e),r(t,"remove"),u(),!0}function y(){return n.size}function w(){return a.length}function T(e){if(!e)return!1;var t=I(e,a);if(t<0)return!1;c(),a.splice(t,1);var i=m(e.fromId),s=m(e.toId);return i&&0<=(t=I(e,i.links))&&i.links.splice(t,1),s&&0<=(t=I(e,s.links))&&s.links.splice(t,1),l(e,"remove"),u(),!0}function b(e,t){var i,s=m(e);if(!s||!s.links)return null;for(i=0;i<s.links.length;++i){var r=s.links[i];if(r.fromId===e&&r.toId===t)return r}return null}function v(){}function S(){t+=1}function _(){0===--t&&0<i.length&&(s.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,s=0;s<i;s+=1)if(t[s]===e)return s;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,s){this.fromId=e,this.toId=t,this.data=i,this.id=s}function x(e,t){return e.toString()+"👉 "+t.toString()}},603:e=>{function s(e,t){if(!(this instanceof s))return new s(e,t);if(Array.isArray(e)||(t=e,e=[]),t=t||{},this.data=e||[],this.length=this.data.length,this.compare=t.compare||a,this.setNodeId=t.setNodeId||r,0<this.length)for(var i=this.length>>1;0<=i;i--)this._down(i);if(t.setNodeId)for(i=0;i<this.length;++i)this.setNodeId(this.data[i],i)}function r(){}function a(e,t){return e-t}(e.exports=s).prototype={push:function(e){this.data.push(e),this.setNodeId(e,this.length),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var e=this.data[0];return this.length--,0<this.length&&(this.data[0]=this.data[this.length],this.setNodeId(this.data[0],0),this._down(0)),this.data.pop(),e}},peek:function(){return this.data[0]},updateItem:function(e){this._down(e),this._up(e)},_up:function(e){for(var t=this.data,i=this.compare,s=this.setNodeId,r=t[e];0<e;){var a=e-1>>1,n=t[a];if(0<=i(r,n))break;s(t[e]=n,e),e=a}s(t[e]=r,e)},_down:function(e){for(var t=this.data,i=this.compare,s=this.length>>1,r=t[e],a=this.setNodeId;e<s;){var n=1+(e<<1),o=n+1,h=t[n];if(o<this.length&&i(t[o],h)<0&&(h=t[n=o]),0<=i(h,r))break;a(t[e]=h,e),e=n}a(t[e]=r,e)}}},142:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.bestEffort,b=e.heuristic;b=b||k.heuristic;var v=e.distance;v=v||k.distance;var S=s();return{find:function(e,t){var a=y.getNode(e);if(!a)throw new Error("fromId is not defined in this graph: "+e);var n=y.getNode(t);if(!n)throw new Error("toId is not defined in this graph: "+t);if(a===n)return[a];S.reset();var i=w?function(e,t){if(d===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,s=new _({compare:k.compareFScore,setNodeId:k.setHeapIndex}),r=new _({compare:k.compareFScore,setNodeId:k.setHeapIndex}),t=S.createNewState(a);o.set(e,t),t.fScore=b(a,n),t.distanceToSource=0,s.push(t),t.open=O;e=S.createNewState(n);e.fScore=b(n,a),e.distanceToSource=0,r.push(e),e.open=I;var h,l,c=Number.POSITIVE_INFINITY,u=s,d=O,p=t;for(;0<s.length&&(0<r.length||T);){var g=(u=s.length<r.length||!r.length&&T?(d=O,s):(d=I,r)).pop();if(g.closed=!0,!(g.distanceToSource>c)&&(y.forEachLinkedNode(g.node.id,i),h&&l))return m(h,l)}return T?m(p):A;function m(e,t){for(var i=[],s=e;s;)i.push(s.node),s=s.parent;for(var r=t;r;)i.unshift(r.node),r=r.parent;return i}function f(e,t,i){var s,r=o.get(e.id);r||(r=S.createNewState(e),o.set(e.id,r)),r.closed||((e=(e=r).open)&&e!==d?(s=r.distanceToSource+i.distanceToSource)<c&&(h=r,l=i,c=s):(e=i.distanceToSource+v(r.node,i.node,t))>=r.distanceToSource||(s=d===O?n:a,t=e+b(r.node,s,r),c<=t||(r.fScore=t,0===r.open&&(u.push(r),u.updateItem(r.heapIndex),r.open=d),r.parent=i,r.distanceToSource=e,s===n&&t-e<p.fScore-p.distanceToSource&&(p=r))))}}}};var _=i(603),s=i(573),r=i(884),k=i(8),O=1,I=2,A=k.NO_PATH;e.exports.l2=r.l2,e.exports.l1=r.l1},118:(e,t,i)=>{e.exports=function(c,e){var u=(e=e||{}).oriented,d=e.bestEffort,p=e.maxExpandedNodes||Number.POSITIVE_INFINITY,g=e.heuristic;g=g||w.heuristic;var m=e.distance;m=m||w.distance;var f=s();return{find:function(e,t){var i=c.getNode(e);if(!i)throw new Error("fromId is not defined in this graph: "+e);var s=c.getNode(t);if(!s)throw new Error("toId is not defined in this graph: "+t);f.reset();var r,a=new Map,n=new y({compare:w.compareFScore,setNodeId:w.setHeapIndex}),t=f.createNewState(i);a.set(e,t),t.fScore=g(i,s),t.distanceToSource=0,n.push(t),t.open=1;var o=t,h=0;for(;0<n.length;){if(function(e,t){return e.node===t}(r=n.pop(),s))return b(r);if(p<++h)break;r.closed=!0,c.forEachLinkedNode(r.node.id,l,u)}return d?b(o):T;function l(e,t){var i=a.get(e.id);i||(i=f.createNewState(e),a.set(e.id,i)),i.closed||(0===i.open&&(n.push(i),i.open=1),(t=r.distanceToSource+m(r.node,e,t))>=i.distanceToSource||(i.parent=r,i.distanceToSource=t,i.fScore=t+g(i.node,s,i),i.fScore-i.distanceToSource<o.fScore-o.distanceToSource&&(o=i),n.updateItem(i.heapIndex)))}}}};var y=i(603),s=i(573),r=i(884),w=i(8),T=w.NO_PATH;function b(e){for(var t=[e.node],i=e.parent;i;)t.push(i.node),i=i.parent;return t}e.exports.l2=r.l2,e.exports.l1=r.l1},8:e=>{var t=[];"function"==typeof Object.freeze&&Object.freeze(t),e.exports={heuristic:function(){return 0},distance:function(){return 1},compareFScore:function(e,t){return e.fScore-t.fScore},NO_PATH:t,setHeapIndex:function(e,t){e.heapIndex=t},setH1:function(e,t){e.h1=t},setH2:function(e,t){e.h2=t},compareF1Score:function(e,t){return e.f1-t.f1},compareF2Score:function(e,t){return e.f2-t.f2}}},884:e=>{e.exports={l2:function(e,t){var i=e.x-t.x,t=e.y-t.y;return Math.sqrt(i*i+t*t)},l1:function(e,t){var i=e.x-t.x,t=e.y-t.y;return Math.abs(i)+Math.abs(t)}}},573:e=>{function r(e){this.node=e,this.parent=null,this.closed=!1,this.open=0,this.distanceToSource=Number.POSITIVE_INFINITY,this.fScore=Number.POSITIVE_INFINITY,this.heapIndex=-1}e.exports=function(){var i=0,s=[];return{createNewState:function(e){var t=s[i];t?(t.node=e,t.parent=null,t.closed=!1,t.open=0,t.distanceToSource=Number.POSITIVE_INFINITY,t.fScore=Number.POSITIVE_INFINITY,t.heapIndex=-1):(t=new r(e),s[i]=t);return i++,t},reset:function(){i=0}}}},377:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.quitFast,b=e.heuristic;b=b||k.heuristic;var v=e.distance;v=v||k.distance;var S=r();return{find:function(e,t){var s=y.getNode(e);if(!s)throw new Error("fromId is not defined in this graph: "+e);var r=y.getNode(t);if(!r)throw new Error("toId is not defined in this graph: "+t);S.reset();var a,i=w?function(e,t){if(t.fromId===p.node.id)return m(e,t)}:m,n=w?function(e,t){if(t.toId===p.node.id)return f(e,t)}:f,o=new Map,h=new _({compare:k.compareF1Score,setNodeId:k.setH1}),l=new _({compare:k.compareF2Score,setNodeId:k.setH2}),c=Number.POSITIVE_INFINITY,u=S.createNewState(s);o.set(e,u),u.g1=0;var d=b(s,r);u.f1=d,h.push(u);u=S.createNewState(r);o.set(t,u),u.g2=0;var p,g=d;u.f2=g,l.push(u);for(;l.length&&h.length&&(h.length<l.length?(p=h.pop()).closed||(p.closed=!0,p.f1<c&&p.g1+g-b(s,p.node)<c&&y.forEachLinkedNode(p.node.id,i),0<h.length&&(d=h.peek().f1)):(p=l.pop()).closed||(p.closed=!0,p.f2<c&&p.g2+d-b(p.node,r)<c&&y.forEachLinkedNode(p.node.id,n),0<l.length&&(g=l.peek().f2)),!T||!a););return function(e){if(!e)return O;var t=[e.node],i=e.p1;for(;i;)t.push(i.node),i=i.p1;var s=e.p2;for(;s;)t.unshift(s.node),s=s.p2;return t}(a);function m(e,t){var i=o.get(e.id);i||(i=S.createNewState(e),o.set(e.id,i)),i.closed||((t=p.g1+v(p.node,e,t))<i.g1&&(i.g1=t,i.f1=t+b(i.node,r),i.p1=p,i.h1<0?h.push(i):h.updateItem(i.h1)),(t=i.g1+i.g2)<c&&(c=t,a=i))}function f(e,t){var i=o.get(e.id);i||(i=S.createNewState(e),o.set(e.id,i)),i.closed||((t=p.g2+v(p.node,e,t))<i.g2&&(i.g2=t,i.f2=t+b(s,i.node),i.p2=p,i.h2<0?l.push(i):l.updateItem(i.h2)),(t=i.g1+i.g2)<c&&(c=t,a=i))}}}};var _=i(603),s=i(884),k=i(8),r=i(808),O=k.NO_PATH;e.exports.l2=s.l2,e.exports.l1=s.l1},808:e=>{function r(e){this.node=e,this.p1=null,this.p2=null,this.closed=!1,this.g1=Number.POSITIVE_INFINITY,this.g2=Number.POSITIVE_INFINITY,this.f1=Number.POSITIVE_INFINITY,this.f2=Number.POSITIVE_INFINITY,this.h1=-1,this.h2=-1}e.exports=function(){var i=0,s=[];return{createNewState:function(e){var t=s[i];t?(t.node=e,t.p1=null,t.p2=null,t.closed=!1,t.g1=Number.POSITIVE_INFINITY,t.g2=Number.POSITIVE_INFINITY,t.f1=Number.POSITIVE_INFINITY,t.f2=Number.POSITIVE_INFINITY,t.h1=-1,t.h2=-1):(t=new r(e),s[i]=t);return i++,t},reset:function(){i=0}}}},45:(e,t,i)=>{e.exports={aStar:i(118),aGreedy:i(142),nba:i(377)}},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:()=>ps,ApiEventType:()=>Hl,ArmorType:()=>si,AttackState:()=>bn,Bot:()=>Cc,BuildCat:()=>Yi,BuildStatus:()=>kn,CombatDamageRules:()=>us,Country:()=>$n,CountryRules:()=>ki,CrateRules:()=>ys,CrewRules:()=>Ei,Cylindrical:()=>lm,DMislRules:()=>Fi,Euler:()=>nm,FactoryStatus:()=>Tn,FactoryType:()=>Ki,GameApi:()=>yc,GameInstanceApi:()=>Vg,GeneralRules:()=>Wi,HoverRules:()=>ji,InfDeathType:()=>Jt,IniFile:()=>c,IniSection:()=>h,LandTargeting:()=>ri,LandType:()=>Yt,LightningStormRules:()=>Di,LocomotorType:()=>ti,MapApi:()=>nc,Matrix4:()=>qs,MissileRules:()=>Mi,MovementZone:()=>ii,NavalTargeting:()=>ai,ObjectRules:()=>Oi,ObjectType:()=>Ct,OrderType:()=>In,OverlayRules:()=>ns,ParadropRules:()=>Ri,PipColor:()=>ei,PrereqCategory:()=>Qt,PrismRules:()=>Pi,ProductionApi:()=>Ac,ProjectileRules:()=>$i,PublicApi:()=>qg,Quaternion:()=>Zi,QueueStatus:()=>gn,QueueType:()=>pn,RadarEventType:()=>Xt,RadarRules:()=>Ci,RadiationRules:()=>ms,RepairRules:()=>Bi,RulesApi:()=>pc,SideType:()=>qt,SpeedType:()=>Kt,Spherical:()=>hm,StanceType:()=>Ds,SuperWeaponStatus:()=>Es,SuperWeaponType:()=>es,Tag:()=>cm,TagRepeatType:()=>Ht,TechnoRules:()=>as,TerrainRules:()=>os,TerrainType:()=>Zt,TheaterType:()=>I,ThreatRules:()=>Ni,V3RocketRules:()=>Li,Vector3:()=>is,VeteranAbility:()=>oi,VeteranLevel:()=>Yr,VeteranRules:()=>xi,VhpScan:()=>hi,WarheadRules:()=>Gi,WeaponRules:()=>Ii,WeaponType:()=>ni,ZoneType:()=>Ts,cdapi:()=>um});__WEBPACK_EXTERNAL_MODULE_websocket_polyfill_8396782d__;const a=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");const e=__WEBPACK_EXTERNAL_MODULE_es_dirname_044d89a0__;const n=__WEBPACK_EXTERNAL_MODULE_file_system_access_58c08c7f__;const o=__WEBPACK_EXTERNAL_MODULE_file_system_access_lib_adapters_node_js_b1c03fd5__;class h{constructor(e){this.entries=new Map,this.name=e}clone(){let i=new h(this.name);return this.entries.forEach((e,t)=>{i.set(t,e)}),i}set(e,t){this.entries.set(e,t)}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}getString(e,t=""){e=this.get(e);return e||t}getNumber(e,t=0){var i=this.get(e);if(!i)return t;var s=this.parseNumber(i);return void 0===s?(console.warn(`Invalid value for key ${e}. "${i}" is not a valid number or percentage string.`),t):s}parseNumber(e){let t;if(t=e.match(/%$/)?Number(e.replace("%",""))/100:Number(e),!isNaN(t))return t}getFixed(e,t=0){return this.toFixedPointPrecision(this.getNumber(e,t))}toFixedPointPrecision(e){return(65536*e|0)/65536}getBool(e,t=!1){let i=this.getString(e).trim();return i=i&&i.toLowerCase(),!(!i||-1===["yes","1","true","on"].indexOf(i))||(!i||-1===["no","0","false","off"].indexOf(i))&&t}getArray(e,t=/\,\s*/,i=[]){let s=this.getString(e).trim();return s=s.replace(/\,$/,"").replace(/\,+/g,","),s?s.split(t):i}getNumberArray(e,t=/\,\s*/,i=[]){let s=this.getString(e).trim();if(!s)return i;let r=[];for(var a of s.split(t)){if(!a)return i;var n=this.parseNumber(a);if(void 0===n)return console.warn(`Invalid value for key ${e}. "${a}" is not a valid number or percentage string.`),i;r.push(n)}return r}getFixedArray(e,t=/\,\s*/,i=[]){return this.getNumberArray(e,t,i).map(e=>this.toFixedPointPrecision(e))}getEnum(e,t,i,s=!1){let r=this.getString(e).trim();if(!r)return i;let a;if(s){let e=Object.getOwnPropertyNames(t);s=e.find(e=>e.toLowerCase()===r.toLowerCase());s&&(a=t[s])}else t.hasOwnProperty(r)&&(a=t[r]);return void 0===a?(console.warn(`Invalid value for key "${e}". "${r}" is not an accepted enum value.`),i):a}getEnumNumeric(e,t,i){var s=this.getString(e).trim();if(!s)return i;let r;return Number.isInteger(parseInt(s,10))&&t.hasOwnProperty(s)&&(r=parseInt(s,10)),void 0===r?(console.warn(`Invalid value for key "${e}". "${s}" is not an accepted enum value.`),i):r}getEnumArray(e,s,t=/\,\s*/,r=[],a=!1){let n=this.getString(e).trim();if(!n)return r;let o=[];for(let i of n.split(t)){if(!i)return r;let t=!1;if(a){let e=Object.getOwnPropertyNames(s);var h=e.find(e=>e.toLowerCase()===i.toLowerCase());h&&(o.push(s[h]),t=!0)}else s.hasOwnProperty(i)&&(o.push(s[i]),t=!0);if(!t)return console.warn(`Invalid value "${i}" for key "${e}".`),r}return o}getHighestNumericIndex(){let i=0,s;return this.entries.forEach((e,t)=>{s=parseInt(t,10),s>i&&(i=s)}),i}getConcatenatedValues(){let e="";for(var t of this.entries.values())e+=t;return e}toString(){let e=[];e.push(`[${this.name}]`);for(var[t,i]of this.entries)e.push(`${t}=${i}`);return e.push(""),e.join("\r\n")}}class t{parse(e){let o={},s=o,r,a=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,t=e.split(/[\r\n]+/g);return t.forEach((t,e,i)=>{if(t&&!t.match(/^\s*[;#]/)){t=(t=t.replace(/]\s*(\/\/|;|#).*$/,"]")).match(a);if(t){if(void 0!==t[1])return r=this.unsafe(t[1]),void(s=o[r]=o[r]||{});let e=this.unsafe(t[2]);t=t[3]?this.unsafe(t[4]||""):"";2<e.length&&"[]"===e.slice(-2)&&(e=e.substring(0,e.length-2),s[e]?Array.isArray(s[e])||(s[e]=[s[e]]):s[e]=[]),Array.isArray(s[e])?s[e].push(t):s[e]=t}}}),Object.keys(o).filter((e,t,i)=>{if(!o[e]||"object"!=typeof o[e]||Array.isArray(o[e]))return!1;let s=this.dotSplit(e),r=o,a=s.pop();var n=a.replace(/\\\./g,".");return s.forEach(function(e,t,i){r[e]&&"object"==typeof r[e]||(r[e]={}),r=r[e]}),(r!==o||n!==a)&&(r[n]=o[e],!0)}).forEach(function(e,t,i){delete o[e]}),o}dotSplit(e){return e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,""))}isQuoted(e){return'"'===e.charAt(0)&&'"'===e.slice(-1)||"'"===e.charAt(0)&&"'"===e.slice(-1)}unsafe(r){if(r=(r||"").trim(),this.isQuoted(r))return r=r.substr(1,r.length-2);{let i=!1,s="";for(let e=0,t=r.length;e<t;e++){var a=r.charAt(e);if(i)-1!=="\\;#".indexOf(a)?s+=a:s+="\\"+a,i=!1;else{if(-1!==";#".indexOf(a))break;"\\"===a?i=!0:s+=a}}return i&&(s+="\\"),s=s.trim(),s}}}class 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 s=new ArrayBuffer(e),t=new Uint8Array(this._buffer);const r=new Uint8Array(s,0,t.length);r.set(t),this.buffer=s,this._byteLength=i}}}_trimAlloc(){if(!this._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,s,r){const a=new Uint8Array(e,t,r);r=new Uint8Array(i,s,r);a.set(r)}static arrayToNative(e,t){return t===this.endianness?e:this.flipArrayEndianness(e)}static nativeToEndian(e,t){return this.endianness===t?e:this.flipArrayEndianness(e)}static flipArrayEndianness(s){const r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);for(let i=0;i<s.byteLength;i+=s.BYTES_PER_ELEMENT)for(let e=i+s.BYTES_PER_ELEMENT-1,t=i;e>t;e--,t++){var a=r[t];r[t]=r[e],r[e]=a}return s}static createStringFromArray(t){const i=[];for(let e=0;e<t.length;e+=32768)i.push(String.fromCharCode.apply(void 0,t.subarray(e,e+32768)));return i.join("")}readStruct(t){const i={};var s,r=this.position;for(let e=0;e<t.length;e+=2){if(s=t[e+1],void 0===(s=this.readType(s,i)))return 0===this.failurePosition&&(this.failurePosition=this.position),void(this.position=r);i[t[e]]=s}return i}readUCS2String(e,t){return w.createStringFromArray(this.readUint16Array(e,t))}writeUCS2String(e,t,i){void 0===i&&(i=e.length);let s=0;for(;s<e.length&&s<i;s++)this.writeUint16(e.charCodeAt(s),t);for(;s<i;s++)this.writeUint16(0);return this}readString(e,t){return void 0===t||"ASCII"===t?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 s=Math.min(t.length,i);for(e=0;e<s;e++)this.writeUint8(t.charCodeAt(e));for(;e<i;e++)this.writeUint8(0)}else for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));else this.writeUint8Array((new TextEncoder).encode(t.substring(0,i)));return this}writeUtf8WithLen(e){e=(new TextEncoder).encode(e);return this.writeUint16(e.length).writeUint8Array(e)}readUtf8WithLen(){var e=this.readUint16();return(new TextDecoder).decode(this.mapUint8Array(e))}readCString(e){var t=this.byteLength-this.position;if(!this._buffer)throw new Error;var i=new Uint8Array(this._buffer,this._byteOffset+this.position);let s=t;void 0!==e&&(s=Math.min(e,t));let r=0;for(;r<s&&0!==i[r];r++);var a=w.createStringFromArray(this.mapUint8Array(r));return void 0!==e?this.position+=s-r:r!==t&&(this.position+=1),a}writeCString(t,i){if(void 0!==i){let e;var s=Math.min(t.length,i);for(e=0;e<s;e++)this.writeUint8(t.charCodeAt(e));for(;e<i;e++)this.writeUint8(0)}else{for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));this.writeUint8(0)}return this}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 s=void 0,t=void 0,r="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],r=a[1]),t=t||0,e){case"uint8":s=this.readUint8();break;case"int8":s=this.readInt8();break;case"uint16":s=this.readUint16(this.endianness);break;case"int16":s=this.readInt16(this.endianness);break;case"uint32":s=this.readUint32(this.endianness);break;case"int32":s=this.readInt32(this.endianness);break;case"float32":s=this.readFloat32(this.endianness);break;case"float64":s=this.readFloat64(this.endianness);break;case"uint16be":s=this.readUint16(w.BIG_ENDIAN);break;case"int16be":s=this.readInt16(w.BIG_ENDIAN);break;case"uint32be":s=this.readUint32(w.BIG_ENDIAN);break;case"int32be":s=this.readInt32(w.BIG_ENDIAN);break;case"float32be":s=this.readFloat32(w.BIG_ENDIAN);break;case"float64be":s=this.readFloat64(w.BIG_ENDIAN);break;case"uint16le":s=this.readUint16(w.LITTLE_ENDIAN);break;case"int16le":s=this.readInt16(w.LITTLE_ENDIAN);break;case"uint32le":s=this.readUint32(w.LITTLE_ENDIAN);break;case"int32le":s=this.readInt32(w.LITTLE_ENDIAN);break;case"float32le":s=this.readFloat32(w.LITTLE_ENDIAN);break;case"float64le":s=this.readFloat64(w.LITTLE_ENDIAN);break;case"cstring":s=this.readCString(t);break;case"string":s=this.readString(t,r);break;case"u16string":s=this.readUCS2String(t,this.endianness);break;case"u16stringle":s=this.readUCS2String(t,w.LITTLE_ENDIAN);break;case"u16stringbe":s=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":s=this.readUint8Array(t);break;case"uint16":s=this.readUint16Array(t,e);break;case"uint32":s=this.readUint32Array(t,e);break;case"int8":s=this.readInt8Array(t);break;case"int16":s=this.readInt16Array(t,e);break;case"int32":s=this.readInt32Array(t,e);break;case"float32":s=this.readFloat32Array(t,e);break;case"float64":s=this.readFloat64Array(t,e);break;case"cstring":case"utf16string":case"string":if(void 0===t)for(s=[];!this.isEof();){var h=this.readType(d,i);if(void 0===h)break;s.push(h)}else{s=new Array(t);for(let e=0;e<t;e++)s[e]=this.readType(d,i)}}}else if("*"===p)for(s=[];;){var l=this.position;try{var c=this.readType(d,i);if(void 0===c){this.position=l;break}s.push(c)}catch(e){this.position=l;break}}else{t=t||0,s=new Array(t);for(let e=0;e<t;e++){var u=this.readType(d,i);if(void 0===u)return;s[e]=u}}break}}return void 0!==t&&(this.position=n+t),s}writeStruct(t,i,e=!1){e&&(t=w.defWriteStruct(t,i));for(let e=0;e<t.length;e+=2){var s=t[e+1];this.writeType(s,i[t[e]],i)}return this}static defWriteStruct(i,s){const r=[];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(s[a]);s[n]=o.length,r.push(e=>e.writeUint8Array(o))}else r.push(t);r.push(a)}return r.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 s=void 0,r="ASCII";var a,n=this.position;switch("string"==typeof e&&/:/.test(e)&&(e=(a=e.split(":"))[0],a=a[1],s=parseInt(void 0!==i[a]?i[a]:a,10)),"string"==typeof e&&/,/.test(e)&&(e=(a=e.split(","))[0],r=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,s);break;case"string":this.writeString(t,r,s);break;case"u16string":this.writeUCS2String(t,this.endianness,s);break;case"u16stringle":this.writeUCS2String(t,w.LITTLE_ENDIAN,s);break;case"u16stringbe":this.writeUCS2String(t,w.BIG_ENDIAN,s);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!==s&&(this.position=n,this._realloc(s),this.position=n+s),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,s=e.byteLength){s=new DataView(e.buffer,e.byteOffset+i,s);const r=new w(s);return r._trimAlloc=()=>{},new this(r,t)}readAsString(e){return this.stream.seek(0),this.stream.readString(this.stream.byteLength,e)}getBytes(){return new Uint8Array(this.stream.buffer,this.stream.byteOffset,this.stream.byteLength)}getSize(){return this.stream.byteLength}asFile(e){return new File([this.getBytes()],this.filename,{type:e})}}class c{constructor(e){this.sections=new Map,e instanceof i?this.fromVirtualFile(e):"object"==typeof e?this.fromJson(e):"string"==typeof e&&this.fromString(e)}fromVirtualFile(e){return this.fromString(e.readAsString())}fromString(e){return this.fromJson((new t).parse(e)),this}fromJson(e){let t,i,s,r;var a;for(t in e)if(e.hasOwnProperty(t)){for(r in i=e[t],s=new h(t),i)i.hasOwnProperty(r)&&(a=i[r],s.set(r,a));this.sections.set(t,s)}}toString(){let e=[];for(var t of this.sections.values())e.push(t.toString());return e.join("\r\n")}clone(){let i=new c;return this.sections.forEach((e,t)=>{i.sections.set(t,e.clone())}),i}getOrCreateSection(e){let t=this.sections.get(e);return t||(t=new h(e),this.sections.set(e,t)),t}getSection(e){return this.sections.get(e)}getOrderedSections(){return[...this.sections.values()]}isValueArray(e){return-1!==["BuildingTypes","AircraftTypes","InfantryTypes","OverlayTypes","TerrainTypes","SmudgeTypes","VehicleTypes","Animations","VoxelAnims","SuperWeaponTypes","Countries","Warheads","Tiberiums"].indexOf(e)}mergeWith(e){return e.sections.forEach((e,t)=>{let s=this.getOrCreateSection(t);if(this.isValueArray(t)){let i=s.getHighestNumericIndex()+1;e.entries.forEach((e,t)=>{s.set((i++).toString(),e)})}else e.entries.forEach((e,t)=>{s.set(t,e)})}),this}}class d{constructor(e){this.height=1,this.width=1,this.x=0,this.y=0,this.imageData=e??new Uint8Array(0)}clip(i,e){let t=new d;t.width=Math.min(this.width,i),t.height=Math.min(this.height,e);let s=new Uint8Array(i*e),r=0;for(let t=0;t<this.height&&!(t>=e);t++)for(let e=0;e<this.width;e++)e>=i||(s[r++]=this.imageData[t*this.width+e]);return t.imageData=s,t.x=this.x,t.y=this.y,t}}class s{constructor(e){this.height=0,this.width=0,this.numImages=0,this.images=[],e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let r=e.stream;if(0===r.readInt16()){this.width=r.readInt16(),this.height=r.readInt16(),this.numImages=r.readInt16();let s=[];for(let e=0;e<this.numImages;++e)s.push(this.readFrameHeader(r));this.images=[];for(let i=0;i<this.numImages;++i){var{compressionType:a,imageDataStartOffset:n,x:o,y:h,width:l,height:c}=s[i];let e=i<this.numImages-1?s[i+1].imageDataStartOffset:r.byteLength;e<n&&(e=r.byteLength);var u=e-n;r.seek(n);u=this.readImageData(r,l,c,a,u);let t=new d(u);t.x=o,t.y=h,t.width=l,t.height=c,this.images.push(t)}}}readFrameHeader(e){var t=e.readInt16(),i=e.readInt16(),s=e.readInt16(),r=e.readInt16(),a=e.readUint8();return e.readUint8(),e.readUint8(),e.readUint8(),e.readInt32(),e.readInt32(),{x:t,y:i,width:s,height:r,compressionType:a,imageDataStartOffset:e.readInt32()}}readImageData(s,e,r,t,i){var a=e*r;if(t<=1){var n=new Uint8Array(s.buffer,s.byteOffset+s.position,a);return s.position+=a,n}if(2===t){let t=0,i=new Uint8Array(a);for(let e=0;e<r;++e){var o=s.readUint16()-2;i.set(new Uint8Array(s.buffer,s.byteOffset+s.position,o),t),s.position+=o,t+=o}return i}if(3!==t)return new Uint8Array;t=new Uint8Array(s.buffer,s.byteOffset+s.position,i);return s.position+=i,class{static decode(s,r,t){let a=new Uint8Array(r*t),n=0,o=0;for(let e=0;e<t;e++){let t=(s[n+1]<<8|s[n])-2;n+=2;let i=0;for(;0<t--;){let e=s[n++];if(0!==e)i++,a[o++]=e;else for(t--,e=s[n++],i+e>r&&(e=r-i&255),i+=e;0!=e--;)a[o++]=0}}return a}}.decode(t,e,r)}getImage(e){if(e<0||this.images.length<=e)throw new RangeError(`Image index out of bounds (file=${this.filename}, index=${e}, length=${this.images.length})`);return this.images[e]}addImage(e){this.images.push(e),this.numImages++}clip(e,t){let i=new s;return i.filename=this.filename,i.width=Math.min(this.width,e),i.height=Math.min(this.height,t),i.images=this.images.map(e=>e.clip(i.width,i.height)),i.numImages=this.numImages,i}}var r=__webpack_require__(949).Vector3;const u=[new r(.54946297,-183e-6,-.835518),new r(.00014400001,.54940403,-.83555698),new r(-.54940403,-68000001e-12,-.83555698),new r(106e-6,-.54946297,-.835518),new r(.94900799,.00031599999,-.31525001),new r(-186e-6,.94899702,-.31528401),new r(-.94899702,.00031800001,-.31528401),new r(-447e-6,-.94900799,-.31525001),new r(.95084399,-279e-6,.30967101),new r(202e-6,.95084798,.30965701),new r(-.95084798,-70000002e-12,.30965701),new r(147e-6,-.95084399,.30967101),new r(.55237001,-11e-6,.83359897),new r(19999999e-12,.55238003,.833592),new r(-.55238003,57000001e-12,.83359301),new r(-66000001e-12,-.55237001,.83359897)],p=[new r(.67121398,.19849201,-.714194),new r(.26964301,.58439398,-.76536),new r(-.040546,.096988,-.99445897),new r(-.57242799,-.091913998,-.81478697),new r(-.17140099,-.57270998,-.80163902),new r(.36255699,-.30299899,-.88133103),new r(.81034702,-.34897199,-.470698),new r(.103962,.93867201,-.328767),new r(-.324047,.58766901,-.74137598),new r(-.80086499,.34046099,-.49264699),new r(-.66549802,-.59014702,-.45698899),new r(.314767,-.803002,-.506073),new r(.97262901,.151076,-.17655),new r(.680291,.68423599,-.26272699),new r(-.52007902,.82777703,-.210483),new r(-.96164399,-.179001,-.207847),new r(-.262714,-.937451,-.22840101),new r(.219707,-.97130102,.091124997),new r(.92380798,-.229975,.30608699),new r(-.082488999,.97065997,.225866),new r(-.59179801,.69678998,.40528899),new r(-.92529601,.36660099,.097111002),new r(-.705051,-.68777502,.172828),new r(.7324,-.68036699,-.026304999),new r(.85516202,.37458199,.358311),new r(.47300601,.83648002,.276705),new r(-.097617,.65411198,.750072),new r(-.90412402,-.153725,.39865801),new r(-.211916,-.85808998,.46773201),new r(.50022697,-.67440802,.543091),new r(.584539,-.110249,.80384099),new r(.43737301,.45464399,.77588898),new r(-.042440999,.083318003,.995619),new r(-.59625101,.22013199,.77202803),new r(-.506455,-.39697701,.76544899),new r(.070569001,-.47847399,.87526202)],g=[new r(.45651099,-.073968001,-.88663799),new r(.50769401,.38511699,-.77067),new r(.095431998,.22666401,-.96928602),new r(-.35876599,.54318798,-.75910097),new r(-.361276,.13299499,-.92292601),new r(-.48311701,-.32406601,-.813375),new r(-.018073,-.197559,-.980124),new r(.3211,-.501477,-.80337799),new r(.79949099,.069615997,-.59662998),new r(.390971,.77130598,-.50222403),new r(.080782004,.61448997,-.784778),new r(-.73275,.41143101,-.54203498),new r(-.73525399,.0091019999,-.67773098),new r(-.80249399,-.39490801,-.44727099),new r(-.13413,-.58915502,-.79680902),new r(.71955299,-.37622699,-.58369303),new r(.96687502,.173593,-.187132),new r(.760831,.51910597,-.38944301),new r(-.114642,.87551898,-.46938601),new r(-.53236699,.76885903,-.354177),new r(-.96226698,.024977,-.27095801),new r(-.46738699,-.721986,-.51018202),new r(.058449998,-.85235399,-.51968902),new r(.49823299,-.74374002,-.44566301),new r(.93915099,-.27024499,-.212044),new r(.58393198,.80944198,-.061857),new r(.183797,.97322798,-.138007),new r(-.88435501,.45221901,-.115822),new r(-.943178,-.33206701,.012138),new r(-.69844002,-.70656699,-.113772),new r(-.228411,-.95470601,-.190694),new r(.73156399,-.675861,-.089588001),new r(.96925098,.046804,.24158201),new r(.85564703,.50347698,.119916),new r(-.25115299,.96794701,-80999998e-12),new r(-.64779502,.75674897,.087711997),new r(-.96916401,.14519399,.1991),new r(-.41479301,-.88896698,.194126),new r(.25077501,-.961178,-.115109),new r(.47862899,-.84259301,.246883),new r(.89004397,-.39614201,.225595),new r(.52405101,.76235998,.37970701),new r(.11962,.94548202,.30291),new r(-.76085001,.49007499,.42536199),new r(-.86978501,-.20215,.450122),new r(-.70946699,-.60242403,.36570701),new r(.019308999,-.95887101,.28318599),new r(.626113,-.564677,.53770101),new r(.769943,-.126663,.62541503),new r(.76419097,.35070199,.54131401),new r(-.001878,.74136698,.67109799),new r(-.37088001,.81836802,.43900099),new r(-.71390897,.12865201,.68831801),new r(-.295165,-.73866397,.60601401),new r(.186195,-.73836899,.648184),new r(.387523,-.35878301,.84917599),new r(.481022,.124846,.86777401),new r(.391808,.54505599,.741216),new r(-.0035359999,.36559799,.93076599),new r(-.42049801,.484961,.76680797),new r(-.35490301,.019470001,.93470001),new r(-.54783702,-.35920799,.75554299),new r(-.106662,-.445115,.88909799),new r(.086796001,-.059307002,.99445897)],m=[new r(.52657801,-.35962099,-.77031702),new r(.150482,.43598399,.88728398),new r(.414195,.73825502,-.53237402),new r(.075152002,.91624898,-.393498),new r(-.316149,.93073601,-.18379299),new r(-.77381903,.62333399,-.11251),new r(-.90084201,.42853701,-.069568001),new r(-.99894202,-.010971,.044665001),new r(-.979761,-.15767001,-.123324),new r(-.91127402,-.362371,-.19562),new r(-.62406898,-.72094101,-.301301),new r(-.310173,-.80934501,-.498752),new r(.146613,-.81581903,-.55941403),new r(-.71651602,-.69435602,-.066887997),new r(.50397199,-.114202,-.85613698),new r(.45549101,.87262702,-.176211),new r(-.00501,-.114373,-.99342501),new r(-.104675,-.327701,-.93896502),new r(.56041199,.75258899,-.34575599),new r(-.060575999,.82162797,-.566796),new r(-.30234101,.79700702,-.522847),new r(-.671543,.67074001,-.314863),new r(-.77840102,-.12835699,.61450499),new r(-.92404997,.278382,-.261985),new r(-.69977301,-.55049098,-.45527801),new r(-.56824797,-.51718903,-.64000797),new r(.054097999,-.93286401,-.356143),new r(.75838202,.57289302,-.31088799),new r(.0036200001,.30502599,-.95233703),new r(-.060849998,-.98688602,-.14951099),new r(.63523,.045478001,-.77098298),new r(.52170497,.241309,-.81828701),new r(.26940399,.63542497,-.72364098),new r(.045676,.67275399,-.738455),new r(-.180511,.67465699,-.71571898),new r(-.397131,.63664001,-.66104198),new r(-.55200398,.47251499,-.687038),new r(-.77217001,.08309,-.62996),new r(-.669819,-.119533,-.73284),new r(-.54045498,-.31844401,-.77878201),new r(-.38613501,-.522789,-.75999397),new r(-.261466,-.68856698,-.676395),new r(-.019412,-.69610298,-.71767998),new r(.30356899,-.48184401,-.82199299),new r(.68193901,-.19512901,-.70490003),new r(-.24488901,-.116562,-.96251899),new r(.80075902,-.022979001,-.59854603),new r(-.37027499,.095583998,-.92399102),new r(-.33067101,-.32657799,-.88543999),new r(-.16322,-.52757901,-.83367902),new r(.12639,-.313146,-.941257),new r(.34954801,-.27222601,-.89649802),new r(.23991799,-.085825004,-.96699202),new r(.390845,.081537001,-.91683799),new r(.25526699,.26869699,-.92878503),new r(.146245,.48043799,-.86474901),new r(-.32601601,.47845599,-.81534898),new r(-.46968201,-.112519,-.87563598),new r(.81844002,-.25852001,-.51315099),new r(-.474318,.292238,-.83043301),new r(.778943,.39584199,-.48637101),new r(.62409401,.39377299,-.67487001),new r(.74088597,.203834,-.63995302),new r(.48021701,.565768,-.67029703),new r(.38093001,.42453501,-.82137799),new r(-.093422003,.50112402,-.86031801),new r(-.236485,.29619801,-.92538702),new r(-.131531,.093959004,-.98684901),new r(-.82356203,.29577699,-.48400599),new r(.61106598,-.624304,-.486664),new r(.069495998,-.52033001,-.85113299),new r(.226522,-.66487902,-.711775),new r(.47130799,-.56890398,-.67395699),new r(.38842499,-.74262398,-.54556),new r(.78367501,-.48072901,-.39338499),new r(.962394,.135676,-.235349),new r(.876607,.172034,-.449406),new r(.63340503,.58979303,-.50094098),new r(.182276,.80065799,-.57072097),new r(.177003,.76413399,.62029701),new r(-.544016,.675515,-.49772099),new r(-.67929697,.28646699,-.67564201),new r(-.59039098,.091369003,-.801929),new r(-.82436001,-.13312399,-.55018902),new r(-.71579403,-.33454201,-.61296099),new r(.17428599,-.89248401,.416049),new r(-.082528003,-.83712298,-.54075301),new r(.28333101,-.88087398,-.37918901),new r(.675134,-.42662701,-.60181701),new r(.84372002,-.512335,-.160156),new r(.97730398,-.098555997,-.18752),new r(.846295,.522672,-.102947),new r(.67714101,.72132498,-.145501),new r(.32096499,.87089199,-.37219399),new r(-.178978,.911533,-.37023601),new r(-.44716901,.82670099,-.341474),new r(-.70320302,.496328,-.50908101),new r(-.97718102,.063562997,-.202674),new r(-.87817001,-.412938,.241455),new r(-.83583099,-.35855001,-.415728),new r(-.499174,-.69343299,-.51959199),new r(-.188789,-.92375302,-.33322501),new r(.19225401,-.96936101,-.152896),new r(.51594001,-.783907,-.34539199),new r(.90592498,-.30095199,-.29787099),new r(.99111199,-.127746,.037106998),new r(.99513501,.098424003,-.0043830001),new r(.76012301,.64627701,.067367002),new r(.205221,.95958,-.192591),new r(-.042750001,.97951299,-.19679099),new r(-.43801701,.89892697,.0084920004),new r(-.82199401,.48078501,-.30523899),new r(-.89991701,.081710003,-.42833701),new r(-.92661202,-.144618,-.347096),new r(-.79365999,-.55779201,-.24283899),new r(-.43134999,-.84777898,-.30855799),new r(-.0054919999,-.96499997,.26219299),new r(.58790499,-.80402601,-.088940002),new r(.69949299,-.66768599,-.254765),new r(.88930303,.359795,-.282291),new r(.780972,.197037,.59267199),new r(.52012098,.50669599,.68755698),new r(.40389499,.69396102,.59605998),new r(-.154983,.89923602,.40909001),new r(-.65733802,.53716803,.528543),new r(-.74619502,.33409101,.575827),new r(-.62495202,-.049144,.77911502),new r(.31814101,-.254715,.913185),new r(-.555897,.405294,.725752),new r(-.79443401,.099405997,.59916002),new r(-.64036101,-.68946302,.33849499),new r(-.12671299,-.73409498,.66711998),new r(.105457,-.78081697,.61579502),new r(.40799299,-.48091599,.77605498),new r(.69513601,-.54512,.468647),new r(.97319102,-.0064889998,.229908),new r(.94689399,.317509,-.050799001),new r(.56358302,.82561201,.027183),new r(.325773,.94542301,.0069490001),new r(-.171821,.98509699,-.0078149997),new r(-.67044097,.73993897,.054768998),new r(-.822981,.55496198,.121322),new r(-.96619302,.117857,.229307),new r(-.95376903,-.29470399,.058945),new r(-.86438698,-.50272799,-.010015),new r(-.53060901,-.84200603,-.097365998),new r(-.162618,-.98407501,.071772002),new r(.081446998,-.99601102,.036439002),new r(.74598402,-.66596299,.00076199998),new r(.94205701,-.32926899,-.064106002),new r(.93970197,-.28108999,.194803),new r(.77121401,.55067003,.319363),new r(.641348,.73069,.23402099),new r(.080682002,.99669099,.0098789996),new r(-.046725001,.97664303,.20972501),new r(-.53107601,.82100099,.209562),new r(-.69581503,.65599,.29243499),new r(-.97612202,.216709,-.014913),new r(-.96166098,-.14412899,.23331399),new r(-.772084,-.61364698,.165299),new r(-.44960001,-.83605999,.314426),new r(-.39269999,-.91461599,.096247002),new r(.390589,-.91947001,.044890001),new r(.58252901,-.79919797,.148127),new r(.866431,-.48981199,.096864),new r(.90458697,.111498,.41145),new r(.95353699,.23232999,.191806),new r(.497311,.77080297,.398177),new r(.194066,.95631999,.218611),new r(.422876,.882276,.206797),new r(-.373797,.84956598,.37217399),new r(-.53449702,.71402299,.4522),new r(-.881827,.23716,.40759799),new r(-.904948,-.014069,.42528901),new r(-.751827,-.51281703,.41445801),new r(-.50101501,-.69791698,.51175803),new r(-.23519,-.92592299,.295555),new r(.228983,-.95393997,.193819),new r(.734025,-.63489801,.241062),new r(.91375297,-.063253,-.40131599),new r(.90573502,-.161487,.391875),new r(.85892999,.342446,.38074899),new r(.62448603,.60758102,.49077699),new r(.28926399,.85747898,.42550799),new r(.069968,.90216899,.42567101),new r(-.28617999,.94069999,.182165),new r(-.57401299,.80511898,-.14930899),new r(.111258,.099717997,-.98877603),new r(-.30539301,-.94422799,-.12316),new r(-.60116601,-.78957599,.123163),new r(-.290645,-.81213999,.50591898),new r(-.064920001,-.87716299,.47578499),new r(.408301,-.862216,.29978901),new r(.56609702,-.72556603,.39126399),new r(.83936399,-.427387,.33586901),new r(.81889999,-.041305002,.57244802),new r(.71978402,.41499701,.55649698),new r(.88174403,.45027,.140659),new r(.40182301,-.89822,-.17815199),new r(-.054019999,.79134399,.60898),new r(-.29377401,.76399398,.57446498),new r(-.450798,.61034697,.65135098),new r(-.63822103,.186694,.74687302),new r(-.87287003,-.25712699,.41470799),new r(-.58725703,-.52170998,.618828),new r(-.35365799,-.64197397,.680291),new r(.041648999,-.61127299,.79032302),new r(.348342,-.77918297,.52108699),new r(.499167,-.62244099,.602826),new r(.79001898,-.30383101,.53250003),new r(.66011798,.060733002,.74870199),new r(.60492098,.29416099,.73996001),new r(.38569701,.37934601,.84103203),new r(.239693,.207876,.94833201),new r(.012623,.25853199,.96591997),new r(-.100557,.457147,.88368797),new r(.046967,.62858802,.77631903),new r(-.43039101,-.44540501,.785097),new r(-.43429101,-.196228,.87913901),new r(-.25663701,-.336867,.90590203),new r(-.131372,-.15891001,.97851402),new r(.102379,-.208767,.972592),new r(.195687,-.450129,.87125802),new r(.62731898,-.42314801,.65377098),new r(.68743902,-.171583,.70568198),new r(.27592,-.021255,.96094602),new r(.45936701,.15746599,.87417799),new r(.285395,.583184,.76055598),new r(-.81217402,.46030301,.35846099),new r(-.189068,.64122301,.743698),new r(-.338875,.47648001,.811252),new r(-.92099398,.347186,.176727),new r(.040638998,.024465,.99887401),new r(-.73913199,-.35374701,.57318997),new r(-.60351199,-.28661501,.74405998),new r(-.188676,-.547059,.81555402),new r(-.026045,-.39782,.91709399),new r(.26789701,-.649041,.71202302),new r(.518246,-.28489101,.80638599),new r(.493451,-.066532999,.86722499),new r(-.328188,.140251,.93414301),new r(.328188,.140251,.93414301),new r(-.328188,.140251,.93414301),new r(-.328188,.140251,.93414301),new r(-.328188,.140251,.93414301)];class f{constructor(e,t,i){this.sizeX=e,this.sizeY=t,this.sizeZ=i,this.arr=new Array(e*t*i)}add(e){this.arr[e.x+e.y*this.sizeX+e.z*this.sizeX*this.sizeY]=e}get(e,t,i){if(!(e>=this.sizeX||t>=this.sizeY||i>=this.sizeZ))return this.arr[e+t*this.sizeX+i*this.sizeX*this.sizeY]}}var y=__webpack_require__(949);class 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=[],s=new f(this.sizeX+1,this.sizeY+1,this.sizeZ+1);for(let e=0,t=this.spans.length;e<t;e++){var r=this.spans[e].voxels;for(let e=0,t=r.length;e<t;e++){var a=r[e];i.push(a),s.add(a)}}return{voxels:i,voxelField:s}}getNormals(){switch(this.normalsMode){case 1:return u;case 2:return p;case 3:return g;case 4:return m;default:throw new Error(`Invalid normalsmode ${this.normalsMode}`)}}scaleHvaMatrix(e){return(e=e.clone()).elements[12]*=this.hvaMultiplier,e.elements[13]*=this.hvaMultiplier,e.elements[14]*=this.hvaMultiplier,e}toPlain(){return{name:this.name,normalsMode:this.normalsMode,minBounds:this.minBounds.toArray(),maxBounds:this.maxBounds.toArray(),sizeX:this.sizeX,sizeY:this.sizeY,sizeZ:this.sizeZ,hvaMultiplier:this.hvaMultiplier,transfMatrix:this.transfMatrix.toArray(),spans:this.spans}}fromPlain(e){return this.name=e.name,this.normalsMode=e.normalsMode,this.minBounds=(new y.Vector3).fromArray(e.minBounds),this.maxBounds=(new y.Vector3).fromArray(e.maxBounds),this.sizeX=e.sizeX,this.sizeY=e.sizeY,this.sizeZ=e.sizeZ,this.hvaMultiplier=e.hvaMultiplier,this.transfMatrix=(new y.Matrix4).fromArray(e.transfMatrix),this.spans=e.spans,this}}class 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 r=e.stream;if(this.sections=[],!(r.byteLength<b.size)){let s=new b;if(s.read(r),s.headerCount&&s.tailerCount&&s.tailerCount===s.headerCount){for(let e=0;e<s.headerCount;++e){const n=new T;this.readSectionHeader(n,r),this.sections.find(e=>e.name===n.name)&&console.warn(`Duplicate section name "${n.name}" found in VXL "${this.filename}".`),this.sections.push(n)}var a=r.position;r.seek(r.position+s.bodySize);let t=[];for(let e=0;e<s.tailerCount;++e)t[e]=this.readSectionTailer(this.sections[e],r);let i=0;for(let e=0;e<s.headerCount;++e)r.seek(a),i+=this.readSectionBodySpans(this.sections[e],t[e],r);this.voxelCount=i}}}readSectionHeader(e,t){e.name=t.readCString(16),t.readUint32(),t.readUint32(),t.readUint32()}readSectionTailer(e,t){var i=t.readUint32(),s=t.readUint32(),r=t.readUint32();return e.hvaMultiplier=t.readFloat32(),e.transfMatrix=this.readTransfMatrix(t),e.minBounds=new v.Vector3(t.readFloat32(),t.readFloat32(),t.readFloat32()),e.maxBounds=new v.Vector3(t.readFloat32(),t.readFloat32(),t.readFloat32()),e.sizeX=t.readUint8(),e.sizeY=t.readUint8(),e.sizeZ=t.readUint8(),e.normalsMode=t.readUint8(),{startingSpanOffset:i,endingSpanOffset:s,dataSpanOffset:r}}readTransfMatrix(t){let i=[];for(let e=0;e<3;++e)i.push(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32());return i.push(0,0,0,1),(new v.Matrix4).fromArray(i).transpose()}readSectionBodySpans(e,t,i){i.seek(i.position+t.startingSpanOffset);var{sizeX:s,sizeY:r,sizeZ:a}=e;let n=new Array(r);for(let t=0;t<r;++t){n[t]=new Array(s);for(let e=0;e<s;++e)n[t][e]=i.readInt32()}let o=new Array(r);for(let t=0;t<r;++t){o[t]=new Array(s);for(let e=0;e<s;++e)o[t][e]=i.readInt32()}let h=e.spans=[],l=0;for(let t=0;t<r;++t)for(let e=0;e<s;++e){var c={x:e,y:t,voxels:this.readSpanVoxels(n[t][e],o[t][e],e,t,a,i)};h.push(c),l+=c.voxels.length}return l}readSpanVoxels(e,t,i,s,r,a){if(-1===e||-1===t)return[];let n=[];for(let t=0;t<r;){t+=a.readUint8();var o=a.readUint8();for(let e=0;e<o;++e){var h={x:i,y:s,z:t++,colorIndex:a.readUint8(),normalIndex:a.readUint8()};n.push(h)}a.readUint8()}return n}fromPlain(e){return this.sections=e.sections.map(e=>(new 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);(r=_=_||{})[r.ExtraData=1]="ExtraData",r[r.ZData=2]="ZData",r[r.DamagedData=4]="DamagedData";const B=e=>e<0?e+256:e;class x{constructor(e,t,i){this.fromStream(e,t,i)}fromStream(e,t,i){this.x=e.readInt32(),this.y=e.readInt32(),e.readInt32(),e.readInt32();var s=e.readInt32();this.extraX=e.readInt32(),this.extraY=e.readInt32(),this.extraWidth=e.readInt32(),this.extraHeight=e.readInt32();var r=e.readUint32();this.height=e.readUint8(),this.terrainType=e.readUint8(),this.rampType=e.readUint8(),this.radarLeft=this.readRadarRgb(e.readInt8(),e.readInt8(),e.readInt8()),this.radarRight=this.readRadarRgb(e.readInt8(),e.readInt8(),e.readInt8()),e.seek(e.position+3),this.tileData=new Uint8Array(e.buffer,e.byteOffset+e.position,t*i/2),e.position+=t*i/2,this.hasZData=(r&_.ZData)===_.ZData,this.hasZData&&(e.position+=t*i/2),this.hasExtraData=(r&_.ExtraData)===_.ExtraData,this.hasExtraData&&(r=Math.abs(this.extraWidth*this.extraHeight),this.extraData=new Uint8Array(e.buffer,e.byteOffset+e.position,r),e.position+=r),this.hasZData&&this.hasExtraData&&0<s&&s<e.byteLength&&(e.position+=Math.abs(this.extraWidth*this.extraHeight))}readRadarRgb(e,t,i){return new C.Color(B(e)/255,B(t)/255,B(i)/255)}}class E{constructor(e){this.images=[],e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){let t=e.stream;this.width=t.readInt32(),this.height=t.readInt32(),this.blockWidth=t.readInt32(),this.blockHeight=t.readInt32();var i=this.width*this.height,s=new Uint8Array(t.buffer,t.byteOffset+t.position,4*i);this.images=[];for(let e=0;e<i;e++){var r=s[4*e+3]<<24|s[4*e+2]<<16|s[4*e+1]<<8|s[4*e];t.seek(r);r=new x(t,this.blockWidth,this.blockHeight);this.images.push(r)}}}class P{static encode(e){return void 0!==globalThis.btoa?globalThis.btoa(e):Buffer.from(e,"binary").toString("base64")}static decode(e){return void 0!==globalThis.atob?globalThis.atob(e):Buffer.from(e,"base64").toString("binary")}}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 s=new Uint8Array(i);for(let e=0;e<i;e++)s[e]=t.charCodeAt(e);return s}function M(e){return D(P.decode(e))}function L(t){var i=t.length;let s="";for(let e=0;e<i;e++){var r=t.charCodeAt(e);s+=String.fromCharCode(r>>8),s+=String.fromCharCode(255&r)}return s}function F(t){var i=t.length;let s="";for(let e=0;e<i;e+=2){var r=(t.charCodeAt(e)<<8)+t.charCodeAt(e+1);s+=String.fromCharCode(r)}return s}class 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 s=0,r=0,a=0;if(e=e/255*360%360,i/=255,0===(t/=255))s=i,r=i,a=i;else{var n=e/60,e=Math.floor(n),n=n-e,o=i*(1-t),h=i*(1-t*n),l=i*(1-t*(1-n));switch(e){case 0:s=i,r=l,a=o;break;case 1:s=h,r=i,a=o;break;case 2:s=o,r=i,a=l;break;case 3:s=o,r=h,a=i;break;case 4:s=l,r=o,a=i;break;case 5:s=i,r=o,a=h}}return j.fromRgb(Math.floor(255*s),Math.floor(255*r),Math.floor(255*a))}asHex(){return(this.r<<16)+(this.g<<8)+this.b}asHexString(){return"#"+N(this.asHex().toString(16),"000000")}clone(){return new j(this.r,this.g,this.b)}}function U(e,t,i){return Math.min(i,Math.max(e,t))}function W(e,t,i){return t<=e&&e<=i}function z(e,t,i){return(1-i)*e+i*t}function V(i){let s=2166136261;for(let e=0,t=i.length;e<t;++e)s^=i[e],s+=(s<<1)+(s<<4)+(s<<7)+(s<<8)+(s<<24);return s>>>0}class H{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 s of e)t[i]=s.r,t[i+1]=s.g,t[i+2]=s.b,i+=3;return V(t)}clone(){let e=new H;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=H.REMAP_START_IDX;e<H.REMAP_START_IDX+i.length;e++)this.colors[e].r=Math.floor(t.r/255*i[e-H.REMAP_START_IDX]*4),this.colors[e].g=Math.floor(t.g/255*i[e-H.REMAP_START_IDX]*4),this.colors[e].b=Math.floor(t.b/255*i[e-H.REMAP_START_IDX]*4);return this._hash=this.computeHash(this.colors),this}}H.REMAP_START_IDX=16;class G{constructor(e,t){this.owner=e,this.index=t,this.files=[]}addFile(e){this.files.push(e)}setAnimation(e){this.animation=e}getAnimation(){return this.animation}getTmpFile(e,t,i=!1){if(this.files.length){t=this.files[t(0,this.files.length-1)];return t.images[Math.min(e,t.images.length-1)].hasDamagedData?this.files[Math.min(i?1:0,this.files.length-1)]:t}}}class ${constructor(e,t,i){this.fileName=e,this.setName=t,this.tilesInSet=i,this.entries=[]}}class q{constructor(e,t,i,s){this.name=e,this.subTile=t,this.offsetX=i,this.offsetY=s}}(r=k=k||{})[r.TopLeft=0]="TopLeft",r[r.BottomRight=1]="BottomRight",r[r.TopRight=2]="TopRight",r[r.BottomLeft=3]="BottomLeft",r[r.MiddleTlBr=4]="MiddleTlBr",r[r.MiddleTrBl=5]="MiddleTrBl";const X=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 Q{constructor(e){this.theaterIni=e,this.tileSets=[],this.orderedEntries=[],this.highBridgeSetNums=[this.getGeneralValue("BridgeSet"),this.getGeneralValue("WoodBridgeSet")],this.cliffSetNums=[this.getGeneralValue("CliffSet"),this.getGeneralValue("WaterCliffs"),this.getGeneralValue("DestroyableCliffs")]}getTile(e){return this.orderedEntries[e]}getTileImage(e,t,i){let s=this.getTile(e);if(!s)throw new Error(`TileNum ${e} not found`);i=s.getTmpFile(t,i);if(!i||t>=i.images.length)throw new Error(`SubTile ${t} not found`);return i.images[t]}getSetNum(e){var t=this.orderedEntries[e];if(!t)throw new Error("Invalid tileNum "+e);return this.tileSets.indexOf(t.owner)}getTileNumFromSet(i,s=0){let r=0;return this.tileSets.some((e,t)=>t===i?(r+=s,!0):(r+=e.entries.length,!1)),r}getGeneralValue(e){let t=this.theaterIni.getSection("General");if(!t)throw new Error("Missing [General] section in theather ini");return t.getNumber(e)}loadTileData(e,t){this.tileSets.length=0,this.orderedEntries.length=0,this.initTileSets(e,t),this.initAnimations()}readMaxTileNum(){let t=0,i=0;for(;;){var s="TileSet"+N(t,"0000");let e=this.theaterIni.getSection(s);if(!e)break;t++,i+=e.getNumber("TilesInSet")}return i}initTileSets(a,n){let e=0,t;for(var i;;){if(i="TileSet"+N(e,"0000"),t=this.theaterIni.getSection(i),!t)break;e++;let r=new $(t.getString("FileName"),t.getString("SetName"),t.getNumber("TilesInSet"));this.tileSets.push(r);for(let s=1;s<=r.tilesInSet;s++){let i=new G(r,s-1);var o="a".charCodeAt(0);for(let t=o-1;t<="z".charCodeAt(0);t++)if(!(t>=o&&"Bridges"===r.setName)){let e=r.fileName+N(s,"00");t>=o&&(e+=String.fromCharCode(t)),e+=n;var h=a.get(e);if(!h)break;i.addFile(h)}r.entries.push(i),this.orderedEntries.push(i)}}}initAnimations(){var s=this.theaterIni.getOrderedSections();for(let e=this.tileSets.length;e<s.length;++e){let t=s[e],i=this.tileSets.find(e=>e.setName===t.name);if(i)for(let e=1;e<=i.tilesInSet;++e){var r=`Tile${N(e,"00")}`,a=`${r}Anim`,n=t.getString(a);n?(r=new q(n,t.getNumber(`${r}AttachesTo`),t.getNumber(`${r}XOffset`),t.getNumber(`${r}YOffset`)),i.entries[e-1].setAnimation(r)):console.warn(`Missing anim "${a}" for tileset ${i.setName}`)}}}isLAT(e){return e===this.getGeneralValue("RoughTile")||e===this.getGeneralValue("SandTile")||e===this.getGeneralValue("GreenTile")||e===this.getGeneralValue("PaveTile")}isCLAT(e){return e===this.getGeneralValue("ClearToRoughLat")||e===this.getGeneralValue("ClearToSandLat")||e===this.getGeneralValue("ClearToGreenLat")||e===this.getGeneralValue("ClearToPaveLat")}getLAT(e){return e===this.getGeneralValue("ClearToRoughLat")?this.getGeneralValue("RoughTile"):e===this.getGeneralValue("ClearToSandLat")?this.getGeneralValue("SandTile"):e===this.getGeneralValue("ClearToGreenLat")?this.getGeneralValue("GreenTile"):e===this.getGeneralValue("ClearToPaveLat")?this.getGeneralValue("PaveTile"):-1}getCLATSet(e){return e===this.getGeneralValue("RoughTile")?this.getGeneralValue("ClearToRoughLat"):e===this.getGeneralValue("SandTile")?this.getGeneralValue("ClearToSandLat"):e===this.getGeneralValue("GreenTile")?this.getGeneralValue("ClearToGreenLat"):e===this.getGeneralValue("PaveTile")?this.getGeneralValue("ClearToPaveLat"):-1}canConnectTiles(e,t){if(e===t)return!1;var i=this.getGeneralValue("GreenTile"),s=this.getGeneralValue("PaveTile"),r=this.getGeneralValue("MiscPaveTile"),a=this.getGeneralValue("ShorePieces"),n=this.getGeneralValue("WaterBridge"),o=this.getGeneralValue("PavedRoads"),h=this.getGeneralValue("Medians");return!(e===i&&t===a||t===i&&e===a)&&(!(e===i&&t===n||t===i&&e===n)&&(!(e===s&&t===o||t===s&&e===o)&&(!(e===s&&t===r||t===s&&e===r)&&!(e===s&&t===h||t===s&&e===h))))}getHighBridgeHeadType(e){for(var[t,i]of X)for(var s of i)if(this.getGeneralValue(s)===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}}(r=O=O||{})[r.None=0]="None",r[r.Iso=1]="Iso",r[r.Unit=2]="Unit",r[r.Overlay=3]="Overlay",r[r.Anim=4]="Anim",r[r.Custom=5]="Custom",r[r.Default=6]="Default";class Z{constructor(e,t,i,s,r,a,n,o,h){this.type=e,this.settings=t,this.palettes=i,this.isoPalette=s,this.ovlPalette=r,this.unitPalette=a,this.animPalette=n,this.libPalette=o,this.tileSets=h}static factory(e,t,i,s,r){var a=r.get(i.IsoPaletteName);if(!a)throw new Error(`Missing palette "${i.IsoPaletteName}"`);var n=r.get(i.OverlayPaletteName);if(!n)throw new Error(`Missing palette "${i.OverlayPaletteName}"`);var o=r.get(i.UnitPaletteName);if(!o)throw new Error(`Missing palette "${i.UnitPaletteName}"`);var h=r.get("anim.pal");if(!h)throw new Error("Missing anim palette");var l=r.get(i.LibPaletteName);if(!l)throw new Error(`Missing lib palette ${i.LibPaletteName}`);let c=new Q(t);return c.loadTileData(s,i.Extension),new this(e,i,r,a,n,o,h,l,c)}getPalette(e,t){switch(e){case 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}}}(r=I=I||{})[r.None=0]="None",r[r.Temperate=1]="Temperate",r[r.Urban=2]="Urban",r[r.Snow=4]="Snow",r[r.Lunar=8]="Lunar",r[r.Desert=16]="Desert",r[r.NewUrban=32]="NewUrban",r[r.All=63]="All";class Y{constructor(){this.fileData=new Map}fromVirtualFile(e,t){var i,s;for([i,s]of t.entries){var r=this.buildWavData(e.stream,s);this.fileData.set(i,r)}return this}getFileList(){return[...this.fileData.keys()]}containsFile(e){return this.fileData.has(e)}openFile(e){if(!this.containsFile(e))throw new Error(`File "${e}" not found`);return new i(this.fileData.get(e),e)}buildWavData(e,t){let i=new w;var s,r,a,n,o=0<(1&t.flags)?2:1;let h=0;0<(2&t.flags)?(i.writeString("RIFF"),i.writeUint32(t.length+36),i.writeString("WAVE"),i.writeString("fmt "),i.writeInt32(16),i.writeInt16(1),i.writeInt16(o),i.writeUint32(t.sampleRate),i.writeUint32(2*o*t.sampleRate),i.writeInt16(2*o),i.writeInt16(16),i.writeString("data"),i.writeUint32(t.length)):0<(8&t.flags)&&(s=11100*o*(t.sampleRate/22050|0),r=t.chunkSize,a=1017*(n=Math.max(2,Math.ceil(t.length/r))),n=n*r,h=n-t.length,i.writeString("RIFF"),i.writeUint32(52+n),i.writeString("WAVE"),i.writeString("fmt "),i.writeUint32(20),i.writeInt16(17),i.writeInt16(o),i.writeUint32(t.sampleRate),i.writeInt32(s),i.writeInt16(r),i.writeInt16(4),i.writeInt16(2),i.writeInt16(1017),i.writeString("fact"),i.writeUint32(4),i.writeInt32(a),i.writeString("data"),i.writeUint32(n)),e.seek(t.offset),i.writeUint8Array(e.readUint8Array(t.length));for(let e=0;e<h;e++)i.writeUint8(0);return i.seek(0),i._trimAlloc=()=>{},i}}class K{}class J{constructor(e){this.entries=new Map,this.parse(e)}parse(t){var e=t.readCString(4);if("GABA"!==e)throw new Error(`Unable to load Idx file, did not find magic id, found ${e} instead`);e=t.readInt32();if(2!==e)throw new Error(`Unable to load Idx file, did not find magic number 2, found ${e} instead`);var i=t.readInt32();for(let e=0;e<i;e++){const r=new K;let e=t.readString(16);var s=e.indexOf("\0");0!==s&&(e=e.substr(0,s)),r.filename=e+".wav",r.offset=t.readUint32(),r.length=t.readUint32(),r.sampleRate=t.readUint32(),r.flags=t.readUint32(),r.chunkSize=t.readUint32(),this.entries.set(r.filename,r)}}}function ee(e){return e=((e=(e<<16>>>0|e>>>16)>>>0)<<8>>>0&4278255360|e>>>8&16711935)>>>0}class te{constructor(i){this.m_p=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731]),this.m_s=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])];for(let e=0,t=0;e<18;++e){var s=i[t++%i.length],r=i[t++%i.length],a=i[t++%i.length],n=i[t++%i.length];this.m_p[e]^=s<<24|r<<16|a<<8|n}let o=0,h=0;for(let e=0;e<18;)[o,h]=this._encrypt(o,h),this.m_p[e++]=o,this.m_p[e++]=h;for(let t=0;t<4;++t)for(let e=0;e<256;)[o,h]=this._encrypt(o,h),this.m_s[t][e++]=o,this.m_s[t][e++]=h}encrypt(e){return this.runCipher(e,this._encrypt.bind(this))}decrypt(e){return this.runCipher(e,this._decrypt.bind(this))}runCipher(e,t){let i=new Uint32Array(e.length),s=e.length/2|0,r=0;for(;0<s--;){var a=ee(e[r]),n=ee(e[r+1]);[a,n]=t(a,n),i[r++]=ee(a),i[r++]=ee(n)}return i}_encrypt(e,t){let i=e,s=t;i^=this.m_p[0];let r=!1;for(let e=1;e<=16;e++,r=!r)r?i=this.round(i,s,e):s=this.round(s,i,e);return s^=this.m_p[17],[s,i]}_decrypt(e,t){let i=e,s=t;i^=this.m_p[17];let r=!1;for(let e=16;1<=e;e--,r=!r)r?i=this.round(i,s,e):s=this.round(s,i,e);return s^=this.m_p[0],[s,i]}s(e,t){return this.m_s[t][e>>(3-t<<3)&255]}bf_f(e){return(this.s(e,0)+this.s(e,1)>>>0^this.s(e,2))+this.s(e,3)>>>0}round(e,t,i){return e^(this.bf_f(t)^this.m_p[i])}}const ie="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 re{constructor(){this.key1=new Uint32Array(64),this.key2=new Uint32Array(64)}}class ae{constructor(){this.pubkey=new re,this.glob1=new Uint32Array(64),this.glob2=new Uint32Array(130),this.glob1_hi=new Uint32Array(4),this.glob1_hi_inv=new Uint32Array(4)}init_bignum(t,e,i){for(let e=0;e<i;e++)t[e]=0;t[0]=e}move_key_to_big(e,t,i,s){let r;r=0!=(128&t[0])?255:0;const a=new Uint8Array(e.buffer,e.byteOffset);let n=4*s;for(;n>i;n--)a[n-1]=r;for(;0<n;n--)a[n-1]=t[i-n]}key_to_bignum(e,t,i){let s,r,a=0;if(2===t[a]){if(a++,0!=(128&t[a])){for(s=0,r=0;r<(127&t[a]);r++)s=(s<<8>>>0|t[a+r+1])>>>0;a+=1+(127&t[a])}else s=t[a],a++;s<=4*i&&this.move_key_to_big(e,t.subarray(a),s,i)}}len_bignum(e,t){let i=t-1;for(;0<=i&&0===e[i];)i--;return i+1}bitlen_bignum(e,t){var i;let s,r;if(0===(i=this.len_bignum(e,t)))return 0;for(s=32*i,r=2147483648;0==(r&e[i-1]);)r>>>=1,s--;return s}init_pubkey(){let e=0,t;var i;const s=new Uint8Array(256);for(this.init_bignum(this.pubkey.key2,65537,64),t=0;e<ie.length;)i=(((se[ie.charCodeAt(e++)]>>>0<<6>>>0|255&se[ie.charCodeAt(e++)])>>>0<<6>>>0|255&se[ie.charCodeAt(e++)])>>>0<<6>>>0|255&se[ie.charCodeAt(e++)])>>>0,s[t++]=i>>16&255,s[t++]=i>>8&255,s[t++]=255&i;this.key_to_bignum(this.pubkey.key1,s,64),this.pubkey.len=this.bitlen_bignum(this.pubkey.key1,64)-1}len_predata(){var e=(this.pubkey.len-1)/8|0;return(1+(55/e|0))*(1+e)>>>0}cmp_bignum(e,t,i){for(;0<i;){if(e[--i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}mov_bignum(t,i,s){for(let e=0;e<s;e++)t[e]=i[e]}shr_bignum(e,t,i){let s;var r=t/32|0;if(0<r){for(s=0;s<i-r;s++)e[s]=e[s+r];for(;s<i;s++)e[s]=0;t%=32}if(0!==t){for(s=0;s<i-1;s++)e[s]=(e[s]>>>t|e[s+1]<<32-t>>>0)>>>0;e[s]=e[s]>>>t}}shl_bignum(e,t,i){let s;var r=t/32|0;if(0<r){for(s=i-1;s>r;s--)e[s]=e[s-r];for(;0<s;s--)e[s]=0;t%=32}if(0!==t){for(s=i-1;0<s;s--)e[s]=(e[s]<<t>>>0|e[s-1]>>>32-t)>>>0;e[0]=e[0]<<t>>>0}}sub_bignum(e,t,i,s,r){var a,n;r+=r;var o=new Uint16Array(t.buffer,t.byteOffset),h=new Uint16Array(i.buffer,i.byteOffset);const l=new Uint16Array(e.buffer,e.byteOffset);let c=0;for(;-1!=--r;)a=o[c],n=h[c],l[c]=a-n-s&65535,s=0!=(a-n-s&65536)?1:0,c++;return s}sub_bignum_word(e,t,i,s,r){var a,n;let o=0;for(;-1!=--r;)a=t[o],n=i[o],e[o]=a-n-s&65535,s=0!=(a-n-s&65536)?1:0,o++;return s}inv_bignum(e,t,i){const s=new Uint32Array(64);var r;let a,n,o=0;for(this.init_bignum(s,0,i),this.init_bignum(e,0,i),n=this.bitlen_bignum(t,i),a=1<<n%32>>>0,o=((n+32)/32|0)-1,r=4*((n-1)/32|0)>>>0,s[r/4|0]=s[r/4|0]|1<<(n-1&31)>>>0;0<n;)n--,this.shl_bignum(s,1,i),-1!==this.cmp_bignum(s,t,i)&&(this.sub_bignum(s,s,t,0,i),e[o]=e[o]|a>>>0),a>>>=1,0===a&&(o--,a=2147483648);this.init_bignum(s,0,i)}inc_bignum(e,t){let i=0;for(;0==++e[i]&&0<--t;)i++}init_two_dw(e,t){this.mov_bignum(this.glob1,e,t),this.glob1_bitlen=this.bitlen_bignum(this.glob1,t),this.glob1_len_x2=(this.glob1_bitlen+15)/16|0,this.mov_bignum(this.glob1_hi,this.glob1.subarray(this.len_bignum(this.glob1,t)-2),2),this.glob1_hi_bitlen=this.bitlen_bignum(this.glob1_hi,2)-32>>>0,this.shr_bignum(this.glob1_hi,this.glob1_hi_bitlen,2),this.inv_bignum(this.glob1_hi_inv,this.glob1_hi,2),this.shr_bignum(this.glob1_hi_inv,1,2),this.glob1_hi_bitlen=(this.glob1_hi_bitlen+15)%16+1>>>0,this.inc_bignum(this.glob1_hi_inv,2),32<this.bitlen_bignum(this.glob1_hi_inv,2)&&(this.shr_bignum(this.glob1_hi_inv,1,2),this.glob1_hi_bitlen--),this.glob1_hi_inv_lo=65535&this.glob1_hi_inv[0],this.glob1_hi_inv_hi=this.glob1_hi_inv[0]>>>16&65535}mul_bignum_word(e,t,i,s){let r,a;var n=new Uint16Array(t.buffer,t.byteOffset);let o=a=0;for(r=0;r<s;r++)a=i*n[o]+e[o]+a,e[o]=65535&a,o++,a>>>=16;e[o]+=65535&a}mul_bignum(e,t,i,s){let r;var a=new Uint16Array(i.buffer,i.byteOffset);let n=new Uint16Array(e.buffer,e.byteOffset);this.init_bignum(e,0,2*s);let o=0;for(r=0;r<2*s;r++)this.mul_bignum_word(n.subarray(o),t,a[o],2*s),o++}not_bignum(e,t){let i;for(i=0;i<t;i++)e[i]=~e[i]>>>0}neg_bignum(e,t){this.not_bignum(e,t),this.inc_bignum(e,t)}get_mulword(e,t){let i=((((65535&(65535^e[t-1]))*this.glob1_hi_inv_lo+65536>>>1)+((65535^e[t-2])*this.glob1_hi_inv_hi+this.glob1_hi_inv_hi>>>1)+1>>>16)+((65535&(65535^e[t-1]))*this.glob1_hi_inv_hi>>>1)+((65535^e[t])*this.glob1_hi_inv_lo>>>1)+1>>>14)+this.glob1_hi_inv_hi*(65535^e[t])*2>>>this.glob1_hi_bitlen>>>0;return 65535<i&&(i=65535),65535&i}dec_bignum(e,t){let i=0;for(;--e[i]>>>0==4294967295&&0<--t;)i++}calc_a_bignum(e,t,s,r){let a;var n=this.glob1,o=this.glob2;if(this.mul_bignum(this.glob2,t,s,r),this.glob2[2*r]=0,(s=2*this.len_bignum(this.glob2,2*r+1))>=this.glob1_len_x2){this.inc_bignum(this.glob2,2*r+1),this.neg_bignum(this.glob2,2*r+1),a=1+s-this.glob1_len_x2;let e=new Uint16Array(o.buffer),t=a,i=1+s;for(;0!==a;a--){i--;var h=this.get_mulword(e,i);t--;var l=e.subarray(t);0<h&&(this.mul_bignum_word(l,this.glob1,h,2*r),0==(32768&e[i])&&0!==this.sub_bignum_word(l,l,new Uint16Array(n.buffer),0,2*r)&&e[i]--)}this.neg_bignum(this.glob2,r),this.dec_bignum(this.glob2,r)}this.mov_bignum(e,this.glob2,r)}clear_tmp_vars(e){this.init_bignum(this.glob1,0,e),this.init_bignum(this.glob2,0,e),this.init_bignum(this.glob1_hi_inv,0,4),this.init_bignum(this.glob1_hi,0,4),this.glob1_bitlen=0,this.glob1_hi_bitlen=0,this.glob1_len_x2=0,this.glob1_hi_inv_lo=0,this.glob1_hi_inv_hi=0}calc_a_key(e,t,i,s,r){var a,n=new Uint32Array(64);let o,h,l=0;for(this.init_bignum(e,1,r),a=this.len_bignum(s,r),this.init_two_dw(s,a),o=this.bitlen_bignum(i,a)<<24>>24,s=((o+31)/32|0)>>>0,h=1<<(o-1)%32>>>1,l+=s-1,o--,this.mov_bignum(e,t,a);-1!=--o;)0===h&&(h=2147483648,l--),this.calc_a_bignum(n,e,e,a),0!=(i[l]&h)?this.calc_a_bignum(e,n,t,a):this.mov_bignum(e,n,a),h>>>=1;this.init_bignum(n,0,a),this.clear_tmp_vars(r)}memcpy(e,t,i){let s=0;for(;0!=i--;)e[s]=t[s],s++}process_predata(e,t,i){var s=new Uint32Array(64),r=new Uint32Array(64);let a=0,n=0;for(var o=(this.pubkey.len-1)/8|0;1+o<=t;)this.init_bignum(s,0,64),this.memcpy(new Uint8Array(s.buffer),e.subarray(a),1+o),this.calc_a_key(r,s,this.pubkey.key2,this.pubkey.key1,64),this.memcpy(i.subarray(n),new Uint8Array(r.buffer),o),t-=1+o,a+=1+o,n+=o}decryptKey(e){this.init_pubkey();let t=new Uint8Array(256);return this.process_predata(e,this.len_predata(),t),t.subarray(0,56)}}class ne{constructor(e=4294967295){this.polynomal=e,this.crc=e}static calculateCrc(i,e=4294967295){let s=e;for(let e=0,t=i.length;e<t;e++)s=(s>>>8^this.lookUp[255&s^i[e]])>>>0;return s=(s^e)>>>0,s}append(i){for(let e=0,t=i.length;e<t;e++)this.crc=(this.crc>>>8^ne.lookUp[255&this.crc^i[e]])>>>0}get(){return(this.crc^this.polynomal)>>>0}}ne.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 oe{constructor(e,t,i){this.hash=e,this.offset=t,this.length=i}static hashFilename(t){var i=(t=t.toUpperCase()).length,s=i>>2;if(0!=(3&i)){t+=String.fromCharCode(i-(s<<2));let e=3-(3&i);for(;0!=e--;)t+=t[s<<2]}return ne.calculateCrc(D(t))}}oe.size=12,(r=A=A||{})[r.Checksum=65536]="Checksum",r[r.Encrypted=131072]="Encrypted";class he{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 ae).decryptKey(t),s=e.readUint32Array(2);const r=new te(i);let a=new w(r.decrypt(s));t=a.readUint16();a.readUint32(),e.position=this.headerStart;i=6+t*oe.size,t=(3+i)/4|0,s=e.readUint32Array(t+t%2);a=new w(r.decrypt(s));i=this.headerStart+i+(1+(~i>>>0)&7);return this.parseTdHeader(a),i}parseTdHeader(t){var i=t.readUint16();t.readUint32();for(let e=0;e<i;e++){var s=new oe(t.readUint32(),t.readUint32(),t.readUint32());this.index.set(s.hash,s)}return t.position}containsFile(e){return this.index.has(oe.hashFilename(e))}openFile(e){var t=this.index.get(oe.hashFilename(e));if(!t)throw new Error(`File "${e}" not found`);return i.factory(this.stream,e,this.dataStart+t.offset,t.length)}}class le extends Error{constructor(){super(...arguments),this.name="FileNotFoundError"}}class ce{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 ue{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 le(`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 he(e.stream))}async addBagFile(e){const i=await this.openFileWithRfs(e.replace(".bag",".idx"));await this.addArchiveByFilename(e,e=>{var t=new J(i.stream);return(new Y).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 le))throw e}if(!t){if(!this.fileExists(e))throw new le(`File "${e}" not found`);t=this.openFile(e)}return t}async loadImplicitMixFiles(e){this.logger.info("Initializing implicit mix files..."),e===At.YurisRevenge&&await this.addMixFile("langmd.mix"),await this.addMixFile("language.mix"),e===At.YurisRevenge&&await this.addMixFile("ra2md.mix"),await this.addMixFile("ra2.mix"),e===At.YurisRevenge&&await this.addMixFile("cachemd.mix"),await this.addMixFile("cache.mix"),e===At.YurisRevenge&&await this.addMixFile("loadmd.mix"),await this.addMixFile("load.mix"),e===At.YurisRevenge&&await this.addMixFile("localmd.mix"),await this.addMixFile("local.mix"),e===At.YurisRevenge&&await this.addMixFile("ntrlmd.mix"),await this.addMixFile("neutral.mix"),e===At.YurisRevenge&&await this.addMixFile("audiomd.mix"),await this.addMixFile("audio.mix"),await this.addBagFile("audio.bag"),await this.addMixFile("conquer.mix"),e===At.YurisRevenge&&(await this.addMixFile("conqmd.mix"),await this.addMixFile("genermd.mix")),await this.addMixFile("generic.mix"),e===At.YurisRevenge&&await this.addMixFile("isogenmd.mix"),await this.addMixFile("isogen.mix"),e===At.YurisRevenge&&await this.addMixFile("cameomd.mix"),await this.addMixFile("cameo.mix"),e===At.YurisRevenge&&await this.addMixFile("multimd.mix"),await this.addMixFile("multi.mix")}async loadExtraMixFiles(i){let s=new Set;for await(var e of this.rfs.getEntries())s.add(e.toLowerCase());for(var r of["ecache","expand","elocal"])for(let t=99;0<=t;t--){let e=[`${r}${N(t,"00")}.mix`];i===At.YurisRevenge&&e.push(`${r}md${N(t,"00")}.mix`);for(var a of e)s.has(a)&&await this.addMixFile(a)}let t=[".mmx"];i===At.YurisRevenge&&t.push(".yro");for(const n of t)for(const o of s)o.endsWith(n)&&this.addArchive(new he((await this.rfs.openFile(o)).stream),o)}async loadStandaloneFiles(e){let i=["ini","csf"],s=new Set(e?.exclude),r=[];for await(var a of this.rfs.getEntries()){let t=a.toLowerCase();i.some(e=>t.endsWith("."+e))&&!s.has(t)&&r.push(await this.rfs.openFile(a,!0))}if(r.length){let e=new ce;for(var t of r)e.addFile(t);this.addArchive(e,"mem.archive")}}}class de extends Error{constructor(e){super("Storage quota exceeded",e),this.name="StorageQuotaError"}}class pe extends l{constructor(){super(...arguments),this.name="NameNotAllowedError"}}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 le(`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 le(`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 s;try{var r=e?t:await this.fixEntryCase(t);s=await this.handle.getFileHandle(r)}catch(e){if("NotFoundError"===e.name)throw new le(`File "${t}" not found in directory "${this.handle.name}"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new pe(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be read (${e.name})`,{cause:e});throw e}t=await s.getFile();return i?new File([t],t.name,{type:i}):t}async openFile(e,t=!1){t=await this.getRawFile(e,t);return i.fromRealFile(t)}async writeFile(i,s){s=s??(i instanceof File?i.name:i.filename);try{var r=await this.fixEntryCase(s);await this.deleteFile(r,!0);let e=await this.handle.getFileHandle(r,{create:!0}),t=await e.createWritable();try{await t.write(i instanceof File?i:new Uint8Array(i.stream.buffer,i.stream.byteOffset,i.stream.byteLength)),await t.close()}catch(e){throw await t.abort(),e}}catch(e){if("QuotaExceededError"===e.name)throw new de({cause:e});if("NotFoundError"===e.name)throw new le(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new pe(`File name "${s}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${s}" could not be written (${e.name})`,{cause:e});throw e}}async deleteFile(t,i=!1){t=i?t:await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t)}catch(e){if(i&&"NotFoundError"===e.name)return;if("QuotaExceededError"===e.name)throw new de({cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new pe(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}async getDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);let s;try{s=await this.handle.getDirectoryHandle(i)}catch(e){if("NotFoundError"===e.name)throw new le(`Directory "${t}" not found or parent directory "${this.handle.name}" is gone`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new pe(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be read (${e.name})`,{cause:e});throw e}return new ge(s,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 de({cause:e});if("NotFoundError"===e.name)throw new le(`Directory "${this.handle.name}" not found"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new pe(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be created (${e.name})`,{cause:e});throw e}}async deleteDirectory(t,e=!1){t=await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t,{recursive:e})}catch(e){if("QuotaExceededError"===e.name)throw new de({cause:e});if("InvalidModificationError"===e.name)throw new l("Can't delete non-empty directory when recursive = false");if(e instanceof TypeError&&e.message.includes("not allowed"))throw new pe(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}}class 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 le))throw e}throw new le(`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(s,e,r,t){if(-1<["32f","64"].indexOf(e)&&-1<["32f","64"].indexOf(t))r.set(s);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,s,!0);for(let e=0,t=s.length;e<t;e++)r[e]=i(s[e],a);_e(t,r,!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 s=t?-128:128;for(let e=0,t=i.length;e<t;e++)i[e]=i[e]+=s}}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 s={index:0,predicted:0,step:7};let r=new Uint8Array(i.length),a=[],n=0,o=0;for(let e=0,t=i.length;e<t;e++)e%505==0&&0!=e&&(r.set(function(i,s){let r=function(e,t){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],s);for(let e=3,t=i.length;e<t;e+=2){var a=Ce(i[e],s),n=Ce(i[e+1],s);r.push(n<<4|a)}return r}(a,s),n),n+=256,a=[],o++),a.push(i[e]);let e=i.length/2;return e%2&&e++,r.slice(0,e+512+4*o)}function Ae(t,e=256){var i={index:0,predicted:0,step:7};let s=new Int16Array(2*t.length),r=[],a=0,n=t.length,o=0;for(;0<n;){var h=Math.min(n,e);for(let e=0;e<h;e++)r.push(t[o]),o++;var l=function(i,s){s.predicted=function(e){return 32767<e?e-65536:e}(i[1]<<8|i[0]),s.index=i[2],s.step=Oe[s.index];let r=[s.predicted];for(let e=4,t=i.length;e<t;e++){var a=i[e],n=a>>4,a=n<<4^a;r.push(Be(a,s)),r.push(Be(n,s))}return r}(r,i);s.set(l,a),a+=l.length,r=[],n-=e}return s.slice(0,a)}function Ce(e,t){let i=e-t.predicted,s=0;0<=i?s=0:(s=8,i=-i);let r=Oe[t.index],a=r>>3;return i>r&&(s|=4,i-=r,a+=r),r>>=1,i>r&&(s|=2,i-=r,a+=r),r>>=1,i>r&&(s|=1,a+=r),function(e,t,i){8&e?i.predicted-=t:i.predicted+=t;i.predicted<-32768?i.predicted=-32768:32767<i.predicted&&(i.predicted=32767);i.index+=ke[7&e],i.index<0?i.index=0:88<i.index&&(i.index=88)}(s,a,t),s}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 xe=[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 Ee(i){let s=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){let t;var i,s=~(e=-32768==e?-32767:e)>>8&128;return s||(e*=-1),32635<e&&(e=32635),t=256<=e?(i=xe[e>>8&127])<<4|e>>i+3&15:e>>4,85^t^s}(i[e]);return s}function Pe(i){let s=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){let t=0;0!=(128&(e^=85))&&(e&=-129,t=-1);var i=4+((240&e)>>4);let s=0;return s=4!=i?1<<i|(15&e)<<i-4|1<<i-5:e<<1|1,s=0===t?s:-s,8*s*-1}(i[e]);return s}const 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 s=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=(r=i[e],a=void 0,0!=(a=r>>8&128)&&(r=-r),(r+=Ne)>Re&&(r=Re),~(a|(a=De[r>>7&255])<<4|r>>a+3&15));var r,a;return s}function Fe(i){let s=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){var t,i;let s;return t=128&(e=~e),i=e>>4&7,e=15&e,s=Me[i]+(e<<3+i),0!=t&&(s=-s),s}(i[e]);return s}function je(t,i,s=0,r=t.length){for(let e=s;e<r;e+=i)!function(t,i,s){i--;for(let e=0;e<i;e++){var r=t[s+e];t[s+e]=t[s+i],t[s+i]=r,i--}}(t,i,e)}function Ue(e,i,s=0){let r=0;for(var t=e.length;r<t;){var a=e.codePointAt(r);if(a<128)i[s]=a,s++;else{let e=0,t=0;for(a<=2047?(e=1,t=192):a<=65535?(e=2,t=224):a<=1114111&&(e=3,t=240,r++),i[s]=(a>>6*e)+t,s++;0<e;)i[s]=128|a>>6*(e-1)&63,s++,e--}r++}return s}const We=new Array(8).fill(0).map((e,t)=>Math.pow(2,8*t));class ze{constructor(e,t=!1){this.bits=e,this.offset=Math.ceil(e/8),this.max=Math.pow(2,e)-1,this.min=0,this.unpack=this.unpack_,t&&(this.max=Math.pow(2,e)/2-1,this.min=-this.max-1,this.unpack=this.unpackSigned_)}pack(i,s,r=0){s=this.clamp_(Math.round(s));for(let e=0,t=this.offset;e<t;e++)i[r]=255&Math.floor(s/We[e]),r++;return r}unpack_(t,i=0){let s=0;for(let e=0;e<this.offset;e++)s+=t[i+e]*We[e];return s}unpackSigned_(e,t=0){return this.sign_(this.unpack_(e,t))}clamp_(e){return e>this.max?this.max:e<this.min?this.min:e}sign_(e){return e>this.max&&(e-=2*this.max+2),e}}class Ve{constructor(e,t){this.offset=Math.ceil((e+t)/8),this.ebits=e,this.fbits=t,this.bias=(1<<e-1)-1,this.biasP2=Math.pow(2,this.bias+1),this.ebitsFbits=e+t,this.fbias=Math.pow(2,-(8*this.offset-1-e))}pack(e,t,i){var s=((t=+(t=Math.abs(t)>this.biasP2-2*this.ebitsFbits?t<0?-1/0:1/0:t))||1/t)<0||t<0?1:0;t=Math.abs(t);let r=Math.min(Math.floor(Math.log(t)/Math.LN2),1023),a=He(t/Math.pow(2,r)*Math.pow(2,this.fbits));return t!=t?(a=Math.pow(2,this.fbits-1),r=(1<<this.ebits)-1):0!==t&&(t>=Math.pow(2,1-this.bias)?(2<=a/Math.pow(2,this.fbits)&&(r+=1,a=1),a=r>this.bias?(r=(1<<this.ebits)-1,0):(r+=this.bias,He(a)-Math.pow(2,this.fbits))):(a=He(t/Math.pow(2,1-this.bias-this.fbits)),r=0)),this.packFloatBits_(e,i,s,r,a)}unpack(t,i){var e=(1<<this.ebits)-1;let s,r="";for(let e=this.offset-1;0<=e;e--){var a=t[e+i].toString(2);r+="00000000".substring(a.length)+a}var n="1"==r.charAt(0)?-1:1;r=r.substring(1);let o=parseInt(r.substring(0,this.ebits),2);return r=r.substring(this.ebits),o==e?0!==parseInt(r,2)?NaN:1/0*n:(s=0===o?(o+=1,parseInt(r,2)):parseInt("1"+r,2),n*s*this.fbias*Math.pow(2,o-this.bias))}packFloatBits_(e,t,i,s,r){let a=[];a.push(i);for(let e=this.ebits;0<e;--e)a[e]=s%2?1:0,s=Math.floor(s/2);var n=a.length;for(let e=this.fbits;0<e;--e)a[n+e]=r%2?1:0,r=Math.floor(r/2);let o=a.join(""),h=this.offset+t-1,l=t;for(;h>=t;)e[h]=parseInt(o.substring(0,8),2),o=o.substring(8),h--,l++;return l}}function 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,s=191,r=!1,a=o[n++];if(0<=a&&a<=127)h+=String.fromCharCode(a);else{let t=0;194<=a&&a<=223?t=1:224<=a&&a<=239?(t=2,224===o[n]&&(i=160),237===o[n]&&(s=159)):240<=a&&a<=244?(t=3,240===o[n]&&(i=144),244===o[n]&&(s=143)):r=!0,a&=(1<<8-t-1)-1;for(let e=0;e<t;e++)(o[n]<i||o[n]>s)&&(r=!0),a=a<<6|63&o[n],n++;r?h+=String.fromCharCode(65533):a<=65535?h+=String.fromCharCode(a):(a-=65536,h+=String.fromCharCode(55296+(a>>10&1023),56320+(1023&a)))}}return h}(e,t,i)}function $e(e){var t=[];return Ue(e,t),t}function qe(e,t,i=0){return Ue(e,t,i)}function Xe(e,t,i,s=0){let r=et((t=t||{}).bits,t.fp,t.signed);var a=Math.ceil(t.bits/8);let n=0;for(var o=s,h=e.length;n<h;n++)s=r.pack(i,e[n],s);return t.be&&je(i,a,o,s),s}function Qe(e,t,i,s=0,r=e.length){var a,n=et((t=t||{}).bits,t.fp,t.signed);r=function(e,t,i){i=(t-e)%i;return t-i}(s,r,n.offset),t.be?(a=new Uint8Array(e),t.be&&je(a,n.offset,s,r),Je(a,i,s,r,n)):Je(e,i,s,r,n)}function Ze(e,t,i,s=0){return Xe([e],t,i,s)}function Ye(e,t){var i=[];return Ze(e,t,i,0),i}function Ke(e,t,i=0){var s=[];return Qe(e,t,s,i,i+Math.ceil(t.bits/8)),s[0]}function Je(i,s,r,a,n){var o=n.offset;for(let e=0,t=r;t<a;t+=o,e++)s[e]=n.unpack(i,t)}function et(e,t,i){return t&&32==e?new Ve(8,23):t&&64==e?new Ve(11,52):new ze(e,i)}function tt(e,t){let i=$e(e);for(let e=i.length;e<t;e++)i.push(0);return i}(class dm extends class{constructor(){this.container="",this.chunkSize=0,this.format="",this.signature=null,this.head=0,this.uInt32={bits:32,be:!1},this.supported_containers=["RIFF","RIFX"]}setSignature(e){if(this.head=0,this.container=this.readString(e,4),-1===this.supported_containers.indexOf(this.container))throw Error("Not a supported format.");this.uInt32.be="RIFX"===this.container,this.chunkSize=this.readUInt32(e),this.format=this.readString(e,4),this.signature={chunkId:this.container,chunkSize:this.chunkSize,format:this.format,subChunks:this.getSubChunksIndex_(e)}}findChunk(t,i=!1){var s=this.signature.subChunks;let r=[];for(let e=0;e<s.length;e++)if(s[e].chunkId==t){if(!i)return s[e];r.push(s[e])}return"LIST"==t&&r.length?r:null}readString(e,t){e=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 dm;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 s=i[e];this.LIST.push({chunkId:s.chunkId,chunkSize:s.chunkSize,format:s.format,subChunks:[]});for(let e=0;e<s.subChunks.length;e++)this.readLISTSubChunks_(s.subChunks[e],s.format,t)}}readLISTSubChunks_(e,t,i){"adtl"==t?-1<["labl","note","ltxt"].indexOf(e.chunkId)&&this.readLISTadtlSubChunks_(i,e):"INFO"==t&&this.readLISTINFOSubChunks_(i,e)}readLISTadtlSubChunks_(e,t){this.head=t.chunkData.start;let i={chunkId:t.chunkId,chunkSize:t.chunkSize,dwName:this.readUInt32(e)};"ltxt"==t.chunkId?(i.dwSampleLength=this.readUInt32(e),i.dwPurposeID=this.readUInt32(e),i.dwCountry=this.readUInt16_(e),i.dwLanguage=this.readUInt16_(e),i.dwDialect=this.readUInt16_(e),i.dwCodePage=this.readUInt16_(e),i.value=""):i.value=this.readZSTR_(e,this.head),this.LIST[this.LIST.length-1].subChunks.push(i)}readLISTINFOSubChunks_(e,t){this.head=t.chunkData.start,this.LIST[this.LIST.length-1].subChunks.push({chunkId:t.chunkId,chunkSize:t.chunkSize,value:this.readZSTR_(e,this.head)})}readJunkChunk_(e){var t=this.findChunk("junk");t&&(this.junk={chunkId:t.chunkId,chunkSize:t.chunkSize,chunkData:[].slice.call(e.slice(t.chunkData.start,t.chunkData.end))})}read_PMXChunk_(e){var t=this.findChunk("_PMX");t&&(this.head=t.chunkData.start,this._PMX.chunkId=t.chunkId,this._PMX.chunkSize=t.chunkSize,this._PMX.value=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 st extends class extends class dm extends class{constructor(){this.container="",this.chunkSize=0,this.format="",this.signature=null,this.head=0,this.uInt32={bits:32,be:!1},this.supported_containers=["RIFF","RIFX"]}setSignature(e){if(this.head=0,this.container=this.readString(e,4),-1===this.supported_containers.indexOf(this.container))throw Error("Not a supported format.");this.uInt32.be="RIFX"===this.container,this.chunkSize=this.readUInt32(e),this.format=this.readString(e,4),this.signature={chunkId:this.container,chunkSize:this.chunkSize,format:this.format,subChunks:this.getSubChunksIndex_(e)}}findChunk(t,i=!1){var s=this.signature.subChunks;let r=[];for(let e=0;e<s.length;e++)if(s[e].chunkId==t){if(!i)return s[e];r.push(s[e])}return"LIST"==t&&r.length?r:null}readString(e,t){e=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 dm;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 s=i[e];this.LIST.push({chunkId:s.chunkId,chunkSize:s.chunkSize,format:s.format,subChunks:[]});for(let e=0;e<s.subChunks.length;e++)this.readLISTSubChunks_(s.subChunks[e],s.format,t)}}readLISTSubChunks_(e,t,i){"adtl"==t?-1<["labl","note","ltxt"].indexOf(e.chunkId)&&this.readLISTadtlSubChunks_(i,e):"INFO"==t&&this.readLISTINFOSubChunks_(i,e)}readLISTadtlSubChunks_(e,t){this.head=t.chunkData.start;let i={chunkId:t.chunkId,chunkSize:t.chunkSize,dwName:this.readUInt32(e)};"ltxt"==t.chunkId?(i.dwSampleLength=this.readUInt32(e),i.dwPurposeID=this.readUInt32(e),i.dwCountry=this.readUInt16_(e),i.dwLanguage=this.readUInt16_(e),i.dwDialect=this.readUInt16_(e),i.dwCodePage=this.readUInt16_(e),i.value=""):i.value=this.readZSTR_(e,this.head),this.LIST[this.LIST.length-1].subChunks.push(i)}readLISTINFOSubChunks_(e,t){this.head=t.chunkData.start,this.LIST[this.LIST.length-1].subChunks.push({chunkId:t.chunkId,chunkSize:t.chunkSize,value:this.readZSTR_(e,this.head)})}readJunkChunk_(e){var t=this.findChunk("junk");t&&(this.junk={chunkId:t.chunkId,chunkSize:t.chunkSize,chunkData:[].slice.call(e.slice(t.chunkData.start,t.chunkData.end))})}read_PMXChunk_(e){var t=this.findChunk("_PMX");t&&(this.head=t.chunkData.start,this._PMX.chunkId=t.chunkId,this._PMX.chunkSize=t.chunkSize,this._PMX.value=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 s=new Uint8Array(i+12),r=0;r=qe(this.container,s,r),r=Ze(i+4,this.uInt32,s,r),r=qe(this.format,s,r);for(let e=0;e<t.length;e++)s.set(t[e],r),r+=t[e].length;return s}getBextBytes_(){let e=[];return this.enforceBext_(),this.bext.chunkId&&(this.bext.chunkSize=602+this.bext.codingHistory.length,e=e.concat($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,s){let r=[];for(let e=0,t=i.length;e<t;e++)"INFO"==s?r=r.concat(this.getLISTINFOSubChunksBytes_(i[e])):"adtl"==s&&(r=r.concat(this.getLISTadtlSubChunksBytes_(i[e]))),this.enforceByteLen_(r);return r}getLISTINFOSubChunksBytes_(e){let t=[];var i=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,s,r){r=r||{},this.clearHeaders(),this.newWavFile_(e,t,i,s,r)}fromBuffer(e,t=!0){super.fromBuffer(e,t),this.bitDepthFromFmt_(),this.updateDataType_()}toBuffer(){return this.validateWavHeader_(),super.toBuffer()}getSamples(e=!1,t=Float64Array){var i=new t(this.data.samples.length/(this.dataType.bits/8));return Qe(this.data.samples,this.dataType,i,0,this.data.samples.length),!e&&1<this.fmt.numChannels?function(s,r,t=Float64Array){let a=[];for(let e=0;e<r;e++)a[e]=new t(s.length/r);for(let i=0;i<r;i++)for(let e=i,t=0;e<s.length;e+=r,t++)a[i][t]=s[e];return a}(i,this.fmt.numChannels,t):i}getSample(e){if((e*=this.dataType.bits/8)+this.dataType.bits/8>this.data.samples.length)throw new Error("Range error");return 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");Ze(t,this.dataType,this.data.samples,e)}getiXML(){return this.iXML.value}setiXML(e){if("string"!=typeof e)throw new TypeError("iXML value must be a string.");this.iXML.value=e,this.iXML.chunkId="iXML"}get_PMX(){return this._PMX.value}set_PMX(e){if("string"!=typeof e)throw new TypeError("_PMX value must be a string.");this._PMX.value=e,this._PMX.chunkId="_PMX"}newWavFile_(e,t,i,s,r){r.container||(r.container="RIFF"),this.container=r.container,this.bitDepth=i,s=function(r){let a=[];if(0<r.length)if(r[0].constructor!==Number){a=new Float64Array(r[0].length*r.length);for(let i=0,e=r[0].length,s=0;i<e;i++)for(let e=0,t=r.length;e<t;e++,s++)a[s]=r[e][i]}else a=r;return a}(s),this.updateDataType_();var a=this.dataType.bits/8;this.data.samples=new Uint8Array(s.length*a),Xe(s,this.dataType,this.data.samples,0),this.makeWavHeader_(i,e,t,a,this.data.samples.length,r),this.data.chunkId="data",this.data.chunkSize=this.data.samples.length,this.validateWavHeader_()}makeWavHeader_(e,t,i,s,r,a){"4"==e?this.createADPCMHeader_(e,t,i,s,r,a):"8a"==e||"8m"==e?this.createALawMulawHeader_(e,t,i,s,r,a):-1==Object.keys(this.WAV_AUDIO_FORMATS).indexOf(e)||2<t?this.createExtensibleHeader_(e,t,i,s,r,a):this.createPCMHeader_(e,t,i,s,r,a)}createPCMHeader_(e,t,i,s,r,a){this.container=a.container,this.chunkSize=36+r,this.format="WAVE",this.bitDepth=e,this.fmt={chunkId:"fmt ",chunkSize:16,audioFormat:this.WAV_AUDIO_FORMATS[e]||65534,numChannels:t,sampleRate:i,byteRate:t*s*i,blockAlign:t*s,bitsPerSample:parseInt(e,10),cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]}}createADPCMHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=40+r,this.fmt.chunkSize=20,this.fmt.byteRate=4055,this.fmt.blockAlign=256,this.fmt.bitsPerSample=4,this.fmt.cbSize=2,this.fmt.validBitsPerSample=505,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:2*r}}createExtensibleHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=60+r,this.fmt.chunkSize=40,this.fmt.bitsPerSample=1+(parseInt(e,10)-1|7),this.fmt.cbSize=22,this.fmt.validBitsPerSample=parseInt(e,10),this.fmt.dwChannelMask=function(e){let t=0;1===e?t=4:2===e?t=3:4===e?t=51:6===e?t=63:8===e&&(t=1599);return t}(t),this.fmt.subformat=[1,1048576,2852126848,1905997824]}createALawMulawHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=40+r,this.fmt.chunkSize=20,this.fmt.cbSize=2,this.fmt.validBitsPerSample=8,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:r}}bitDepthFromFmt_(){3===this.fmt.audioFormat&&32===this.fmt.bitsPerSample?this.bitDepth="32f":6===this.fmt.audioFormat?this.bitDepth="8a":7===this.fmt.audioFormat?this.bitDepth="8m":this.bitDepth=this.fmt.bitsPerSample.toString()}validateBitDepth_(){if(this.WAV_AUDIO_FORMATS[this.bitDepth])return!0;if(8<parseInt(this.bitDepth,10)&&parseInt(this.bitDepth,10)<54)return!0;throw new Error("Invalid bit depth.")}updateDataType_(){this.dataType={bits:1+(parseInt(this.bitDepth,10)-1|7),fp:"32f"==this.bitDepth||"64"==this.bitDepth,signed:"8"!=this.bitDepth,be:"RIFX"==this.container},-1<["4","8a","8m"].indexOf(this.bitDepth)&&(this.dataType.bits=8,this.dataType.signed=!1)}validateWavHeader_(){if(this.validateBitDepth_(),e=this.fmt.numChannels,t=this.fmt.bitsPerSample,e<1||65535<e*t/8)throw new Error("Invalid number of channels.");var e,t;if(!it(this.fmt.numChannels,this.fmt.bitsPerSample,this.fmt.sampleRate))throw new Error("Invalid sample rate.")}}class rt extends st{getTag(e){e=this.getTagIndex_(e);return null!==e.TAG?this.LIST[e.LIST].subChunks[e.TAG].value:null}setTag(e,t){e=function(i){{if(i.constructor!==String)throw new Error("Invalid tag name.");if(i.length<4)for(let e=0,t=4-i.length;e<t;e++)i+=" "}return i}(e);var i=this.getTagIndex_(e);null!==i.TAG?(this.LIST[i.LIST].subChunks[i.TAG].chunkSize=t.length+1,this.LIST[i.LIST].subChunks[i.TAG].value=t):null!==i.LIST?this.LIST[i.LIST].subChunks.push({chunkId:e,chunkSize:t.length+1,value:t}):(this.LIST.push({chunkId:"LIST",chunkSize:8+t.length+1,format:"INFO",subChunks:[]}),this.LIST[this.LIST.length-1].subChunks.push({chunkId:e,chunkSize:t.length+1,value:t}))}deleteTag(e){e=this.getTagIndex_(e);return null!==e.TAG&&(this.LIST[e.LIST].subChunks.splice(e.TAG,1),!0)}listTags(){var i=this.getLISTIndex("INFO");let s={};if(null!==i)for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)s[this.LIST[i].subChunks[e].chunkId]=this.LIST[i].subChunks[e].value;return s}getLISTIndex(i){for(let e=0,t=this.LIST.length;e<t;e++)if(this.LIST[e].format==i)return e;return null}getTagIndex_(s){let r={LIST:null,TAG:null};for(let i=0,e=this.LIST.length;i<e;i++)if("INFO"==this.LIST[i].format){r.LIST=i;for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)if(this.LIST[i].subChunks[e].chunkId==s){r.TAG=e;break}break}return r}}class at extends rt{listCuePoints(){let i=this.getCuePoints_();for(let e=0,t=i.length;e<t;e++)i[e].position=i[e].dwSampleOffset/this.fmt.sampleRate*1e3,i[e].dwSampleLength?(i[e].end=i[e].dwSampleLength/this.fmt.sampleRate*1e3,i[e].end+=i[e].position):i[e].end=null,delete i[e].value;return i}setCuePoint(e){this.cue.chunkId="cue ",e.label||(e.label="");var t=this.getCuePoints_();this.clearLISTadtl_(),this.cue.points=[],e.dwSampleOffset=e.position*this.fmt.sampleRate/1e3,e.dwSampleLength=0,e.end&&(e.dwSampleLength=e.end*this.fmt.sampleRate/1e3-e.dwSampleOffset),0===t.length?this.setCuePoint_(e,1):this.setCuePointInOrder_(t,e),this.cue.dwCuePoints=this.cue.points.length}deleteCuePoint(t){this.cue.chunkId="cue ";var i=this.getCuePoints_();this.clearLISTadtl_();var s=this.cue.points.length;this.cue.points=[];for(let e=0;e<s;e++)e+1!==t&&this.setCuePoint_(i[e],e+1);this.cue.dwCuePoints=this.cue.points.length,this.cue.dwCuePoints?this.cue.chunkId="cue ":(this.cue.chunkId="",this.clearLISTadtl_())}updateLabel(i,s){var r=this.getLISTIndex("adtl");if(null!==r)for(let e=0,t=this.LIST[r].subChunks.length;e<t;e++)this.LIST[r].subChunks[e].dwName==i&&(this.LIST[r].subChunks[e].value=s)}getCuePoints_(){let i=[];for(let t=0;t<this.cue.points.length;t++){var s=this.cue.points[t];let e=this.getDataForCuePoint_(s.dwName);e.label=e.value||"",e.dwPosition=s.dwPosition,e.fccChunk=s.fccChunk,e.dwChunkStart=s.dwChunkStart,e.dwBlockStart=s.dwBlockStart,e.dwSampleOffset=s.dwSampleOffset,i.push(e)}return i}getDataForCuePoint_(e){var t=this.getLISTIndex("adtl"),i={};return null!==t&&this.getCueDataFromLIST_(i,t,e),i}getCueDataFromLIST_(i,s,r){for(let e=0,t=this.LIST[s].subChunks.length;e<t;e++){var a;this.LIST[s].subChunks[e].dwName==r&&(a=this.LIST[s].subChunks[e],i.value=a.value||i.value,i.dwName=a.dwName||0,i.dwSampleLength=a.dwSampleLength||0,i.dwPurposeID=a.dwPurposeID||0,i.dwCountry=a.dwCountry||0,i.dwLanguage=a.dwLanguage||0,i.dwDialect=a.dwDialect||0,i.dwCodePage=a.dwCodePage||0)}}setCuePoint_(e,t){this.cue.points.push({dwName:t,dwPosition:e.dwPosition||0,fccChunk:e.fccChunk||"data",dwChunkStart:e.dwChunkStart||0,dwBlockStart:e.dwBlockStart||0,dwSampleOffset:e.dwSampleOffset}),this.setLabl_(e,t)}setCuePointInOrder_(t,i){let s=!1;for(let e=0;e<t.length;e++)t[e].dwSampleOffset>i.dwSampleOffset&&!s?(this.setCuePoint_(i,e+1),this.setCuePoint_(t[e],e+2),s=!0):this.setCuePoint_(t[e],s?e+2:e+1);s||this.setCuePoint_(i,this.cue.points.length+1)}clearLISTadtl_(){for(let e=0,t=this.LIST.length;e<t;e++)"adtl"==this.LIST[e].format&&this.LIST.splice(e)}setLabl_(e,t){let i=this.getLISTIndex("adtl");null===i&&(this.LIST.push({chunkId:"LIST",chunkSize:4,format:"adtl",subChunks:[]}),i=this.LIST.length-1),this.setLabelText_(i,e,t),e.dwSampleLength&&this.setLtxtChunk_(i,e,t)}setLabelText_(e,t,i){this.LIST[e].subChunks.push({chunkId:"labl",chunkSize:4,dwName:i,value:t.label}),this.LIST[e].chunkSize+=12}setLtxtChunk_(e,t,i){this.LIST[e].subChunks.push({chunkId:"ltxt",chunkSize:20,dwName:i,dwSampleLength:t.dwSampleLength,dwPurposeID:t.dwPurposeID||0,dwCountry:t.dwCountry||0,dwLanguage:t.dwLanguage||0,dwDialect:t.dwDialect||0,dwCodePage:t.dwCodePage||0,value:t.label}),this.LIST[e].chunkSize+=28}}class nt{constructor(e,t,i){var s;this.length_=e,this.scaleFactor_=(e-1)/t,this.interpolate=this.sinc,"point"===i.method?this.interpolate=this.point:"linear"===i.method?this.interpolate=this.linear:"cubic"===i.method&&(this.interpolate=this.cubic),this.tangentFactor_=1-Math.max(0,Math.min(1,i.tension||0)),this.sincFilterSize_=i.sincFilterSize||1,this.kernel_=(s=i.sincWindow||ot,function(e){return(0!==(t=e)?Math.sin(Math.PI*t)/(Math.PI*t):1)*s(e);var t})}point(e,t){return this.getClippedInput_(Math.round(this.scaleFactor_*e),t)}linear(e,t){e=this.scaleFactor_*e;var i=Math.floor(e);return(1-(e-=i))*this.getClippedInput_(i,t)+e*this.getClippedInput_(i+1,t)}cubic(e,t){e=this.scaleFactor_*e;var i=Math.floor(e),s=[this.getTangent_(i,t),this.getTangent_(i+1,t)],r=[this.getClippedInput_(i,t),this.getClippedInput_(i+1,t)],t=(e-=i)*e,i=e*t;return(2*i-3*t+1)*r[0]+(i-2*t+e)*s[0]+(-2*i+3*t)*r[1]+(i-t)*s[1]}sinc(t,i){t=this.scaleFactor_*t;var e=Math.floor(t),s=e-this.sincFilterSize_+1,r=e+this.sincFilterSize_;let a=0;for(let e=s;e<=r;e++)a+=this.kernel_(t-e)*this.getClippedInput_(e,i);return a}getTangent_(e,t){return this.tangentFactor_*(this.getClippedInput_(e+1,t)-this.getClippedInput_(e-1,t))/2}getClippedInput_(e,t){return 0<=e&&e<this.length_?t[e]:0}}function 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,s){let r=[];for(let e=0;e<t;e++)r.push(this.getCoeffs_({Fs:i,Fc:s,Q:.5/Math.sin(Math.PI/(2*t)*(e+.5))}));this.stages=[];for(let e=0;e<r.length;e++)this.stages[e]={b0:r[e].b[0],b1:r[e].b[1],b2:r[e].b[2],a1:r[e].a[0],a2:r[e].a[1],k:r[e].k,z:[0,0]}}filter(e){let i=e;for(let e=0,t=this.stages.length;e<t;e++)i=this.runStage_(e,i);return i}getCoeffs_(e){let t={a:[],b:[]};e=this.preCalc_(e,t);return t.k=1,t.b.push((1-e.cw)/(2*e.a0)),t.b.push(2*t.b[0]),t.b.push(t.b[0]),t}preCalc_(e,t){let i={};var s=2*Math.PI*e.Fc/e.Fs;return i.alpha=Math.sin(s)/(2*e.Q),i.cw=Math.cos(s),i.a0=1+i.alpha,t.a0=i.a0,t.a.push(-2*i.cw/i.a0),t.k=1,t.a.push((1-i.alpha)/i.a0),i}runStage_(e,t){var i=t*this.stages[e].k-this.stages[e].a1*this.stages[e].z[0]-this.stages[e].a2*this.stages[e].z[1],t=this.stages[e].b0*i+this.stages[e].b1*this.stages[e].z[0]+this.stages[e].b2*this.stages[e].z[1];return this.stages[e].z[1]=this.stages[e].z[0],this.stages[e].z[0]=i,t}reset(){for(let e=0;e<this.stages.length;e++)this.stages[e].z=[0,0]}},FIR:class{constructor(t,e,i){var s=2*Math.PI*i/e;let r=0;this.filters=[];for(let e=0;e<=t;e++)e-t/2==0?this.filters[e]=s:(this.filters[e]=Math.sin(s*(e-t/2))/(e-t/2),this.filters[e]*=.54-.46*Math.cos(2*Math.PI*e/t)),r+=this.filters[e];for(let e=0;e<=t;e++)this.filters[e]/=r;this.z=this.initZ_()}filter(e){this.z.buf[this.z.pointer]=e;let i=0;for(let e=0,t=this.z.buf.length;e<t;e++)i+=this.filters[e]*this.z.buf[(this.z.pointer+e)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,i}reset(){this.z=this.initZ_()}initZ_(){let t=[];for(let e=0;e<this.filters.length-1;e++)t.push(0);return{buf:t,pointer:0}}}};function ut(e,t,i,s=null){s=s||{};var r=new Float64Array(e.length*((i-t)/t+1));s.method=s.method||"cubic";var a=new nt(e.length,r.length,{method:s.method,tension:s.tension||0,sincFilterSize:s.sincFilterSize||6,sincWindow:s.sincWindow||void 0,clip:s.clip||"mirror"});if(void 0===s.LPF&&(s.LPF=ht[s.method]),s.LPF){s.LPFType=s.LPFType||"IIR";const n=ct[s.LPFType];t<i?function(i,s,r,a){for(let e=0,t=s.length;e<t;e++)s[e]=a.filter(r.interpolate(e,i));a.reset();for(let e=s.length-1;0<=e;e--)s[e]=a.filter(s[e])}(e,r,a,new n(s.LPForder||lt[s.LPFType],i,t/2)):function(i,e,t,s){for(let e=0,t=i.length;e<t;e++)i[e]=s.filter(i[e]);s.reset();for(let e=i.length-1;0<=e;e--)i[e]=s.filter(i[e]);dt(i,e,t)}(e,r,a,new n(s.LPForder||lt[s.LPFType],t,i/2))}else dt(e,r,a);return r}function dt(i,s,r){for(let e=0,t=s.length;e<t;e++)s[e]=r.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 r;if(1<this.fmt.numChannels){if(2<this.fmt.numChannels)throw new Error("Only 1 or 2 channels are supported");var a=this.data.samples.length/2;let t=new Uint8Array(a),i=new Uint8Array(a),s=0;for(let e=0;e<a;e++)e&&e%4==0&&(s+=4),t[e]=this.data.samples[s+e],i[e]=this.data.samples[s+e+4];r=[Ae(t,this.fmt.blockAlign/2),Ae(i,this.fmt.blockAlign/2)]}else r=Ae(this.data.samples,this.fmt.blockAlign);this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",r,{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toALaw(){this.assure16Bit_();var e=new Int16Array(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",Ee(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,s=this.bitDepth;t||("32f"!=e&&(i=this.dataType.bits.toString()),s=""+this.dataType.bits),this.assureUncompressed_();var r=this.getSamples(!0),t=new Float64Array(r.length);we(r,s,t,i),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,e,t,{container:this.correctContainer_()})}toSampleRate(t,i){this.validateResample_(t);var s=this.getSamples();let r=[];if(s.constructor===Float64Array)r=ut(s,this.fmt.sampleRate,t,i);else for(let e=0;e<s.length;e++)r.push(ut(s[e],this.fmt.sampleRate,t,i));this.fromExisting_(this.fmt.numChannels,t,this.bitDepth,r,{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,s,r){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,s,r)}}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 s=new Uint8Array(256);for(let e=0;e<ye.length;e++)s[ye.charCodeAt(e)]=e;let e=.75*i.length;"="===i[i.length-1]&&(e--,"="===i[i.length-2]&&e--);let r=new Uint8Array(e);for(let e=0,t=0;e<i.length;e+=4){var a=s[i.charCodeAt(e)],n=s[i.charCodeAt(e+1)],o=s[i.charCodeAt(e+2)],h=s[i.charCodeAt(e+3)];r[t++]=a<<2|n>>4,r[t++]=(15&n)<<4|o>>2,r[t++]=(3&o)<<6|63&h}return r}(e))}toBase64(){return function(t){let i="";for(let e=0;e<t.length;e+=3)i+=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"]);r=["addon.shp","bkgdlg.shp","bkgdmd.shp","bkgdsm.shp","bttnbkgd.shp","button00.shp","button01.shp","button02.shp","button03.shp","button04.shp","button05.shp","button06.shp","button07.shp","button08.shp","button09.shp","button10.shp","button11.shp","credits.shp","diplobtn.shp","gclock2.shp","key.ini","lendcap.shp","lspacer.shp","optbtn.shp","pbeacon.shp","power.shp","powerp.shp","pwrlvl.shp","radar.shp","radar01.shp","radar02.shp","r-dn.shp","rdrbeacn.shp","rendcap.shp","repair.shp","r-up.shp","sell.shp","side1.shp","side2.shp","side2b.shp","side3.shp","sidebar.pal","sidebttn.shp","tab00.shp","tab01.shp","tab02.shp","tab03.shp","tabs.shp","top.shp","uibkgd.pal","wayp.shp"];Tt.set("sidec01.mix",r).set("sidec02.mix",r);var bt,vt,r=["reportbug.shp"];Tt.set("sidec01cd.mix",r).set("sidec02cd.mix",r),(r=bt=bt||{})[r.Archive=0]="Archive",r[r.Cdn=1]="Cdn",r[r.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}}(r=vt=vt||{})[r.Battle=0]="Battle",r[r.ManBattle=1]="ManBattle",r[r.FreeForAll=2]="FreeForAll",r[r.Unholy=3]="Unholy",r[r.Cooperative=4]="Cooperative";class _t{constructor(e,t){this.modeIniLoader=t,this.entries=new Map,this.loadIni(e)}loadIni(e){e.getOrderedSections().forEach(s=>{let r=vt[s.name]??vt.Battle;[...s.entries.keys()].forEach(e=>{let t=s.getArray(e);if(t.length<5)throw new Error(`Invalid format for mp mode entry "${e}".`);var i=Number(e),e=t[2].toLowerCase(),e={id:i,type:r,label:t[0],description:t[1],rulesOverride:e,mapFilter:t[3],randomMapsAllowed:t[4],aiAllowed:i<3,mpDialogSettings:(new 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 s=e.filename;const r=new c(this.extractIniSection("Basic",i)).getSection("Basic");if(!r)throw new Error(`Map "${s}" is missing the [Basic] section`);this.fileName=s,this.uiName="NOSTR:"+(r.getString("Name")||s.replace(/\.[^.]+$/,""));let a=r.getNumber("MaxPlayer");if(!a){i=this.extractIniSection("Header",i);const o=i?new c(i).getSection("Header"):void 0;a=o?.getNumber("NumberStartingPoints")||2}this.maxSlots=a,this.official=r.getBool("Official");let n=r.getArray("GameMode",void 0,["standard"]);return this.gameModes=t.filter(e=>n.includes(e.mapFilter)),this}extractIniSection(t,i){t=i.indexOf(`[${t}]`);if(-1!==t){let e=t+1;for(;e<i.length&&("["!==i[e]||"\n"!==i[e-1]);e++);return i.slice(t,e)}}}class 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 xt{constructor(e){e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let i=e.stream;this.sections=[],i.readCString(16);var s=i.readInt32(),r=i.readInt32();for(let e=0;e<r;++e){let e=new It;e.name=i.readCString(16),e.matrices=new Array(s),this.sections.push(e)}for(let t=0;t<s;++t)for(let e=0;e<r;++e)this.sections[e].matrices[t]=this.readMatrix(i)}readMatrix(t){let i=[];for(let e=0;e<3;++e)i.push(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32());return i.push(0,0,0,1),(new Bt.Matrix4).fromArray(i).transpose()}}(r=At=At||{})[r.AutoDetect=0]="AutoDetect",r[r.TiberianSun=1]="TiberianSun",r[r.Firestorm=2]="Firestorm",r[r.RedAlert2=3]="RedAlert2",r[r.YurisRevenge=4]="YurisRevenge";class Et{static getVersion(){return"0.49.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 ue(e,t),Et.iniFiles.setVfs(this.vfs),Et.palettes.setVfs(this.vfs),Et.images.setVfs(this.vfs),Et.voxels.setVfs(this.vfs),Et.voxelAnims.setVfs(this.vfs),Et.tileData.setVfs(this.vfs),Et.sounds.setVfs(this.vfs),Et.themes.setDir(await this.rfs?.findDirectory(Et.rfsSettings.musicDir)),Et.taunts.setDir(await this.rfs?.findDirectory(Et.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(!Et.rules||!Et.art)throw new Error("Rules and art should be loaded first");if(void 0===Et.gameResSource)throw new Error("No gameResSource is set");var t=Et.getActiveEngine();let i;var s,r=Et.getTheaterSettings(t,e);if(Et.gameResSource!==bt.Cdn)for(var a of r.Mixes)await Et.vfs.addMixFile(a);return Et.theaters.has(e)?i=Et.theaters.get(e):(s=Et.getTheaterIni(t,e),t=Et.getTileData(),i=Z.factory(e,s,r,t,Et.palettes),Et.theaters.set(e,i)),Et.activeTheater=i,i}static unloadTheater(e){if(Et.vfs){var t,i=Et.getActiveEngine();for(t of Et.getTheaterSettings(i,e).Mixes)Et.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()?Et.palettes:Et.images).clear(t)}}static getTheaterIni(e,t){t=Et.getTheaterSettings(e,t).TheaterIni;return Et.getIni(t)}static loadRules(){var e=this.getFileNameVariant("rules.ini"),t=this.getFileNameVariant("art.ini");let i=this.iniFiles.get(e),s=this.iniFiles.get(t);if(!i)throw new Error(`Rules "${e}" not found`);if(!s)throw new Error(`Art "${t}" not found`);e=this.iniFiles.get(Et.customRulesFileName),t=this.iniFiles.get(Et.customArtFileName);if(!e)throw new Error(`Rules "${Et.customRulesFileName}" not found`);if(!t)throw new Error(`Art "${Et.customArtFileName}" not found`);Et.art=s.clone().mergeWith(t),Et.rules=i.clone().mergeWith(e),Et.modHash=Et.computeModHash()}static computeModHash(){if(!this.vfs)throw new Error("VFS not initialized");let e=[this.customRulesFileName,this.customArtFileName,this.customMpModesFileName,this.getFileNameVariant("rules.ini"),this.getFileNameVariant("art.ini"),this.getFileNameVariant("ai.ini")];var t,i,s,r=this.theaterSettings.get(this.getActiveEngine());if(!r)throw new Error(`Unsupported engineType "${this.getActiveEngine()}`);for(t of r)e.push(this.getFileNameVariant(t.TheaterIni));let a=this.getMpModes();for(i of a.getAll())e.push(i.rulesOverride);let n=new ne;for(s of e){if(!this.vfs.fileExists(s))throw new Error(`File ${s} not found`);var o=this.vfs.openFile(s).stream;n.append(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}return n.append(D(this.getVersion())),n.get()}static getRules(){if(!Et.rules)throw new Error("Rules must be loaded first");return Et.rules}static getArt(){if(!Et.art)throw new Error("Art must be loaded first");return Et.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,s,t=this.getMpModes();let r=new Ot(t);r.addFromIni(this.getIni(this.getFileNameVariant("missions.pkt")));for(e of this.vfs.listArchives()){var a=e.toLowerCase().replace(/\.[^.]+$/,"")+".pkt";this.vfs.fileExists(a)&&r.addFromIni(new c(this.vfs.openFile(a)))}let n=new 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)),r.addFromIni(i)):this.supportedMapTypes.some(e=>t.endsWith("."+e))&&(s=await this.rfs.openFile(o,!0),n.addFromMapFile(s))}catch(e){console.warn(`Couldn't read file "${o}"`,e)}}return n.sortByName(),r.mergeWith(n),this.mapList=r,r}static getTileData(){return Et.tileData}static getImages(){return Et.images}static getVoxels(){return Et.voxels}static getVoxelAnims(){return Et.voxelAnims}static getPalettes(){return Et.palettes}static getSounds(){return Et.sounds}static getThemes(){return Et.themes}static getTaunts(){return Et.taunts}static getActiveEngine(){return At.RedAlert2}static getLastTheaterType(){return Et.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(Et.rfsSettings.replayDir)}return this.getOrCreateDir(this.rfsSettings.replayDir)}static getModDir(){return this.getOrCreateDir(Et.rfsSettings.modDir)}static getMapDir(){return this.getOrCreateDir(Et.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()}}Et.UI_ANIM_SPEED=2,Et.rfsSettings={menuVideoFileName:"ra2ts_l.webm",splashImgFileName:"glsl.png",mapDir:"maps",modDir:"mods",musicDir:"music",tauntsDir:"Taunts",cacheDir:"cache",replayDir:"replays"},Et.supportedMapTypes=["mpr","map"],Et.images=new fe(e=>new s(e)),Et.voxels=new fe(e=>new S(e)),Et.voxelAnims=new fe(e=>new xt(e)),Et.sounds=new fe(e=>new ft(e)),Et.themes=new yt(e=>new wt(e),!1),Et.taunts=new yt(async e=>new ft(new Uint8Array(await e.arrayBuffer()))),Et.iniFiles=new fe(e=>new c(e)),Et.tileData=new fe(e=>new E(e)),Et.palettes=new fe(e=>new H(e)),Et.theaters=new Map,Et.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"}]),Et.customRulesFileName="rulescd.ini",Et.customArtFileName="artcd.ini",Et.customMpModesFileName="mpmodescd.ini",(r=Ct=Ct||{})[r.None=0]="None",r[r.Aircraft=1]="Aircraft",r[r.Building=2]="Building",r[r.Infantry=3]="Infantry",r[r.Overlay=4]="Overlay",r[r.Smudge=5]="Smudge",r[r.Terrain=6]="Terrain",r[r.Vehicle=7]="Vehicle",r[r.Animation=8]="Animation",r[r.Projectile=9]="Projectile",r[r.VoxelAnim=10]="VoxelAnim",r[r.Debris=11]="Debris";class 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 Ut extends Nt{constructor(){super(Ct.Smudge)}}class Wt extends Pt{constructor(){super(Ct.Overlay)}}class zt{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)),s=0;for(;;){var r=i.readUint8();if(0==(128&r)){var a=i.readUint8(),n=3+((112&r)>>4);this.replicatePrevious(t,s,s-(((15&r)<<8)+a),n),s+=n}else if(0==(64&r)){n=63&r;if(0==n)return s;t.set(i.readUint8Array(n),s),s+=n}else{r=63&r;if(62==r)for(var o=i.readInt16(),h=i.readUint8(),l=s+o;s<l;s++)t[s]=h;else if(63==r){o=i.readInt16();let e=i.readInt16();if(e>=s)throw new Error(`srcIndex >= destIndex ${e} ${s}`);for(var c=s+o;s<c;s++)t[s]=t[e++]}else{r=3+r;let e=i.readInt16();if(e>=s)throw new Error(`srcIndex >= destIndex ${e} ${s}`);for(var u=s+r;s<u;s++)t[s]=t[e++]}}}}static replicatePrevious(t,i,s,r){if(i<s)throw new Error(`srcIndex > destIndex ${s} ${i}`);if(i-s==1)for(let e=0;e<r;e++)t[i+e]=t[i-1];else for(let e=0;e<r;e++)t[i+e]=t[s+e]}}var Vt,Ht,Gt,$t,qt,Xt,Qt,Zt,Yt,Kt,Jt,ei,ti,ii,si,ri,ai,ni,oi,hi,li=__webpack_require__(251).default;class ci{static decompress(e,t){e={inputBuffer:e,outputBuffer:null},t=li.decompress(e,{outputSize:t});if(0!==t)throw new Error(`MiniLzo decode failed with code ${t}`);return e.outputBuffer}}class ui{static decode(e,t,i=5){t=new Uint8Array(t);return this.decodeInto(e,t,i),t}static decodeInto(e,i,s=5){var t=i.length;let r=0,a=0;for(;a<t;){var n=e[r+1]<<8|e[r];r+=2;var o=e[r+1]<<8|e[r];if(r+=2,!n||!o)break;let t;t=80===s?zt.decode(e.subarray(r,r+n),o):ci.decompress(e.subarray(r,r+n),o);for(let e=0;e<o;++e)i[a+e]=t[e];r+=n,a+=o}}}function di(e){switch(e){case Vt.Indexed:return 1;case Vt.Rgb:return 3;case Vt.Rgba:return 4;default:throw new Error(`Unsupported pixel format ${e}`)}}(r=Vt=Vt||{})[r.Rgb=1]="Rgb",r[r.Rgba=2]="Rgba",r[r.Indexed=3]="Indexed";class pi{constructor(e,t,i,s=Vt.Rgba){var r=di(s);this.data=i||new Uint8Array(r*e*t),this.pixelFormat=s,this.width=e,this.height=t}drawIndexedImage(t,e,i){var s=di(this.pixelFormat);const r=this.data;var a=this.width,n=s*a,o=s*a*this.height;let h=0+n*i+s*e,l=0;for(let e=0;e<t.height;e++){for(let e=0;e<t.width;e++){var c=t.data[l];0!==c&&0<=h&&h<o&&(r[h]=c,3<=s&&(r[h+1]=0,r[h+2]=0),4===s&&(r[h+3]=255)),h+=s,l++}h+=n-t.width*s}}}class gi extends pi{constructor(e,t,i){super(e,t,i,Vt.Rgb)}}(r=Ht=Ht||{})[r.OnceAny=0]="OnceAny",r[r.OnceAll=1]="OnceAll",r[r.Repeat=2]="Repeat";class mi{read(e){let t=[];for(var[i,s]of e.entries){var r=s.split(",");r.length<3?console.warn(`Invalid tag ${i}=${s}. Skipping.`):(s=Number(r[0]),void 0!==Ht[s]?(r={id:i,repeatType:s,name:r[1],triggerId:r[2]},t.push(r)):console.warn(`Invalid repeat value ${s} for tag id ${i}. Skipping.`))}return t}}(r=Gt=Gt||{})[r.NoEvent=0]="NoEvent",r[r.EnteredBy=1]="EnteredBy",r[r.SpiedBy=2]="SpiedBy",r[r.AttackedByAny=6]="AttackedByAny",r[r.DestroyedByAny=7]="DestroyedByAny",r[r.AnyEvent=8]="AnyEvent",r[r.DestroyedAllUnits=9]="DestroyedAllUnits",r[r.DestroyedAllBuildings=10]="DestroyedAllBuildings",r[r.DestroyedAll=11]="DestroyedAll",r[r.CreditsExceed=12]="CreditsExceed",r[r.ElapsedTime=13]="ElapsedTime",r[r.MissionTimerExpired=14]="MissionTimerExpired",r[r.DestroyedBuildings=15]="DestroyedBuildings",r[r.DestroyedUnits=16]="DestroyedUnits",r[r.NoFactoriesLeft=17]="NoFactoriesLeft",r[r.BuildBuilding=19]="BuildBuilding",r[r.BuildUnit=20]="BuildUnit",r[r.BuildInfantry=21]="BuildInfantry",r[r.BuildAircraft=22]="BuildAircraft",r[r.GlobalIsSet=27]="GlobalIsSet",r[r.GlobalIsCleared=28]="GlobalIsCleared",r[r.DestroyedOrCaptured=29]="DestroyedOrCaptured",r[r.LowPower=30]="LowPower",r[r.DestroyedBridge=31]="DestroyedBridge",r[r.BuildingExists=32]="BuildingExists",r[r.ComesNearWaypoint=34]="ComesNearWaypoint",r[r.LocalIsSet=36]="LocalIsSet",r[r.LocalIsCleared=37]="LocalIsCleared",r[r.FirstDamagedCombat=38]="FirstDamagedCombat",r[r.HalfHealthCombat=39]="HalfHealthCombat",r[r.QuarterHealthCombat=40]="QuarterHealthCombat",r[r.FirstDamagedAny=41]="FirstDamagedAny",r[r.HalfHealthAny=42]="HalfHealthAny",r[r.QuarterHealthAny=43]="QuarterHealthAny",r[r.AttackedByHouse=44]="AttackedByHouse",r[r.AmbientLightBelow=45]="AmbientLightBelow",r[r.AmbientLightAbove=46]="AmbientLightAbove",r[r.ElapsedScenarioTime=47]="ElapsedScenarioTime",r[r.DestroyedOrCapturedOrInfiltrated=48]="DestroyedOrCapturedOrInfiltrated",r[r.PickupCrate=49]="PickupCrate",r[r.PickupCrateAny=50]="PickupCrateAny",r[r.RandomDelay=51]="RandomDelay",r[r.CreditsBelow=52]="CreditsBelow",r[r.SpyEnteringAsHouse=53]="SpyEnteringAsHouse",r[r.SpyEnteringAsInfantry=54]="SpyEnteringAsInfantry",r[r.DestroyedAllUnitsNaval=55]="DestroyedAllUnitsNaval",r[r.DestroyedAllUnitsLand=56]="DestroyedAllUnitsLand",r[r.BuildingNotExists=57]="BuildingNotExists",(r=$t=$t||{})[r.NoAction=0]="NoAction",r[r.FireSale=9]="FireSale",r[r.TextTrigger=11]="TextTrigger",r[r.DestroyTrigger=12]="DestroyTrigger",r[r.ChangeHouse=14]="ChangeHouse",r[r.RevealMap=16]="RevealMap",r[r.RevealAroundWaypoint=17]="RevealAroundWaypoint",r[r.PlaySoundFx=19]="PlaySoundFx",r[r.PlaySpeech=21]="PlaySpeech",r[r.ForceTrigger=22]="ForceTrigger",r[r.TimerStart=23]="TimerStart",r[r.TimerStop=24]="TimerStop",r[r.TimerExtend=25]="TimerExtend",r[r.TimerShorten=26]="TimerShorten",r[r.TimerSet=27]="TimerSet",r[r.GlobalSet=28]="GlobalSet",r[r.GlobalClear=29]="GlobalClear",r[r.DestroyObject=32]="DestroyObject",r[r.AddOneTimeSuperWeapon=33]="AddOneTimeSuperWeapon",r[r.AddRepeatingSuperWeapon=34]="AddRepeatingSuperWeapon",r[r.AllChangeHouse=36]="AllChangeHouse",r[r.ResizePlayerView=40]="ResizePlayerView",r[r.PlayAnimAt=41]="PlayAnimAt",r[r.DetonateWarhead=42]="DetonateWarhead",r[r.ReshroudMap=51]="ReshroudMap",r[r.EnableTrigger=53]="EnableTrigger",r[r.DisableTrigger=54]="DisableTrigger",r[r.CreateRadarEvent=55]="CreateRadarEvent",r[r.LocalSet=56]="LocalSet",r[r.LocalClear=57]="LocalClear",r[r.SellBuilding=60]="SellBuilding",r[r.TurnOffBuilding=61]="TurnOffBuilding",r[r.TurnOnBuilding=62]="TurnOnBuilding",r[r.ApplyOneHundredDamage=63]="ApplyOneHundredDamage",r[r.DestroyTag=70]="DestroyTag",r[r.SetAmbientStep=71]="SetAmbientStep",r[r.SetAmbientRate=72]="SetAmbientRate",r[r.SetAmbientLight=73]="SetAmbientLight",r[r.NukeStrike=95]="NukeStrike",r[r.PlaySoundFxAt=99]="PlaySoundFxAt",r[r.UnrevealAroundWaypoint=101]="UnrevealAroundWaypoint",r[r.LightningStrike=102]="LightningStrike",r[r.TimerText=103]="TimerText",r[r.CreateCrate=108]="CreateCrate",r[r.IronCurtainAt=109]="IronCurtainAt",r[r.EvictOccupiers=111]="EvictOccupiers",r[r.Cheer=113]="Cheer",r[r.StopSoundsAt=116]="StopSoundsAt";class fi{read(e,t,i,s){let r=this.readTriggers(e),{events:a,unknownEventTypes:n}=this.readEvents(t),{actions:o,unknownActionTypes:h}=this.readActions(i),l=[...s.values()],c=new Set(r);for(let t of r.values()){var u=a.get(t.id);u&&t.events.push(...u);u=o.get(t.id);u&&t.actions.push(...u),!t.attachedTriggerId||(u=r.find(e=>e.id===t.attachedTriggerId))&&(t.attachedTrigger=u,c.delete(u))}for(let t of c){var d=l.find(e=>e.triggerId===t.id);if(d){let e=t;for(;e;)e.tag=d,e=e.attachedTrigger}else{let e=t;for(;e;){console.warn(`Trigger ${e.id} has no associated tag or valid root trigger. Skipping.`);var p=r.indexOf(e);-1!==p&&r.splice(p,1),e=e.attachedTrigger}}}return{triggers:r,unknownEventTypes:n,unknownActionTypes:h}}readTriggers(e){let t=[];for(var[i,s]of e.entries){var r=s.split(",");r.length<8?console.warn(`Invalid trigger ${i}=${s}. Skipping.`):(r={id:i,houseName:r[0],attachedTriggerId:"<none>"!==r[1]?r[1]:void 0,attachedTrigger:void 0,name:r[2],disabled:Boolean(Number(r[3])),difficulties:{easy:Boolean(Number(r[4])),medium:Boolean(Number(r[5])),hard:Boolean(Number(r[6]))},events:[],actions:[],tag:void 0},t.push(r))}return t}readEvents(e){let t=new Map,r=new Set;for(var[a,i]of e.entries){let s=i.split(",");if(s.length<4)console.warn(`Invalid event ${a}=${i}. Skipping.`);else{var n=Number(s.shift());let i=[];for(let t=0;t<n;t++){var o=Number(s.shift()),h=Number(s.shift());let e=s.splice(0,2===h?2:1);void 0!==Gt[o]?(h={triggerId:a,eventIndex:t,type:o,params:[h,...e.map(e=>e||"0")]},i.push(h)):(r.add(o),console.warn(`Unknown event type ${o} for trigger id ${a}. Skipping.`))}t.set(a,i)}}return{events:t,unknownEventTypes:r}}readActions(e){let s=new Map,r=new Set;for(var[a,t]of e.entries){let i=t.split(",");if(i.length<9)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{var n=Number(i.shift());if(i.length<8*n)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{let t=[];for(let e=0;e<n;e++){var o=Number(i.shift()),h=i.splice(0,7);void 0!==$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)):(r.add(o),console.warn(`Unknown action type ${o} for trigger id "${a}". Skipping.`))}s.set(a,t)}}}return{actions:s,unknownActionTypes:r}}readAZActionParam(e){var t="Z".charCodeAt(0),i="A".charCodeAt(0),t=t-i+1;return 1<e.length?e.charCodeAt(1)-i+(e.charCodeAt(0)-i+1)*t:e.charCodeAt(0)-i}}class yi{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 wi{read(e,t){let i=[];for(var[s,r]of e.entries){s={tagId:r,coords:this.readCoords(Number(s),t)};i.push(s)}return i}readCoords(e,t){t=t<4?128:1e3;return{x:e%t,y:Math.floor(e/t)}}}class Ti{constructor(e,t){this.name=e,this.value=t}clone(){return new Ti(this.name,this.value)}}class bi{read(e){return this.initialVeteran=e.getBool("InitialVeteran"),this}}class vi extends c{fromString(e){super.fromString(e);let t=this.getSection("Map");if(!t)throw new Error("[Map] section not found");e=t.getNumberArray("Size");if(this.fullSize={x:e[0],y:e[1],width:e[2],height:e[3]},e=t.getNumberArray("LocalSize"),this.localSize={x:e[0],y:e[1],width:e[2],height:e[3]},this.theaterType=t.getEnum("Theater",I,I.None,!0),this.theaterType===I.None)throw new Error(`Unsupported theater type "${t.getString("Theater")}"`);let i=this.getSection("Basic");e=this.iniFormat=i?.getNumber("NewINIFormat")??0;return this.readTiles(),i?.getBool("MultiplayerOnly")&&this.readWaypoints(this.getOrCreateSection("Waypoints")),this.readStructures(this.getOrCreateSection("Structures")),this.readVehicles(),this.readInfantries(),this.readAircrafts(),this.readTerrains(this.getOrCreateSection("Terrain")),this.readOverlays(),this.readSmudges(),this.readLighting(),this.readTagsAndTriggers(),this.readCellTags(e),this.readVariableNames(),this.startingLocations=this.readStartingLocations(this.waypoints),this.specialFlags=(new bi).read(this.getOrCreateSection("SpecialFlags")),this}readStartingLocations(e){let t=[];var i;for(i of e.filter(e=>e.number<8).sort((e,t)=>e.number<t.number?-1:1))t.push({x:i.rx,y:i.ry});return t}readLighting(){var e=this.getOrCreateSection("Lighting");this.lighting=(new yi).read(e),this.ionLighting=(new yi).read(e,"Ion"),this.ionLighting.forceTint=!0}readTagsAndTriggers(){this.tags=(new mi).read(this.getOrCreateSection("Tags"));var e=this.getOrCreateSection("Triggers"),t=this.getOrCreateSection("Events"),i=this.getOrCreateSection("Actions"),{triggers:e,unknownEventTypes:t,unknownActionTypes:i}=(new fi).read(e,t,i,this.tags);this.triggers=e,this.unknownEventTypes=t,this.unknownActionTypes=i}readCellTags(e){this.cellTags=(new wi).read(this.getOrCreateSection("CellTags"),e)}readVariableNames(){var e,t,i=this.getOrCreateSection("VariableNames");let s=new Map;for([e,t]of i.entries){var r,a,n=Number(e);Number.isNaN(n)?console.warn(`Map [VariableNames] contains non-numeric index "${e}". Skipping.`):([r,a]=t.split(","),a=new Ti(r,Boolean(Number(a))),s.set(n,a))}this.variables=s}readTiles(){let e=this.getSection("IsoMapPack5");if(!e)throw new Error("[IsoMapPack5] section not found");var t=M(e.getConcatenatedValues()),i=(2*this.fullSize.width-1)*this.fullSize.height,s=new Uint8Array(11*i+4);ui.decodeInto(t,s);let r=new w(s.buffer),a=2*this.fullSize.width-1;var n,o,h,l,s=this.fullSize.height,c=(e,t)=>t*a+e;this.tiles=new Array(a*s);for(let e=this.maxTileNum=0;e<i;e++){var u=r.readUint16(),d=r.readUint16(),p=Math.max(0,r.readInt16());this.maxTileNum=Math.max(this.maxTileNum,p),r.readInt16();var g=r.readUint8(),m=r.readUint8();r.readUint8();var f=u-d+this.fullSize.width-1,y=u+d-this.fullSize.width-1;0<=f&&f<2*this.fullSize.width&&0<=y&&y<2*this.fullSize.height&&(g={dx:f,dy:y,rx:u,ry:d,z:m,tileNum:p,subTile:g},this.tiles[c(f,Math.floor(y/2))]=g)}for(let t=0;t<this.fullSize.height;t++)for(let e=0;e<=2*this.fullSize.width-2;e++)null==this.tiles[c(e,t)]&&(n=e,l=(o=2*t+e%2)-(h=(n+o)/2+1)+this.fullSize.width+1,this.tiles[c(e,t)]={dx:n,dy:o,rx:h,ry:l,z:0,tileNum:0,subTile:0})}readWaypoints(e){this.waypoints=[];for(var[t,i]of e.entries){var s;let e;isNaN(s=parseInt(t,10))||isNaN(e=parseInt(i,10))||(t=Math.floor(e/1e3),i=e-1e3*t,this.waypoints.push({number:s,rx:i,ry:t}))}}readStructures(e){this.structures=[];for(var[,t]of e.entries){t=t.split(",");if(!(t.length<=15)){let e=new 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=[],this.maxOverlayId=0;let t=this.getSection("OverlayPack");if(t){var i=M(t.getConcatenatedValues()),s=new Uint8Array(1<<18);ui.decodeInto(i,s,80);let e=this.getSection("OverlayDataPack");if(e){var i=M(e.getConcatenatedValues()),r=new Uint8Array(1<<18);ui.decodeInto(i,r,80);for(let t=0;t<this.fullSize.height;t++)for(let e=2*this.fullSize.width-2;0<=e;e--){var a=e,n=2*t+e%2,o=(a+n)/2+1,h=n-o+this.fullSize.width+1,a=o+512*h,n=s[a];if(255!==n){a=r[a];let e=new Wt;e.id=n,e.value=a,e.rx=o,e.ry=h,this.overlays.push(e),this.maxOverlayId=Math.max(this.maxOverlayId,n)}}}else console.warn("[OverlayDataPack] section not found. Skipping.")}else console.warn("[Overlay] section not found. Skipping.")}readSmudges(){this.smudges=[];let e=this.getSection("Smudge");if(e)for(var t of e.entries.values()){t=t.split(",");if(t.length<=2)console.warn(`Invalid Smudge entry: "${t}"`);else{let e=new 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,s]=e.getArray("Size").map(e=>Number(e)),r=M(t.getConcatenatedValues()),s=new gi(i,s);return ui.decodeInto(r,s.data),s}}}(r=qt=qt||{})[r.GDI=0]="GDI",r[r.Nod=1]="Nod",r[r.Civilian=2]="Civilian",r[r.Mutant=3]="Mutant";const Si=(new Map).set("GDI",qt.GDI).set("Nod",qt.Nod).set("Civilian",qt.Civilian).set("Mutant",qt.Mutant),_i=new Map([["Americans","STT:PlayerSideAmerica"],["Alliance","STT:PlayerSideKorea"],["French","STT:PlayerSideFrance"],["Germans","STT:PlayerSideGermany"],["British","STT:PlayerSideBritain"],["Africans","STT:PlayerSideLibya"],["Arabs","STT:PlayerSideIraq"],["Confederation","STT:PlayerSideCuba"],["Russians","STT:PlayerSideRussia"]]);class ki{constructor(e){this.id=e}readIni(e){this.name=e.name,this.uiName=e.getString("UIName"),this.uiTooltip=e.get("UITooltip")||_i.get(this.name);var t=e.getString("Side");if(!t)throw new Error(`Missing Side for country "${this.name}"`);var i=Si.get(t);if(void 0===i)throw new Error(`Unknown side "${t}" for country "${this.name}"`);this.side=i,this.multiplay=e.getBool("Multiplay"),this.multiplayPassive=e.getBool("MultiplayPassive"),this.veteranAircraft=e.getArray("VeteranAircraft"),this.veteranInfantry=e.getArray("VeteranInfantry"),this.veteranUnits=e.getArray("VeteranUnits")}}class Oi{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}}Oi.IMAGE_NONE="none";class Ii{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=Oi.iniSpeedToLeptonsPerTick(e),this.suicide=this.rules.getBool("Suicide"),this.useSparkParticles=this.rules.getBool("UseSparkParticles"),this.warhead=this.rules.getString("Warhead")}}class Ai{readIni(e){this.ini=e,this.ambientChangeRate=e.getNumber("AmbientChangeRate"),this.ambientChangeStep=e.getNumber("AmbientChangeStep"),this.behind=e.getString("Behind"),this.bridgeExplosions=e.getArray("BridgeExplosions"),this.chronoBeamColor=e.getNumberArray("ChronoBeamColor"),this.chronoBlast=e.getString("ChronoBlast"),this.chronoBlastDest=e.getString("ChronoBlastDest"),this.chronoPlacement=e.getString("ChronoPlacement"),this.chronoSparkle1=e.getString("ChronoSparkle1"),this.conditionRed=e.getNumber("ConditionRed"),this.conditionYellow=e.getNumber("ConditionYellow"),this.creditTicks=e.getArray("CreditTicks"),this.extraAircraftLight=e.getNumber("ExtraAircraftLight"),this.extraInfantryLight=e.getNumber("ExtraInfantryLight"),this.extraUnitLight=e.getNumber("ExtraUnitLight");let t=e.getString("DamageFireTypes");t=t||"FIRE01,FIRE02,FIRE03",this.fireNames=t.split(/\.|,/).filter(e=>""!==e),this.flyerHelper=e.getString("FlyerHelper"),this.gravity=e.getNumber("Gravity"),this.idleActionFrequency=60*e.getNumber("IdleActionFrequency"),this.impactLandSound=e.getString("ImpactLandSound")||void 0,this.impactWaterSound=e.getString("ImpactWaterSound")||void 0,this.infantryExplode=e.getString("InfantryExplode"),this.flamingInfantry=e.getString("FlamingInfantry"),this.infantryHeadPop=e.getString("InfantryHeadPop"),this.infantryNuked=e.getString("InfantryNuked"),this.ironCurtainInvokeAnim=e.getString("IronCurtainInvokeAnim"),this.messageDuration=e.getNumber("MessageDuration",10),this.metallicDebris=e.getArray("MetallicDebris"),this.nukeTakeOff=e.getString("NukeTakeOff"),this.deadBodies=e.getArray("DeadBodies"),this.wake=e.getString("Wake"),this.parachute=e.getString("Parachute"),this.moveFlash=e.getString("MoveFlash"),this.warpOut=e.getString("WarpOut"),this.warpAway=e.getString("WarpAway"),this.weaponNullifyAnim=e.getString("WeaponNullifyAnim"),this.weatherConClouds=e.getArray("WeatherConClouds"),this.weatherConBoltExplosion=e.getString("WeatherConBoltExplosion"),this.weatherConBolts=e.getArray("WeatherConBolts")}}(r=Xt=Xt||{})[r.GenericCombat=0]="GenericCombat",r[r.GenericNonCombat=1]="GenericNonCombat",r[r.DropZone=2]="DropZone",r[r.BaseUnderAttack=3]="BaseUnderAttack",r[r.HarvesterUnderAttack=4]="HarvesterUnderAttack",r[r.EnemyObjectSensed=5]="EnemyObjectSensed";class Ci{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 ${Xt[e]}`);return this.eventSuppressionDistances[e]}getEventVisibilityDuration(e){if(e>this.eventVisibilityDurations.length-1)throw new RangeError(`No event visibility duration is defined for type ${Xt[e]}`);return this.eventVisibilityDurations[e]}getEventDuration(e){if(e>this.eventDurations.length-1)throw new RangeError(`No event duration is defined for type ${Xt[e]}`);return this.eventDurations[e]}}class Bi{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 xi{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 Ei{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 Pi{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 Ni{readIni(e){return this.myEffectivenessCoefficientDefault=e.getNumber("MyEffectivenessCoefficientDefault"),this.targetEffectivenessCoefficientDefault=e.getNumber("TargetEffectivenessCoefficientDefault"),this.targetSpecialThreatCoefficientDefault=e.getNumber("TargetSpecialThreatCoefficientDefault"),this.targetStrengthCoefficientDefault=e.getNumber("TargetStrengthCoefficientDefault"),this.targetDistanceCoefficientDefault=e.getNumber("TargetDistanceCoefficientDefault"),this}}class Ri{readIni(e){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 s=[];for(let e=0;e<t.length;++e)0<i[e]&&s.push({inf:t[e],num:i[e]});return s}getParadropSquads(e){switch(e){case qt.GDI:return this.allyParaDrop;case qt.Nod:return this.sovParaDrop;default:throw new Error(`Unhandled side type "${e}"`)}}}class Di{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 Mi{}class Li extends Mi{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 Fi extends Mi{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 ji{readIni(e){return this.height=e.getNumber("HoverHeight"),this.dampen=e.getNumber("HoverDampen"),this.bob=e.getNumber("HoverBob"),this.boost=e.getNumber("HoverBoost"),this.acceleration=e.getNumber("HoverAcceleration"),this.brake=e.getNumber("HoverBrake"),this}}(r=Qt=Qt||{})[r.Power=0]="Power",r[r.Factory=1]="Factory",r[r.Barracks=2]="Barracks",r[r.Radar=3]="Radar",r[r.Tech=4]="Tech",r[r.Proc=5]="Proc";const Ui=(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 Wi{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 Ei).readIni(e),this.defaultMirageDisguises=e.getArray("DefaultMirageDisguises"),this.dMisl=(new Fi).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 ji).readIni(e),this.infantryBlinkDisguiseTime=e.getNumber("InfantryBlinkDisguiseTime"),this.lightningStorm=(new Di).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 Ri).readIni(e),this.prism=(new Pi).readIni(e),this.purifierBonus=e.getNumber("PurifierBonus"),this.radar=(new Ci).readIni(e),this.refundPercent=U(e.getNumber("RefundPercent"),0,1),this.repair=(new Bi).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 Ni).readIni(e),this.treeStrength=e.getNumber("TreeStrength"),this.v3Rocket=(new Li).readIni(e),this.veteran=(new xi).readIni(e),this.wallBuildSpeedCoefficient=e.getNumber("WallBuildSpeedCoefficient"),this.readPrereqCategories(e)}readPrereqCategories(e){for(var[t,i]of Ui){if(!e.has(i))throw new Error(`Missing prerequisite category ${i} in [General] section`);this.prereqCategories.set(t,e.getArray(i))}}getMissileRules(e){switch(e){case this.v3Rocket.type:return this.v3Rocket;case this.dMisl.type:return this.dMisl;default:throw new Error(`Unsupported missile type "${e}"`)}}}(r=Zt=Zt||{})[r.Default=0]="Default",r[r.Tunnel=5]="Tunnel",r[r.Railroad=6]="Railroad",r[r.Rock1=7]="Rock1",r[r.Rock2=8]="Rock2",r[r.Water=9]="Water",r[r.Shore=10]="Shore",r[r.Pavement=11]="Pavement",r[r.Dirt=12]="Dirt",r[r.Clear=13]="Clear",r[r.Rough=14]="Rough",r[r.Cliff=15]="Cliff",(r=Yt=Yt||{})[r.Clear=0]="Clear",r[r.Road=1]="Road",r[r.Rock=2]="Rock",r[r.Beach=3]="Beach",r[r.Rough=4]="Rough",r[r.Railroad=5]="Railroad",r[r.Weeds=6]="Weeds",r[r.Water=7]="Water",r[r.Wall=8]="Wall",r[r.Tiberium=9]="Tiberium",r[r.Cliff=10]="Cliff";const zi=new Map([[Zt.Default,Yt.Clear],[Zt.Clear,Yt.Clear],[Zt.Tunnel,Yt.Cliff],[Zt.Railroad,Yt.Railroad],[Zt.Rock1,Yt.Rock],[Zt.Rock2,Yt.Rock],[Zt.Water,Yt.Water],[Zt.Shore,Yt.Beach],[Zt.Pavement,Yt.Road],[Zt.Dirt,Yt.Road],[Zt.Rough,Yt.Rough],[Zt.Cliff,Yt.Cliff]]);function Vi(e){if(!zi.has(e))throw new Error(`Unknown terrain type ${e}`);return zi.get(e)}(r=Kt=Kt||{})[r.Foot=0]="Foot",r[r.Track=1]="Track",r[r.Wheel=2]="Wheel",r[r.Hover=3]="Hover",r[r.Float=4]="Float",r[r.FloatBeach=5]="FloatBeach",r[r.Amphibious=6]="Amphibious",r[r.Winged=7]="Winged";class Hi{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}}(r=Jt=Jt||{})[r.None=0]="None",r[r.Gunfire=1]="Gunfire",r[r.Explode=2]="Explode",r[r.ExplodeAlt=3]="ExplodeAlt",r[r.Fire=4]="Fire",r[r.Electro=5]="Electro",r[r.HeadExplode=6]="HeadExplode",r[r.Nuke=7]="Nuke";class Gi{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.getEnumNumeric("InfDeath",Jt,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 $i extends Oi{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=Oi.iniRotToDegsPerTick(e),this.iniRot=e,this.shadow=this.ini.getBool("Shadow",!0),this.shrapnelWeapon=this.ini.getString("ShrapnelWeapon")||void 0,this.shrapnelCount=this.ini.getNumber("ShrapnelCount"),this.subjectToCliffs=this.ini.getBool("SubjectToCliffs"),this.subjectToElevation=this.ini.getBool("SubjectToElevation"),this.subjectToWalls=this.ini.getBool("SubjectToWalls"),this.vertical=this.ini.getBool("Vertical")}}(r=ei=ei||{})[r.Green=0]="Green",r[r.Yellow=1]="Yellow",r[r.White=2]="White",r[r.Red=3]="Red",r[r.Blue=4]="Blue",(r=ti=ti||{})[r.Statue=0]="Statue",r[r.Aircraft=1]="Aircraft",r[r.Chrono=2]="Chrono",r[r.Hover=3]="Hover",r[r.Infantry=4]="Infantry",r[r.Jumpjet=5]="Jumpjet",r[r.Missile=6]="Missile",r[r.Ship=7]="Ship",r[r.Vehicle=8]="Vehicle";const qi=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]]),Xi=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]]);(r=ii=ii||{})[r.Amphibious=0]="Amphibious",r[r.AmphibiousCrusher=1]="AmphibiousCrusher",r[r.AmphibiousDestroyer=2]="AmphibiousDestroyer",r[r.Crusher=3]="Crusher",r[r.CrusherAll=4]="CrusherAll",r[r.Destroyer=5]="Destroyer",r[r.Fly=6]="Fly",r[r.Infantry=7]="Infantry",r[r.InfantryDestroyer=8]="InfantryDestroyer",r[r.Normal=9]="Normal",r[r.Subterranean=10]="Subterranean",r[r.Water=11]="Water",(r=si=si||{})[r.None=0]="None",r[r.Flak=1]="Flak",r[r.Plate=2]="Plate",r[r.Light=3]="Light",r[r.Medium=4]="Medium",r[r.Heavy=5]="Heavy",r[r.Wood=6]="Wood",r[r.Steel=7]="Steel",r[r.Concrete=8]="Concrete",r[r.Special_1=9]="Special_1",r[r.Special_2=10]="Special_2",(r=ri=ri||{})[r.LandOk=0]="LandOk",r[r.LandNotOk=1]="LandNotOk",r[r.LandSecondary=2]="LandSecondary",(r=ai=ai||{})[r.UnderwaterNever=0]="UnderwaterNever",r[r.UnderwaterSecondary=1]="UnderwaterSecondary",r[r.UnderwaterOnly=2]="UnderwaterOnly",r[r.OrganicSecondary=3]="OrganicSecondary",r[r.SealSpecial=4]="SealSpecial",r[r.NavalAll=5]="NavalAll",r[r.NavalNone=6]="NavalNone",(r=ni=ni||{})[r.Primary=0]="Primary",r[r.Secondary=1]="Secondary",r[r.DeathWeapon=2]="DeathWeapon",(r=oi=oi||{})[r.FASTER=0]="FASTER",r[r.STRONGER=1]="STRONGER",r[r.FIREPOWER=2]="FIREPOWER",r[r.SCATTER=3]="SCATTER",r[r.ROF=4]="ROF",r[r.SIGHT=5]="SIGHT",r[r.SELF_HEAL=6]="SELF_HEAL",r[r.CLOAK=7]="CLOAK",r[r.EXPLODES=8]="EXPLODES",r[r.RADAR_INVISIBLE=9]="RADAR_INVISIBLE",r[r.SENSORS=10]="SENSORS",r[r.FEARLESS=11]="FEARLESS",r[r.C4=12]="C4",r[r.GUARD_AREA=13]="GUARD_AREA",r[r.CRUSHER=14]="CRUSHER",(r=hi=hi||{})[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Strong=2]="Strong";class Qi{static reverseSinTableLookup(e,t,i,s){for(;t<=i;){var r=Math.floor((t+i)/2),a=this.SIN_TABLE[r];if(a===e)return r;(s?e<a:a<e)?t=r+1:i=r-1}return Math.abs(e-this.SIN_TABLE[t])<Math.abs(e-this.SIN_TABLE[i])?t:i}static pow(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||Number.isSafeInteger(e)&&Number.isSafeInteger(t))return e**t;if(!Number.isSafeInteger(t))throw new Error("Exponent must be a safe integer");return Math.floor(e*this.EXP_10_PRECISION)**t/this.EXP_10_PRECISION**t}static sqrt(e){if(0===e)return 0;var t;let i=e/3;for(;t=i,i=(e/i+i)/2,5e-15<Math.abs(t-i););return i}static sin(e){if(!Number.isFinite(e))return NaN;if(!e)return e;e=e/(2*Math.PI)-Math.floor(e/(2*Math.PI)),e=Math.floor(e*this.SIN_TABLE.length);return this.SIN_TABLE[e]}static cos(e){return this.sin(e+Math.PI/2)}static asin(e){if(!W(e,-1,1))return NaN;if(!e)return 0;let t;var i=this.SIN_TABLE.length;return t=0<e?2*Math.PI*this.reverseSinTableLookup(e,0,i/4,!1)/i:Math.PI-2*Math.PI*this.reverseSinTableLookup(e,i/2,.75*i,!0)/i,t}static acos(e){return Math.PI/2-this.asin(e)}static atan2(e,t){if(Number.isNaN(t)||Number.isNaN(e))return NaN;let i;return i=Number.isFinite(e)||Number.isFinite(t)?Number.isFinite(t)&&0!==e?Number.isFinite(e)&&0!==t?this.atan2FiniteNonZero(e,t):this.signIncZero(e)*Math.PI*.5:this.signIncZero(e)*(this.signIncZero(t)<0?Math.PI:0):Math.sign(e)*Math.PI*(0<Math.sign(t)?.25:.75),i}static atan2FiniteNonZero(e,t){var i=Math.abs(t),s=Math.abs(e),r=Math.min(i,s)/Math.max(i,s),a=r*r;let n=((-.0464964749*a+.15931422)*a-.327622764)*a*r+r;return i<s&&(n=Math.PI/2-n),t<0&&(n=Math.PI-n),e<0&&(n=-n),n}static signIncZero(e){return e===-1/0||1/e<0?-1:1}}Qi.PRECISION=6,Qi.EXP_10_PRECISION=10**Qi.PRECISION,Qi.SIN_TABLE=[0,.004848117819001859,.009696121685978396,.014543897651582654,.01939133177182437,.024238310110748135,.0290847187431114,.03393044375706223,.03877537125681671,.043619387365336,.04846237822700296,.05330423001029823,.05814482891047582,.06298406115223795,.06782181299240934,.0726579707226106,.07749242067193093,.08232504920959989,.08715574274765817,.09198438774362744,.09681087070317909,.10163507818280187,.10645689679246824,.11127621319829964,.11609291412523022,.12090688635966935,.12571801675216268,.13052619222005157,.13533129975013108,.14013322640130627,.14493185930724672,.1497270856790396,.15451879280784048,.15930686806752256,.16409119891732396,.1688716729044928,.17364817766693033,.17842060093583212,.18318883053832663,.18795275440011186,.19271226054808968,.19746723711299752,.20221757233203794,.20696315455150538,.2117038722294107,.21643961393810288,.22117026836688775,.2258957243246448,.23061587074244014,.2353305966761376,.24003979130900588,.2447433439543238,.24944114405798126,.25413308120107847,.25881904510252074,.26349892562161076,.2681726127606373,.272839996667461,.27750096763809573,.28215541611928774,.2868032327110902,.29144430816943495,.2960785334086999,.3007057995042731,.3053259976951131,.30993901938630514,.31454475615161365,.31914309973603083,.323733942058321,.328317175213561,.33289269147567657,.3374603832999741,.3420201433256687,.34657186437840753,.3511154394727888,.3556507618148765,.3601777248047104,.36469622203881186,.3692061473126844,.3737073946233105,.3781998581716425,.3826834323650898,.3871580118200006,.3916234913641391,.3960797660391568,.4005267311030606,.4049642820326736,.4093923145260926,.4138107245051391,.4182194081178064,.42261826174069944,.4270071819814715,.4313860656812534,.4357548099170794,.4401133120043048,.44446146949902104,.4487991802004621,.4531263421534082,.4574428536505808,.4617486132350339,.46604351970253877,.4703274721039625,.4746003697476404,.4788621122017435,.4831125992966384,.48735173112724234,.49157940805537054,.49579553071207916,.49999999999999994,.5041927170956704,.5083735834518556,.5125425007998652,.5166993711518628,.5208440968031697,.5249765803345602,.5290967246145525,.5332044328016912,.5372996083468239,.5413821549953696,.5454519767895825,.549508978070806,.5535530634817223,.5575841379685927,.5616021067834929,.5656068754865385,.5695983499481065,.573576436351046,.5775410411928851,.5814920712880266,.5854294337699405,.5893530360933448,.593262786036382,.5971585917027862,.6010403615240428,.6049080042615417,.6087614290087207,.6126005451932028,.6164252625789254,.62023549126826,.6240311417041269,.6278121246720986,.6315783513024975,.6353297330724851,.6390661818081416,.6427876096865393,.6464939292378065,.6501850533471834,.6538608952570697,.6575213685690636,.6611663872459932,.6647958656139378,.6684097183642425,.6720078605555224,.6755902076156601,.6791566753437932,.6827071799122926,.6862416378687335,.6897599661378576,.6932620820235242,.696747903210655,.7002173477671685,.7036703341459059,.7071067811865475,.710526608117521,.713929734557899,.7173160805192894,.7206855664077146,.7240381130254825,.7273736415730487,.7306920736508674,.7339933312612352,.7372773368101241,.7405440131090046,.7437932833766612,.747025071240996,.7502393007408245,.7534358963276606,.7566147828674927,.7597758856425494,.7629191303530553,.766044443118978,.7691517504817651,.7722409794060692,.7753120572814658,.7783649119241599,.7813994715786823,.7844156649195757,.7874134210530723,.7903926695187593,.7933533402912352,.7962953637817558,.7992186708398696,.8021231927550437,.8050088612582783,.8078756085237111,.8107233671702122,.8135520702629676,.8163616513150519,.8191520442889918,.821923183598318,.8246750041091067,.8274074411415104,.8301204304712788,.8328139083312671,.8354878114129364,.8381420768678404,.8407766423091032,.8433914458128856,.845986425919841,.848561521636559,.8511166724369997,.8536518182639162,.8561668995302665,.8586618571206132,.8611366323925137,.8635911671778986,.8660254037844386,.8684392849969005,.870832754078492,.8732057547721958,.8755582313020908,.8778901283746645,.8802013911801111,.8824919653936212,.8847617971766577,.8870108331782216,.8892390205361062,.8914463068781385,.8936326403234122,.8957979694835052,.8979422434636881,.9000654118641211,.9021674247810376,.9042482328079179,.9063077870366499,.9083460390586793,.9103629409661466,.9123584453530141,.9143325053161794,.9162850744565779,.918216106880274,.9201255571995389,.9220133805339185,.9238795325112867,.9257239692688903,.9275466474543786,.9293475242268224,.9311265572577219,.9328837047320004,.9346189253489884,.9363321783233931,.9380234233862578,.9396926207859083,.9413397312888874,.942964716180876,.9445675372676047,.9461481568757504,.947706537853822,.9492426435730339,.9507564379281666,.9522478853384153,.9537169507482269,.955163599628123,.9565877979755122,.9579895123154889,.9593687097016201,.9607253577167205,.9620594244736131,.9633708786158803,.9646596893185995,.9659258262890683,.9671692597675166,.9683899605278059,.969587899878116,.97076304966162,.9719153822571454,.9730448705798238,.9741514880817275,.9752352087524931,.9762960071199334,.9773338582506355,.9783487377505475,.9793406217655515,.980309486982024,.9812553106273847,.9821780704706308,.98307774482286,.9839543125377807,.984807753012208,.9856380461865492,.9864451725452739,.987229113117374,.987989849476809,.9887273637429388,.9894416385809445,.9901326572022359,.9908004033648453,.9914448613738104,.9920660160815423,.9926638528881819,.993238357741943,.9937895171394426,.9943173181260184,.9948217482960331,.9953027957931658,.9957604493106914,.9961946980917455,.9966055319295779,.996992941167792,.9973569167005722,.9976974499728977,.9980145329807433,.9983081582712682,.9985783189429907,.9988250086459504,.9990482215818578,.99924795250423,.9994241967185149,.9995769500822006,.9997062090049132,.9998119704485015,.9998942319271075,.9999529915072262,.9999882478077495,1,.9999882478077495,.9999529915072262,.9998942319271075,.9998119704485015,.9997062090049132,.9995769500822006,.9994241967185149,.99924795250423,.9990482215818578,.9988250086459504,.9985783189429907,.9983081582712682,.9980145329807433,.9976974499728977,.9973569167005722,.996992941167792,.9966055319295779,.9961946980917455,.9957604493106914,.9953027957931658,.9948217482960331,.9943173181260184,.9937895171394426,.993238357741943,.9926638528881819,.9920660160815423,.9914448613738105,.9908004033648453,.9901326572022359,.9894416385809446,.9887273637429388,.987989849476809,.987229113117374,.9864451725452739,.9856380461865492,.984807753012208,.9839543125377807,.98307774482286,.9821780704706307,.9812553106273847,.9803094869820241,.9793406217655516,.9783487377505476,.9773338582506356,.9762960071199334,.9752352087524931,.9741514880817276,.9730448705798238,.9719153822571455,.9707630496616201,.969587899878116,.9683899605278059,.9671692597675166,.9659258262890683,.9646596893185995,.9633708786158803,.9620594244736133,.9607253577167205,.9593687097016202,.9579895123154889,.9565877979755123,.9551635996281231,.9537169507482269,.9522478853384153,.9507564379281666,.949242643573034,.9477065378538221,.9461481568757505,.9445675372676048,.942964716180876,.9413397312888873,.9396926207859084,.9380234233862579,.9363321783233931,.9346189253489885,.9328837047320006,.9311265572577219,.9293475242268225,.9275466474543786,.9257239692688904,.9238795325112867,.9220133805339185,.920125557199539,.918216106880274,.916285074456578,.9143325053161794,.9123584453530141,.9103629409661467,.9083460390586793,.90630778703665,.904248232807918,.9021674247810377,.9000654118641213,.8979422434636883,.8957979694835051,.8936326403234123,.8914463068781386,.8892390205361062,.8870108331782218,.8847617971766579,.8824919653936212,.8802013911801111,.8778901283746644,.8755582313020909,.8732057547721958,.8708327540784921,.8684392849969006,.8660254037844387,.8635911671778987,.8611366323925138,.858661857120613,.8561668995302665,.8536518182639163,.8511166724369997,.8485615216365591,.8459864259198412,.8433914458128856,.8407766423091031,.8381420768678404,.8354878114129364,.8328139083312672,.8301204304712789,.8274074411415107,.8246750041091069,.8219231835983182,.819152044288992,.8163616513150518,.8135520702629675,.8107233671702123,.8078756085237112,.8050088612582784,.802123192755044,.7992186708398695,.7962953637817556,.7933533402912352,.7903926695187593,.7874134210530723,.7844156649195758,.7813994715786824,.7783649119241601,.775312057281466,.7722409794060693,.769151750481765,.766044443118978,.7629191303530551,.7597758856425494,.756614782867493,.7534358963276608,.7502393007408243,.7470250712409959,.7437932833766611,.7405440131090045,.7372773368101241,.7339933312612353,.7306920736508675,.7273736415730488,.7240381130254827,.7206855664077148,.7173160805192896,.713929734557899,.710526608117521,.7071067811865476,.703670334145906,.7002173477671687,.6967479032106549,.6932620820235241,.6897599661378576,.6862416378687336,.6827071799122926,.6791566753437933,.6755902076156604,.6720078605555225,.6684097183642426,.6647958656139381,.6611663872459935,.6575213685690636,.6538608952570697,.6501850533471835,.6464939292378067,.6427876096865395,.6390661818081418,.635329733072485,.6315783513024975,.6278121246720986,.6240311417041269,.6202354912682602,.6164252625789255,.612600545193203,.6087614290087209,.6049080042615419,.6010403615240432,.5971585917027862,.593262786036382,.5893530360933449,.5854294337699406,.5814920712880268,.5775410411928852,.5735764363510459,.5695983499481064,.5656068754865385,.5616021067834929,.5575841379685929,.5535530634817224,.5495089780708062,.5454519767895827,.5413821549953699,.5372996083468241,.5332044328016912,.5290967246145525,.5249765803345602,.5208440968031698,.516699371151863,.5125425007998654,.5083735834518555,.5041927170956703,.49999999999999994,.49579553071207916,.49157940805537065,.48735173112724245,.48311259929663863,.4788621122017437,.47460036974764064,.47032747210396275,.46604351970253877,.4617486132350339,.45744285365058085,.4531263421534083,.44879918020046233,.4444614694990212,.4401133120043047,.43575480991707927,.43138606568125343,.4270071819814714,.4226182617406995,.4182194081178065,.4138107245051393,.40939231452609276,.4049642820326738,.40052673110306086,.3960797660391572,.39162349136413904,.38715801182000065,.3826834323650899,.37819985817164264,.3737073946233107,.3692061473126843,.36469622203881175,.3601777248047104,.3556507618148765,.35111543947278884,.34657186437840765,.3420201433256689,.3374603832999743,.33289269147567685,.32831717521356135,.3237339420583214,.31914309973603083,.3145447561516137,.30993901938630525,.30532599769511326,.30070579950427334,.29607853340870016,.2914443081694349,.2868032327110902,.28215541611928774,.2775009676380958,.2728399966674611,.26817261276063753,.263498925621611,.258819045102521,.2541330812010788,.24944114405798165,.24474334395432376,.24003979130900596,.2353305966761377,.23061587074244033,.225895724324645,.22117026836688802,.21643961393810274,.21170387222941067,.20696315455150538,.20221757233203796,.19746723711299763,.19271226054808982,.18795275440011205,.18318883053832688,.17842060093583242,.17364817766693072,.16887167290449276,.16409119891732402,.15930686806752267,.15451879280784062,.1497270856790398,.14493185930724697,.14013322640130613,.135331299750131,.13052619222005157,.12571801675216274,.12090688635966945,.11609291412523036,.11127621319829985,.1064568967924685,.10163507818280217,.09681087070317945,.09198438774362741,.0871557427476582,.08232504920959997,.07749242067193107,.07265797072261079,.0678218129924096,.06298406115223781,.05814482891047573,.0533042300102982,.04846237822700297,.04361938736533607,.038775371256816835,.03393044375706242,.029084718743111644,.02423831011074843,.01939133177182472,.014543897651583058,.009696121685978408,.004848117819001927,12246467991473532e-32,-.004848117819001238,-.009696121685978163,-.01454389765158237,-.019391331771824474,-.02423831011074774,-.029084718743111398,-.03393044375706173,-.03877537125681659,-.04361938736533583,-.048462378227003174,-.05330423001029795,-.05814482891047593,-.06298406115223758,-.06782181299240934,-.07265797072261056,-.07749242067193128,-.08232504920959974,-.08715574274765794,-.09198438774362716,-.09681087070317876,-.10163507818280193,-.10645689679246781,-.1112762131982996,-.11609291412523012,-.12090688635966965,-.1257180167521625,-.13052619222005177,-.13533129975013078,-.14013322640130632,-.14493185930724675,-.14972708567904,-.1545187928078404,-.15930686806752198,-.16409119891732377,-.16887167290449254,-.17364817766693047,-.17842060093583176,-.18318883053832663,-.1879527544001114,-.1927122605480896,-.19746723711299738,-.20221757233203816,-.20696315455150513,-.21170387222941087,-.21643961393810252,-.2211702683668878,-.22589572432464475,-.23061587074244053,-.23533059667613745,-.2400397913090053,-.2447433439543235,-.24944114405798098,-.2541330812010786,-.25881904510252035,-.2634989256216107,-.26817261276063686,-.2728399966674609,-.27750096763809556,-.2821554161192879,-.28680323271108993,-.29144430816943506,-.29607853340869994,-.30070579950427306,-.30532599769511304,-.3099390193863046,-.3145447561516135,-.3191430997360306,-.3237339420583211,-.3283171752135607,-.33289269147567657,-.3374603832999737,-.34202014332566866,-.3465718643784074,-.35111543947278906,-.35565076181487626,-.36017772480471055,-.3646962220388115,-.3692061473126845,-.3737073946233105,-.3781998581716428,-.38268343236508967,-.38715801182000004,-.3916234913641388,-.39607976603915657,-.40052673110306064,-.4049642820326732,-.40939231452609254,-.41381072450513867,-.4182194081178062,-.4226182617406993,-.4270071819814716,-.4313860656812532,-.43575480991707943,-.4401133120043045,-.444461469499021,-.4487991802004621,-.4531263421534085,-.4574428536505806,-.46174861323503374,-.46604351970253854,-.47032747210396214,-.4746003697476404,-.47886211220174313,-.4831125992966384,-.4873517311272422,-.4915794080553708,-.49579553071207894,-.5000000000000001,-.50419271709567,-.5083735834518556,-.5125425007998652,-.5166993711518633,-.5208440968031696,-.5249765803345596,-.5290967246145523,-.533204432801691,-.5372996083468239,-.5413821549953693,-.5454519767895825,-.5495089780708056,-.5535530634817222,-.5575841379685926,-.5616021067834931,-.5656068754865384,-.5695983499481065,-.5735764363510458,-.577541041192885,-.5814920712880266,-.5854294337699408,-.5893530360933448,-.5932627860363815,-.597158591702786,-.6010403615240426,-.6049080042615417,-.6087614290087203,-.6126005451932028,-.6164252625789249,-.6202354912682599,-.6240311417041268,-.6278121246720987,-.6315783513024973,-.6353297330724852,-.6390661818081416,-.6427876096865393,-.6464939292378065,-.6501850533471829,-.6538608952570695,-.6575213685690635,-.6611663872459933,-.6647958656139376,-.6684097183642425,-.6720078605555221,-.6755902076156601,-.6791566753437931,-.6827071799122927,-.6862416378687334,-.6897599661378577,-.693262082023524,-.696747903210655,-.7002173477671685,-.7036703341459061,-.7071067811865475,-.7105266081175206,-.7139297345578989,-.7173160805192892,-.7206855664077146,-.7240381130254823,-.7273736415730487,-.7306920736508671,-.7339933312612352,-.737277336810124,-.7405440131090048,-.743793283376661,-.747025071240996,-.7502393007408242,-.7534358963276607,-.7566147828674927,-.7597758856425493,-.7629191303530554,-.7660444431189779,-.7691517504817651,-.7722409794060688,-.7753120572814659,-.7783649119241597,-.7813994715786822,-.7844156649195754,-.7874134210530722,-.7903926695187589,-.7933533402912349,-.7962953637817558,-.79921867083987,-.8021231927550437,-.8050088612582785,-.8078756085237111,-.8107233671702119,-.8135520702629674,-.8163616513150515,-.8191520442889916,-.8219231835983181,-.8246750041091064,-.8274074411415104,-.830120430471279,-.8328139083312671,-.8354878114129365,-.8381420768678401,-.8407766423091032,-.8433914458128855,-.8459864259198411,-.8485615216365587,-.8511166724369996,-.8536518182639165,-.8561668995302664,-.8586618571206132,-.8611366323925135,-.8635911671778986,-.8660254037844385,-.8684392849969005,-.8708327540784918,-.8732057547721956,-.8755582313020905,-.8778901283746643,-.8802013911801112,-.8824919653936215,-.8847617971766578,-.8870108331782218,-.889239020536106,-.8914463068781383,-.8936326403234122,-.8957979694835049,-.897942243463688,-.9000654118641208,-.9021674247810375,-.9042482328079179,-.90630778703665,-.9083460390586792,-.9103629409661468,-.912358445353014,-.9143325053161795,-.9162850744565778,-.918216106880274,-.9201255571995388,-.9220133805339183,-.9238795325112865,-.9257239692688903,-.9275466474543786,-.9293475242268223,-.9311265572577219,-.9328837047320003,-.9346189253489884,-.9363321783233929,-.9380234233862578,-.9396926207859082,-.9413397312888873,-.9429647161808761,-.9445675372676049,-.9461481568757504,-.9477065378538222,-.9492426435730339,-.9507564379281666,-.9522478853384153,-.9537169507482267,-.9551635996281229,-.956587797975512,-.9579895123154888,-.9593687097016201,-.9607253577167205,-.9620594244736131,-.9633708786158804,-.9646596893185994,-.9659258262890683,-.9671692597675166,-.9683899605278059,-.9695878998781159,-.97076304966162,-.9719153822571452,-.9730448705798238,-.9741514880817276,-.975235208752493,-.9762960071199334,-.9773338582506355,-.9783487377505475,-.9793406217655514,-.980309486982024,-.9812553106273846,-.9821780704706307,-.98307774482286,-.9839543125377805,-.984807753012208,-.9856380461865493,-.9864451725452739,-.9872291131173742,-.9879898494768089,-.9887273637429387,-.9894416385809445,-.9901326572022358,-.9908004033648452,-.9914448613738104,-.9920660160815423,-.9926638528881818,-.993238357741943,-.9937895171394426,-.9943173181260184,-.994821748296033,-.9953027957931658,-.9957604493106913,-.9961946980917455,-.9966055319295779,-.996992941167792,-.9973569167005722,-.9976974499728977,-.9980145329807433,-.9983081582712682,-.9985783189429907,-.9988250086459504,-.9990482215818578,-.99924795250423,-.9994241967185149,-.9995769500822006,-.9997062090049132,-.9998119704485015,-.9998942319271076,-.9999529915072262,-.9999882478077495,-1,-.9999882478077495,-.9999529915072262,-.9998942319271076,-.9998119704485015,-.9997062090049132,-.9995769500822006,-.9994241967185149,-.99924795250423,-.9990482215818578,-.9988250086459504,-.9985783189429907,-.9983081582712682,-.9980145329807433,-.9976974499728977,-.9973569167005724,-.996992941167792,-.9966055319295779,-.9961946980917455,-.9957604493106914,-.9953027957931658,-.9948217482960331,-.9943173181260185,-.9937895171394426,-.993238357741943,-.9926638528881819,-.9920660160815424,-.9914448613738105,-.9908004033648453,-.9901326572022358,-.9894416385809446,-.9887273637429387,-.987989849476809,-.9872291131173742,-.986445172545274,-.9856380461865493,-.9848077530122081,-.9839543125377807,-.9830777448228601,-.9821780704706308,-.9812553106273846,-.9803094869820241,-.9793406217655515,-.9783487377505476,-.9773338582506355,-.9762960071199335,-.9752352087524931,-.9741514880817276,-.9730448705798239,-.9719153822571454,-.9707630496616201,-.969587899878116,-.968389960527806,-.9671692597675167,-.9659258262890684,-.9646596893185995,-.9633708786158806,-.9620594244736133,-.9607253577167206,-.9593687097016202,-.9579895123154889,-.9565877979755121,-.955163599628123,-.9537169507482268,-.9522478853384154,-.9507564379281668,-.949242643573034,-.9477065378538223,-.9461481568757506,-.944567537267605,-.9429647161808762,-.9413397312888874,-.9396926207859083,-.9380234233862579,-.936332178323393,-.9346189253489885,-.9328837047320004,-.9311265572577221,-.9293475242268224,-.9275466474543788,-.9257239692688904,-.9238795325112866,-.9220133805339186,-.9201255571995389,-.9182161068802742,-.9162850744565779,-.9143325053161796,-.9123584453530141,-.9103629409661469,-.9083460390586794,-.9063077870366503,-.9042482328079181,-.9021674247810376,-.9000654118641209,-.8979422434636882,-.895797969483505,-.8936326403234123,-.8914463068781384,-.8892390205361063,-.887010833178222,-.8847617971766579,-.8824919653936216,-.8802013911801113,-.8778901283746645,-.8755582313020907,-.8732057547721959,-.870832754078492,-.8684392849969007,-.8660254037844386,-.8635911671778989,-.8611366323925137,-.8586618571206134,-.8561668995302666,-.8536518182639167,-.8511166724369998,-.848561521636559,-.8459864259198413,-.8433914458128857,-.8407766423091034,-.8381420768678404,-.8354878114129367,-.8328139083312672,-.8301204304712791,-.8274074411415107,-.8246750041091067,-.8219231835983183,-.8191520442889918,-.8163616513150517,-.8135520702629676,-.8107233671702121,-.8078756085237113,-.8050088612582788,-.802123192755044,-.7992186708398701,-.796295363781756,-.7933533402912352,-.7903926695187591,-.7874134210530724,-.7844156649195756,-.7813994715786825,-.7783649119241599,-.7753120572814661,-.7722409794060691,-.7691517504817653,-.7660444431189781,-.7629191303530556,-.7597758856425495,-.7566147828674927,-.753435896327661,-.7502393007408246,-.7470250712409963,-.7437932833766612,-.740544013109005,-.7372773368101242,-.7339933312612357,-.7306920736508676,-.7273736415730492,-.7240381130254828,-.7206855664077145,-.7173160805192891,-.7139297345578991,-.7105266081175208,-.7071067811865477,-.7036703341459063,-.7002173477671687,-.6967479032106556,-.6932620820235246,-.6897599661378577,-.6862416378687334,-.6827071799122926,-.679156675343793,-.6755902076156605,-.6720078605555223,-.6684097183642427,-.6647958656139378,-.6611663872459935,-.6575213685690637,-.6538608952570701,-.6501850533471836,-.6464939292378064,-.6427876096865396,-.6390661818081416,-.6353297330724854,-.6315783513024976,-.627812124672099,-.624031141704127,-.6202354912682606,-.6164252625789255,-.6126005451932034,-.6087614290087209,-.6049080042615417,-.6010403615240425,-.5971585917027863,-.5932627860363818,-.589353036093345,-.585429433769941,-.5814920712880269,-.5775410411928856,-.5735764363510465,-.5695983499481065,-.5656068754865391,-.561602106783493,-.5575841379685926,-.5535530634817225,-.5495089780708059,-.5454519767895828,-.5413821549953696,-.5372996083468242,-.5332044328016913,-.5290967246145529,-.5249765803345603,-.5208440968031696,-.5166993711518632,-.5125425007998651,-.5083735834518559,-.5041927170956704,-.5000000000000004,-.49579553071207927,-.49157940805537115,-.48735173112724256,-.48311259929663913,-.4788621122017438,-.47460036974764036,-.4703274721039621,-.4660435197025389,-.46174861323503363,-.45744285365058096,-.4531263421534088,-.44879918020046244,-.4444614694990217,-.4401133120043052,-.43575480991708015,-.4313860656812539,-.42700718198147153,-.4226182617406992,-.4182194081178066,-.413810724505139,-.40939231452609287,-.40496428203267354,-.400526731103061,-.3960797660391569,-.39162349136413954,-.38715801182000076,-.3826834323650904,-.37819985817164276,-.3737073946233104,-.3692061473126848,-.36469622203881186,-.3601777248047109,-.3556507618148766,-.3511154394727894,-.34657186437840776,-.34202014332566943,-.3374603832999744,-.3328926914756765,-.32831717521356063,-.32373394205832107,-.31914309973603056,-.3145447561516138,-.3099390193863049,-.30532599769511337,-.30070579950427384,-.2960785334087003,-.29144430816943584,-.2868032327110907,-.28215541611928785,-.2775009676380955,-.2728399966674612,-.2681726127606372,-.2634989256216111,-.2588190451025207,-.2541330812010789,-.24944114405798135,-.24474334395432432,-.24003979130900607,-.23533059667613823,-.23061587074244044,-.2258957243246447,-.22117026836688813,-.21643961393810288,-.21170387222941123,-.2069631545515055,-.20221757233203852,-.19746723711299774,-.19271226054809037,-.1879527544001122,-.18318883053832655,-.17842060093583256,-.1736481776669304,-.16887167290449245,-.16409119891732413,-.15930686806752234,-.15451879280784075,-.14972708567904036,-.1449318593072471,-.14013322640130713,-.13533129975013158,-.13052619222005168,-.1257180167521624,-.12090688635966958,-.11609291412523004,-.11127621319829996,-.10645689679246818,-.10163507818280229,-.09681087070317913,-.09198438774362797,-.08715574274765832,-.08232504920960054,-.0774924206719312,-.07265797072261047,-.06782181299240972,-.06298406115223794,-.0581448289104763,-.05330423001029832,-.04846237822700354,-.043619387365336194,-.038775371256817404,-.03393044375706254,-.02908471874311221,-.02423831011074855,-.019391331771824397,-.014543897651582293,-.009696121685978531,-.004848117819001606];r=__webpack_require__(949);class Zi extends r.Quaternion{setFromEuler(e,t){if(!e||!e.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var i=e.x,s=e.y,r=e.z,a=e.order,n=Qi.cos(i/2),o=Qi.cos(s/2),e=Qi.cos(r/2),i=Qi.sin(i/2),s=Qi.sin(s/2),r=Qi.sin(r/2);return"XYZ"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e-i*s*r):"YXZ"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e+i*s*r):"ZXY"===a?(this._x=i*o*e-n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e-i*s*r):"ZYX"===a?(this._x=i*o*e-n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e+i*s*r):"YZX"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e-i*s*r):"XZY"===a&&(this._x=i*o*e-n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e+i*s*r),!1!==t&&this.onChangeCallback(),this}setFromAxisAngle(e,t){var i=t/2,t=Qi.sin(i);return this._x=e.x*t,this._y=e.y*t,this._z=e.z*t,this._w=Qi.cos(i),this.onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,i=t[0],s=t[4],r=t[8],a=t[1],n=t[5],o=t[9],h=t[2],l=t[6],c=t[10],u=i+n+c,d;return 0<u?(d=.5/Qi.sqrt(u+1),this._w=.25/d,this._x=(l-o)*d,this._y=(r-h)*d,this._z=(a-s)*d):n<i&&c<i?(d=2*Qi.sqrt(1+i-n-c),this._w=(l-o)/d,this._x=.25*d,this._y=(s+a)/d,this._z=(r+h)/d):c<n?(d=2*Qi.sqrt(1+n-i-c),this._w=(r-h)/d,this._x=(s+a)/d,this._y=.25*d,this._z=(o+l)/d):(d=2*Qi.sqrt(1+c-i-n),this._w=(a-s)/d,this._x=(r+h)/d,this._y=(o+l)/d,this._z=.25*d),this.onChangeCallback(),this}length(){return Qi.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);var i=this._x,s=this._y,r=this._z,a=this._w;let n=a*e._w+i*e._x+s*e._y+r*e._z;if(n<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,n=-n):this.copy(e),1<=n)return this._w=a,this._x=i,this._y=s,this._z=r,this;var o=1-n*n;if(o<=Number.EPSILON){var h=1-t;return this._w=h*a+t*this._w,this._x=h*i+t*this._x,this._y=h*s+t*this._y,this._z=h*r+t*this._z,this.normalize()}e=Qi.sqrt(o),h=Qi.atan2(e,n),o=Qi.sin((1-t)*h)/e,e=Qi.sin(t*h)/e;return this._w=a*o+this._w*e,this._x=i*o+this._x*e,this._y=s*o+this._y*e,this._z=r*o+this._z*e,this.onChangeCallback(),this}}var Yi,Ki,Ji,es,ts,r=__webpack_require__(949);class is extends r.Vector3{applyEuler(e){return e&&e.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(ss.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ss.setFromAxisAngle(e,t))}length(){return Qi.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}projectOnPlane(e){return rs.copy(this).projectOnVector(e),this.sub(rs)}reflect(e){return this.sub(rs.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){e=this.dot(e)/Qi.sqrt(this.lengthSq()*e.lengthSq());return Qi.acos(U(e,-1,1))}distanceTo(e){return Qi.sqrt(this.distanceToSquared(e))}setFromSpherical(e){var t=Qi.sin(e.phi)*e.radius;return this.x=t*Qi.sin(e.theta),this.y=Qi.cos(e.phi)*e.radius,this.z=t*Qi.cos(e.theta),this}setFromCylindrical(e){return this.x=e.radius*Qi.sin(e.theta),this.y=e.y,this.z=e.radius*Qi.cos(e.theta),this}}const ss=new Zi,rs=new is;(r=Yi=Yi||{})[r.Combat=0]="Combat",r[r.Tech=1]="Tech",r[r.Resource=2]="Resource",r[r.Power=3]="Power",(r=Ki=Ki||{})[r.None=0]="None",r[r.BuildingType=1]="BuildingType",r[r.InfantryType=2]="InfantryType",r[r.UnitType=3]="UnitType",r[r.NavalUnitType=4]="NavalUnitType",r[r.AircraftType=5]="AircraftType";class as extends Oi{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",Yi,Yi.Combat),this.adjacent=this.ini.getNumber("Adjacent",1),this.baseNormal=this.ini.getBool("BaseNormal",!0),this.buildLimit=this.ini.getNumber("BuildLimit",Number.POSITIVE_INFINITY),this.airRangeBonus=this.ini.getNumber("AirRangeBonus"),this.guardRange=this.ini.getNumber("GuardRange"),this.defaultToGuardArea=this.ini.getBool("DefaultToGuardArea"),this.eligibileForAllyBuilding=this.ini.getBool("EligibileForAllyBuilding"),this.numberImpassableRows=this.ini.getNumber("NumberImpassableRows"),this.bridgeRepairHut=this.ini.getBool("BridgeRepairHut"),this.constructionYard=this.ini.getBool("ConstructionYard"),this.refinery=this.ini.getBool("Refinery"),this.unitRepair=this.ini.getBool("UnitRepair"),this.unitReload=this.ini.getBool("UnitReload"),this.isBaseDefense=this.ini.getBool("IsBaseDefense"),this.superWeapon=this.parseWeaponName(this.ini.getString("SuperWeapon")),this.chargedAnimTime=this.ini.getNumber("ChargedAnimTime");var t=this.ini.getBool("Naval");this.naval=t,this.underwater=this.ini.getBool("Underwater"),this.waterBound=this.ini.getBool("WaterBound"),this.orePurifier=this.ini.getBool("OrePurifier"),this.cloning=this.ini.getBool("Cloning"),this.nukeSilo=this.ini.getBool("NukeSilo"),this.repairable=this.ini.getBool("Repairable",this.type===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",Ki,Ki.None),this.factory===Ki.UnitType&&t&&(this.factory=Ki.NavalUnitType),this.weaponsFactory=this.ini.getBool("WeaponsFactory"),this.helipad=this.ini.getBool("Helipad"),this.hospital=this.ini.getBool("Hospital"),this.landTargeting=this.ini.getEnumNumeric("LandTargeting",ri,ri.LandOk),this.navalTargeting=this.ini.getEnumNumeric("NavalTargeting",ai,ai.UnderwaterNever),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"),this.primary=this.parseWeaponName(this.ini.getString("Primary")),this.secondary=this.parseWeaponName(this.ini.getString("Secondary")),this.elitePrimary=this.parseWeaponName(this.ini.getString("ElitePrimary")),this.eliteSecondary=this.parseWeaponName(this.ini.getString("EliteSecondary")),this.weaponCount=this.ini.getNumber("WeaponCount"),this.deathWeapon=this.parseWeaponName(this.ini.getString("DeathWeapon")),this.deathWeaponDamageModifier=this.ini.getNumber("DeathWeaponDamageModifier",1),this.occupyWeapon=this.parseWeaponName(this.ini.getString("OccupyWeapon")),this.eliteOccupyWeapon=this.parseWeaponName(this.ini.getString("EliteOccupyWeapon")),this.veteranAbilities=new Set(this.ini.getEnumArray("VeteranAbilities",oi)),this.eliteAbilities=new Set([...this.veteranAbilities,...this.ini.getEnumArray("EliteAbilities",oi)]),this.selfHealing=this.ini.getBool("SelfHealing"),this.wall=this.ini.getBool("Wall"),this.gate=this.ini.getBool("Gate"),this.armor=this.ini.getEnum("Armor",si,si.None,!0),this.strength=Math.floor(this.ini.getNumber("Strength")),this.immune=this.ini.getBool("Immune"),this.immuneToRadiation=this.ini.getBool("ImmuneToRadiation"),this.immuneToPsionics=this.ini.getBool("ImmuneToPsionics"),this.typeImmune=this.ini.getBool("TypeImmune"),this.warpable=this.ini.getBool("Warpable",!0),this.isTilter=this.ini.getBool("IsTilter",!0),this.walkRate=this.ini.getNumber("WalkRate",1),this.idleRate=this.ini.getNumber("IdleRate",0),this.noSpawnAlt=this.ini.getBool("NoSpawnAlt"),this.crusher=this.ini.getBool("Crusher"),this.consideredAircraft=this.ini.getBool("ConsideredAircraft"),this.crashable=this.ini.getBool("Crashable");var i=this.ini.getBool("Landable");this.landable=i,this.airportBound=this.ini.getBool("AirportBound"),this.balloonHover=this.ini.getBool("BalloonHover"),this.hoverAttack=this.ini.getBool("HoverAttack"),this.omniFire=this.ini.getBool("OmniFire"),this.fighter=this.ini.getBool("Fighter"),this.flightLevel=this.ini.getNumber("FlightLevel")||void 0;var s=this.ini.getString("Locomotor"),e=this.type===Ct.Building?ti.Statue:ti.Chrono;if(s?(t=qi.get(s))?this.locomotor=t:(console.warn(`Object rules "${this.name}" has invalid Locomotor "${s}"`),this.locomotor=e):this.locomotor=e,this.locomotor!==ti.Statue){let e=Xi.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,!0)}this.speed=Oi.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",ni.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",hi,hi.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(as.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&&!i)&&this.ini.getBool("Selectable",!0),this.isSelectableCombatant=this.ini.getBool("IsSelectableCombatant"),this.invisibleInGame=this.ini.getBool("InvisibleInGame"),this.moveToShroud=this.ini.getBool("MoveToShroud",this.type!==Ct.Aircraft),this.leadershipRating=this.ini.getNumber("LeadershipRating",5),this.allowedToStartInMultiplayer=this.ini.getBool("AllowedToStartInMultiplayer",!0),this.rot=Oi.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=Oi.iniRotToDegsPerTick(this.ini.getNumber("JumpJetTurnRate",4)),this.jumpjetWobbles=this.ini.getNumber("JumpjetWobbles",.15),this.pitchSpeed=this.ini.getNumber("PitchSpeed",.25),this.pitchAngle=1<=this.pitchSpeed?0:20,this.damageParticleSystems=this.ini.getArray("DamageParticleSystems");i=this.ini.getNumberArray("DamageSmokeOffset",void 0,[0,0,0]);this.damageSmokeOffset=new is(i[0],i[2]/Math.SQRT2,i[1]),this.minDebris=this.ini.getNumber("MinDebris"),this.maxDebris=this.ini.getNumber("MaxDebris"),this.debrisTypes=this.ini.getArray("DebrisTypes"),this.debrisAnims=this.ini.getArray("DebrisAnims"),this.isLightpost="GALITE"===this.imageName,this.lightVisibility=this.ini.getNumber("LightVisibility",5e3),this.lightIntensity=this.ini.getNumber("LightIntensity"),this.lightRedTint=this.ini.getNumber("LightRedTint",1),this.lightGreenTint=this.ini.getNumber("LightGreenTint",1),this.lightBlueTint=this.ini.getNumber("LightBlueTint",1),this.ambientSound=this.ini.getString("AmbientSound")||void 0,this.createSound=this.ini.getString("CreateSound")||void 0,this.deploySound=this.ini.getString("DeploySound")||void 0,this.undeploySound=this.ini.getString("UndeploySound")||void 0,this.voiceSelect=this.ini.getString("VoiceSelect")||void 0,this.voiceMove=this.ini.getString("VoiceMove")||void 0,this.voiceAttack=this.ini.getString("VoiceAttack")||void 0,this.voiceFeedback=this.ini.getString("VoiceFeedback")||void 0,this.voiceSpecialAttack=this.ini.getString("VoiceSpecialAttack")||void 0,this.voiceEnter=this.ini.getString("VoiceEnter")||void 0,this.voiceCapture=this.ini.getString("VoiceCapture")||void 0,this.voiceCrashing=this.ini.getString("VoiceCrashing")||void 0,this.crashingSound=this.ini.getString("CrashingSound")||void 0,this.impactLandSound=this.ini.getString("ImpactLandSound")||void 0,this.auxSound1=this.ini.getString("AuxSound1")||void 0,this.auxSound2=this.ini.getString("AuxSound2")||void 0,this.dieSound=this.ini.getString("DieSound")||void 0,this.moveSound=this.ini.getString("MoveSound")||void 0,this.enterWaterSound=this.ini.getString("EnterWaterSound")||void 0,this.leaveWaterSound=this.ini.getString("LeaveWaterSound")||void 0,this.turretRotateSound=this.ini.getString("TurretRotateSound")||void 0,this.workingSound=this.ini.getString("WorkingSound")||void 0,this.notWorkingSound=this.ini.getString("NotWorkingSound")||void 0,this.chronoInSound=this.ini.getString("ChronoInSound")||void 0,this.chronoOutSound=this.ini.getString("ChronoOutSound")||void 0,this.enterTransportSound=this.ini.getString("EnterTransportSound")||void 0,this.leaveTransportSound=this.ini.getString("LeaveTransportSound")||void 0}parseWeaponName(e){return e&&"none"!==e.toLowerCase()?e:void 0}parseTurretIndexes(){let i=new Map;return this.ini.getBool("Gunner")&&this.ini.entries.forEach((e,t)=>{t=t.match(/^(.*)TurretWeapon$/i);t&&(t=t[1]+"TurretIndex",this.ini.has(t)&&i.set(Number(e),this.ini.getNumber(t)))}),i}parseBurstDelay(){let t=[];for(let e=0;e<4;++e)t.push(this.ini.has(`BurstDelay${e}`)?this.ini.getNumber(`BurstDelay${e}`):void 0);return t}hasOwner(e){return!!this.owner.length&&-1!==this.owner.indexOf(e.name)}isAvailableTo(e){return(!this.requiredHouses.length||-1!==this.requiredHouses.indexOf(e.name))&&-1===this.forbiddenHouses.indexOf(e.name)}get proneWhenAttacked(){return!this.fearless&&this.isHuman}getWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`Weapon${e+1}`))}getEliteWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`EliteWeapon${e+1}`))}}as.MAX_SIGHT=11,as.MAGIC_SPEED_MULT=.65;class ns extends Oi{parse(){super.parse(),this.armor=this.ini.getEnum("Armor",si,si.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)}}(r=Ji=Ji||{})[r.All=7]="All",r[r.Right=1]="Right",r[r.Left=2]="Left",r[r.Bottom=4]="Bottom";class os extends Oi{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",Ji.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",Ji.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===Ji.All)return e;let s=[];for(t of e)!function(e,t){switch(e){case 0:case 1:return 1;case 2:return 0!=(t&Ji.Right);case 3:return 0!=(t&Ji.Left);case 4:return 0!=(t&Ji.Bottom);default:throw new Error(`Invalid subCell "${e}`)}}(t,i)||s.push(t);return s}}class hs extends Oi{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 ls extends Oi{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 cs{create(e,t,i){switch(e){case Ct.Aircraft:case Ct.Building:case Ct.Infantry:case Ct.Vehicle:return new as(e,t,i);case Ct.Overlay:return new ns(e,t,i);case Ct.Terrain:return new os(e,t,i);case Ct.Smudge:return new hs(e,t,i);case Ct.VoxelAnim:return new ls(e,t,i);default:return new Oi(e,t,i)}}}class us{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 ds{readIni(e){return this.value=e.getNumber("Value"),this}}class ps{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 gs{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 ms{readIni(e){this.radDurationMultiple=e.getNumber("RadDurationMultiple"),this.radApplicationDelay=e.getNumber("RadApplicationDelay"),this.radLevelMax=e.getNumber("RadLevelMax"),this.radLevelDelay=e.getNumber("RadLevelDelay"),this.radLightDelay=e.getNumber("RadLightDelay"),this.radLevelFactor=e.getNumber("RadLevelFactor"),this.radLightFactor=e.getNumber("RadLightFactor"),this.radTintFactor=e.getNumber("RadTintFactor"),this.radColor=e.getNumberArray("RadColor"),this.radSiteWarhead=e.getString("RadSiteWarhead")}}(r=es=es||{})[r.MultiMissile=0]="MultiMissile",r[r.IronCurtain=1]="IronCurtain",r[r.LightningStorm=2]="LightningStorm",r[r.ChronoSphere=3]="ChronoSphere",r[r.ChronoWarp=4]="ChronoWarp",r[r.ParaDrop=5]="ParaDrop",r[r.AmerParaDrop=6]="AmerParaDrop";class fs{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",es,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",es,void 0),this.uiName=e.getString("UIName"),this.weaponType=e.getString("WeaponType")||void 0,this}}class ys{readIni(e){this.crateMaximum=e.getNumber("CrateMaximum"),this.crateMinimum=e.getNumber("CrateMinimum"),this.crateRadius=e.getNumber("CrateRadius"),this.crateRegen=e.getNumber("CrateRegen");let t=e.getString("UnitCrateType");return this.unitCrateType="none"!==t.toLowerCase()?t:void 0,this.healCrateSound=e.getString("HealCrateSound"),this.crateImg=e.getString("CrateImg"),this.waterCrateImg=e.getString("WaterCrateImg"),this.freeMCV=e.getBool("FreeMCV"),this}}(r=ts=ts||{})[r.Cheer=0]="Cheer",r[r.UnitDeployUndeploy=1]="UnitDeployUndeploy",r[r.WeaponFire=2]="WeaponFire",r[r.ObjectDestroy=3]="ObjectDestroy",r[r.ObjectSpawn=4]="ObjectSpawn",r[r.ObjectUnspawn=5]="ObjectUnspawn",r[r.ObjectMorph=6]="ObjectMorph",r[r.ObjectLiftOff=7]="ObjectLiftOff",r[r.ObjectLand=8]="ObjectLand",r[r.ObjectCrashing=9]="ObjectCrashing",r[r.ObjectDisguiseChange=10]="ObjectDisguiseChange",r[r.ObjectCloakChange=11]="ObjectCloakChange",r[r.ObjectAttacked=12]="ObjectAttacked",r[r.ShipSubmergeChange=13]="ShipSubmergeChange",r[r.BridgeRepair=14]="BridgeRepair",r[r.BuildStatusChange=15]="BuildStatusChange",r[r.BuildingPlace=16]="BuildingPlace",r[r.BuildingFailedPlace=17]="BuildingFailedPlace",r[r.BuildingSell=18]="BuildingSell",r[r.BuildingRepairFull=19]="BuildingRepairFull",r[r.BuildingCapture=20]="BuildingCapture",r[r.BuildingInfiltration=21]="BuildingInfiltration",r[r.BuildingGarrison=22]="BuildingGarrison",r[r.BuildingEvacuate=23]="BuildingEvacuate",r[r.BuildingRepairStart=24]="BuildingRepairStart",r[r.UnitRepairStart=25]="UnitRepairStart",r[r.UnitRepairFinish=26]="UnitRepairFinish",r[r.UnitRecycle=27]="UnitRecycle",r[r.InflictDamage=28]="InflictDamage",r[r.HealthChange=29]="HealthChange",r[r.WarheadDetonate=30]="WarheadDetonate",r[r.PlayerDefeated=31]="PlayerDefeated",r[r.PlayerResigned=32]="PlayerResigned",r[r.PlayerDropped=33]="PlayerDropped",r[r.DeployNotAllowed=34]="DeployNotAllowed",r[r.PowerChange=35]="PowerChange",r[r.PowerLow=36]="PowerLow",r[r.PowerRestore=37]="PowerRestore",r[r.RadarOnOff=38]="RadarOnOff",r[r.ObjectOwnerChange=39]="ObjectOwnerChange",r[r.RadarEvent=40]="RadarEvent",r[r.InsufficientFunds=41]="InsufficientFunds",r[r.RallyPointChange=42]="RallyPointChange",r[r.PrimaryFactoryChange=43]="PrimaryFactoryChange",r[r.FactoryProduceUnit=44]="FactoryProduceUnit",r[r.ObjectTeleport=45]="ObjectTeleport",r[r.AllianceChange=46]="AllianceChange",r[r.UnitPromote=47]="UnitPromote",r[r.EnterTransport=48]="EnterTransport",r[r.LeaveTransport=49]="LeaveTransport",r[r.EnterObject=50]="EnterObject",r[r.EnterTile=51]="EnterTile",r[r.SuperWeaponReady=52]="SuperWeaponReady",r[r.SuperWeaponActivate=53]="SuperWeaponActivate",r[r.LightningStormManifest=54]="LightningStormManifest",r[r.LightningStormCloud=55]="LightningStormCloud",r[r.CratePickup=56]="CratePickup",r[r.PingLocation=57]="PingLocation",r[r.StalemateDetect=58]="StalemateDetect",r[r.TriggerSoundFx=59]="TriggerSoundFx",r[r.TriggerStopSoundFx=60]="TriggerStopSoundFx",r[r.TriggerEva=61]="TriggerEva",r[r.TriggerAnim=62]="TriggerAnim",r[r.TriggerText=63]="TriggerText",r[r.TimerExpire=64]="TimerExpire";class ws{constructor(e,t,i,s){this.target=e,this.player=t,this.source=i,this.tile=s,this.type=ts.CratePickup}}var Ts,bs,r=__webpack_require__(949);class vs extends r.Vector2{length(){return Qi.sqrt(this.x*this.x+this.y*this.y)}angle(){let e=Qi.atan2(this.y,this.x);return e<0&&(e+=2*Math.PI),e}distanceTo(e){return Qi.sqrt(this.distanceToSquared(e))}rotateAround(e,t){var i=Qi.cos(t),s=Qi.sin(t),r=this.x-e.x,t=this.y-e.y;return this.x=r*i-t*s+e.x,this.y=r*s+t*i+e.y,this}}class Ss{static tileToWorld(e,t){return{x:e*Ss.LEPTONS_PER_TILE,y:t*Ss.LEPTONS_PER_TILE}}static vecWorldToGround(e){return new vs(e.x,e.z)}static vecGroundToWorld(e){return new is(e.x,0,e.y)}static tileHeightToWorld(e){return e*(Ss.LEPTONS_PER_TILE/2)*Ss.zScale}static worldToTileHeight(e){return e/(Ss.LEPTONS_PER_TILE/2*Ss.zScale)}static tile3dToWorld(e,t,i){t=Ss.tileToWorld(e,t),i=Ss.tileHeightToWorld(i);return new is(t.x,i,t.y)}static screenDistanceToWorld(e,t){return{x:Math.floor((e+2*t)/2*Ss.ISO_WORLD_SCALE),y:Math.floor((2*t-e)/2*Ss.ISO_WORLD_SCALE)}}static getWorldTileSize(){return Ss.LEPTONS_PER_TILE}}function _s(e){return[Yt.Water,Yt.Beach].includes(e)?Ts.Water:Ts.Ground}Ss.ISO_TILE_SIZE=30,Ss.LEPTONS_PER_TILE=256,Ss.ISO_WORLD_SCALE=Ss.LEPTONS_PER_TILE/Ss.ISO_TILE_SIZE,Ss.ISO_CAMERA_ALPHA=Math.PI/6,Ss.ISO_CAMERA_BETA=Math.PI/4,Ss.COS_ISO_CAMERA_BETA=Qi.cos(Ss.ISO_CAMERA_BETA),Ss.zScale=Ss.COS_ISO_CAMERA_BETA/Qi.cos(Ss.ISO_CAMERA_ALPHA),(r=Ts=Ts||{})[r.Ground=0]="Ground",r[r.Air=1]="Air",r[r.Water=2]="Water";const ks=e=>void 0!==e.position,Os=e=>void 0!==e.addScalar;class Is{constructor(e){this.tileOccupation=e}isInWeaponRange(e,t,i,s,r){var a=r??e;if(i.rules.limboLaunch&&2<Math.abs((ks(a)?a.position.tileElevation+a.tile.z:a.z)-(ks(t)?t.position.tileElevation+t.tile.z:t.z)))return!1;var{minRange:r,range:s}=this.computeWeaponRangeVsTarget(a,t,i,s);return i.rules.cellRangefinding?this.isInTileRange(a,t,r,s):e.isUnit()&&e.rules.movementZone===ii.Fly?this.isInRange2(a,t,r,s):this.isInRange3(a,t,r,s)}computeWeaponRangeVsTarget(e,t,i,s){let r=0;var a,n;return!ks(t)||!t.isBuilding()||i.projectileRules.arcing||i.projectileRules.vertical||i.warhead.rules.ivanBomb||1<(n=t.getFoundation()).width&&1<n.height&&(r+=Math.ceil(Math.min(n.width,n.height)/2)),!i.projectileRules.subjectToElevation||i.projectileRules.arcing&&!ks(t)||(a=ks(e)?e.tile.z+e.tileElevation:e.z,(n=ks(t)?t.tile.z+t.tileElevation:t.z)<a&&(r+=s.elevationModel.getBonus(a,n))),i.projectileRules.isAntiAir&&ks(e)&&e.isTechno()&&ks(t)&&t.isUnit()&&t.zone===Ts.Air&&(r+=e.rules.airRangeBonus),{minRange:i.minRange,range:i.range+r}}isInRange(e,t,i,s,r=!1){return r?this.isInTileRange(e,t,i,s):e.isUnit()&&e.rules.movementZone===ii.Fly?this.isInRange2(e,t,i,s):this.isInRange3(e,t,i,s)}isInRange3(e,t,i,s){return W(this.distance3(e,t)/Ss.LEPTONS_PER_TILE,i,s)}isInRange2(e,t,i,s){return W(this.distance2(e,t)/Ss.LEPTONS_PER_TILE,i,s)}distance3(e,t){let i=ks(e)?e.position.worldPosition:Os(e)?e:Ss.tile3dToWorld(e.rx+.5,e.ry+.5,e.z);t=ks(t)?t.position.worldPosition:Os(t)?t:Ss.tile3dToWorld(t.rx+.5,t.ry+.5,t.z);return i.distanceTo(t)}distance2(e,t){let i=ks(e)?new vs(e.position.worldPosition.x,e.position.worldPosition.z):Os(e)?new vs(e.x,e.z):new vs(e.rx+.5,e.ry+.5).multiplyScalar(Ss.LEPTONS_PER_TILE);t=ks(t)?new vs(t.position.worldPosition.x,t.position.worldPosition.z):Os(t)?new vs(t.x,t.z):new vs(t.rx+.5,t.ry+.5).multiplyScalar(Ss.LEPTONS_PER_TILE);return i.distanceTo(t)}isInTileRange(e,t,i,s){return W(this.tileDistance(e,t),i,s)}tileDistance(e,t){var i,e=ks(e)?this.tileOccupation.calculateTilesForGameObject(e.tile,e):Array.isArray(e)?e:[e],s=ks(t)?this.tileOccupation.calculateTilesForGameObject(t.tile,t):Array.isArray(t)?t:[t];let r=new vs,a=new vs,n=Number.POSITIVE_INFINITY;for(i of e)for(var o of s){r.set(i.rx,i.ry),a.set(o.rx,o.ry);o=r.distanceTo(a);o<=n&&(n=o)}return n}}const As=e=>"name"in e;(r=bs=bs||{})[r.Brutal=0]="Brutal",r[r.Medium=1]="Medium",r[r.Easy=2]="Easy";var Cs,Bs,xs,Es,Ps,Ns,Rs,Ds,Ms;(new Map).set(bs.Easy,"GUI:AIDummy");class Ls{static computeGameSpeed(e){let t;return t=6===e?60:5===e?45:60/(6-e),t/Ls.BASE_TICKS_PER_SECOND}}Ls.BASE_TICKS_PER_SECOND=15;class Fs{constructor(e,t,i,s,r,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=s,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=r,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var s=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var r=this.startTile.rx-this.distance,a=this.startTile.ry-this.distance,n=this.startTile.rx+this.foundation.width-1+this.distance,o=this.startTile.ry+this.foundation.height-1+this.distance;let e,t,i;if(0<this.distance){for(e=n;e>=r;e--)i=s(e,o),i&&(yield i);for(t=o-1;t>=a;t--)i=s(n,t),i&&(yield i);for(e=r;e<n;e++)i=s(e,a),i&&(yield i);for(t=1+a;t<o;t++)i=s(r,t),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}(r=Cs=Cs||{})[r.Armor=0]="Armor",r[r.Firepower=1]="Firepower",r[r.HealBase=2]="HealBase",r[r.Money=3]="Money",r[r.Reveal=4]="Reveal",r[r.Speed=5]="Speed",r[r.Veteran=6]="Veteran",r[r.Unit=7]="Unit",r[r.Invulnerability=8]="Invulnerability",r[r.IonStorm=9]="IonStorm",r[r.Gas=10]="Gas",r[r.Tiberium=11]="Tiberium",r[r.Pod=12]="Pod",r[r.Cloak=13]="Cloak",r[r.Darkness=14]="Darkness",r[r.Explosion=15]="Explosion",r[r.ICBM=16]="ICBM",r[r.Napalm=17]="Napalm",r[r.Squad=18]="Squad",(Bs=Bs||{}).onTick=Symbol(),(xs=xs||{}).onChange=Symbol();class js{constructor(e){this.target=e,this.type=ts.SuperWeaponReady}}(r=Es=Es||{})[r.Charging=0]="Charging",r[r.Paused=1]="Paused",r[r.Ready=2]="Ready";class Us{constructor(e,t,i,s=!1){this.name=e,this.rules=t,this.owner=i,this.oneTimeOnly=s,this.status=Es.Charging,this.isGift=!1,this.rechargeTicks=60*t.rechargeTime*Ls.BASE_TICKS_PER_SECOND,this.chargeTicks=this.rechargeTicks,s&&(this.status=Es.Ready,this.chargeTicks=0)}update(e){0<this.chargeTicks&&this.status!==Es.Paused&&(this.chargeTicks--,0===this.chargeTicks&&(this.status=Es.Ready,e.events.dispatch(new js(this))))}pauseTimer(){this.status=Es.Paused}resumeTimer(){this.status=0<this.chargeTicks?Es.Charging:Es.Ready}resetTimer(){this.chargeTicks=this.rechargeTicks,this.status===Es.Ready&&(this.status=Es.Charging)}getTimerSeconds(){return this.chargeTicks/Ls.BASE_TICKS_PER_SECOND}getChargeProgress(){return(this.rechargeTicks-this.chargeTicks)/this.rechargeTicks}}(r=Ps=Ps||{})[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Finished=2]="Finished";class Ws{constructor(e,t,i){this.type=e,this.owner=t,this.tile=i,this.status=Ps.NotStarted}onStart(e){}onTick(e){return!0}}(r=Ns=Ns||{}).onPowerLow=Symbol(),r.onPowerRestore=Symbol(),r.onPowerChange=Symbol(),(Rs=Rs||{}).onActivate=Symbol();class zs{constructor(e,t,i,s,r){this.target=e,this.owner=t,this.atTile=i,this.atTile2=s,this.noSfxWarning=r,this.type=ts.SuperWeaponActivate}}(r=Ds=Ds||{})[r.None=0]="None",r[r.Guard=1]="Guard",r[r.Prone=2]="Prone",r[r.Deployed=3]="Deployed",r[r.Paradrop=4]="Paradrop",r[r.Cheer=5]="Cheer",(r=Ms=Ms||{})[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Finished=2]="Finished",r[r.Cancelling=3]="Cancelling",r[r.Cancelled=4]="Cancelled";class Vs{constructor(){this.status=Ms.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===Ms.Running}isCancelling(){return this.status===Ms.Cancelling}setCancellable(e){return this.cancellable=e,this}onStart(e){}onEnd(e){}cancel(){if(this.cancellable)if(this.status===Ms.Running)this.status=Ms.Cancelling,this.children.length&&this.children.forEach(e=>e.cancel());else if(this.status===Ms.NotStarted&&(this.status=Ms.Cancelled,this.children.length))throw new Error("Should't have any children before starting a task")}getTargetLinesConfig(e){}}function Hs(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return e;return-1}class Gs extends Vs{constructor(e){super(),this.ticks=e}onTick(){return!!this.isCancelling()||!(0<this.ticks--)}}class $s{constructor(e){this.map=e}findPositions(e,s,r){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(s.rx+t.tile.rx-o.rx,s.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,r,s))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 Fs(this.map.tiles,this.map.mapBounds,s,{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,r,s)))){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,s)),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,s){return i?.isHighBridge()||t?.isHighBridge()?e.z+(t?.tileElevation??0)===s.z+(i?.tileElevation??0):!(!i&&!t)||Math.abs(e.z-s.z)<2}clusterObjects(e){let r=new Map;e.forEach(e=>{var t=e.tile.rx+"_"+e.tile.ry;r.set(t,[...r.get(t)||[],e])});let t=[],a=new Set(e);for(;a.size;){let e=new Set,s=[];var i=[...a][0].tile;for(r.get(i.rx+"_"+i.ry).forEach(e=>{s.push(e)});s.length;){var n=s.shift();e.add(n),a.delete(n);for(let i=-1;i<=1;i++)for(let t=-1;t<=1;t++)if(i||t){let e=r.get(n.tile.rx+i+"_"+(n.tile.ry+t));e&&e.length&&e.forEach(e=>{a.has(e)&&(a.delete(e),s.push(e))})}}t.push({objects:e})}return t}findCenterTile(e){let t=0,i=0;e.forEach(e=>{t+=e.tile.rx,i+=e.tile.ry}),t=Math.round(t/e.length),i=Math.round(i/e.length);let s=this.map.tiles.getByMapCoords(t,i);if(!s&&(s=e.find(e=>Math.abs(e.tile.rx-t)<=1&&Math.abs(e.tile.ry-i)<=1)?.tile,!s))throw new Error("At least one adjacent object should have been found");return s}}r=__webpack_require__(949);class qs extends r.Matrix4{extractRotation(e){let t=this.elements;var i=e.elements,s=1/Xs.setFromMatrixColumn(e,0).length(),r=1/Xs.setFromMatrixColumn(e,1).length(),e=1/Xs.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*e,t[9]=i[9]*e,t[10]=i[10]*e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){e&&e.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");let t=this.elements;var i,s,r,a,n,o,h,l,c,u,d,p=e.x,g=e.y,m=e.z,f=Qi.cos(p),y=Qi.sin(p),w=Qi.cos(g),T=Qi.sin(g),p=Qi.cos(m),g=Qi.sin(m);return"XYZ"===e.order?(i=f*p,r=f*g,s=y*p,m=y*g,t[0]=w*p,t[4]=-w*g,t[8]=T,t[1]=r+s*T,t[5]=i-m*T,t[9]=-y*w,t[2]=m-i*T,t[6]=s+r*T,t[10]=f*w):"YXZ"===e.order?(a=w*p,i=w*g,s=T*p,r=T*g,t[0]=a+r*y,t[4]=s*y-i,t[8]=f*T,t[1]=f*g,t[5]=f*p,t[9]=-y,t[2]=i*y-s,t[6]=r+a*y,t[10]=f*w):"ZXY"===e.order?(h=w*p,a=w*g,n=T*p,o=T*g,t[0]=h-o*y,t[4]=-f*g,t[8]=n+a*y,t[1]=a+n*y,t[5]=f*p,t[9]=o-h*y,t[2]=-f*T,t[6]=y,t[10]=f*w):"ZYX"===e.order?(n=f*p,o=f*g,l=y*p,h=y*g,t[0]=w*p,t[4]=l*T-o,t[8]=n*T+h,t[1]=w*g,t[5]=h*T+n,t[9]=o*T-l,t[2]=-T,t[6]=y*w,t[10]=f*w):"YZX"===e.order?(u=f*w,l=f*T,c=y*w,d=y*T,t[0]=w*p,t[4]=d-u*g,t[8]=c*g+l,t[1]=g,t[5]=f*p,t[9]=-y*p,t[2]=-T*p,t[6]=l*g+c,t[10]=u-d*g):"XZY"===e.order&&(c=f*w,u=f*T,d=y*w,e=y*T,t[0]=w*p,t[4]=-g,t[8]=T*p,t[1]=c*g+e,t[5]=f*p,t[9]=u*g-d,t[2]=d*g-u,t[6]=y*p,t[10]=e*g+c),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}lookAt(e,t,i){Qs.set(0,0,0),Zs.set(0,0,0),Ys.set(0,0,0);const s=this.elements;return Ys.subVectors(e,t),0===Ys.lengthSq()&&(Ys.z=1),Ys.normalize(),Qs.crossVectors(i,Ys),0===Qs.lengthSq()&&(1===Math.abs(i.z)?Ys.x+=1e-4:Ys.z+=1e-4,Ys.normalize(),Qs.crossVectors(i,Ys)),Qs.normalize(),Zs.crossVectors(Ys,Qs),s[0]=Qs.x,s[4]=Zs.x,s[8]=Ys.x,s[1]=Qs.y,s[5]=Zs.y,s[9]=Ys.y,s[2]=Qs.z,s[6]=Zs.z,s[10]=Ys.z,this}getMaxScaleOnAxis(){var e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],e=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Qi.sqrt(Math.max(t,i,e))}makeRotationX(e){var t=Qi.cos(e),e=Qi.sin(e);return this.set(1,0,0,0,0,t,-e,0,0,e,t,0,0,0,0,1),this}makeRotationY(e){var t=Qi.cos(e),e=Qi.sin(e);return this.set(t,0,e,0,0,1,0,0,-e,0,t,0,0,0,0,1),this}makeRotationZ(e){var t=Qi.cos(e),e=Qi.sin(e);return this.set(t,-e,0,0,e,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){var i=Qi.cos(t),s=Qi.sin(t),r=1-i,a=e.x,n=e.y,o=e.z,t=r*a,e=r*n;return this.set(t*a+i,t*n-s*o,t*o+s*n,0,t*n+s*o,e*n+i,e*o-s*a,0,t*o-s*n,e*o+s*a,r*o*o+i,0,0,0,0,1),this}decompose(e,t,i){var s=this.elements;let r=Xs.set(s[0],s[1],s[2]).length();var a=Xs.set(s[4],s[5],s[6]).length(),n=Xs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),e.x=s[12],e.y=s[13],e.z=s[14],Ks.copy(this);var o=1/r,e=1/a,s=1/n;return Ks.elements[0]*=o,Ks.elements[1]*=o,Ks.elements[2]*=o,Ks.elements[4]*=e,Ks.elements[5]*=e,Ks.elements[6]*=e,Ks.elements[8]*=s,Ks.elements[9]*=s,Ks.elements[10]*=s,t.setFromRotationMatrix(Ks),i.x=r,i.y=a,i.z=n,this}}const Xs=new is,Qs=new is,Zs=new is,Ys=new is,Ks=new qs;var Js=__webpack_require__(949);function er(e){return e*Js.Math.RAD2DEG}function tr(e){return e*Js.Math.DEG2RAD}const ir=new vs;function sr(e,t){t=tr(Math.floor(t));return e.rotateAround(ir,t)}function rr(e){return Math.round(er(e.angle()))}function ar(e,t){t=er(2*Qi.acos(Math.abs(U(e.dot(t),-1,1))));return Math.round(t)}function nr(e,t){e=rr(e),t=rr(t);return Math.min((e-t+360)%360,(t-e+360)%360)}function or(e,t){return ar(hr(e,pr),hr(t,gr))}function hr(e,t=new Zi){return t.setFromRotationMatrix(lr.lookAt(e,cr,ur))}const lr=new qs,cr=new is(0,0,0),ur=new is(0,1,0);function dr(e,t,i){var s=e.length(),r=hr(t,pr),t=hr(e,gr);!function(e,t,i){var s=ar(e,t);if(0!==s){s=Math.min(1,i/s);e.slerp(t,s)}}(t,r,i),e.set(0,0,1).applyQuaternion(t).setLength(s)}const pr=new Zi,gr=new Zi;class mr extends Vs{constructor(e,t){super(),this.game=e,this.fromDirection=t,this.resolved=!1,this.chainPushIssued=!1}onEnd(e){e.moveTrait.collisionState=$r.Resolved}onTick(i){if(this.timeoutTicks=void 0===this.timeoutTicks?0:this.timeoutTicks+1,40<this.timeoutTicks||this.resolved||this.isCancelling())return!0;let s=this.game.map,t=new $s(s),r=i.onBridge?s.tileOccupation.getBridgeOnTile(i.tile):void 0,a,n;for(let e=0;e<360;e+=45)if((0!==e||this.chainPushIssued)&&180!==e){var o=sr(this.fromDirection.clone(),e).round(),o=s.tiles.getByMapCoords(i.tile.rx+Math.sign(o.x),i.tile.ry+Math.sign(o.y));if(o&&s.mapBounds.isWithinBounds(o)&&(n=!r||r.isHighBridge()?s.tileOccupation.getBridgeOnTile(o):void 0,i.rules.movementZone===ii.Fly||!s.terrain.findObstacles({tile:o,onBridge:n},i).length&&t.isEligibleTile(o,n,r,i.tile))){a=o;break}}if(a)return this.resolved=!0,i.isInfantry()&&i.deployerTrait&&i.deployerTrait.isDeployed()&&i.deployerTrait.setDeployed(!1),!!i.moveTrait.isDisabled()||(this.children.push(new ba(this.game,a,!!n,{closeEnoughTiles:0,strictCloseEnough:!0})),!1);{if(this.chainPushIssued)return this.children.push(new Gs(5)),!1;let t=s.tiles.getByMapCoords(i.tile.rx+Math.sign(this.fromDirection.x),i.tile.ry+Math.sign(this.fromDirection.y));if(!t||!s.mapBounds.isWithinBounds(t))return!0;n=!r||r.isHighBridge()?s.tileOccupation.getBridgeOnTile(t):void 0;let e=s.tileOccupation.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&e.owner===i.owner&&e.tile===t&&e.onBridge===!!n&&!(e.isInfantry()&&e.stance===Ds.Paradrop)&&!(e.isAircraft()&&e.missileSpawnTrait));return e.find(e=>e.moveTrait.collisionState===$r.Waiting||e.unitOrderTrait.hasTasks())?(this.children.push(new Gs(5)),i.moveTrait.collisionState=$r.Waiting,i.moveTrait.moveState=Hr.PlanMove,!1):(e.forEach(e=>{e.unitOrderTrait.addTask(new mr(this.game,this.fromDirection))}),this.children.push(new Gs(1)),i.moveTrait.collisionState=$r.Waiting,i.moveTrait.moveState=Hr.PlanMove,!(this.chainPushIssued=!0))}}}const fr=__webpack_require__(163);class yr{constructor(e){this.game=e,this.ignoresTerrain=!0,this.distanceToWaypoint=new vs}onNewWaypoint(e,t){}tick(e,t,i,s){if(s)return{distance:new is,done:!0};this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());s=this.game.rules.general;return s.chronoTrigger&&(s=(t=this.distanceToWaypoint.length())<s.chronoRangeMinimum?s.chronoMinimumDelay:t/s.chronoDistanceFactor,e.warpedOutTrait.setTimed(s,!1,this.game)),{distance:new is(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!0,isTeleport:!0}}}class wr{static tick(e,t,i){if(e===t)return{facing:e,delta:0};var s=(e-t+360)%360,r=(t-e+360)%360;if(Math.min(s,r)<i)return{facing:t,delta:0};i*=r<=s?1:-1;return{facing:(e+i+360)%360,delta:i}}static fromMapCoords(e){return(-rr(e)-90+720)%360}static toMapCoords(e){return sr(new vs(1e3,0),wr.toWorldDeg(e)).round().normalize()}static toWorldDeg(e){return-(e+90)}}class Tr extends Vs{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}=wr.tick(e.direction,this.direction,t);return e.direction=i,e.spinVelocity=t,!1}}r=__webpack_require__(949);class br extends r.LineCurve{constructor(e,t){super(e||new vs,t||new vs)}getPoint(e,t){return super.getPoint(e,t||new vs)}}r=__webpack_require__(949);class vr extends r.CurvePath{closePath(){let e=this.curves[0].getPoint(0);var t=this.curves[this.curves.length-1].getPoint(1);e.equals(t)||this.curves.push(new br(t,e))}}var Sr,_r,r=__webpack_require__(949);class kr extends r.QuadraticBezierCurve{constructor(e,t,i){super(e||new vs,t||new vs,i||new vs)}getPoint(e,t){return super.getPoint(e,t||new vs)}}(r=Sr=Sr||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.Normal=2]="Normal",r[r.End=3]="End",r[r.Single=4]="Single";class Or{constructor(e){this.game=e,this.hasMomentum=!1,this.moveOnCurve=!1,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=Sr.None}selectNextWaypoint(i,s){if(this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==Sr.End?Sr.Normal:Sr.Start,this.initialPosition=i.position.getMapPosition(),this.currentWaypointType!==Sr.Start?i.moveTrait.speedPenalty=0:this.currentSpeed=0,1<s.length){var r=s[s.length-1],a=s[s.length-2],e=new vs(r.tile.rx-i.tile.rx,r.tile.ry-i.tile.ry),n=Math.abs(rr(e)-rr(new vs(a.tile.rx-r.tile.rx,a.tile.ry-r.tile.ry)));if(!Math.abs(wr.fromMapCoords(e)-i.direction)&&0<n&&n<90&&this.hasMomentum){this.moveOnCurve=!0,this.currentWaypointType=2===s.length?this.currentWaypointType===Sr.Start?Sr.Single:Sr.End:Sr.Normal;let e=this.initialPosition;i=new vs(r.tile.rx+.5,r.tile.ry+.5).multiplyScalar(Ss.LEPTONS_PER_TILE);let t=new vs(a.tile.rx+.5,a.tile.ry+.5).multiplyScalar(Ss.LEPTONS_PER_TILE);n=e.clone().lerp(i,.5),r=t.clone().lerp(i,.5);return this.steerCurve=new vr,this.steerCurve.add(new br(e,n)),this.steerCurve.add(new kr(n,i,r)),this.steerCurve.add(new br(r,t)),this.lastPosition=e,a}}else this.currentWaypointType=this.currentWaypointType===Sr.Start?Sr.Single:Sr.End;return this.hasMomentum=!0,this.moveOnCurve=!1,s[s.length-1]}onNewWaypoint(e,t,i){let s=(new vs).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=this.moveOnCurve?this.steerCurve.getLength():s.length();t=wr.fromMapCoords(s);if(t!==e.direction&&(this.pointTurretToTarget(e,i),!this.moveOnCurve))return e.moveTrait.velocity.set(0,0,0),[new Tr(t)]}tick(i,s,r){this.pointTurretToTarget(i,r);let a=this.currentSpeed;a=i.rules.accelerates?(h=this.distanceTravelled/this.totalDistanceToTravel,this.currentSpeed=this.applyAcceleration(i,a,i.moveTrait.baseSpeed,h)):this.currentSpeed=i.moveTrait.baseSpeed;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 r=this.steerCurve.getLength(),h=Math.min(this.distanceTravelled+a,r);this.carryOverDistance=Math.max(0,this.distanceTravelled+a-r),this.distanceTravelled=h;let e=this.steerCurve.getPointAt(this.distanceTravelled/r),t=this.steerCurve.getTangentAt(this.distanceTravelled/r);h=t.clone().setLength(a);i.moveTrait.velocity.set(h.x,0,h.y);var r=i.rules.rot,{facing:h,delta:r}=wr.tick(i.direction,wr.fromMapCoords(t),r);i.direction=h,i.spinVelocity=r;r=this.lastPosition;this.lastPosition=e.clone(),o=e.sub(r)}else{let e=(new vs).copy(s).sub(n);n=Math.min(e.length(),a);o=e.clone().setLength(n);let t=o.clone();this.carryOverDistance&&t.add(Ss.vecWorldToGround(i.moveTrait.velocity)),i.moveTrait.velocity.set(t.x,0,t.y),this.distanceTravelled+=n,this.carryOverDistance=Math.max(0,a-e.length())}return{distance:new is(o.x,0,o.y),done:!o.length()||!!this.carryOverDistance}}pointTurretToTarget(t,i){if(t.turretTrait){t.attackTrait?.currentTarget?.obj&&(i=t.attackTrait.currentTarget.obj.position.getMapPosition());var s=t.position.getMapPosition();let e=(new vs).copy(i).sub(s);e.length()&&(s=wr.fromMapCoords(e),t.turretTrait.desiredFacing=s)}}applyAcceleration(e,t,i,s){if(this.currentWaypointType===Sr.Single)return.3*i;if(this.currentWaypointType!==Sr.End)return Math.min(t+e.rules.accelerationFactor*i,i);return z(1,i,1-(s=this.moveOnCurve&&this.currentWaypointType===Sr.End?s<=.5?0:2*(s-.5):s))}}class Ir{constructor(e){this.game=e,this.currentMoveDirection=new vs,this.distanceToWaypoint=new vs,this.carryOverDistance=0}onNewWaypoint(e,t){this.currentMoveDirection.copy(t).sub(e.position.getMapPosition());t=wr.fromMapCoords(this.currentMoveDirection);t!==e.direction&&(e.direction=t)}onWaypointUpdate(e,t){this.onNewWaypoint(e,t)}tick(e,t){let i=e.moveTrait.baseSpeed*as.MAGIC_SPEED_MULT;e.stance===Ds.Prone&&(i/=2),e.isPanicked&&(i*=2);let s=this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge,void 0,!0);s?this.lastTileSpeed=s:s=this.lastTileSpeed||1,i*=s,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);t=Math.min(this.distanceToWaypoint.length(),i);return this.carryOverDistance=Math.max(0,i-this.distanceToWaypoint.length()),this.distanceToWaypoint.setLength(t),{distance:new is(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!this.distanceToWaypoint.length()||!!this.carryOverDistance}}}(r=_r=_r||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.Normal=2]="Normal",r[r.End=3]="End",r[r.Single=4]="Single";class Ar{constructor(e){this.hoverRules=e,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=_r.None,this.nextWaypointDir=new vs}selectNextWaypoint(e,t){var i;return this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==_r.End?_r.Normal:_r.Start,this.initialPosition=e.position.getMapPosition(),this.currentWaypointType===_r.Start&&(this.currentSpeed=0),t.length<=1?(this.currentWaypointType=this.currentWaypointType===_r.Start?_r.Single:_r.End,(i=t[t.length-1])&&this.nextWaypointDir.set(i.tile.rx-e.tile.rx,i.tile.ry-e.tile.ry)):(i=t[t.length-1],e=t[t.length-2],this.nextWaypointDir.set(e.tile.rx-i.tile.rx,e.tile.ry-i.tile.ry)),t[t.length-1]}onNewWaypoint(e,t,i){let s=(new vs).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=s.length();t=this.maxSpeed=e.moveTrait.baseSpeed*as.MAGIC_SPEED_MULT,e=60*this.hoverRules.acceleration*Ls.BASE_TICKS_PER_SECOND;this.acceleration=t/e;e=60*this.hoverRules.brake*Ls.BASE_TICKS_PER_SECOND;this.deceleration=t/e}tick(e,t){var i=e.position.getMapPosition();let s=t.clone().sub(i);t=s.length(),i=this.maxSpeed;this.currentWaypointType===_r.Single?this.currentSpeed=i/2:this.currentWaypointType===_r.End?(r=this.computeBrakeDistance(this.currentSpeed,this.deceleration),this.totalDistanceToTravel-this.distanceTravelled<=r&&(this.currentSpeed=Math.max(0,this.currentSpeed-this.deceleration))):this.currentSpeed=Math.min(this.currentSpeed+this.acceleration,i);var r=wr.fromMapCoords(s),i=wr.fromMapCoords(this.nextWaypointDir);let a=r,n=e.rules.rot;this.currentWaypointType===_r.Normal&&r!==i&&(r=(o=nr(this.nextWaypointDir,wr.toMapCoords(e.direction)))/n,r=Math.max(this.currentSpeed*r,this.totalDistanceToTravel),this.totalDistanceToTravel-this.distanceTravelled<=r&&(a=i,n=o/((this.totalDistanceToTravel-this.distanceTravelled)/this.currentSpeed)));var o=wr.tick(e.direction,a,n)["facing"];e.direction=o;let h=this.currentSpeed;this.carryOverDistance&&(h=this.carryOverDistance);o=Math.min(h,t);let l=s.clone().setLength(o),c=l.clone();return this.carryOverDistance&&c.add(Ss.vecWorldToGround(e.moveTrait.velocity)),e.moveTrait.velocity.set(c.x,0,c.y),this.distanceTravelled+=o,this.carryOverDistance=Math.max(0,h-t),{distance:new is(l.x,0,l.y),done:!l.length()||!!this.carryOverDistance}}computeBrakeDistance(e,t){var i=e/t;return Math.max(0,e*i-t*i*i/2)}}class Cr{static computeInterceptPoint(e,t,i,s){let r=e.clone().sub(i);var a=s.length(),e=t*t-a*a,t=2*r.dot(s),a=-r.dot(r);if(t*t-4*e*a<0)return new is;e=(-t+Qi.sqrt(t*t-4*e*a))/(2*e);return s.clone().multiplyScalar(e).add(i)}static computeTurnCircle(e,t,i,s){s/=tr(Math.abs(i));let r=sr(t.clone(),90*-Math.sign(i));return{center:isFinite(s)?r.setLength(s).add(e):e.clone(),radius:s}}}var Br=__webpack_require__(949);function xr(e,t){var i=e.center;return(i.x-t.x)*(i.x-t.x)+(i.y-t.y)*(i.y-t.y)<=e.radius*e.radius}function Er(e,t){let i=new Br.Box2(new Br.Vector2(e.x,e.y),new Br.Vector2(e.x+e.width,e.y+e.height));return i.containsPoint(new Br.Vector2(t.x,t.y))}class Pr{constructor(e){this.gameObject=e,this.type=ts.ObjectLiftOff}}class Nr{constructor(e){this.gameObject=e,this.type=ts.ObjectLand}}class Rr{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.currentMoveDir=new vs,this.currentHorizSpeed=0}static tickStationary(t,i){if(t.zone===Ts.Air){var s=t.tile.onBridgeLandType?i.map.tileOccupation.getBridgeOnTile(t.tile):void 0,r=!t.rules.balloonHover&&(!t.unitOrderTrait.getCurrentTask()?.preventLanding||!t.rules.hoverAttack)&&(i.map.getGroundObjectsOnTile(t.tile).find(e=>e.isBuilding()&&e.dockTrait?.isDocked(t))||i.map.getTileZone(t.tile)!==Ts.Water&&0<i.map.terrain.getPassableSpeed(t.tile,Kt.Foot,!!t.tile.onBridgeLandType)&&0===i.map.terrain.findObstacles({tile:t.tile,onBridge:s},t).length);let e;e=r?(a=t.tile.z+(s?.tileElevation??0),Ss.tileHeightToWorld(a)):(n=t.tile.z+i.map.getGroundObjectsOnTile(t.tile).filter(e=>!(e.isInfantry()&&e.stance===Ds.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0),Ss.tileHeightToWorld(n)+t.rules.jumpjetHeight);var a,n,o=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 is(0,n,0))):r&&(t.zone=Ts.Ground,t.onBridge=!!s,i.events.dispatch(new Nr(t)))}}static tickCrash(e,t,i){var s=2*e.rules.jumpjetCrash;return e.direction=(e.direction-6+360)%360,new is(0,-s,0)}onNewWaypoint(e,t,i){this.currentMoveDir=wr.toMapCoords(e.direction),this.cancelDestLeptons=void 0}tick(t,e,i,s){if(t.zone!==Ts.Air&&(t.onBridge=!1,t.zone=Ts.Air,this.game.events.dispatch(new Pr(t))),s){if(!this.cancelDestLeptons){let e=t.tile;this.game.map.isWithinBounds(e)||(e=this.game.map.clampWithinBounds(e)),this.cancelDestLeptons=this.computeCancelDest(e,i)}i=this.cancelDestLeptons}var r=t.position.getMapPosition();let a=i.clone().sub(r),n=this.findTilesToCheckForBlockers(t.tile,r,this.currentMoveDir,a.length());var o=n.map(e=>e.z+this.game.map.getGroundObjectsOnTile(e).filter(e=>!(e.isDestroyed||e.isInfantry()&&e.stance===Ds.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=Ss.tileHeightToWorld(o),c=Ss.tileHeightToWorld(o+h),u=t.position.worldPosition.y,d=wr.fromMapCoords(a),p=a.length()<t.rules.jumpjetSpeed;let g=0;l<=u&&!p&&({facing:T,delta:s}=wr.tick(t.direction,d,t.rules.jumpjetTurnRate),g=s,t.direction=T,this.currentMoveDir.copy(wr.toMapCoords(t.direction))),t.isVehicle()&&(t.spinVelocity=g);let m,f=!1,y=0,w=0;var T=t.rules.jumpjetClimb;u<c?(y=Math.min(T,c-u),m=!1,this.currentHorizSpeed=0):(this.lastClearZ=o,o=l+t.rules.jumpjetHeight,m=!0,o!==u&&(l=Math.abs(o-u),y=Math.sign(o-u)*Math.min(T,l),m=l<=T),T=this.currentHorizSpeed,this.currentHorizSpeed=Math.min(this.currentHorizSpeed+2,t.rules.jumpjetSpeed),f=d===t.direction?(w=Math.min(T,a.length()),T>=a.length()):((r=T||g?Cr.computeTurnCircle(r,this.currentMoveDir,Math.sign(g)*t.rules.jumpjetTurnRate,T):void 0)&&xr(r,i)?(w=0,this.currentHorizSpeed=0):w=T,!1));let b;b=p?(f=!0,a):this.currentMoveDir.clone().setLength(w);let v=new is(b.x,y,b.y);p=v.clone();return t.moveTrait.velocity.copy(p),{distance:v,done:f&&m}}findTilesToCheckForBlockers(e,t,i,s){s=i.clone().setLength(Math.min(s,Ss.LEPTONS_PER_TILE)).add(t).multiplyScalar(1/Ss.LEPTONS_PER_TILE).floor(),t=this.game.map.tiles.getByMapCoords(s.x,s.y);if(!t||t===e)return[e];s=Math.sign(t.rx-e.rx),t=Math.sign(t.ry-e.ry);let r=[e],a;return s&&(a=this.game.map.tiles.getByMapCoords(e.rx+s,e.ry),a&&r.push(a)),t&&(a=this.game.map.tiles.getByMapCoords(e.rx,e.ry+t),a&&r.push(a)),s&&t&&(a=this.game.map.tiles.getByMapCoords(e.rx+s,e.ry+t),a&&r.push(a)),r}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/Ss.LEPTONS_PER_TILE).floor().multiplyScalar(Ss.LEPTONS_PER_TILE),i=t.clone().sub(i);return new vs(e.rx,e.ry).multiplyScalar(Ss.LEPTONS_PER_TILE).add(i)}}var Dr,Mr,Lr,Fr,jr,Ur,Wr,zr,Vr,Hr,Gr,$r,qr,Xr,Qr,Zr,Yr,Kr,Jr,ea,ta,ia,sa,ra,aa,na,oa,ha,r=__webpack_require__(949);class la extends r.CubicBezierCurve3{constructor(e,t,i,s){super(e||new is,t||new is,i||new is,s||new is)}getPoint(e,t){return super.getPoint(e,t||new is)}}(r=Dr=Dr||{})[r.Boost=0]="Boost",r[r.Midcourse=1]="Midcourse",r[r.Terminal=2]="Terminal";class ca{constructor(e,t){this.game=e,this.missileRules=t,this.flightPhase=Dr.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=Ss.tile3dToWorld(i.tile.rx+.5,i.tile.ry+.5,t),this.cruiseAltitude=Ss.tileHeightToWorld(t)+this.missileRules.altitude,i}onNewWaypoint(e,t,i){}tick(i,e,t){let s=i.position.worldPosition.clone(),r=this.targetPosition.clone().sub(s);i.zone!==Ts.Air&&(i.onBridge=!1,i.zone=Ts.Air,this.game.events.dispatch(new Pr(i)));let a;var n;a=this.currentVelocity?(n=i.rules.speed*as.MAGIC_SPEED_MULT,Math.min(this.currentVelocity.length()+this.missileRules.acceleration,n)):(p=this.missileRules.acceleration,this.missileRules.lazyCurve?this.currentVelocity=new is(r.x,0,r.z):this.currentVelocity=Ss.vecGroundToWorld(wr.toMapCoords(i.direction)),dr(this.currentVelocity,new is(this.currentVelocity.x,1e8,this.currentVelocity.z),i.pitch),p),this.currentVelocity.setLength(a);let o=!1;switch(this.flightPhase){case Dr.Boost:if(!(i.position.worldPosition.y>=this.cruiseAltitude)){o=!1;break}this.flightPhase=Dr.Midcourse;case Dr.Midcourse:var h,l=new vs(r.x,r.z).length();if(!this.missileRules.lazyCurve){dr(this.currentVelocity,new is(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)),dr(this.currentVelocity,new is(r.x,this.currentVelocity.y,r.z),i.rules.rot),i.direction=wr.fromMapCoords(Ss.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*or(this.currentVelocity,new is(this.currentVelocity.x,0,this.currentVelocity.z)),l/(s.y-this.targetPosition.y)<1&&(this.flightPhase=Dr.Terminal);break}this.flightPhase=Dr.Terminal;var c=s.clone().add(this.currentVelocity.clone().setLength(l/3/Qi.cos(tr(i.pitch)))),u=this.targetPosition.clone().lerp(s,.15).setY(c.y);this.descentCurve=new la(s,c,u,this.targetPosition);case Dr.Terminal:c=this.missileRules.bodyLength;if(this.missileRules.lazyCurve){var d=this.descentCurve.getLength();this.descentTravelled??(this.descentTravelled=0),this.descentTravelled+=Math.min(a,d-c-this.descentTravelled);u=this.descentTravelled/d;let e=this.descentCurve.getPointAt(u),t=this.descentCurve.getTangentAt(u);this.currentVelocity.copy(e.sub(s));u=t.clone().setY(0);i.pitch=Math.sign(t.y-u.y)*or(u,t),o=1<=(this.descentTravelled+c)/d}else{dr(this.currentVelocity,r,i.rules.rot),i.direction=wr.fromMapCoords(Ss.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*or(this.currentVelocity,new is(this.currentVelocity.x,0,this.currentVelocity.z));d=r.length()-c;(d<a||d<1)&&(this.currentVelocity.copy(r.clone().addScalar(-c)),o=!0)}break;default:throw new Error(`Unhandled flight phase "${this.flightPhase}"`)}var p=s.clone().add(this.currentVelocity);return this.game.map.isWithinHardBounds(p)?(i.moveTrait.velocity.copy(this.currentVelocity),{distance:this.currentVelocity,done:o}):(this.game.destroyObject(i),{done:!0,distance:new is})}}class ua extends Gs{constructor(e){super(Math.floor(Ls.BASE_TICKS_PER_SECOND*e*60))}}class da extends Vs{constructor(e){super(),this.cb=e}onTick(e){return this.cb(e),!0}}(Mr=Mr||{}).onTick=Symbol(),(r=Lr=Lr||{})[r.Idle=0]="Idle",r[r.MoveToQueueingTile=1]="MoveToQueueingTile",r[r.WaitForTurn=2]="WaitForTurn",r[r.MoveToDock=3]="MoveToDock",r[r.Docking=4]="Docking",r[r.Docked=5]="Docked";class pa extends Vs{constructor(e,t){super(),this.game=e,this.target=t,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.dockingStatus=Lr.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=Lr.MoveToDock:void 0!==(t=this.target.dockTrait.getFirstAvailableDockNumber())?(this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=Lr.MoveToDock):this.target.helipadTrait?this.cancel():this.dockingStatus=Lr.MoveToQueueingTile}onEnd(e){this.dockingStatus!==Lr.Docked&&this.target.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),this.dockingStatus=Lr.Idle}onTick(e){if(this.isCancelling())return!0;if(!this.isValidTarget(this.target,e))return!0;if(this.dockingStatus===Lr.MoveToQueueingTile){var t=this.findReachableQueueingTile(e);if(!t)return!0;if(e.tile!==t)return this.children.push(new ba(this.game,t,!1,{closeEnoughTiles:5}),new da(()=>{e.moveTrait.lastMoveResult===Gr.Fail?this.cancel():e.moveTrait.lastMoveResult===Gr.CloseEnough&&(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)||(this.dockingStatus=Lr.WaitForTurn))})),!1;this.dockingStatus=Lr.WaitForTurn}if(this.dockingStatus===Lr.WaitForTurn){var i=this.target.dockTrait.getFirstAvailableDockNumber();if(void 0===i)return this.children.push(new ua(1/60)),!1;this.target.dockTrait.reserveDockAt(e,i),this.dockingStatus=Lr.MoveToDock}if(this.dockingStatus===Lr.MoveToDock){var s=this.target.dockTrait.getReservedDockForUnit(e),i=this.target.dockTrait.getDockTile(s),s=Ss.vecWorldToGround(this.target.dockTrait.getDockOffset(s)).add(this.target.position.getMapPosition()).sub(new vs(i.rx,i.ry).multiplyScalar(Ss.LEPTONS_PER_TILE));if(e.tile!==i)return this.children.push(new ba(this.game,i,!1,{targetOffset:e.isAircraft()?s:void 0,closeEnoughTiles:0,strictCloseEnough:!0}),new da(()=>{e.moveTrait.lastMoveResult===Gr.Fail&&this.cancel()})),this.game.afterTick(()=>e.unitOrderTrait[Mr.onTick](e,this.game)),!1;this.dockingStatus=Lr.Docking}if(this.dockingStatus!==Lr.Docking)return!1;s=this.target.dockTrait.getReservedDockForUnit(e);return this.target.dockTrait.unreserveDockForUnit(e),this.target.dockTrait.dockUnitAt(e,s),e.isAircraft()&&e.airportBoundTrait&&this.target.helipadTrait&&(e.airportBoundTrait.preferredAirport=this.target),this.dockingStatus=Lr.Docked,!0}isValidTarget(e,t){return e.isSpawned&&this.game.areFriendly(e,t)}findReachableQueueingTile(t){var e=this.target.getFoundation(),e=new vs(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 Fs(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)}}(r=Fr=Fr||{})[r.None=0]="None",r[r.CircleStrafe=1]="CircleStrafe",r[r.HoverStrafe=2]="HoverStrafe";class ga{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.lastDestLeptons=new vs,this.currentMoveDir=new vs,this.currentHorizSpeed=0,this.maneuverType=Fr.None,this.deceleratingToTurn=!1}static tickStationary(r,a){if(r.zone===Ts.Air){var n=r.tile.onBridgeLandType?a.map.tileOccupation.getBridgeOnTile(r.tile):void 0;let e=r.rules.landable&&!r.unitOrderTrait.getCurrentTask()?.preventLanding,i=r.spawnLinkTrait?.getParent();e&&i?e=!((!i.isUnit()||!i.onBridge)&&n||i.tile!==r.tile):e&&!r.airportBoundTrait&&(e=a.map.getTileZone(r.tile)!==Ts.Water&&0<a.map.terrain.getPassableSpeed(r.tile,Kt.Foot,!!r.tile.onBridgeLandType)&&0===a.map.terrain.findObstacles({tile:r.tile,onBridge:n},r).length);let s;if(e){let e=r.airportBoundTrait?.preferredAirport?.dockTrait;var o=e?.isDocked(r)||e?.hasReservedDockForUnit(r);if(!r.airportBoundTrait||o){var h=o?0:270;if(r.direction!==h)return void(r.direction=wr.tick(r.direction,h,r.rules.rot).facing)}if(r.airportBoundTrait){let e=r.airportBoundTrait.preferredAirport;if(!e?.dockTrait?.isDocked(r))return e?.dockTrait?.getAvailableDockCount()||(e=r.airportBoundTrait.findAvailableAirport(r),r.airportBoundTrait.preferredAirport=e,e&&(h=e.dockTrait.getFirstAvailableDockNumber(),e.dockTrait.reserveDockAt(r,h))),void(e?(r.unitOrderTrait.addTask(new pa(a,e)),r.unitOrderTrait[Mr.onTick](r,a)):r.crashableTrait.crash(void 0))}let t;t=i?i.tile.z+i.tileElevation:r.tile.z+(n?.tileElevation??0),s=Ss.tileHeightToWorld(t)}else{var t=r.tile.z+(n?.tileElevation??0),l=r.rules.flightLevel??a.rules.general.flightLevel;s=Ss.tileHeightToWorld(t)+l}t=r.position.worldPosition.y;s!==t?(l=Math.abs(s-t),l=Math.sign(s-t)*Math.min(30,l),r.position.moveByLeptons3(new is(0,l,0))):e&&(r.zone=Ts.Ground,i?i.airSpawnTrait.storeAircraft(r,a):r.onBridge=!!n,a.events.dispatch(new Nr(r)))}}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=Ss.vecWorldToGround(e.moveTrait.velocity);return new is(e.x,-30,e.y)}onNewWaypoint(e,t,i){this.currentHorizSpeed=Ss.vecWorldToGround(e.moveTrait.velocity).length(),this.cancelDestLeptons=void 0}tick(t,e,i,s){if(s){if(!this.cancelDestLeptons){let e=t.tile;this.game.map.isWithinBounds(e)||(e=this.game.map.clampWithinBounds(e)),this.cancelDestLeptons=this.computeCancelDest(e,i)}i=this.cancelDestLeptons}var r=t.position.getMapPosition();let a=i.clone().sub(r);var n=a.length();this.lastDestLeptons.equals(i)||(this.lastDestLeptons.copy(i),s?this.maneuverType=Fr.HoverStrafe:t.zone===Ts.Air&&this.currentHorizSpeed<5?this.maneuverType=n>Ss.LEPTONS_PER_TILE?Fr.CircleStrafe:Fr.HoverStrafe:this.maneuverType=Fr.None,this.deceleratingToTurn=!1),t.zone!==Ts.Air&&(t.onBridge=!1,t.zone=Ts.Air,this.game.events.dispatch(new Pr(t)));var o=t.tile.onBridgeLandType?this.game.map.tileOccupation.getBridgeOnTile(t.tile):void 0,h=t.tile.z+(o?.tileElevation??0),l=t.rules.flightLevel??this.game.rules.general.flightLevel,s=Ss.tileHeightToWorld(h)+l,o=t.position.worldPosition.y,c=wr.fromMapCoords(a);t.direction===c&&this.maneuverType===Fr.None&&n<=Ss.LEPTONS_PER_TILE?this.maneuverType=Fr.HoverStrafe:t.direction===c&&this.maneuverType===Fr.CircleStrafe&&(this.maneuverType=Fr.None);let u;switch(this.maneuverType){case Fr.HoverStrafe:if(t.attackTrait?.currentTarget){let e=Ss.vecWorldToGround(t.attackTrait.currentTarget.getWorldCoords());u=wr.fromMapCoords(e.sub(r))}else u=t.airportBoundTrait?.preferredAirport?.dockTrait?.hasReservedDockForUnit(t)?0:270;break;case Fr.CircleStrafe:case Fr.None:u=c;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}var{facing:d,delta:p}=wr.tick(t.direction,u,t.rules.rot);t.direction=d,t.roll=Math.sign(p)*t.rules.pitchAngle;let g;switch(this.maneuverType){case Fr.HoverStrafe:g=c;break;case Fr.CircleStrafe:g=(d-90*Math.sign(p)+360)%360;break;case Fr.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}=wr.tick(this.thrustFacing,g,h);this.thrustFacing=l,this.currentMoveDir.copy(wr.toMapCoords(this.thrustFacing));let m=!1,f=0,y=0;let w=!0;s!==o&&(b=Math.abs(s-o),f=Math.sign(s-o)*Math.min(30,b),w=b<=30);let T=t.rules.speed*as.MAGIC_SPEED_MULT;n<=Ss.LEPTONS_PER_TILE&&this.maneuverType!==Fr.CircleStrafe&&(T=z(1,T/2,Qi.sqrt(n/Ss.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?Cr.computeTurnCircle(r,this.currentMoveDir,Math.sign(h)*t.rules.rot,b):void 0,0!==b&&!xr(h,i)||(this.maneuverType===Fr.HoverStrafe||n>Ss.LEPTONS_PER_TILE?this.deceleratingToTurn=!0:this.maneuverType===Fr.None&&(this.maneuverType=Fr.HoverStrafe)),y=b,!1):(y=Math.min(b,n),n<=b);let v;v=n<1?(m=!0,a):m?a:this.currentMoveDir.clone().setLength(y);let S=new is(v.x,f,v.y);n=S.clone();return t.moveTrait.velocity.copy(n),{distance:S,done:m&&w}}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/Ss.LEPTONS_PER_TILE).floor().multiplyScalar(Ss.LEPTONS_PER_TILE),i=t.clone().sub(i);return new vs(e.rx,e.ry).multiplyScalar(Ss.LEPTONS_PER_TILE).add(i)}}class ma{constructor(e){this.game=e}create(e){var t=e.rules.locomotor;switch(t){case ti.Infantry:return new Ir(this.game);case ti.Jumpjet:return new Rr(this.game);case ti.Vehicle:case ti.Ship:return new Or(this.game);case ti.Chrono:return e.isVehicle()&&e.harvesterTrait&&e.rules.teleporter?new Or(this.game):new yr(this.game);case ti.Aircraft:return new ga(this.game);case ti.Missile:return new ca(this.game,this.game.rules.general.getMissileRules(e.name));case ti.Hover:return new Ar(this.game.rules.general.hover);default:throw new Error(`Unhandled locomotor type ${t}`)}}}class fa{constructor(e,t,i,s,r,a,n=!1,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.rng=r,this.predicate=a,this.includeStartTile=n,this.checkBounds=o,this.pool=[],this.pool=new Array(Qi.pow(2*this.maxDistance+1,2)).fill(0).map((e,t)=>t),this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){for(var e=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(this.includeStartTile||t!==this.startTile)return t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t)?t:void 0},t=2*this.maxDistance+1;this.pool.length;){var i=1<this.pool.length?this.rng.generateRandomInt(0,this.pool.length):0,s=this.pool.splice(i,1)[0],i=s%t,s=Math.floor(s/t),s=e(this.startTile.rx-this.maxDistance+i,this.startTile.ry-this.maxDistance+s);s&&(yield s)}}}class ya{constructor(e,t,i){this.target=e,this.isChronoshift=t,this.prevTile=i,this.type=ts.ObjectTeleport}}(jr=jr||{}).onBeforeTeleport=Symbol();class wa{constructor(e){this.game=e,this.movePositionHelper=new $s(e.map)}findPositions(e,t){let i=new Set,s=new Map;for(var r of e){var a=this.findFreeMovePosition(r,i,t);a&&(s.set(r,a),i.add(a.tile))}return s}findFreeMovePosition(i,e,{ignoredBlockers:t,excludedTiles:s,noSlopes:r}={}){let a=this.game.map,n=i.onBridge?a.tileOccupation.getBridgeOnTile(i.tile):void 0,o=new fa(a.tiles,a.mapBounds,i.tile,1,this.game,e=>{if(s?.includes(e))return!1;var t=a.tileOccupation.getBridgeOnTile(e);return(t&&this.movePositionHelper.isEligibleTile(e,t,n,i.tile)||this.movePositionHelper.isEligibleTile(e,void 0,n,i.tile))&&(!r||0===e.rampType)}),h,l;for(;;){var c=o.getNextTile();if(!c)break;if(h=c,l=a.tileOccupation.getBridgeOnTile(c),l&&!this.movePositionHelper.isEligibleTile(c,l,n,i.tile)&&(l=void 0),!e.has(c)){let e=a.terrain.findObstacles({tile:c,onBridge:l},i);if(t&&t.length&&(e=e.filter(e=>!t.includes(e.obj))),!e.length)break}}if(h)return{tile:h,onBridge:l}}}class Ta extends Vs{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 wa(this.game).findPositions([i],this.options).get(i);if(!i)return;e=i.tile,t=!!i.onBridge}this.children.push(new ba(this.game,e,t,{closeEnoughTiles:0,ignoredBlockers:this.options?.ignoredBlockers}))}}onTick(e){return!0}}class ba extends Vs{constructor(e,t,i,s){super(),this.game=e,this.targetTile=t,this.toBridge=i,this.options=s,this.preventOpportunityFire=!1,this.logger=fr.get("move"),this.destinationLeptons=new vs,this.currentWaypointLeptons=new vs,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 ma(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=Hr.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 s=this.targetTile,r=this.toBridge?i.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.options?.ignoredBlockers;var n=new Fs(i.tiles,i.mapBounds,s,{width:1,height:1},0,5,e=>0<i.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType,a)&&!i.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).find(e=>!a?.includes(e.obj))).getNextTile();return n?(n!==s&&(s=n,r=i.tileOccupation.getBridgeOnTile(s)),[{tile:s,onBridge:r},{tile:t.tile,onBridge:e}]):[]}computeGroundPath(t){let e=t.tile,i=t.onBridge?this.game.map.tileOccupation.getBridgeOnTile(e):void 0;t.moveTrait.moveState===Hr.Moving&&t.moveTrait.currentWaypoint&&(e=t.moveTrait.currentWaypoint.tile,i=t.moveTrait.currentWaypoint.onBridge);let s;var r=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.nodeIsBlockedForPathfinding({tile:this.targetTile,onBridge:r},t);if(Math.abs(e.rx-this.targetTile.rx)<=1&&Math.abs(e.ry-this.targetTile.ry)<=1&&new $s(this.game.map).isEligibleTile(e,i,r,this.targetTile)&&a)s=[];else{const o=this.game.map.getObjectsOnTile(e).find(e=>e.isBuilding());if(o&&!this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)){this.options??(this.options={});var n=this.options?.ignoredBlockers?.includes(o);if(this.options.ignoredBlockers=[...new Set([...this.options?.ignoredBlockers??[],o])],!n&&o.dockTrait){let t=new Set(o.dockTrait?.getAllDockTiles()),e=this.game.map.tileOccupation.calculateTilesForGameObject(o.tile,o);e.filter(e=>!t.has(e)).forEach(e=>this.blockedPathNodes.push({node:{tile:e,onBridge:void 0},obj:o}))}}n=this.game.map.getGroundObjectsOnTile(this.targetTile).find(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()&&!(this.game.alliances.haveSharedIntel(t.owner,e.owner)||e.owner.sharedDetectDisguiseTrait?.has(t)));n&&this.blockedPathNodes.push({node:{tile:this.targetTile,onBridge:r},obj:n}),s=this.game.map.terrain.computePath(t.rules.speedType,e,!!i,this.targetTile,this.toBridge,{maxExpandedNodes:this.allObstaclesAreBlockers?Math.min(300,this.options?.maxExpandedPathNodes??Number.POSITIVE_INFINITY):this.options?.maxExpandedPathNodes,bestEffort:!this.options?.strictCloseEnough,ignoredBlockers:[...new Set([...this.options?.ignoredBlockers??[],...this.options?.pathFinderIgnoredBlockers??[]])],excludeTiles:this.allObstaclesAreBlockers||this.blockedPathNodes.length?e=>this.nodeIsBlockedForPathfinding(e,t):void 0})}return s}nodeIsBlockedForPathfinding(t,e){return this.allObstaclesAreBlockers?!!this.game.map.terrain.findObstacles(t,e).find(e=>!this.options?.ignoredBlockers?.includes(e.obj)):!!this.blockedPathNodes.find(({node:e})=>e.tile===t.tile&&e.onBridge===t.onBridge)}updateDestination(e,t){e=e.length?e[0].tile:this.targetTile;this.destinationLeptons.set(e.rx*Ss.LEPTONS_PER_TILE,e.ry*Ss.LEPTONS_PER_TILE).add(t)}canStopAtTile(t,i,s){if(t.zone===Ts.Air){if((!t.isAircraft()||!t.airportBoundTrait)&&!t.rules.spawned&&this.game.map.getObjectsOnTile(i).filter(e=>e.isBuilding()&&!e.isDestroyed&&!e.dockTrait?.hasReservedDockForUnit(t)&&!t.rules.dock.includes(e.name)||e.isUnit()&&e.tile===i&&e.moveTrait.moveState!==Hr.Moving&&e!==t).length)return!1}else if(t.isInfantry()){let e=this.game.map.getGroundObjectsOnTile(i).filter(e=>e.isInfantry()&&e.tile===i&&e.onBridge===s&&e.moveTrait.moveState!==Hr.Moving&&e!==t);if(2<e.length||e.find(e=>e.position.subCell===t.position.subCell))return!1}return!(t.zone!==Ts.Air&&t.rules.tooBigToFitUnderBridge&&!s&&i.onBridgeLandType&&this.game.map.tileOccupation.getBridgeOnTile(i)?.isHighBridge())&&!(!this.isCancelling()&&this.options?.strictCloseEnough&&void 0!==this.options?.closeEnoughTiles&&!this.isCloseEnoughToDest(t,i,this.options.closeEnoughTiles))}isCloseEnoughToDest(e,t,i){if(void 0===i)return!0;let s=new Is(this.game.map.tileOccupation);return!(s.tileDistance(this.targetTile,t)>i)}hasReachedDestination(e){return!this.path.length}updateTarget(e,t){this.targetTile=e,this.toBridge=t,this.needsPathUpdate=!0,this.targetChangeRequested=!0}onEnd(e){e.moveTrait.collisionState=$r.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!==Ms.Running&&this.status!==Ms.Cancelling||(e.moveTrait.unreservePathNodes(),e.moveTrait.lastMoveResult=Gr.Cancel,this.onEnd(e),e.moveTrait.lastTargetOffset=this.targetOffset,e.moveTrait.lastVelocity=e.moveTrait.velocity.clone()),this.status=Ms.Cancelled,!0))}onTick(r){if(r.moveTrait.isDisabled()&&r.moveTrait.moveState===Hr.ReachedNextWaypoint)return!!this.isCancelling()&&(r.moveTrait.lastMoveResult=Gr.Cancel,!0);this.needsPathUpdate&&(r.moveTrait.moveState===Hr.PlanMove&&(this.inPlanningForTicks=void 0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.collisionState=$r.Resolved,r.moveTrait.moveState=Hr.ReachedNextWaypoint,r.moveTrait.velocity.set(0,0,0)),this.computePath(r,r.moveTrait.locomotor),this.path.length||this.unreachableTargets.push({tile:this.targetTile,toBridge:this.toBridge}),this.updateDestination(this.path,this.targetOffset),this.targetLinesConfig.isRecalc=!this.targetChangeRequested,this.targetChangeRequested=!1,this.needsPathUpdate=!1,this.allObstaclesAreBlockers=!1);let i=this.game.map;if(r.moveTrait.moveState===Hr.ReachedNextWaypoint){r.moveTrait.unreservePathNodes();var t=this.path.findIndex(e=>e===r.moveTrait.currentWaypoint);if(-1!==t?this.path.splice(t):this.path.pop(),r.moveTrait.currentWaypoint=void 0,this.isCancelling()?!this.cancelProcessed:this.hasReachedDestination(r)){var a=!this.isCancelling()&&!this.isCloseEnoughToDest(r,r.tile,this.options?.closeEnoughTiles);if(!a&&this.canStopAtTile(r,r.tile,r.onBridge))return r.moveTrait.lastMoveResult=this.isCancelling()?Gr.Cancel:Gr.Success,!0;{if(5<this.unreachableTargets.length)return r.moveTrait.lastMoveResult=Gr.Fail,this.log(r,"bail_max_unreachable_dest"),!0;let e=r.tile,t=r.onBridge?i.tileOccupation.getBridgeOnTile(e):void 0;a&&(e=this.targetTile,t=this.toBridge?i.tileOccupation.getBridgeOnTile(e):void 0);var n=this.findRelocationTile(e,t,r);if(!n)return r.moveTrait.lastMoveResult=a?Gr.Fail:Gr.CloseEnough,this.log(r,"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 r.moveTrait.lastMoveResult=Gr.Cancel,!0;this.cancelProcessed=!1,r.moveTrait.moveState=Hr.PlanMove;let e=r.moveTrait.locomotor;r.moveTrait.currentWaypoint=e.selectNextWaypoint?e.selectNextWaypoint(r,this.path):this.path[this.path.length-1],this.currentWaypointLeptons.set(r.moveTrait.currentWaypoint.tile.rx,r.moveTrait.currentWaypoint.tile.ry).multiplyScalar(Ss.LEPTONS_PER_TILE).add(this.targetOffset);n=e.onNewWaypoint(r,this.currentWaypointLeptons,this.destinationLeptons);if(n)return this.children.push(...n),!1}if(r.moveTrait.moveState===Hr.PlanMove){if(this.isCancelling()&&!this.cancelRepositionPending)return r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r);if(this.inPlanningForTicks=void 0===this.inPlanningForTicks?0:this.inPlanningForTicks+1,200<this.inPlanningForTicks)return this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,r.moveTrait.velocity.set(0,0,0),this.log(r,"repath_plan_timeout"),!1;if(r.rules.movementZone!==ii.Fly&&!r.moveTrait.locomotor.ignoresTerrain){let t=this.path.slice(this.path.indexOf(r.moveTrait.currentWaypoint)).reverse();var s,e,o=r.moveTrait.velocity.length();for(s of t){if(!i.terrain.getPassableSpeed(s.tile,r.rules.speedType,!!s.onBridge,this.options?.ignoredBlockers))return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r);if(!s.onBridge){var h=i.getGroundObjectsOnTile(s.tile).find(e=>e.isOverlay()&&e.rules.crate);if(h)if(this.game.crateGeneratorTrait.peekInsideCrate(h)===Cs.Unit){this.game.crateGeneratorTrait.pickupCrate(r,h,this.game);h=this.game.map.getGroundObjectsOnTile(s.tile).find(e=>e.isUnit()&&!e.onBridge);if(h)return this.needsPathUpdate=!0,this.blockedPathNodes.push({node:s,obj:h}),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r)}}for(e of i.terrain.findObstacles(s,r).filter(e=>!this.options?.ignoredBlockers?.includes(e.obj))){if(e.static)return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r);if(e.obj.rules.crushable){if(!(r.rules.speedType!==Kt.Track||!r.crusher||e.obj.isTechno()&&this.game.areFriendly(e.obj,r)))continue;if(!e.obj.isTechno())return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r)}if(e.obj.isTerrain()){if(!r.isInfantry())throw new Error(`Obstacle ${e.obj.name} should be a blocker for non infantry`);var l=this.findFreeSubCell(r,s);return void 0!==l?this.relocateToSubCell(r,l):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:s,obj:e.obj}),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint),this.onTick(r)}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!==Ts.Ground||!this.options?.ignoredBlockers?.some(e=>e.isBuilding()&&e.dockTrait?.isDocked(m))){if(1===t.length&&m.isUnit()&&c&&o&&o<=c&&r.direction===m.direction&&m.tile===s.tile&&m.moveTrait.currentWaypoint?.tile!==s.tile)break;if(m.isBuilding()||m.moveTrait.moveState===Hr.Idle||m.moveTrait.collisionState!==$r.Resolved){if(!o&&r.moveTrait.collisionState!==$r.Resolved&&m.isUnit()&&m.moveTrait.collisionState!==$r.Resolved)return 200<this.inPlanningForTicks+1&&(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(r,"repath_waited_too_long_blocker "+m.id),r.moveTrait.velocity.set(0,0,0)),!1;{if(m.isInfantry()&&r.isInfantry()&&m.moveTrait.collisionState===$r.Resolved){var u=this.findFreeSubCell(r,s);if(void 0!==u)return this.relocateToSubCell(r,u),this.onTick(r)}l=Hs(this.path.slice(0,this.path.indexOf(s)),e=>!i.terrain.findObstacles(e,r).length);if(-1===l){if(this.canStopAtTile(r,r.tile,r.onBridge)&&this.isCloseEnoughToDest(r,r.tile,this.options?.closeEnoughTiles))return r.moveTrait.lastMoveResult=Gr.CloseEnough,this.log(r,"bail_waypoints_blocked_close_enough"),!0;if(!(0===this.options?.closeEnoughTiles||Math.abs(r.tile.rx-this.targetTile.rx)<=1&&Math.abs(r.tile.ry-this.targetTile.ry)<=1))return this.needsPathUpdate=!0,this.blockedPathNodes.push(...this.path.slice(0,this.path.indexOf(s)+1).map(e=>({node:e,obj:i.terrain.findObstacles(e,r)[0].obj}))),r.moveTrait.velocity.set(0,0,0),this.log(r,"repath_waypoints_blocked_too_far"),!1}let e;if(e=-1!==l?(u=this.path[l],i.terrain.computePath(r.rules.speedType,r.tile,r.onBridge,u.tile,!!u.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:e=>!!i.terrain.findObstacles(e,r).length})):[],e.length||m.owner!==r.owner||1!==t.length)return e.length?(this.path.splice(l,this.path.length,...e),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r)):((d=this.selectWeaponVsObstacle(r,m))?(this.children.push(r.attackTrait.createAttackTask(this.game,m,m.tile,d,{passive:!0,holdGround:!0})),r.moveTrait.velocity.set(0,0,0)):this.options?.forceWaitOnPathBlocked&&1===t.length?(this.children.push(new Gs(40)),this.inPlanningForTicks=0,r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=$r.Waiting):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:s,obj:m}),m.isBuilding()&&(this.allObstaclesAreBlockers=!0),this.log(r,"repath_unavoidable_blocker "+m.id),r.moveTrait.velocity.set(0,0,0)),!1);d=m.unitOrderTrait.hasTasks();if(this.pushTried||m.isBuilding()||m.moveTrait.collisionState===$r.Waiting||d||m.isAircraft()&&m.missileSpawnTrait)return!this.options?.forceWaitOnPathBlocked&&(m.isBuilding()||d&&m.moveTrait.moveState===Hr.Idle||200<this.inPlanningForTicks+40)?(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(r,"repath_blocker_busy_wait_timeout "+m.id),r.moveTrait.velocity.set(0,0,0)):(this.children.push(new Gs(40)),this.options?.forceWaitOnPathBlocked?this.inPlanningForTicks=0:this.inPlanningForTicks+=40,r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=$r.Waiting),!1;var d,d=new vs(m.tile.rx-r.tile.rx,m.tile.ry-r.tile.ry);return this.pushTried=!0,m.unitOrderTrait.addTask(new mr(this.game,d)),this.children.push(new Gs(1)),r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=$r.Waiting,this.log(r,"push "+m.id),!1}}if(!o)return 40<this.inPlanningForTicks&&(r.moveTrait.collisionState=$r.Waiting),!1;if(180===Math.abs(r.direction-m.direction))return r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=$r.Waiting,!1;if(Math.abs(r.direction-m.direction)<=45&&1.5*c<o){c=this.path.indexOf(s);if(5<=c){let e=Hs(this.path.slice(0,c-5),e=>!i.terrain.findObstacles(e,r).length);if(-1!==e){c=this.path[e],c=i.terrain.computePath(r.rules.speedType,r.tile,r.onBridge,c.tile,!!c.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:t=>!!i.terrain.findObstacles(t,r).length||this.path.findIndex(e=>e.tile===t.tile&&e.onBridge===t.onBridge)>e});if(c.length)return this.path.splice(e,this.path.length,...c),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r)}}return r.moveTrait.collisionState=$r.Waiting,r.moveTrait.velocity.set(0,0,0),!1}return r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=$r.Waiting,!1}}}if(r.rules.speedType===Kt.Track&&o){var p,g=this.path.indexOf(r.moveTrait.currentWaypoint);if(0<g){let t=this.path[g-1];for(p of i.getGroundObjectsOnTile(t.tile).filter(e=>e.isUnit()&&e.onBridge===!!t.onBridge&&e.rules.crushable&&e.veteranTrait?.hasVeteranAbility(oi.SCATTER)&&!this.game.areFriendly(e,r)))p.unitOrderTrait.hasTasks()||p.unitOrderTrait.addTask(new Ta(this.game))}}r.moveTrait.reservedPathNodes.length||(r.moveTrait.reservedPathNodes.push(...t),t.forEach(e=>{i.tileOccupation.occupySingleTile(e.tile,r)}))}r.moveTrait.moveState=Hr.Moving,this.inPlanningForTicks=void 0,this.unreachableTargets.length=0,this.pushTried=!1,r.moveTrait.collisionState===$r.Waiting&&(r.moveTrait.collisionState=$r.Resolved)}if(r.moveTrait.moveState===Hr.Moving){let e=r.moveTrait.locomotor,{distance:t,done:i,isTeleport:s}=e.tick(r,this.currentWaypointLeptons,this.destinationLeptons,(this.isCancelling()||!this.path.length)&&!this.cancelRepositionPending);if(s&&r.traits.filter(jr).forEach(e=>{e[jr.onBeforeTeleport](r,this.game,!0,!0)}),t.length()){a=r.tile,n=e.allowOutOfBounds;if(t.y?r.position.moveByLeptons3(t,n):r.position.moveByLeptons(t.x,t.z,n),r.tile!==a){g=r.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===r.tile),g=n?n.onBridge:g||r.moveTrait.currentWaypoint.onBridge?this.game.map.tileOccupation.getBridgeOnTile(r.tile):void 0;if(r.moveTrait.handleTileChange(a,g,!1,this.game,s),s&&(r.moveTrait.lastTeleportTick=this.game.currentTick,this.game.events.dispatch(new ya(r,!0,a))),r.isDestroyed)return!0}}if(i)return r.moveTrait.moveState=Hr.ReachedNextWaypoint,this.onTick(r)}return!1}selectWeaponVsObstacle(e,t){let i;if(!this.game.areFriendly(t,e)&&e.attackTrait&&!e.attackTrait.isDisabled()&&e.attackTrait.isIdle()&&(i=e.attackTrait.selectWeaponVersus(e,t,this.game,!1,!0))&&i.name!==e.armedTrait?.deathWeapon?.name&&(!i.rules.limboLaunch||!i.warhead.rules.parasite)&&!i.warhead.rules.mindControl)return i}findRelocationTile(s,r,a){let n=this.game.map,i;if(a.rules.movementZone===ii.Fly){let e=new fa(n.tiles,n.mapBounds,s,1,this.game,e=>!0);i=e.getNextTile()}else{let e=new $s(n),t=new Fs(n.tiles,n.mapBounds,s,{width:1,height:1},0,5,t=>{let i=!r||r.isHighBridge()?n.tileOccupation.getBridgeOnTile(t):void 0;return!this.unreachableTargets.find(e=>e.tile===t&&e.toBridge===!!i)&&(a.zone===Ts.Air||!n.terrain.findObstacles({tile:t,onBridge:i},a).length&&e.isEligibleTile(t,i,r,s))&&this.canStopAtTile(a,t,!!i)});i=t.getNextTile()}return i}findFreeSubCell(t,i){let e=this.game.map.getGroundObjectsOnTile(i.tile);var s=e.filter(e=>e.isInfantry()&&e.onBridge===!!i.onBridge&&e!==t).map(e=>e.position.desiredSubCell),r=e.filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(this.game.map.getTheaterType())).flat();let a=[...s,...r];return Na.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(Ss.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 ma(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}`)}}(Ur=Ur||{}).onDestroy=Symbol(),(r=Wr=Wr||{})[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Demolish=2]="Demolish",r[r.Crush=3]="Crush",r[r.Temporal=4]="Temporal",r[r.Sink=5]="Sink",(zr=zr||{}).onTileChange=Symbol(),(Vr=Vr||{}).onTileChange=Symbol();class va{constructor(e,t){this.target=e,this.source=t,this.type=ts.EnterTile}}(r=Hr=Hr||{})[r.Idle=0]="Idle",r[r.ReachedNextWaypoint=1]="ReachedNextWaypoint",r[r.PlanMove=2]="PlanMove",r[r.Moving=3]="Moving",(r=Gr=Gr||{})[r.Success=0]="Success",r[r.Cancel=1]="Cancel",r[r.CloseEnough=2]="CloseEnough",r[r.Fail=3]="Fail",(r=$r=$r||{})[r.Waiting=0]="Waiting",r[r.Resolved=1]="Resolved";const Sa=e=>e instanceof ba||e.children[0]&&Sa(e.children[0]);class _a{constructor(e,t){this.gameObject=e,this.tileOccupation=t,this.disabled=!1,this.speedPenalty=0,this.velocity=new is,this.reservedPathNodes=[],this.moveState=Hr.Idle,this.collisionState=$r.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===Hr.Moving}isIdle(){return this.moveState===Hr.Idle}isWaiting(){return this.collisionState===$r.Waiting}[Mr.onTick](e,t){var i;this.moveState!==Hr.Idle&&this.collisionState===$r.Resolved&&((i=e.unitOrderTrait.getCurrentTask())&&Sa(i)||(this.velocity.set(0,0,0),this.moveState=Hr.Idle,this.locomotor=void 0,!i&&!e.attackTrait?.currentTarget&&e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction))),this.moveState===Hr.Idle&&(e.rules.locomotor===ti.Jumpjet?Rr.tickStationary(e,t):e.isAircraft()&&e.rules.locomotor===ti.Aircraft&&ga.tickStationary(e,t))}[Ur.onDestroy](e,t){this.unreservePathNodes()}teleportUnitToTile(e,t,i,s,r){let a=this.gameObject;var n=a.tile;a.traits.filter(jr).forEach(e=>{e[jr.onBeforeTeleport](a,r,i,s)}),a.position.tileElevation=a.tileElevation,a.position.tile=e,a.position.subCell=a.position.desiredSubCell,this.handleTileChange(n,t,!0,r,!0),s||(this.unreservePathNodes(),this.speedPenalty=0,this.velocity.set(0,0,0),this.moveState=Hr.Idle,this.collisionState=$r.Resolved,this.locomotor=void 0,this.currentWaypoint=void 0,this.lastTargetOffset=void 0,this.lastVelocity=void 0,this.lastMoveResult=Gr.Cancel,a.isVehicle()&&(a.spinVelocity=0,a.turretTrait&&(a.turretTrait.desiredFacing=a.direction))),this.lastTeleportTick=r.currentTick,r.events.dispatch(new ya(a,i,n))}handleTileChange(t,e,i,s,r=!1){const a=this.gameObject;if(s.map.tileOccupation.unoccupyTileRange(t,a),s.map.tileOccupation.occupyTileRange(a.tile,a),s.map.technosByTile.updateObject(a),a.zone!==Ts.Air){var n=a.onBridge?s.map.tileOccupation.getBridgeOnTile(t):void 0,o=a.onBridge?t.onBridgeLandType:t.landType,h=e?a.tile.onBridgeLandType:a.tile.landType;o!==h&&(0<s.rules.getLandRules(h).getSpeedModifier(a.rules.speedType)||a.rules.speedType===Kt.Amphibious||r)&&(a.zone=_s(h)),e!==n&&(a.position.tileElevation+=-(n?.tileElevation??0)+(e?.tileElevation??0),a.onBridge=!!e);var l,e=a.moveTrait.reservedPathNodes.findIndex(e=>e.tile===a.tile&&!!e.onBridge===a.onBridge);if(-1!==e&&a.moveTrait.reservedPathNodes.splice(e,1),a.crusher)for(l of s.map.getGroundObjectsOnTile(a.tile).filter(e=>(!e.isUnit()||e.onBridge===a.onBridge)&&e.rules.crushable&&!(e.isInfantry()&&e.stance===Ds.Paradrop)&&(!(e.isTechno()&&!i)||!s.areFriendly(e,a))))l.isDestroyed||(l.isInfantry()&&(l.infDeathType=Jt.None),a.isVehicle()&&l.isOverlay()&&l.rules.wall&&a.applyRocking(0,.5),l.deathType=Wr.Crush,s.destroyObject(l,{player:a.owner,obj:a}));a.onBridge||(e=s.map.tileOccupation.getGroundObjectsOnTile(a.tile).find(e=>e.isOverlay()&&e.rules.crate))&&s.crateGeneratorTrait.pickupCrate(a,e,s)}s.traits.filter(zr).forEach(e=>{e[zr.onTileChange](a,s,t,r)}),a.traits.filter(Vr).forEach(e=>{e[Vr.onTileChange](a,s,t,r)}),s.events.dispatch(new va(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 ka{constructor(){this.suppressionTicks=0,this.enabled=!0}disable(){this.enabled=!1}isSuppressed(){return this.enabled&&0<this.suppressionTicks}supress(){this.enabled&&(this.suppressionTicks=30)}[Mr.onTick](){0<this.suppressionTicks&&this.suppressionTicks--}}class Oa{constructor(){this.allTraits=[],this.traitsByTypeCache=new Map}add(e){this.allTraits.push(e),this.traitsByTypeCache.clear()}addToFront(e){this.allTraits.unshift(e),this.traitsByTypeCache.clear()}remove(e){e=this.allTraits.indexOf(e);-1!==e&&(this.allTraits.splice(e,1),this.traitsByTypeCache.clear())}filter(t){let e=this.traitsByTypeCache.get(t);return e||(e="function"==typeof t?this.allTraits.filter(e=>e instanceof t):this.allTraits.filter(e=>this.traitImplements(e,t)),this.traitsByTypeCache.set(t,e)),e}get(e){e=this.find(e);if(!e)throw new Error("No matching trait found");return e}find(e){return this.filter(e)[0]}getAll(){return this.allTraits}traitImplements(e,t){for(var i of Object.getOwnPropertyNames(t))if(void 0===e[t[i]])return!1;return!0}clear(){this.allTraits.length=0,this.traitsByTypeCache.clear()}dispose(){this.getAll().forEach(e=>e.dispose?.()),this.clear()}}(qr=qr||{}).onChange=Symbol(),(Xr=Xr||{}).onSpawn=Symbol(),(Qr=Qr||{}).onUnspawn=Symbol(),(Zr=Zr||{}).onAttack=Symbol();class Ia{constructor(e,t,i,s){this.traits=new Oa,this.cachedTraits={tick:[]},this.isCrashing=!1,this.isDestroyed=!1,this.deathType=Wr.Normal,this.isDisposed=!1,this.isSpawned=!1,this.type=e,this.name=t,this.rules=i,this.art=s}get tile(){return this.position.tile}get tileElevation(){return this.position.tileElevation}getFoundation(){return{width:1,height:1}}isSmudge(){return this.type===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[Mr.onTick](this,e)}onSpawn(t){this.isSpawned=!0,this.traits.filter(Xr).forEach(e=>{e[Xr.onSpawn](this,t)})}onUnspawn(t){this.isSpawned=!1,this.traits.filter(Qr).forEach(e=>{e[Qr.onUnspawn](this,t)})}onDestroy(t,i,s){this.traits.filter(Ur).forEach(e=>{e[Ur.onDestroy](this,t,i,s)})}onOwnerChange(t,i){this.traits.filter(qr).forEach(e=>{e[qr.onChange](this,t,i)})}onAttack(t,i){this.traits.filter(Zr).forEach(e=>{e[Zr.onAttack](this,i,t)})}addTrait(e){this.traits.add(e),e[Mr.onTick]&&this.cachedTraits.tick.push(e)}getUiName(){return this.rules.uiName}getHash(){var e=this.position.worldPosition;return V([this.id,...new Uint8Array(new Float64Array([e.x,e.y,e.z]).buffer),...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{id:this.id,position:this.position.worldPosition.toArray(),traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.isDisposed=!0,this.traits.dispose(),this.cachedTraits.tick.length=0}}(r=Yr=Yr||{})[r.None=0]="None",r[r.Veteran=1]="Veteran",r[r.Elite=2]="Elite";class Aa extends Ia{constructor(e,t,i,s){super(e,t,i,s),this.explodes=this.rules.explodes,this.radarInvisible=this.rules.radarInvisible,this.c4=this.rules.c4,this.crusher=this.rules.crusher,this.defaultToGuardArea=this.rules.defaultToGuardArea,this.guardMode=this.rules.defaultToGuardArea,this.purchaseValue=this.rules.cost}get primaryWeapon(){return this.armedTrait?.primaryWeapon}get secondaryWeapon(){return this.armedTrait?.secondaryWeapon}get ammo(){return this.ammoTrait?.ammo}get sight(){return Math.min(as.MAX_SIGHT,this.rules.sight*(this.veteranTrait?.getVeteranSightMultiplier()??1))}get veteranLevel(){return this.veteranTrait?.veteranLevel??Yr.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[Mr.onTick](this,e);else super.update(e)}isTechno(){return!0}}class Ca{constructor(){this.cooldownTicks=Number.POSITIVE_INFINITY,this._actionDueThisTick=!1}[Mr.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 Ta(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*Ls.BASE_TICKS_PER_SECOND)}}class Ba{constructor(e){this.gameObject=e,this.type=ts.ObjectCrashing}}(Kr=Kr||{}).onCrash=Symbol();class xa{constructor(e){this.gameObject=e,this.crashingEvtSent=!1,this.crashState={}}[Mr.onTick](i,s){if(i.isCrashing){if(this.crashingEvtSent||(this.crashingEvtSent=!0,i.traits.filter(Kr).forEach(e=>e[Kr.onCrash](i,s)),s.events.dispatch(new Ba(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=Rr.tickCrash(i,s,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=ga.tickCrash(i,s,this.crashState)}let t=!1;var r,a=e.clone().add(i.position.worldPosition);s.map.isWithinHardBounds(a)?(r=i.tile,i.position.moveByLeptons3(e),i.tile!==r&&i.moveTrait.handleTileChange(r,void 0,!1,s),r=(a=i.tile.onBridgeLandType?s.map.tileOccupation.getBridgeOnTile(i.tile):void 0)?.tileElevation??0,i.position.tileElevation=Math.max(i.position.tileElevation,r),i.position.tileElevation===r&&(i.zone=s.map.getTileZone(i.tile),i.onBridge=!!a,t=!0)):t=!0,t&&s.destroyObject(i,this.attackerInfo)}}}crash(e){this.attackerInfo=e,this.gameObject.isCrashing=!0,this.gameObject.cachedTraits.tick.length=0,this.gameObject.cachedTraits.tick=[this]}dispose(){this.gameObject=void 0}}class Ea{infiltrate(e,t,i){var s;t.rules.radar&&![...t.owner.buildings].some(e=>e.rules.spySat)&&i.mapShroudTrait.resetShroud(t.owner,i),0<t.rules.power&&(s=i.rules.general.spyPowerBlackout,t.owner.powerTrait?.setBlackoutFor(s,i)),t.superWeaponTrait&&t.superWeaponTrait.getSuperWeapon(t)?.resetTimer(),0<t.rules.storage&&(s=U(i.rules.general.spyMoneyStealPercent,0,1),s=Math.floor(t.owner.credits*s),t.owner.credits-=s,e.owner.credits+=s),!i.rules.ai.buildTech.includes(t.name)||void 0!==(i=t.rules.aiBasePlanningSide)&&e.owner.production.addStolenTech(i),[Ki.InfantryType,Ki.UnitType].includes(t.factoryTrait?.type)&&e.owner.production?.addVeteranType(t.factoryTrait.type)}}class Pa{constructor(){this.firepower=1,this.armor=1,this.speed=1}}class Na extends Aa{constructor(e,t,i){super(Ct.Infantry,e,t,i),this.direction=0,this.onBridge=!1,this.zone=Ts.Ground,this._stance=Ds.None,this.isFiring=!1,this.isPanicked=!1,this.infDeathType=Jt.Gunfire,this.crateBonuses=new Pa}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s){let r=new this(e,t,i);return r.moveTrait=new _a(r,s),r.traits.add(r.moveTrait),r.rules.crashable&&(r.crashableTrait=new xa(r),r.traits.add(r.crashableTrait)),r.rules.proneWhenAttacked&&(r.suppressionTrait=new ka,r.traits.add(r.suppressionTrait)),r.rules.agent&&(r.agentTrait=new Ea,r.traits.add(r.agentTrait)),r.idleActionTrait=new Ca,r.traits.add(r.idleActionTrait),r}get stance(){return this._stance===Ds.None&&this.suppressionTrait?.isSuppressed()?Ds.Prone:this._stance}set stance(e){this._stance=e,this.moveTrait.setDisabled([Ds.Deployed,Ds.Cheer].includes(e)),this.attackTrait?.setDisabled([Ds.Paradrop,Ds.Cheer].includes(e))}isUnit(){return!0}isInfantry(){return!0}}Na.SUB_CELLS=[2,4,3];class Ra extends Vs{constructor(e){super(),this.game=e}onTick(e){var t=Math.abs(this.game.rules.general.parachuteMaxFallRate),i=e.tile.onBridgeLandType?this.game.map.tileOccupation.getBridgeOnTile(e.tile).tileElevation:0,s=Ss.tileHeightToWorld(i),r=Ss.tileHeightToWorld(e.tileElevation);return s<Math.max(s,r-t)?(e.position.moveByLeptons3(new is(0,-t,0)),!1):(e.position.tileElevation=i,e.stance=Ds.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 Da(i,s,r,a,n){let o=[];n=n||((e,t)=>{o.push({x:e,y:t})});var e=r-i,t=a-s,h=Math.abs(e),l=Math.abs(t);let c=0;var u=0<e?1:-1,d=0<t?1:-1;if(l<h)for(let e=i,t=s;u<0?e>=r:e<=r;e+=u)n(e,t),c+=l,c<<1>=h&&(t+=d,c-=h);else for(let e=i,t=s;d<0?t>=a:t<=a;t+=d)n(e,t),c+=h,c<<1>=l&&(e+=u,c-=l);return o}function Ma(e){return null!=e}class La extends Vs{constructor(...e){super(),this.children.push(...e)}onTick(e){return!0}}class Fa{constructor(){this.enabled=!0}setEnabled(e){this.enabled=e}[Mr.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 La(new ba(t,i,!1,{allowOutOfBoundsTarget:!0}),new da(e=>t.unspawnObject(e))).setCancellable(!1)))}chooseExitTile(e,t){var i=t.map.tiles.getMapSize(),i=.5<t.generateRandom()?new vs(Math.floor(i.width/2),0):new vs(0,Math.floor(i.height/2)),e=new vs(e.rx,e.ry),i=Da(e.x,e.y,i.x,i.y).map(e=>t.map.tiles.getByMapCoords(e.x,e.y)).filter(Ma);if(!i.length)throw new Error("No valid exit tile found");return i[i.length-1]}}(r=Jr=Jr||{})[r.Spawning=0]="Spawning",r[r.EnRoute=1]="EnRoute",r[r.Dropping=2]="Dropping",r[r.TurningAround=3]="TurningAround";const ja=5*Ls.BASE_TICKS_PER_SECOND;class Ua extends Ws{constructor(e,t,i,s,r){super(e,t,i),this.paradropSquad=s,this.state=Jr.Spawning,this.spawnDelay=r*ja}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 s=e.clone().sub(t);e=i.rules.general.paradrop.paradropRadius/Ss.LEPTONS_PER_TILE,e=t.clone().add(s.clone().setLength(s.length()+2*e)).floor();let r=Da(t.x,t.y,e.x,e.y).map(e=>i.map.tiles.getByMapCoords(e.x,e.y)??i.map.tiles.getPlaceholderTile(e.x,e.y));for(;r.length;){var a=r[0],a=Ss.tileToWorld(a.rx+.5,a.ry+.5);if(i.map.isWithinHardBounds(new vs(a.x,a.y)))break;r.shift()}if(!r.length)throw new Error("No valid paradrop path found");return{fromTile:r[0],toTile:r[r.length-1]}}onTick(r){if(this.state===Jr.Spawning){if(0<this.spawnDelay)return this.spawnDelay--,!1;var a=r.map.tiles.getMapSize(),n=[new vs(0,0),new vs(Math.floor(a.width/2),0),new vs(0,Math.floor(a.height/2))][r.generateRandomInt(0,2)];let t=this.passengerRules.speedType,e=new Fs(r.map.tiles,r.map.mapBounds,this.tile,{width:1,height:1},0,50,e=>0<r.map.terrain.getPassableSpeed(e,t,!!e.onBridgeLandType));var o=this.targetTile=e.getNextTile();if(!o)return!0;let i=new vs(o.rx,o.ry);var{fromTile:h,toTile:a}=this.computeFlightPath(i,n,r),o=r.rules.general.paradrop.paradropPlane,n=r.rules.getObject(o,Ct.Aircraft);let s=this.pdPlane=r.createUnitForPlayer(n,this.owner);r.spawnObject(s,h),s.direction=wr.fromMapCoords(i.clone().sub(new vs(h.rx,h.ry))),s.position.tileElevation=Ss.worldToTileHeight(s.rules.flightLevel??r.rules.general.flightLevel),s.zone=Ts.Air,s.onBridge=!1,s.unitOrderTrait.addTask(new ba(r,a,!1,{allowOutOfBoundsTarget:!0})),s.traits.get(Fa).setEnabled(!1),this.state=Jr.EnRoute}if(!this.pdPlane||this.pdPlane.isDestroyed||this.pdPlane.isCrashing)return!0;o=this.targetTile;if(!this.pdPlane.unitOrderTrait.hasTasks())return this.state=Jr.TurningAround,this.pdPlane.unitOrderTrait.addTask(new ba(r,o,!1,{allowOutOfBoundsTarget:!0})),!1;n=r.rules.general.paradrop.paradropRadius/Ss.LEPTONS_PER_TILE;let e=new Is(r.map.tileOccupation);h=e.isInTileRange(this.pdPlane.tile,o,0,n);if(this.state===Jr.EnRoute&&h&&(this.state=Jr.Dropping),this.state===Jr.Dropping)if(h&&0<this.passengerCount){a=this.pdPlane.tile;let t=!!a.onBridgeLandType;if(!r.map.terrain.getPassableSpeed(a,this.passengerRules.speedType,t))return!1;let e=r.map.getGroundObjectsOnTile(a);if(e.some(e=>e.isVehicle()&&e.onBridge===t||e.isBuilding()&&!e.isDestroyed||e.isInfantry()&&e.stance===Ds.Paradrop))return!1;n=this.findFreeSubCell(r,a);if(!n)return!1;this.passengerCount--;let i=r.createUnitForPlayer(this.passengerRules,this.owner);i.stance=Ds.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(Yr.Veteran),r.spawnObject(i,a),i.unitOrderTrait.addTask(new Ra(r).setCancellable(!1))}else{if(!(0<this.passengerCount))return this.pdPlane.unitOrderTrait.getCurrentTask().forceCancel(this.pdPlane),this.pdPlane.traits.get(Fa).setEnabled(!0),!0;this.state=Jr.TurningAround,this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!!o.onBridgeLandType)}return this.state===Jr.TurningAround&&h&&(o=this.computeFlightPath(new vs(o.rx,o.ry),new vs(this.pdPlane.tile.rx,this.pdPlane.tile.ry),r)["toTile"],this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!1),this.state=Jr.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=Na.SUB_CELLS.filter(e=>-1===i.indexOf(e));if(e.length)return 1<e.length?e[t.generateRandomInt(0,e.length-1)]:e[0]}}(r=ea=ea||{})[r.NotBridge=0]="NotBridge",r[r.Concrete=1]="Concrete",r[r.Wood=2]="Wood";class Wa{static getOverlayBridgeType(e){return W(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)||W(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)?ea.Concrete:W(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||W(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)?ea.Wood:ea.NotBridge}static isBridge(e){return this.isHighBridge(e)||this.isLowBridge(e)}static isBridgePlaceholder(e){return this.bridgePlaceholderIds.includes(e)}static isHighBridge(e){return W(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||W(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)}static isLowBridge(e){return W(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)||W(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)}static isXBridge(e){return e===this.minHighBridgeWoodId||e===this.minHighBridgeConcreteId||W(e,this.minLowBridgeWoodId,this.minLowBridgeWoodId+8)||W(e,this.minLowBridgeWoodId+18,this.minLowBridgeWoodId+21)||W(e,this.minLowBridgeConcreteId,this.minLowBridgeConcreteId+8)||W(e,this.minLowBridgeConcreteId+18,this.minLowBridgeConcreteId+21)}static isLowBridgeHead(e){return W(e,this.minLowBridgeWoodId+18,this.minLowBridgeWoodId+25)||W(e,this.minLowBridgeConcreteId+18,this.minLowBridgeConcreteId+25)}static isLowBridgeHeadStart(e){return W(e,this.minLowBridgeWoodId+20,this.minLowBridgeWoodId+23)||W(e,this.minLowBridgeConcreteId+20,this.minLowBridgeConcreteId+23)}static calculateLowBridgeOverlayId(e,t){let i;if(e===ea.Concrete)i=this.minLowBridgeConcreteId;else{if(e!==ea.Wood)throw new Error("Not implemented");i=this.minLowBridgeWoodId}return i+(t?0:9)}static calculateHighBridgeOverlayId(e,t){let i;if(e===ea.Concrete)i=this.minHighBridgeConcreteId;else{if(e!==ea.Wood)throw new Error("Not implemented");i=this.minHighBridgeWoodId}return i+(t?0:1)}}Wa.minLowBridgeWoodId=74,Wa.maxLowBridgeWoodId=99,Wa.minLowBridgeConcreteId=205,Wa.maxLowBridgeConcreteId=230,Wa.minHighBridgeConcreteId=24,Wa.maxHighBridgeConcreteId=25,Wa.minHighBridgeWoodId=237,Wa.maxHighBridgeWoodId=238,Wa.bridgePlaceholderIds=[100,101,231,232],(ta=ta||{}).onAttack=Symbol(),(r=ia=ia||{})[r.None=0]="None",r[r.Ground=1]="Ground",r[r.Wall=2]="Wall",r[r.Cliff=3]="Cliff",r[r.OnBridge=4]="OnBridge",r[r.UnderBridge=5]="UnderBridge",r[r.Shore=6]="Shore";class za{constructor(e,t,i,s){this.target=e,this.position=t,this.explodeAnim=i,this.isLightningStrike=s,this.type=ts.WarheadDetonate}}(r=sa=sa||{})[r.Top=0]="Top",r[r.TopLeft=1]="TopLeft",r[r.TopRight=2]="TopRight",r[r.Left=3]="Left",r[r.Right=4]="Right",r[r.BottomLeft=5]="BottomLeft",r[r.Bottom=6]="Bottom",r[r.BottomRight=7]="BottomRight";class Va{constructor(i,s,e,r){this.tileSets=s,this.generalRules=e;let a=this.rSize={width:0,height:0},n=this.dSize={width:0,height:0};for(let e=0,t=i.length;e<t;++e)a.width=Math.max(a.width,i[e].rx),a.height=Math.max(a.height,i[e].ry),n.width=Math.max(n.width,i[e].dx),n.height=Math.max(n.height,i[e].dy);a.width++,a.height++,n.width++,n.height++;let o=this.tilesByRxy=new Array(a.width*a.height);o.fill(void 0);let h=this.tilesByDxy=new Array(n.width*n.height);h.fill(void 0);let l=this.tiles=new Array(i.length),c=[],u=this.bridgeSetTiles=[],d=new Set(Object.values(Zt));this.minTileHeight=Number.POSITIVE_INFINITY;for(let e=this.maxTileHeight=0,t=i.length;e<t;++e){var p=i[e],g=s.getTileImage(p.tileNum,p.subTile,r),m=g.terrainType;if(!d.has(m))throw new Error(`Tile (${p.rx}, ${p.ry}) has unknown terrain type "${m}"`);var f={...p,terrainType:m,landType:Vi(m),onBridgeLandType:void 0,rampType:g.rampType,id:p.rx+"_"+p.ry,occluded:!1},y=f.rx,w=f.ry,m=f.dx,g=f.dy;l[e]=f,o[y+w*a.width]=f,h[m+g*n.width]=f,this.minTileHeight=Math.min(this.minTileHeight,f.z),this.maxTileHeight=Math.max(this.maxTileHeight,f.z),f.terrainType!==Zt.Cliff&&!s.isCliffTile(f.tileNum)||c.push(f),s.isHighBridgeBoundaryTile(p.tileNum)&&u.push(f)}this.computeLandBehindCliffTiles(c),this.cutoffTileHeight=Math.max(9,this.computeCutoffTileHeight())}computeLandBehindCliffTiles(e){e.forEach(i=>{var s=this.generalRules.cliffBackImpassability;for(let t=0;t<=s;t++)for(let e=0;e<=s;e++)if(t||e){const r=this.getByMapCoords(i.rx-t,i.ry-e);r&&1<=t&&t===e&&r.z<i.z&&0===r.rampType&&([[1,0],[0,1]].some(([e,t])=>{t=this.getByMapCoords(r.rx-e,r.ry-t);return t?.terrainType===Zt.Cliff&&t.z===r.z})||(r.landType=Yt.Rock))}})}getTileRadarColor(e){let t=this.tileSets.getTileImage(e.tileNum,e.subTile,()=>0);return t.radarLeft.clone().multiplyScalar(.5)}getAll(){return[...this.tiles]}forEach(i){for(let e=0,t=this.tiles.length;e<t;++e)i(this.tiles[e],e)}reduce(t,e){let i=e;return this.forEach(e=>{i=t(i,e)}),i}getMinTileHeight(){return this.minTileHeight}getMaxTileHeight(){return this.maxTileHeight}getCutoffTileHeight(){return this.cutoffTileHeight}computeCutoffTileHeight(){var t=this.dSize.width-1;let i=this.dSize.height-1,s=0,r=!0;for(;r&&0<i;){for(let e=1;e<t-3;e++){var a=this.getByDisplayCoords(e,i);a&&(r=!1,a.z>s&&(s=a.z))}r&&i--}return s}getAllBridgeSetTiles(){return this.bridgeSetTiles}getAllNeighbourTiles(e){var t=e.rx,e=e.ry;return[this.getByMapCoords(t+1,e+1),this.getByMapCoords(t-1,e-1),this.getByMapCoords(t-1,e+1),this.getByMapCoords(t+1,e-1),this.getByMapCoords(t,e+1),this.getByMapCoords(t+1,e),this.getByMapCoords(t-1,e),this.getByMapCoords(t,e-1)].filter(Ma)}getNeighbourTile(e,t){var i=e.rx,s=e.ry;switch(t){case sa.Bottom:return this.getByMapCoords(i+1,s+1);case sa.Top:return this.getByMapCoords(i-1,s-1);case sa.Left:return this.getByMapCoords(i-1,s+1);case sa.Right:return this.getByMapCoords(i+1,s-1);case sa.BottomLeft:return this.getByMapCoords(i,s+1);case sa.BottomRight:return this.getByMapCoords(i+1,s);case sa.TopLeft:return this.getByMapCoords(i-1,s);case sa.TopRight:return this.getByMapCoords(i,s-1);default:throw new Error("Invalid direction")}}getByDisplayCoords(e,t){if(!(e>=this.dSize.width||t>=this.dSize.height))return this.tilesByDxy[e+t*this.dSize.width]}getByMapCoords(e,t){if(!(e>=this.rSize.width||t>=this.rSize.height))return this.tilesByRxy[e+t*this.rSize.width]}getMapSize(){return this.rSize}getDisplaySize(){return this.dSize}getInRectangle(i,s){let r=[];for(let t=0;t<s.width;t++)for(let e=0;e<s.height;e++){var a=i.rx+t,n=i.ry+e,n=this.getByMapCoords(a,n);n&&r.push(n)}return r}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:Zt.Rock1,rampType:0,subTile:0,tileNum:0,occluded:!1,onBridgeLandType:void 0}}}(r=ra=ra||{})[r.NotSpecial=0]="NotSpecial",r[r.Riparius=1]="Riparius",r[r.Cruentus=2]="Cruentus",r[r.Vinifera=4]="Vinifera",r[r.Aboreus=8]="Aboreus",r[r.Ore=1]="Ore",r[r.Gems=2]="Gems",r[r.All=15]="All";class Ha{static getOverlayTibType(e){return this.isRiparius(e)?ra.Riparius:this.isCruentus(e)?ra.Cruentus:this.isVinifera(e)?ra.Vinifera:this.isAboreus(e)?ra.Aboreus:ra.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}}Ha.minIdRiparius=102,Ha.maxIdRiparius=127,Ha.minIdCruentus=27,Ha.maxIdCruentus=38,Ha.minIdVinifera=127,Ha.maxIdVinifera=146,Ha.minIdAboreus=147,Ha.maxIdAboreus=166,(r=aa=aa||{})[r.Riparius=0]="Riparius",r[r.Cruentus=1]="Cruentus",r[r.Vinifera=2]="Vinifera",r[r.Aboreus=3]="Aboreus",r[r.Ore=0]="Ore",r[r.Gems=1]="Gems";class Ga{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=Ha.getOverlayTibType(this.gameObject.overlayId);switch(e){case ra.Ore:return aa.Ore;case ra.Gems:return aa.Gems;case ra.Vinifera:return aa.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(Ga.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}}Ga.maxBails=11;class $a{destroyOre(i,s,r){if(s.landType===Yt.Tiberium&&(r.art.hasObject(i,Ct.Animation)?r.art.getAnimation(i):void 0)?.crater){let t=r.map.getObjectsOnTile(s).find(e=>e.isOverlay()&&e.isTiberium());if(t){s=Math.ceil(Ga.maxBails/2),s=i.startsWith("S_CLSN")?s:r.generateRandomInt(1,s);let e=t.traits.get(Ga);e.removeBails(s),e.getBailCount()||r.unspawnObject(t)}}}spawnSmudges(e,r,a){if(r.landType===Yt.Clear&&0===r.rampType&&a.map.mapBounds.isWithinBounds(r)&&!a.map.getObjectsOnTile(r).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,s=[sa.Bottom,sa.BottomLeft,sa.BottomRight].every(e=>a.map.tiles.getNeighbourTile(r,e));e=[...a.rules.smudgeRules.values()].filter(e=>(e.crater&&e.width===t&&e.height===t||i&&e.burn)&&!((1<e.width||1<e.height)&&!s));e.length&&(e=e[a.generateRandomInt(0,e.length-1)].name,e=a.createObject(Ct.Smudge,e),a.spawnObject(e,r))}}}}class qa{constructor(e,t,i){this.target=e,this.attacker=t,this.incidental=i,this.type=ts.ObjectAttacked}}class Xa{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!==Ts.Air||i===Ts.Air)&&(!(!e.isUnit()&&i===Ts.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()||!Wa.isLowBridgeHead(e.overlayId))))))))))))}computeDamage(t,i,s=!1){let r=t;if(0<t&&i.isTechno()&&i.invulnerableTrait.isActive())return 0;if(i.isAircraft()&&i.missileSpawnTrait&&i.zone!==Ts.Air)return 0;if(this.rules.radiation||this.rules.temporal||!i.isInfantry()||i.stance!==Ds.Prone||(r*=this.rules.proneDamage),i.isTechno()||i.isOverlay()||i.isTerrain()){let e=i.isTerrain()?si.Wood:i.rules.armor;i.isOverlay()&&i.isBridge()&&((t=Wa.getOverlayBridgeType(i.overlayId))===ea.Wood?e=si.Wood:t===ea.Concrete&&(e=si.Concrete)),s&&i.isOverlay()&&(i.isBridge()||i.rules.wall)||(r*=this.rules.verses.get(e)),0<r&&i.isTechno()&&i.veteranTrait&&(r/=i.veteranTrait.getVeteranArmorMultiplier()),0<r&&i.isUnit()&&(r/=i.crateBonuses.armor)}return(i.isOverlay()||i.isBuilding())&&i.rules.wall&&(this.rules.wallAbsoluteDestroyer?r=Number.POSITIVE_INFINITY:this.rules.wall||this.rules.wood&&i.rules.armor===si.Wood||(r=0)),i.isOverlay()&&i.isBridge()&&(this.rules.wall||(r=0)),r=0<r?Math.floor(r):Math.ceil(r),r}inflictDamage(e,t,i,s,r=!1){let a=t.healthTrait;return e===Number.POSITIVE_INFINITY&&(e=a.getHitPoints()),a.inflictDamage(e,i,s),s.traits.filter(ta).forEach(e=>{e[ta.onAttack](t,i?.obj,s)}),t.onAttack(s,i),s.events.dispatch(new qa(t,i,r)),t.isTechno()&&!this.rules.temporal&&this.supressOrScatterTarget(t,s),!a.health&&(t.isInfantry()&&(t.infDeathType=this.rules.infDeath),this.rules.temporal&&(t.deathType=Wr.Temporal),t.isUnit()&&t.crashableTrait&&t.zone===Ts.Air&&!this.rules.temporal?t.crashableTrait.crash(i):s.destroyObject(t,i,void 0,r),!0)}supressOrScatterTarget(e,t){e.rules.fraidycat||e.isVehicle()&&!e.owner.isCombatant()&&e.rules.insignificant?e.unitOrderTrait.hasTasks()||(e.isInfantry()&&(e.isPanicked=!0),e.unitOrderTrait.addTask(new Ta(t)),e.isInfantry()&&e.unitOrderTrait.addTask(new da(()=>e.isPanicked=!1).setCancellable(!1))):e.isInfantry()&&e.suppressionTrait?.supress()}createDummyWeaponInfo(){return{minRange:0,range:0,speed:Number.POSITIVE_INFINITY,type:ni.Primary,rules:new Ii(new h("Dummy")),projectileRules:new $i(Ct.Projectile,new h("Dummy")),warhead:this}}detonate(i,e,t,s,r,a,n,o,h,l,c,u,d,p=!1){var g,m,f,y=h?.weapon??this.createDummyWeaponInfo(),w=h?.obj,T=h?.player,b=d?d/Ss.LEPTONS_PER_TILE:this.rules.cellSpread,v=this.rules.percentAtMax;let S=new Set,_=new Map,k=new Is(i.map.tileOccupation),O=new Fs(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!==ia.UnderBridge||!m.isUnit()||!m.onBridge)&&!(w&&m.isTechno()&&m.rules.typeImmune&&m.owner===T&&m.name===w.name)&&this.canDamage(m,g,a)&&(!m.isOverlay()||!(!n&&.1<Math.abs(m.tileElevation-s)||n===ia.OnBridge&&!m.isBridge()))){let e=m.isBuilding()?g===t?0:k.distance3(g,r)/Ss.LEPTONS_PER_TILE:m.isTerrain()||m.isOverlay()?k.distance3(g,t)/Ss.LEPTONS_PER_TILE:k.distance3(m,r)/Ss.LEPTONS_PER_TILE;if(e<.001&&(e=0),!(l&&m.isInfantry()&&T)||m.owner!==T&&!i.alliances.areAllied(m.owner,T)){if(!b)if(m.isTerrain()){if(g!==t||!this.rules.wall)continue}else if(!l&&(g!==t||!m.isBuilding()&&m!==(o.obj||o.getBridge())))continue;b&&e>b||(S.add(m),_.set(m,m.isBuilding()?(_.get(m)||[]).concat(e):[e]))}}let I=!1,A;for(f of S)if(!f.isDestroyed&&!f.isCrashing){var C,B=this.computeDamage(e,f,c);if(B)for(var x of _.get(f)){let t=B;if(0<b&&Number.isFinite(t)&&(t=z(t,v*t,x/b)),Math.abs(t)<1&&(!b||.25<=t/B)&&(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&&(A=f),this.inflictDamage(t,f,h,i,!A))break;f.isVehicle()&&this.rules.rocker&&(0<(C=U(B/300,0,1))&&(x=wr.fromMapCoords(f.position.getMapPosition().clone().sub(Ss.vecWorldToGround(r)))-f.direction,f.applyRocking(x,C)))}}}else f.isTechno()&&f.invulnerableTrait.isActive()&&(I=!0)}y=y.rules.radLevel;y&&b&&i.mapRadiationTrait.createRadSite(t,y,b+1);p=p?void 0:I?i.rules.audioVisual.weaponNullifyAnim:this.pickExplodeAnim(e,A,a,i,c);if(!I&&a===Ts.Ground){let e=new $a;p&&e.destroyOre(p,t,i),u&&e.spawnSmudges(u,t,i),p&&e.spawnSmudges(p,t,i)}i.events.dispatch(new za(this,r,p,c))}pickExplodeAnim(t,i,s,r,a){if(t){if(a)return r.rules.audioVisual.weatherConBoltExplosion;if(this.rules.conventional&&s===Ts.Water&&(!i||i.isBuilding()||i.isVehicle()&&i.submergibleTrait)){var n=r.rules.combatDamage.splashList;return n[U(Math.floor(t/50),0,n.length-1)]}n=this.rules.animList.length;let e;return n?(e=r.rules.combatDamage.c4Warhead===this.rules.name?n-1:this.rules.emEffect?r.generateRandomInt(0,n-1):U(Math.floor(t/25),0,n-1),this.rules.animList[e]):void 0}}}Xa.SPECIAL_WARHEAD_NAME="Special",Xa.HE_WARHEAD_NAME="HE";class Qa{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 Qa([this.forward,this.lateral,this.vertical])}}class Za{constructor(e,t){this.weapon=e,this.gameObject=t,this.type=ts.WeaponFire}}class Ya{constructor(e,t,i,s,r,a){this.weaponType=e,this.projectileRules=t,this.weaponRules=i,this.warheadRules=s,this.gameObject=r,this.generalRules=a,this.targetChecks=[],this.initConditions()}initConditions(){this.projectileRules.isAntiGround||this.targetChecks.push(e=>!!e);const a=this.generalRules.prism.type;this.gameObject.name===a&&this.weaponType===ni.Secondary?this.targetChecks.push((e,t,i,s,r)=>!(!r||!e?.isBuilding()||e.name!==a||e.owner!==this.gameObject.owner)):this.warheadRules.electricAssault?this.targetChecks.push((e,t,i,s,r)=>!(!s&&!r||!e?.isBuilding()||!e.overpoweredTrait||e.owner!==this.gameObject.owner)):this.weaponRules.damage<0?this.targetChecks.push((e,t,i)=>!!(e!==this.gameObject&&e?.isUnit()&&i.areFriendly(e,this.gameObject)&&e.healthTrait.health<100&&this.gameObject.isAircraft()===e.isAircraft())):(this.gameObject.rules.attackCursorOnFriendlies||this.warheadRules.bombDisarm?this.targetChecks.push((e,t,i,s,r)=>!r&&!!(!this.warheadRules.bombDisarm||e?.isTechno()&&e.tntChargeTrait?.hasCharge())):this.targetChecks.push((e,t,i,s)=>!((!s||this.warheadRules.mindControl)&&e?.isTechno()&&i.areFriendly(e,this.gameObject))),this.targetChecks.push((e,t,i)=>!(e?.isTechno()&&e.cloakableTrait?.isCloaked()&&!i.alliances.haveSharedIntel(this.gameObject.owner,e.owner))),this.weaponRules.limboLaunch&&this.targetChecks.push((e,t,i,s,r)=>!(r&&e&&(e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested())),this.gameObject.rules.ivan&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.tntChargeTrait||e.tntChargeTrait.hasCharge())),this.warheadRules.parasite&&this.targetChecks.push((e,t,i,s)=>!!(!e&&s||e?.isInfantry()||(e?.isVehicle()||e?.isAircraft())&&e.parasiteableTrait)),this.warheadRules.mindControl&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.mindControllableTrait)),this.warheadRules.temporal||this.targetChecks.push((e,t,i,s,r)=>!(r&&e?.isTechno()&&e.warpedOutTrait.isInvulnerable()))),this.targetChecks.push((e,t)=>this.canTargetZone(e,t))}canTarget(t,i,s,r,a){return this.targetChecks.every(e=>e(t,i,s,r,a))}canTargetZone(e,t){let i;if(e?.isUnit()){if(e?.isInfantry()&&e.stance===Ds.Paradrop)return this.projectileRules.isAntiAir&&(this.projectileRules.isAntiGround||this.weaponType===ni.Secondary);if(e.zone===Ts.Air)return this.projectileRules.isAntiAir;if(this.weaponType===ni.Secondary&&this.projectileRules.isAntiAir)return!1;i=e.zone}else i=t.landType===Yt.Water?Ts.Water:Ts.Ground;return i===Ts.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 ri.LandOk:return!0;case ri.LandNotOk:return!1;case ri.LandSecondary:return t===ni.Secondary;default:throw new Error(`Unhandled LandTargeting value "${e}"`)}}canTargetNaval(e,t,i,s){switch(e){case ai.UnderwaterNever:return!i||!(i.isVehicle()&&i.submergibleTrait?.isSubmerged());case ai.UnderwaterSecondary:return i&&i.isVehicle()&&i.submergibleTrait&&!t.rules.spawned?s===ni.Secondary:s===ni.Primary;case ai.UnderwaterOnly:return!!(i&&i.isVehicle()&&i.submergibleTrait);case ai.OrganicSecondary:return i?.isTechno()&&i.rules.organic?s===ni.Secondary:s===ni.Primary;case ai.SealSpecial:return i?.isTechno()&&i.rules.naval&&!i.rules.organic&&(i.isBuilding()||i.rules.speedType===Kt.Float)?s===ni.Secondary:s===ni.Primary;case ai.NavalAll:return!0;case ai.NavalNone:return!1;default:throw new Error(`Unhandled NavalTargeting value "${e}"`)}}}class Ka{constructor(e,t,i,s,r,a,n){this.type=e,this.gameObject=t,this.rules=i,this.warhead=s,this.projectileRules=r,this.flh=a,this.targeting=n,this.cooldownTicks=0,this.burstsLeft=0,this.burstIndex=0,this.useBurstDelay=!1,this.lateralMuzzleMult=1,this.distributedFireAngle=t.rules.distributedFire&&t.rules.radialFireSegments?-90:0}static factory(e,t,i,s,r){var a=s.getWeapon(e);let n=a.warhead;n===Xa.SPECIAL_WARHEAD_NAME&&(n=Ka.findSpecialWarheadName(a,i,s));var o=new Xa(s.getWarhead(n)),e=s.getProjectile(a.projectile),s=new Ya(t,e,a,o.rules,i,s.general);return new this(t,i,a,o,e,r||new Qa,s)}static findSpecialWarheadName(e,t,i){let s;if(!e.spawner)throw new Error(`Weapon "${e.name} can't use "Special" warhead without Spawner=yes`);if(t.rules.spawns===i.general.v3Rocket.type)s=i.combatDamage.v3Warhead;else if(t.rules.spawns===i.general.dMisl.type)s=i.combatDamage.dMislWarhead;else{if(!t.rules.spawns)throw new Error(`Can't use "Special" warhead on unit type "${t.name}" without "Spawns"`);t=i.getObject(t.rules.spawns,Ct.Aircraft);if(!t.primary)throw new Error(`Spawned unit "${t.name}" doesn't have a primary weapon`);s=i.getWeapon(t.primary).warhead}return s}static computeSpeed(e,t){return t.arcing?.75*Oi.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===ni.Secondary&&this.gameObject.primaryWeapon?Math.min(this.gameObject.primaryWeapon.rules.range,this.rules.range):this.rules.range}get speed(){return Ka.computeSpeed(this.rules,this.projectileRules)}get rof(){let e=this.rules.rof;return this.gameObject.isBuilding()&&this.gameObject.garrisonTrait?.isOccupied()&&(e/=this.gameObject.garrisonTrait.units.length),this.gameObject.veteranTrait&&(e*=this.gameObject.veteranTrait.getVeteranRofMultiplier()),Math.floor(e)}getCooldownTicks(){return this.cooldownTicks}expireCooldown(){this.cooldownTicks=0}resetCooldown(){this.cooldownTicks=this.rof}hasBurstsLeft(){return 0<this.burstsLeft}resetBursts(){this.burstsLeft=0,this.burstIndex=0,this.resetCooldown(),this.gameObject.ammoTrait&&0<this.gameObject.ammoTrait.ammo&&this.gameObject.ammoTrait.ammo--}tick(){0<this.cooldownTicks&&this.cooldownTicks--}getBurstsFired(){return this.burstIndex}fire(r,a,n=1){let o=this.gameObject,e,t=0;if(!o.airSpawnTrait||!this.rules.spawner||(e=o.airSpawnTrait.prepareLaunch(o,r,a),t=o.airSpawnTrait.availableSpawns,e)){this.burstsLeft?(this.burstsLeft--,this.burstIndex++,this.lateralMuzzleMult*=-1):(this.useBurstDelay=!1,this.burstIndex=0,e?this.burstsLeft=t:this.gameObject.isAircraft()?this.burstsLeft=this.projectileRules.iniRot<=1?4:this.gameObject.rules.fighter?0:1:(this.burstsLeft=this.rules.burst-1,this.useBurstDelay=!0),this.lateralMuzzleMult=1),0<this.burstsLeft&&(e&&0<t?this.cooldownTicks=this.rules.iniSpeed:this.gameObject.isAircraft()?this.cooldownTicks=this.rules.rof:this.cooldownTicks=this.useBurstDelay&&void 0!==this.gameObject.rules.burstDelay[this.burstIndex]?this.gameObject.rules.burstDelay[this.burstIndex]:a.generateRandomInt(3,5)),this.burstsLeft||this.resetBursts(),this.rules.limboLaunch&&(a.limboObject(this.gameObject,{selected:a.getUnitSelection().isSelected(this.gameObject),controlGroup:a.getUnitSelection().getOrCreateSelectionModel(this.gameObject).getControlGroupNumber()}),this.warhead.rules.parasite&&(r.obj?.isVehicle()||r.obj?.isAircraft())&&r.obj.parasiteableTrait&&(r.obj.parasiteableTrait.beingBoarded=!0));let i=e??a.createProjectile(this.projectileRules.name,this.gameObject,this,r,!1);i.isAircraft()||(i.baseDamageMultiplier=n*(this.gameObject.isUnit()?this.gameObject.crateBonuses.firepower:1));let s=this.flh.clone();s.lateral*=this.lateralMuzzleMult;var h=o.position.getMapPosition();if(a.map.isWithinHardBounds(h)){i.position.moveToLeptons(h),i.position.tileElevation=o.position.tileElevation;let e=new vs(s.lateral,s.forward);n=this.getMuzzleFacing()+this.distributedFireAngle;e=sr(e,n);var h=sr(h=new vs(0,o.art.turretOffset),o.direction);e.add(h),o.rules.radialFireSegments&&o.rules.distributedFire&&(h=Math.floor(180/o.rules.radialFireSegments),this.distributedFireAngle=(this.distributedFireAngle+h+90)%180-90),i.direction=n,o.isBuilding()&&o.rules.turretAnim&&(l=Ss.screenDistanceToWorld(o.rules.turretAnimX,o.rules.turretAnimY),n=o.getFoundationCenterOffset(),i.position.moveByLeptons(-n.x+l.x,-n.y+l.y));let t=new is(e.x,s.vertical,-e.y);var l=t.clone().add(i.position.worldPosition);if(a.map.isWithinHardBounds(l)&&i.position.moveByLeptons3(t),i.tileElevation<0&&(i.position.tileElevation=0),i.isAircraft()?a.unlimboObject(i,i.position.tile):a.spawnObject(i,i.position.tile),this.rules.revealOnFire&&r.obj?.isTechno()){let e=a.mapShroudTrait.getPlayerShroud(r.obj.owner);e?.isShrouded(o.tile)&&e.revealTemporarily(o)}this.rules.decloakToFire&&this.gameObject.cloakableTrait?.uncloak(a),a.events.dispatch(new Za(this,this.gameObject))}else e&&(e.owner.removeOwnedObject(e),e.dispose())}}getMuzzleFacing(){let e=this.gameObject,t;return t=!e.isInfantry()&&!e.isAircraft()&&(e.isBuilding()||e.isVehicle())&&e.turretTrait?e.turretTrait.facing:e.direction,t}}Ka.NUKE_PAYLOAD_NAME="NukePayload";class Ja extends Ws{constructor(e,t,i,s){super(e,t,i),this.weaponType=s}onStart(t){var i=t.rules.getWeapon(this.weaponType),s=t.createTarget(void 0,this.tile),r=this.owner.getOwnedObjectsByType(Ct.Building).find(e=>e.rules.nukeSilo);if(r){let e=Ka.factory(i.name,ni.Primary,r,t.rules);e.fire(s,t)}else this.fireLooseNuke(i,s,t)}fireLooseNuke(t,i,s){var r=new vs(this.tile.rx+.5,this.tile.ry+.5).multiplyScalar(Ss.LEPTONS_PER_TILE);if(s.map.isWithinHardBounds(r)){let e=s.createLooseProjectile(t.name,this.owner,i);e.position.moveToLeptons(r),e.position.tileElevation=Ss.worldToTileHeight(e.rules.detonationAltitude),s.spawnObject(e,e.position.tile)}}onTick(e){return!0}}class en{constructor(e){this.position=e,this.type=ts.LightningStormCloud}}class tn{constructor(e){this.target=e,this.type=ts.LightningStormManifest}}(r=na=na||{})[r.Approaching=0]="Approaching",r[r.Manifesting=1]="Manifesting";class sn extends Ws{constructor(){super(...arguments),this.state=na.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===na.Approaching&&(0<this.manifestStartTimer?this.manifestStartTimer--:(this.state=na.Manifesting,t.events.dispatch(new tn(this.tile)))),this.state===na.Manifesting){var i,r=t.rules.general.lightningStorm;if(0<this.manifestEndTimer&&(this.manifestEndTimer--,0<this.nextDirectHitTimer&&this.nextDirectHitTimer--,this.nextDirectHitTimer<=0&&(this.nextDirectHitTimer=r.hitDelay,this.spawnCloudAt(this.tile,t)),0<this.nextRandomHitTimer&&this.nextRandomHitTimer--,this.nextRandomHitTimer<=0)){this.nextRandomHitTimer=r.scatterDelay;var a=Math.floor(r.cellSpread/2);let i=r.separation,s=new Is(t.map.tileOccupation),e=new fa(t.map.tiles,t.map.mapBounds,this.tile,a,t,t=>!this.clouds.some(e=>s.tileDistance(t,e.tile)<i),!1);a=e.getNextTile();a&&this.spawnCloudAt(a,t)}for(i of this.clouds.slice())if(0<i.ticksLeft){if(i.ticksLeft--,i.ticksLeft===Math.floor(i.durationTicks/2)){var s=r.warhead;let e=new Xa(t.rules.getWarhead(s));var n=i.tile,o=t.map.tileOccupation.getBridgeOnTile(n),h=o?.tileElevation??0,s=t.map.getTileZone(n);e.detonate(t,r.damage,n,h,Ss.tile3dToWorld(n.rx+.5,n.ry+.5,n.z+h),s,o?ia.OnBridge:ia.None,t.createTarget(o,n),{player:this.owner,weapon:void 0},!1,!0,void 0)}}else this.clouds.splice(this.clouds.indexOf(i),1);if(!this.clouds.length&&this.manifestEndTimer<=0)return!0}return!1}spawnCloudAt(e,t){var i=t.rules.audioVisual.weatherConClouds,i=t.generateRandomInt(0,i.length-1);let s=t.art.getAnimation(t.rules.audioVisual.weatherConClouds[i]);i=s.art.getNumber("Rate",60*Ls.BASE_TICKS_PER_SECOND)/60,i=Math.floor(Ls.BASE_TICKS_PER_SECOND/i*60);this.clouds.push({tile:e,durationTicks:i,ticksLeft:i});i=(t.map.tileOccupation.getBridgeOnTile(e)?.tileElevation??0)+Ss.worldToTileHeight(t.rules.general.flightLevel),i=Ss.tile3dToWorld(e.rx+.5,e.ry+.5,e.z+i);t.events.dispatch(new en(i))}}class rn extends Ws{onStart(e){var t,i,s=e.rules.combatDamage.ironCurtainDuration,r={player:this.owner};let a=new Fs(e.map.tiles,e.map.mapBounds,this.tile,{width:1,height:1},0,1,()=>!0);for(;t=a.getNextTile();)for(i of e.map.getGroundObjectsOnTile(t))!i.isTechno()||i.isUnit()&&i.tile!==t||i.rules.missileSpawn||(i.rules.organic?i.isDestroyed||e.destroyObject(i,r):(i.invulnerableTrait.setActiveFor(s,e.currentTick),(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isInfested()&&i.parasiteableTrait.destroyParasite(r,e)))}onTick(e){return!0}}class an extends Ws{constructor(e,t,i,s){super(e,t,i),this.tile2=s,this.objectsToTeleport=[]}onStart(i){this.delayTicks=i.rules.general.chronoDelay;let s=i.map.tiles;for(let t=-1;t<=1;t++)for(let e=-1;e<=1;e++){var r=s.getByMapCoords(this.tile.rx+t,this.tile.ry+e);if(r){var a,n=!!r.onBridgeLandType,o=s.getByMapCoords(this.tile2.rx+t,this.tile2.ry+e);for(a of i.map.getGroundObjectsOnTile(r))!a.isUnit()||a.tile!==r||a.onBridge!==n||a.isInfantry()&&a.stance===Ds.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,s=h?l.map.tileOccupation.getBridgeOnTile(h):void 0,r=l.map.getGroundObjectsOnTile(h),a=r.find(e=>e.isBuilding());var c=r.some(e=>l.rules.general.padAircraft.includes(e.name)),t=l.rules.general.padAircraft.includes(o.name)&&!!a?.helipadTrait&&!!a.dockTrait?.getAllDockTiles().includes(h)&&a.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,!!s)&&u)){let t=!1;if(!c&&(0<l.map.terrain.getPassableSpeed(h,n,!!s,void 0,!0)||!u)){a&&(i=!0);let e=new Fs(l.map.tiles,l.map.mapBounds,h,{width:1,height:1},1,15,e=>0<l.map.terrain.getPassableSpeed(e,n,!!e.onBridgeLandType)&&!l.map.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},o).length);u=e.getNextTile();u&&(h=u,s=l.map.tileOccupation.getBridgeOnTile(h),r=l.map.getGroundObjectsOnTile(h),t=!0)}t||(o.moveTrait.teleportUnitToTile(h,s,!0,!1,l),o.warpedOutTrait.setActive(!1,!0,l),l.map.getTileZone(h)===Ts.Water&&(o.deathType=Wr.Sink),l.destroyObject(o,{player:this.owner}),e=!0)}if(!e||c)for(let t of r)t.isDisposed||t.isUnit()&&(this.objectsToTeleport.some(({obj:e})=>e===t)||t.onBridge!==!!s&&t.tile===h||2<Math.abs(t.tileElevation-o.tileElevation)||(t.isInfantry()&&t.stance!==Ds.Paradrop&&(t.deathType=Wr.Crush),l.destroyObject(t,{player:this.owner,obj:o})));e||(o.moveTrait.teleportUnitToTile(h,s,!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}}(oa=oa||{}).onDeactivate=Symbol();class nn{constructor(){this.effects=[]}[Bs.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===Ps.NotStarted&&(t.onStart(i),t.status=Ps.Running),t.onTick(i)&&(t.status=Ps.Finished,i.traits.filter(oa).forEach(e=>{e[oa.onDeactivate](t.type,t.owner,i)}));this.effects=this.effects.filter(e=>e.status!==Ps.Finished)}[Ns.onPowerLow](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!1)})}[Ns.onPowerRestore](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!0)})}[Ns.onPowerChange](e,t){}[xs.onChange](e,t){var i;e.owner.powerTrait&&e.isBuilding()&&e.superWeaponTrait&&((i=e.superWeaponTrait.getSuperWeapon(e))&&this.updateTimer(i,!e.owner.powerTrait.isLowPower()))}updateTimer(e,t){var i=this.superWeaponHasValidBuilding(e);t&&i?e.resumeTimer():e.pauseTimer()}superWeaponHasValidBuilding(t){return[...t.owner.buildings].find(e=>!(e.superWeaponTrait?.getSuperWeapon(e)!==t||e.warpedOutTrait.isActive()&&t.rules.isPowered))}addEffect(e){this.effects.push(e)}activateSuperWeapon(t,e,i,s,r){let a=e.superWeaponsTrait?.getAll().find(e=>e.rules.type===t);if(a&&a.status===Es.Ready){if(a.oneTimeOnly){e.superWeaponsTrait.remove(a.name);for(var n of e.buildings)n.rules.superWeapon===a.name&&n.superWeaponTrait&&n.superWeaponTrait.addSuperWeaponToPlayerIfNeeded(e,i)}else a.resetTimer();this.activateEffect(a.rules,e,i,s,r)}}activateEffect(e,i,s,r,a,n=!1){const o=e.type;if(void 0!==o){let t=[];switch(o){case es.AmerParaDrop:for(var[h,l]of s.rules.general.paradrop.amerParaDrop.entries())t.push(new Ua(o,i,r,l,h));break;case es.ParaDrop:{let e=s.rules.general.paradrop.getParadropSquads(i.country.side);for(var[c,u]of e.entries())t.push(new Ua(o,i,r,u,c));break}case es.MultiMissile:if(!e.weaponType)throw new Error("Missing WeaponType in super weapon rules");t.push(new Ja(o,i,r,e.weaponType));break;case es.LightningStorm:t.push(new sn(o,i,r));break;case es.IronCurtain:t.push(new rn(o,i,r));break;case es.ChronoSphere:if(!a)throw new Error("Missing tile2 action param");t.push(new an(o,i,r,a))}for(var d of t)this.addEffect(d);s.traits.filter(Rs).forEach(e=>{e[Rs.onActivate](o,i,s,r,a)}),s.events.dispatch(new zs(o,i,r,a,n))}}}class on{constructor(e){this.target=e,this.type=ts.ObjectCloakChange}}(ha=ha||{}).onDamage=Symbol();class hn{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 on(this.gameObject)))}resetCloakCooldown(){this.cooldownTicks=Math.floor(60*this.cloakDelayMinutes*Ls.BASE_TICKS_PER_SECOND)}[Xr.onSpawn](e,t){this.resetCloakCooldown()}[Mr.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 on(this.gameObject)))}[ha.onDamage](e,t){this.uncloak(t)}dispose(){this.gameObject=void 0}}class ln{static calculateOverlayId(e,t){if(e!==ra.NotSpecial){var i=t.dx,t=t.dy,i=Math.floor((t-9)/2%12*((t-8)/2%12)%12-(i-13)/2%12*((i-12)/2%12)%12+12e4);return i%=12,e===ra.Ore?Ha.minIdRiparius+i:e===ra.Gems?Ha.minIdCruentus+i:e===ra.Vinifera?Ha.minIdVinifera+i:e===ra.Aboreus?Ha.minIdAboreus+i:void 0}}}var cn,un,dn,pn,gn,mn,fn,yn,wn,Tn,bn,vn,Sn,_n,kn,On,In,An,Cn,Bn,xn,En,Pn,Nn,Rn,Dn,r=__webpack_require__(949);class Mn extends r.Box2{}const Ln=[Cs.IonStorm,Cs.Gas,Cs.Pod,Cs.Squad];class Fn{constructor(e){this.randomCrateSpawn=e,this.crates=[],this.availEdgeTiles=[],this.allTiles=[]}init(n){var o=n.map.tiles.getMapSize();let h=n.map.tiles,e=[],l=0;for(let a=0;a<o.width;++a){let t,i,s=!1,r=!1;for(let e=0;e<o.height;++e){var c=h.getByMapCoords(a,e);if(c&&this.canPlaceCrateOnTile(n,c)){var u=n.map.getTileZone(c)===Ts.Water;t?(u||(i=c),r=u):u?s=r=!0:t=i=c}else if(t&&!c)break}t&&(e.push(t),i&&i!==t&&e.push(i),s||r||l++)}this.availEdgeTiles=e,this.allTiles=h.getAll(),this.mapEdgeIsWater=0===l,this.minCrates=n.rules.crateRules.crateMinimum*n.gameOpts.humanPlayers.filter(e=>-3!==e.countryId).length}[Bs.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)===Ts.Water,i=this.choosePowerup(i,t.rules.powerups.powerups,t);if(i)return this.spawnCrateAt(e,i,t)}}spawnCrateAt(t,i,s){if(this.canPlaceCrateOnTile(s,t)){var r=s.map.getTileZone(t,!0)===Ts.Water,a=s.rules.crateRules,r=r?a.waterCrateImg:a.crateImg;let e=s.createObject(Ct.Overlay,r);e.overlayId=s.rules.getOverlayId(r),e.value=0,s.spawnObject(e,t);s=60*a.crateRegen*Ls.BASE_TICKS_PER_SECOND*(.5+1.5*s.generateRandom());return this.crates.push({obj:e,powerup:i,ticksLeft:s}),e}}chooseSpawnTile(e,t){return t.generateRandom()<(this.mapEdgeIsWater?1/3:2/3)&&this.availEdgeTiles.length&&(e=this.availEdgeTiles),this.chooseRandomTile(e,t)}chooseRandomTile(e,t){let i;let s=0;for(;i=e[t.generateRandomInt(0,e.length-1)],s++,s<100&&!this.canPlaceCrateOnTile(t,i););if(100<=s){var r=t.map.tileOccupation.getEmptyTiles();if(!r.length)return;i=r[t.generateRandomInt(0,r.length-1)]}return i}canPlaceCrateOnTile(e,t){return e.map.mapBounds.isWithinBounds(t)&&!e.map.getGroundObjectsOnTile(t).length&&0<e.map.terrain.getPassableSpeed(t,Kt.Amphibious,!1)&&t.terrainType!==Zt.Shore&&0===t.rampType}choosePowerup(t,i,s){if((i=t?i.filter(e=>e.waterAllowed):i).length){var r,t=i.reduce((e,t)=>e+t.probShares,0),a=s.generateRandomInt(0,t);let e=0;for(r of i)if(e+=r.probShares,a<e)return r}}peekInsideCrate(t){return this.crates.find(e=>e.obj===t)?.powerup.type}pickupCrate(e,t,i){let s=this.crates.find(e=>e.obj===t);if(s){this.crates.splice(this.crates.indexOf(s),1),i.unspawnObject(s.obj),s.obj.dispose();let t=this.grantPowerup(e,s.powerup,s.obj.tile,i);var r;return void 0!==t&&(e.owner.cratesPickedUp++,r=i.rules.powerups.powerups.find(e=>e.type===t),i.events.dispatch(new ws(r,e.owner,e,s.obj.tile))),this.randomCrateSpawn&&this.spawnCrateAtRandom(this.allTiles,i),t}}grantPowerup(t,i,s,r){let a=t.owner,n=!1;if(a.isCombatant()){if(i.type===Cs.Unit){let e;if(![...a.buildings].some(e=>e.rules.constructionYard)&&r.rules.crateRules.freeMCV){let t=r.rules.general.baseUnit;if(!a.getOwnedObjects(!0).some(e=>t.includes(e.name))&&a.credits>=[...r.rules.ai.buildPower,...r.rules.ai.buildRefinery].map(e=>r.rules.getBuilding(e)).filter(e=>e.aiBasePlanningSide===a.country.side).reduce((e,t)=>e+t.cost,0)){var o=t.find(e=>{let t=r.rules.getObject(e,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=r.rules.getObject(o,Ct.Vehicle)}}if(e||(h=(h=r.rules.crateRules.unitCrateType)?r.rules.hasObject(h,Ct.Vehicle)?[r.rules.getObject(h,Ct.Vehicle)]:[]:[...r.rules.vehicleRules.values()].filter(e=>e.crateGoodie&&0<r.map.terrain.getPassableSpeed(s,e.speedType,!1))).length&&(e=h[r.generateRandomInt(0,h.length-1)]),e){let t=r.createUnitForPlayer(e,a);var h=new Fs(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},0,3,e=>0<r.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length).getNextTile();h?(r.spawnObject(t,h),n=!0):(a.removeOwnedObject(t),t.dispose())}}else if(i.type===Cs.Money){if(!i.data)throw new Error("Money powerup missing data field");a.credits=Math.max(0,a.credits+Math.floor(Number(i.data)*(.55+2*r.generateRandom()*.45))),n=!0}else if(i.type===Cs.HealBase){var e;for(e of a.getOwnedObjects(!0))e.isDestroyed||e.healthTrait.healToFull(void 0,r);n=!0}else if(i.type===Cs.Reveal)r.mapShroudTrait.revealMap(a,r),n=!0;else if(i.type===Cs.Darkness)r.mapShroudTrait.resetShroud(a,r),n=!0;else if(i.type===Cs.Veteran){if(t.veteranTrait&&!t.veteranTrait.isMaxLevel()){n=!0;var l,c=Number(i.data);for(l of this.getUnitsInCrateRadius(r,s,a))l.veteranTrait?.promote(c,r)}}else if(i.type===Cs.Armor){if(1===t.crateBonuses.armor){n=!0;var u,d=Number(i.data);for(u of this.getUnitsInCrateRadius(r,s,a))1===u.crateBonuses.armor&&(u.crateBonuses.armor=d)}}else if(i.type===Cs.Firepower){if(1===t.crateBonuses.firepower){n=!0;var p,g=Number(i.data);for(p of this.getUnitsInCrateRadius(r,s,a))1===p.crateBonuses.firepower&&(p.crateBonuses.firepower=g)}}else if(i.type===Cs.Speed){if(1===t.crateBonuses.speed){n=!0;var m,f=Number(i.data);for(m of this.getUnitsInCrateRadius(r,s,a))1===m.crateBonuses.speed&&(m.crateBonuses.speed=f)}}else if(i.type===Cs.Cloak){if(!t.cloakableTrait){n=!0;for(var y of this.getUnitsInCrateRadius(r,s,a))y.cloakableTrait||(y.cloakableTrait=new hn(y,r.rules.general.cloakDelay),r.addObjectTrait(y,y.cloakableTrait))}}else if(i.type===Cs.ICBM){var w=[...r.rules.superWeaponRules.values()].find(e=>e.type===es.MultiMissile);if(w&&a.superWeaponsTrait&&!a.superWeaponsTrait.has(w.name)){let e=r.createSuperWeapon(w.name,a,!0);e.isGift=!0,a.superWeaponsTrait.add(e),n=!0}}else if(i.type===Cs.Invulnerability){var T=[...r.rules.superWeaponRules.values()].find(e=>e.type===es.IronCurtain);T&&(r.traits.get(nn).activateEffect(T,a,r,s,void 0,!0),n=!0)}else if(i.type===Cs.Explosion||i.type===Cs.Napalm){n=!0;w=Number(i.data),T=i.type===Cs.Napalm?r.rules.combatDamage.flameDamage:r.rules.combatDamage.c4Warhead;let e=new Xa(r.rules.getWarhead(T));e.detonate(r,w,t.tile,t.tileElevation,t.position.worldPosition,t.zone,ia.None,r.createTarget(t,t.tile),{player:t.owner,weapon:void 0},!1,!1,void 0,0)}else{if(i.type!==Cs.Tiberium)return void console.warn(`Unhandled powerup type "${Cs[i.type]}"`);{let e=new fa(r.map.tiles,r.map.mapBounds,s,2,r,e=>Ga.canBePlacedOn(e,r.map)),t,i=0;for(;i++<6&&(t=e.getNextTile());){var b=ln.calculateOverlayId(ra.Ore,t);if(void 0===b)throw new Error("Expected an overlayId");let e=r.createObject(Ct.Overlay,r.rules.getOverlayName(b));e.overlayId=b,e.value=3,r.spawnObject(e,t),n=!0}}}if(n)return i.type;i=r.rules.powerups.powerups.find(e=>e.type===Cs.Money&&0<e.probShares);return i?this.grantPowerup(t,i,s,r):void 0}}getUnitsInCrateRadius(e,t,i){let s=e.rules.crateRules.crateRadius,r=new Is(e.map.tileOccupation);return e.map.technosByTile.queryRange((new Mn).setFromCenterAndSize(new vs(t.rx,t.ry),new vs(s,s))).filter(e=>e.owner===i&&e.isUnit()&&r.tileDistance(e,t)<=s)}}class jn{constructor(){this.powerups=[]}readIni(e){for(var[r,a]of e.entries){let[e,t,i,s]=a.split(",");var n=Number(e),a=Cs[r];void 0!==a?Ln.includes(a)||this.powerups.push({type:a,probShares:n,animName:"<none>"!==t.toLowerCase()?t:void 0,waterAllowed:"yes"===i,data:s}):console.warn(`Unknown powerup "${r}". Skipping.`)}return this}}const Un=["Gold","DarkRed","DarkBlue","DarkGreen","Orange","DarkSky","Purple","Magenta"];class Wn{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 jn,this.colors=new Map,this.general=new Wi,this.ai=new ps,this.crateRules=new ys,this.elevationModel=new gs,this.mpDialogSettings=new St,this.audioVisual=new Ai,this.combatDamage=new us,this.radiation=new ms,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 Ii(i),this.cachedWeaponRules.set(e,t)}return t}getWeaponByInternalId(e){var t=this.weaponTypes.get(e);if(!t)throw new RangeError(`Weapon with internal ID "${e}" not found`);return this.getWeapon(t)}getWarhead(e){let t=this.warheadRules.get(e.toLowerCase());var i;if(t||(i=this.ini.getSection(e))&&(t=new Gi(i),this.warheadRules.set(e.toLowerCase(),t)),!t)throw new Error(`Unknown warhead ${e}`);return t}getProjectile(e){let t=this.cachedProjectileRules.get(e);if(!t){var i=this.ini.getSection(e);if(!i)throw new Error(`Projectile ${e} is missing ini section`);t=new $i(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}hasOverlayId(e){return this.overlayTypes.has(e)}getOverlayId(e){var t=this.overlayIdsByType.get(e);if(void 0===t)throw new Error(`Invalid overlay name ${e}`);return t}getOverlay(e){var t=this.overlayRules.get(e);if(!t)throw new Error(`Missing rules for overlay "${e}"`);return t}getAnimationName(e){return this.animationTypes.get(e)}getCountry(e){if(!this.countryRules.has(e))throw new Error(`Unknown country ${e}`);return this.countryRules.get(e)}getMultiplayerCountries(){return[...this.countryRules.values()].filter(e=>e.multiplay)}getMultiplayerColors(){let t=new Map;return Un.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 Hi).readIni(this.ini.getOrCreateSection(i)),this.landRules.set(e,t)),t}getTiberium(e){var t=this.tiberiumTypes.get(e);if(!t)throw new Error(`Unknown tiberium type ${e}`);return this.tiberiumRules.get(t)}getSuperWeapon(e){if(!this.superWeaponRules.has(e))throw new Error(`Unknown superweapon type "${e}"`);return this.superWeaponRules.get(e)}getIni(){return this.ini}applySpecialFlags(e){e.initialVeteran&&(this.general.veteran.initialVeteran=!0)}init(){this.readAudioVisual(),this.readCombatDamage(),this.readRadiation(),this.readGeneral(),this.readAi(),this.readCrateRules(),this.readElevationModel(),this.readMpDialogSettings(),this.readObjectTypes("BuildingTypes",this.buildingTypes),this.readObjectTypes("InfantryTypes",this.infantryTypes),this.readObjectTypes("VehicleTypes",this.vehicleTypes),this.readObjectTypes("AircraftTypes",this.aircraftTypes),this.readObjectTypes("TerrainTypes",this.terrainTypes),this.readObjectTypes("SmudgeTypes",this.smudgeTypes),this.readObjectTypes("Animations",this.animationTypes),this.animationNames=new Set(this.animationTypes.values()),this.readObjectTypes("VoxelAnims",this.voxelAnimTypes),this.readObjectTypes("OverlayTypes",this.overlayTypes),this.overlayTypes.forEach((e,t)=>this.overlayIdsByType.set(e,t)),this.readColors(),this.readObjectTypes("Countries",this.countryTypes),this.readObjectTypes("Warheads",this.warheadTypes),this.readObjectTypes("Tiberiums",this.tiberiumTypes),this.readObjectTypes("SuperWeaponTypes",this.superWeaponTypes),this.allObjectRules.set(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,s){let e=this.ini.getSection(i);if(!e)throw new Error(`Missing [${i}] section`);let r=0,a=new Set;e.entries.forEach((e,t)=>{Number.isNaN(Number(t))?this.logger?.debug(`Non-numeric id "${t}" found in rules section [${i}]. Skipping.`):a.has(e)?this.logger?.debug(`Duplicate type "${e}" in rules section [${i}]. Skipping.`):(s.set(r++,e),a.add(e))})}readColors(){let e=this.ini.getSection("Colors");if(!e)throw new Error("Missing [Colors] section");e.entries.forEach((e,t)=>{var[i,s,e]=e.split(","),e=j.fromHsv(parseInt(i,10),parseInt(s,10),parseInt(e,10));this.colors.set(t,e)})}readObjects(s,e,r){e.forEach((e,t)=>{var i=this.ini.getSection(e);i?(t=(new cs).create(s,i,t),r.set(e,t)):this.logger?.debug(`${Ct[s]} type "${e}" has no rules section`)})}readCountries(){this.countryTypes.forEach((e,t)=>{var i=this.ini.getSection(e);if(!i)throw new Error(`Missing ini section for country ${e}`);let s=new ki(t);s.readIni(i),this.countryRules.set(e,s)})}readWarheads(){this.warheadTypes.forEach(e=>{var t=this.ini.getSection(e);t?(t=new Gi(t),this.warheadRules.set(e.toLowerCase(),t)):this.logger?.debug(`Warhead "${e}" has no rules section`)})}readPowerups(){var e=this.ini.getSection("Powerups");if(!e)throw new Error("Missing [Powerups] section");this.powerups.readIni(e)}readTiberiums(){this.tiberiumTypes.forEach(e=>{var t=this.ini.getSection(e);if(!t)throw new Error(`Missing rules section for tiberium type ${e}`);this.tiberiumRules.set(e,(new ds).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 fs(t).readIni(i))})}buildWeaponsList(){let e=new Set;e.add(this.general.dropPodWeapon);for(var t of this.superWeaponRules.values())t.weaponType&&e.add(t.weaponType);var s,i;e.add(Ka.NUKE_PAYLOAD_NAME);for(let i of[...this.buildingRules.values(),...this.aircraftRules.values(),...this.vehicleRules.values(),...this.infantryRules.values()])for(s of[i.deathWeapon,i.primary,i.secondary,i.elitePrimary,i.eliteSecondary,i.occupyWeapon,i.eliteOccupyWeapon,...i.weaponCount?new Array(i.weaponCount).fill(0).map((e,t)=>[i.getWeaponAtIndex(t),i.getEliteWeaponAtIndex(t)]).flat():[]].filter(Ma).filter(e=>""!==e))e.add(s);let r=0;for(i of e)this.weaponTypes.set(r++,i)}}(r=cn=cn||{})[r.Ready=0]="Ready",r[r.Guard=1]="Guard",r[r.Prone=2]="Prone",r[r.Walk=3]="Walk",r[r.FireUp=4]="FireUp",r[r.Down=5]="Down",r[r.Crawl=6]="Crawl",r[r.Up=7]="Up",r[r.FireProne=8]="FireProne",r[r.Idle1=9]="Idle1",r[r.Idle2=10]="Idle2",r[r.Die1=11]="Die1",r[r.Die2=12]="Die2",r[r.Hover=13]="Hover",r[r.Fly=14]="Fly",r[r.FireFly=15]="FireFly",r[r.Tumble=16]="Tumble",r[r.AirDeathStart=17]="AirDeathStart",r[r.AirDeathFalling=18]="AirDeathFalling",r[r.AirDeathFinish=19]="AirDeathFinish",r[r.Tread=20]="Tread",r[r.Swim=21]="Swim",r[r.WetAttack=22]="WetAttack",r[r.WetIdle1=23]="WetIdle1",r[r.WetIdle2=24]="WetIdle2",r[r.WetDie1=25]="WetDie1",r[r.WetDie2=26]="WetDie2",r[r.Deploy=27]="Deploy",r[r.Deployed=28]="Deployed",r[r.DeployedFire=29]="DeployedFire",r[r.DeployedIdle=30]="DeployedIdle",r[r.Undeploy=31]="Undeploy",r[r.Paradrop=32]="Paradrop",r[r.Cheer=33]="Cheer",r[r.Panic=34]="Panic";const zn=new Map([["E",5],["S",3],["W",1],["N",7]]);class Vn{readIni(e){let t=new Map;for(var[i,s]of e.entries){i=cn[i];void 0!==i&&(s=s.split(","),s={type:i,startFrame:Number(s[0]),frameCount:Number(s[1]),facingMult:Number(s[2]),onlyFacing:s[3]?zn.get(s[3]):void 0},t.set(i,s))}return t}}(r=un=un||{})[r.None=0]="None",r[r.Global=1]="Global",r[r.Level=2]="Level",r[r.Ambient=3]="Ambient",r[r.Full=4]="Full",r[r.Default=5]="Default";class Hn{constructor(e,t,i){this.sequences=new Map,this.dockingOffsets=[],this.type=e,this.rules=t,this.art=i,this.init()}static getDefaultPalette(e){switch(e){case 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 un.None;case Ct.Aircraft:case Ct.Building:case Ct.Infantry:case Ct.Vehicle:return un.Ambient;case Ct.Projectile:case Ct.VoxelAnim:return un.Global;case Ct.Overlay:case Ct.Smudge:case Ct.Terrain:default:return un.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 vs(0,0);case Ct.Terrain:case Ct.Aircraft:return new vs(0,(Ss.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,s){var r=t.imageName;let a=i.getSection(r);a||(s?.debug(`Image ${r} (${Ct[e]}: ${t.name}) has no section in art.ini`),a=new h(r));let n=new this(e,t,a);return e===Ct.Infantry&&(!(e=a.getString("Sequence"))||(e=i.getSection(e))&&(n.sequences=(new Vn).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 vs(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",Hn.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",Hn.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")||Hn.MISSING_CAMEO;return e.toLowerCase()}get altCameo(){let e=this.art.getString("AltCameo")||Hn.MISSING_CAMEO;return e.toLowerCase()}get useTheaterExtension(){return this.art.getBool("Theater")}readPaletteAndLightingTypes(){this.paletteType=O.Default,this.lightingType=un.Default,(this.rules instanceof ns?this.rules.noUseTileLandType:void 0)&&(this.paletteType=O.Iso,this.lightingType=un.Full),this.art.getBool("TerrainPalette")||this.art.getBool("ShouldUseCellDrawer")?this.paletteType=O.Iso:this.art.getBool("AnimPalette")?(this.paletteType=O.Anim,this.lightingType=un.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 ns||this.rules instanceof as)&&this.rules.wall&&(this.paletteType=O.Unit,this.lightingType=un.Ambient),(this.rules instanceof os||this.rules instanceof as)&&this.rules.gate&&(this.paletteType=O.Unit),this.rules instanceof os&&this.rules.spawnsTiberium&&(this.paletteType=O.Unit,this.lightingType=un.None),this.rules instanceof ns&&(this.rules.isVeins&&(this.paletteType=O.Unit,this.lightingType=un.None),this.rules.isVeinholeMonster&&(this.paletteType=O.Unit,this.lightingType=un.None),this.rules.tiberium&&(this.lightingType=un.None),this.rules.land===Yt.Railroad&&(this.paletteType=O.Iso,this.lightingType=un.Full),this.rules.crate&&(this.paletteType=O.Iso,this.lightingType=un.Full)),this.paletteType===O.Default&&(this.paletteType=Hn.getDefaultPalette(this.type)),this.lightingType===un.Default&&(this.lightingType=Hn.getDefaultLighting(this.type))}readRemapability(){this.remapable=Hn.getDefaultRemapability(this.type),this.art.getBool("TerrainPalette")||this.art.getBool("AnimPalette")?this.remapable=!1:this.rules instanceof $i&&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 ns&&(this.rules.wall||this.rules.crate||this.rules.isARock||(e=!0)),this.flat=e}readRotors(){var i=this.art.getArray("Rotors");if(i.length){let t=[];for(let e=0;e<i.length;++e){var s=this.art.getNumberArray(`Rotor${e+1}Axis`,void 0,[0,1,0]),s=new is(-s[2],-s[0],s[1]).normalize();t.push({name:i[e],axis:s,speed:this.art.getNumber(`Rotor${e+1}Rate`)||void 0,idleSpeed:this.art.getNumber(`Rotor${e+1}IdleRate`)||void 0})}t.length&&(this.rotors=t)}}readMuzzleFlash(){let e=0,t=`MuzzleFlash${e}`,i=[];for(;this.art.has(t);){var[s,r]=this.art.getNumberArray(t);i.push({x:s,y:r}),e++,t=`MuzzleFlash${e}`}this.muzzleFlash=i.length?i:void 0}readDockingOffsets(){if(this.type===Ct.Building){var t=this.rules.numberOfDocks;for(let e=0;e<t;e++){var[i,s,r]=this.art.getNumberArray(`DockingOffset${e}`,/\,\s*/,[0,0,0]);this.dockingOffsets.push(new is(i,r,s))}}}readAddRemoveOccupy(e){let t=0,i=[];for(;;){var s=this.art.getNumberArray(e+ ++t);if(!s.length)break;i.push(new vs(s[0],s[1]))}return i}get bibShape(){return this.art.getString("BibShape")}get foundation(){let e=this.art.getString("Foundation","1x1");var[t,i]=e.split("x");return{width:parseInt(t,10),height:parseInt(i,10)}}get foundationCenter(){return{x:Math.floor(this.foundation.width/2-.5),y:Math.floor(this.foundation.height/2-.5)}}getDrawOffset(){if(this.rules instanceof os&&this.rules.spawnsTiberium)return new vs(0,0);let e=Hn.getDefaultDrawOffset(this.type);return this.rules instanceof ns&&this.rules.isARock&&(e.y+=(Ss.ISO_TILE_SIZE+1)/2),e}get hasShadow(){return this.art.getBool("Shadow",Hn.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 Qa(this.art.getNumberArray("PrimaryFireFLH"))}get elitePrimaryFireFlh(){var e=this.art.getNumberArray("ElitePrimaryFireFLH");return e.length?new Qa(e):this.primaryFireFlh}get primaryFirePixelOffset(){return this.art.getNumberArray("PrimaryFirePixelOffset")}get secondaryFirePixelOffset(){return this.art.getNumberArray("SecondaryFirePixelOffset")}get secondaryFireFlh(){return new Qa(this.art.getNumberArray("SecondaryFireFLH"))}get eliteSecondaryFireFlh(){var e=this.art.getNumberArray("EliteSecondaryFireFLH");return e.length?new Qa(e):this.secondaryFireFlh}getSpecialWeaponFlh(e){return new Qa(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}}Hn.DEFAULT_LINE_TRAIL_DEC=16,Hn.MISSING_CAMEO="xxicon";class Gn{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){if(!e)throw new Error(`Must specify an art name for type "${Ct[t]}"`);var i=this.objectArt.get(t)?.get(e);return i||(this.logger?.debug(`Missing art for object "${e}"`),new Hn(t,this.rules.hasObject(e,t)?this.rules.getObject(e,t):new Oi(t,new h(e)),new h(e)))}getAnimation(e){return this.getObject(e,Ct.Animation)}getProjectile(e){e=this.rules.getProjectile(e);return Hn.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=Hn.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(([s,e])=>{let r=new Map;this.objectArt.set(s,r),e.forEach(e=>{var t,i=this.artIni.getSection(e);i?(t=new Oi(s,new h(e)),i=new Hn(s,t,i),r.set(e,i)):this.logger?.debug(`${Ct[s]} "${e}" has no art section`)})})}}class $n{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 qn{constructor(e,t){this.target=e,this.player=t,this.type=ts.BuildingEvacuate}}class Xn{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}[ha.onDamage](e,t){e.healthTrait.health<=100*this.evacThreshold&&this.evacuate(t)}[Ur.onDestroy](e,t,i,s){if(s){for(var r of this.units)t.destroyObject(r,i,!0);this.units=[]}else this.evacuate(t)}getHash(){return V(this.units.map(e=>e.getHash()))}debugGetState(){return{units:this.units.map(e=>e.debugGetState())}}dispose(){this.building=void 0}evacuate(s,r=!1){let a=this.building,n=this.units;if(n.length){let e=new Map;for(var t of n)e.set(t.rules.speedType,(e.get(t.rules.speedType)||[]).concat(t));for(let[t,i]of e){var o,h=new Fs(s.map.tiles,s.map.mapBounds,a.tile,a.art.foundation,1,1,e=>0<s.map.terrain.getPassableSpeed(e,t,!1)&&Math.abs(e.z-a.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},i[0]).length).getNextTile();for(o of i){var l=n.indexOf(o);h?(n.splice(l,1),s.unlimboObject(o,h),o.unitOrderTrait.addTask(new Ta(s))):r||(s.destroyObject(o,{player:o.owner}),n.splice(l,1))}}var i=a.owner;n.length||a.isDestroyed||s.changeObjectOwner(a,s.getCivilianPlayer()),s.events.dispatch(new qn(a,i))}}}class Qn{constructor(){this.facing=0,this.desiredFacing=0}isRotating(){return this.facing!==this.desiredFacing}[Mr.onTick](e){this.desiredFacing!==this.facing&&(e=e.rules.rot,this.facing=wr.tick(this.facing,this.desiredFacing,e||Number.POSITIVE_INFINITY).facing)}}class Zn{constructor(e,t){this.target=e,this.status=t,this.type=ts.BuildStatusChange}}class Yn{constructor(e){this.target=e,this.type=ts.PowerLow}}class Kn{constructor(e){this.target=e,this.type=ts.PowerRestore}}class Jn{constructor(e,t,i){this.target=e,this.power=t,this.drain=i,this.type=ts.PowerChange}}(r=dn=dn||{})[r.Low=0]="Low",r[r.Normal=1]="Normal";class eo{constructor(e){this.player=e,this.power=0,this.drain=0,this.level=dn.Normal,this.blackoutFrames=0,this.powerByObject=new Map}isLowPower(){return this.level===dn.Low}setBlackoutFor(e,t){var i=0<this.blackoutFrames;this.blackoutFrames=e,i||this.updateLevel(t)}updateBlackout(e){0<this.blackoutFrames&&(this.blackoutFrames--,this.blackoutFrames<=0&&this.updateLevel(e))}getBlackoutDuration(){return this.blackoutFrames}updateFrom(t,i,s){var r=t.rules.power;if(r){if(r<0)"add"!==i&&"remove"!==i||(this.drain+="add"===i?-r:r);else{let e=0;if("add"===i){var a=Math.ceil(r*t.healthTrait.health/100);this.powerByObject.set(t,a),e=a}else if("update"===i||"remove"===i){a=this.powerByObject.get(t);if(void 0===a)throw new Error("Cannot update power before add.");e="update"===i?(r=Math.ceil(r*t.healthTrait.health/100),this.powerByObject.set(t,r),r-a):(this.powerByObject.delete(t),-a)}this.power+=e}this.updateLevel(s),s.traits.filter(Ns).forEach(e=>{e[Ns.onPowerChange](this.player,s)}),s.events.dispatch(new Jn(this.player,this.power,this.drain))}}updateLevel(t){var e=this.level;this.level=this.power>=this.drain&&!this.blackoutFrames?dn.Normal:dn.Low,this.level!==e&&(e===dn.Normal&&this.level===dn.Low&&(t.traits.filter(Ns).forEach(e=>{e[Ns.onPowerLow](this.player,t)}),t.events.dispatch(new Yn(this.player))),e===dn.Low&&this.level===dn.Normal&&(t.traits.filter(Ns).forEach(e=>{e[Ns.onPowerRestore](this.player,t)}),t.events.dispatch(new Kn(this.player))))}getHash(){return V([this.power,this.drain])}debugGetState(){return{power:this.power,drain:this.drain}}dispose(){this.player=void 0,this.powerByObject.clear()}}class to{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!==dn.Low))}dispose(){this.obj=void 0}}class io{constructor(){this.listeners=new Set}subscribe(e){this.listeners.add(e)}subscribeOnce(i){let s=(e,t)=>{i(e,t),this.unsubscribe(s),s=void 0};this.subscribe(s)}unsubscribe(e){this.listeners.delete(e)}dispatch(t,i){this.listeners.forEach(e=>e(i,t))}asEvent(){return this}}(r=pn=pn||{})[r.Structures=0]="Structures",r[r.Armory=1]="Armory",r[r.Infantry=2]="Infantry",r[r.Vehicles=3]="Vehicles",r[r.Aircrafts=4]="Aircrafts",r[r.Ships=5]="Ships",(r=gn=gn||{})[r.Idle=0]="Idle",r[r.Active=1]="Active",r[r.OnHold=2]="OnHold",r[r.Ready=3]="Ready";class so{constructor(e,t,i){this.type=e,this._maxSize=t,this.maxItemQuantity=i,this.items=[],this.size=0,this._status=gn.Idle,this._onUpdate=new io}get onUpdate(){return this._onUpdate.asEvent()}get status(){return this._status}set status(e){var t=this._status;(this._status=e)!==t&&this._onUpdate.dispatch(this)}get maxSize(){return this._maxSize}set maxSize(e){var t=this.size;this.size=Math.min(e,this.size);let i=0,s=0;for(;i<=this.size&&s<this.items.length;){let e=this.items[s];i+=e.quantity,i>this.size&&(e.quantity-=i-this.size),0<e.quantity&&s++}this._maxSize=e,this.items[s]&&this.items.splice(s),t!==this.size&&(this.size||(this._status=gn.Idle),this._onUpdate.dispatch(this))}get currentSize(){return this.size}find(t){return this.items.filter(e=>e.rules===t)}getFirst(){return this.items[0]}getAll(){return[...this.items]}push(e,t,i){t=Math.min(this.maxSize-this.size,t);var s=this.find(e).reduce((e,t)=>e+t.quantity,0);t=Math.min(this.maxItemQuantity-s,t),this.items[this.items.length-1]?.rules===e?this.items[this.items.length-1].quantity+=t:this.items.push({rules:e,quantity:t,creditsEach:i,creditsSpent:0,creditsSpentLeftover:0,progress:0}),this.size+=t,t&&(this._status===gn.Idle&&(this._status=gn.Active),this._onUpdate.dispatch(this))}pop(e,t){this.remove(e,t,!1)}shift(e,t){this.remove(e,t,!0)}remove(e,t,i){let s=this.find(e);if(!s.length)throw new Error(`Can't remove non-existent item ${e.name} from queue ${pn[this.type]}`);var r;if(s.reduce((e,t)=>e+t.quantity,0)<t)throw new Error(`Attempted to remove a quantity larger than the one in queue (${e.name})`);let a=t;for(;0<a;){let e=i?s.shift():s.pop();e.quantity<=a?(r=this.getFirst()===e,this.items.splice(this.items.indexOf(e),1),r&&(this._status=gn.Active),a-=e.quantity):(e.quantity-=a,a=0)}this.size-=t,t&&(this.size||(this._status=gn.Idle),this._onUpdate.dispatch(this))}notifyUpdated(){this._onUpdate.dispatch(this)}}class ro extends ba{constructor(e,t,i,s){super(e,i,!1,{ignoredBlockers:[t],closeEnoughTiles:0,strictCloseEnough:!0,forceWaitOnPathBlocked:t.factoryTrait?.type!==Ki.InfantryType}),this.factory=t,this.rallyPoint=s,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===Hr.ReachedNextWaypoint&&this.options?.ignoredBlockers&&!this.game.map.terrain.isBlockerObject(this.factory,e.tile,!1,e.rules.speedType)&&(this.options.ignoredBlockers=void 0,this.preventOpportunityFire=!1,this.rallyPoint&&(this.updateTarget(this.rallyPoint.tile,!!this.rallyPoint.onBridge),this.cancellable=!0,this.options.closeEnoughTiles=this.game.rules.general.closeEnough,this.options.strictCloseEnough=!1,this.options.forceWaitOnPathBlocked=!1)),super.onTick(e)}}class ao{constructor(e,t,i,s,r,a=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.predicate=a,this.dirVec=new vs(10,0),this.finished=!1,this.diagonal=!0,this.distance=s}getNextTile(){if(!this.finished){let t;do{let e={x:this.startTile.rx,y:this.startTile.ry};e.x+=this.distance*Math.sign(this.dirVec.x),e.y+=this.distance*Math.sign(this.dirVec.y),this.dirVec.rotateAround(new vs,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}}}(mn=mn||{}).onSell=Symbol();class no{[Qr.onUnspawn](e){this.undock(e),this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[qr.onChange](e){e.owner!==this.dock?.owner&&this.undock(e),e.owner!==this.reservedDock?.owner&&this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[jr.onBeforeTeleport](e,t,i,s){s||this.undock(e)}undock(e){this.dock&&!this.dock.isDisposed&&this.dock.dockTrait.undockUnit(e)}dispose(){this.dock=void 0,this.reservedDock=void 0}}class oo{constructor(e,t,i,s){this.building=e,this.tiles=t,this.numberOfDocks=i,this.dockingOffsets=s,this.ticksWhenWarpedOut=!0,this.unitsByDockNumber=new Array(i).fill(void 0),this.reservedDocks=new Array(i).fill(void 0)}[Xr.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}}[Qr.onUnspawn](){for(let e=0;e<this.numberOfDocks;e++)this.unreserveDockAt(e)}[Mr.onTick](){for(let e=0;e<this.numberOfDocks;e++){var t=this.unitsByDockNumber[e];t&&t.tile!==this.getDockTile(e)&&this.undockUnit(t)}}[Ur.onDestroy](e,t,i,s){var r=(e.rules.unitRepair||e.helipadTrait)&&!e.rules.naval&&!i?.weapon?.warhead.rules.temporal;if(r)for(var a of this.unitsByDockNumber)a&&!a.isDestroyed&&(r?t.destroyObject(a,i,s):this.undockUnit(a))}[mn.onSell](s,r){if(s.helipadTrait&&this.hasDockedUnits()){var a,e,n;let t=[],i=0;for(a of[...s.owner.buildings].filter(e=>e.helipadTrait&&(e.dockTrait?.getAvailableDockCount()??!1)&&e!==s)){let e=a.dockTrait?.getAvailableDockCount()??0;for(;0<e&&i<this.unitsByDockNumber.length;)t.push(a),e--,i++;if(i===this.unitsByDockNumber.length)break}i=0;for(e of this.unitsByDockNumber)e&&((n=t[i])?e.unitOrderTrait.addTask(new pa(r,n)):e.unitOrderTrait.addTask(new La(new ba(r,e.tile,!1),new da(e=>{e.crashableTrait?e.crashableTrait.crash({player:s.owner}):r.destroyObject(e,{player:s.owner})})).setCancellable(!1))),i++}else{var t,i=s.rules.unitRepair&&!s.rules.naval;for(t of this.unitsByDockNumber)t&&(i?r.sellTrait.sell(t):this.undockUnit(t))}}[qr.onChange](e,t,i){for(var s of this.unitsByDockNumber)s&&i.changeObjectOwner(s,e.owner)}getFirstAvailableDockNumber(){if(!this.building?.warpedOutTrait.isActive()){var e=this.unitsByDockNumber.findIndex((e,t)=>!e&&!this.reservedDocks[t]);if(-1!==e)return e}}getAvailableDockCount(){return this.building?.warpedOutTrait.isActive()?0:this.unitsByDockNumber.filter((e,t)=>!e&&!this.reservedDocks[t]).length}getFirstEmptyDockNumber(){if(!this.building?.warpedOutTrait.isActive()){var e=this.unitsByDockNumber.findIndex(e=>!e);if(-1!==e)return e}}getDockOffset(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);return this.dockingOffsets[e]}getDockTile(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);return this.dockTiles[e]}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)/Ss.LEPTONS_PER_TILE),Math.floor((t.y+e.z)/Ss.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}`);let i=e.traits.find(no);if(!i)throw new Error(`Unit "${e.name}" cannot be docked to ${this.building.name}`);this.unitsByDockNumber[t]=e,i.dock=this.building}undockUnitAt(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);let t=this.unitsByDockNumber[e];t&&(this.unitsByDockNumber[e]=void 0,t.traits.get(no).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(Ma)}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(no).reservedDock?.dockTrait.unreserveDockForUnit(e),e.traits.get(no).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(no).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 ho{constructor(e){this.target=e,this.type=ts.FactoryProduceUnit}}(r=fn=fn||{})[r.All=0]="All",r[r.Ground=1]="Ground",r[r.Air=2]="Air";class lo{constructor(e){this.tiles=e,this.tileOccupation=[],this.emptyTiles=new Set,this._onChange=new io;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=Vi(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 _s(t?e.landType:e.onBridgeLandType??e.landType)}getBridgeOnTile(e){for(var t of this.tileOccupation[e.rx]?.[e.ry]??[])if(t.isOverlay()&&t.isBridge())return t}getObjectsOnTile(e){return[...this.tileOccupation[e.rx]?.[e.ry]??[]]}getGroundObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isTechno()&&!i.isBuilding()&&i.zone===Ts.Air||t.push(i);return t}getAirObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isUnit()&&i.zone===Ts.Air&&t.push(i);return t}getObjectsOnTileByLayer(e,t){if(t===fn.Ground)return this.getGroundObjectsOnTile(e);if(t===fn.Air)return this.getAirObjectsOnTile(e);if(t===fn.All)return this.getObjectsOnTile(e);throw new Error(`Unhandled layer type "${t}"`)}getEmptyTiles(){return[...this.emptyTiles]}}(yn=yn||{}).onChange=Symbol(),(wn=wn||{}).onProduce=Symbol(),(r=Tn=Tn||{})[r.Idle=0]="Idle",r[r.Delivering=1]="Delivering";class co{constructor(e,t=!1){this.type=e,this.isCloningVats=t,this.status=Tn.Idle}[Xr.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;[Ki.BuildingType,Ki.AircraftType].includes(this.type)||(i=this.computeDefaultRallyPoint(e,this.type,t.map),e.rallyTrait?.changeRallyPoint(i,e,t))}[yn.onChange](t,e,i){if(t.owner.production){let e=[];e=this.type===Ki.BuildingType?[pn.Structures,pn.Armory]:[t.owner.production.getQueueTypeForFactory(this.type)];for(var s of e)t.owner.production.getQueue(s).notifyUpdated()}}[Mr.onTick](i,s){if(this.status===Tn.Delivering){if(!this.deliveringUnit||this.deliveringUnit.isDestroyed){if(this.buildingProductionTicks=this.buildingProductionTicks??1,0<this.buildingProductionTicks--)return;this.buildingProductionTicks=void 0}else if(s.map.tileOccupation.isTileOccupiedBy(this.deliveringUnit.tile,i)){if(!this.deliveringUnit.rules.consideredAircraft)return;if(this.deliveringUnit.position.tileElevation<i.art.height)return}return this.status=Tn.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===Ki.UnitType)&&this.type!==Ki.BuildingType){let e=i.owner.production.getQueueForFactory(this.type);if(e&&e.status===gn.Ready){let t=e.getFirst();if(this.type===Ki.AircraftType){let e=this.produceAircraftAt(i,t,s);var r;if(!e)for(r of[...i.owner.buildings].filter(e=>e.factoryTrait?.type===Ki.AircraftType&&e.helipadTrait)){if(e)break;e=this.produceAircraftAt(r,t,s)}if(!e)return}else if(this.produceGroundUnitAt(i,t,s),!this.isCloningVats&&this.type===Ki.InfantryType){let e=[...i.owner.buildings].find(e=>e.factoryTrait&&e.rules.cloning);e?.factoryTrait.status===Tn.Idle&&e?.factoryTrait.produceGroundUnitAt(e,t,s)}i.owner.addUnitsBuilt(t.rules.type,1),t.creditsSpent=0,t.progress=0,e.shift(t.rules,1),e.currentSize&&(e.status=gn.Active)}}}}produceGroundUnitAt(e,t,i){let s=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(s.rules)&&s.veteranTrait?.setVeteranLevel(Yr.Veteran),s.isInfantry()&&(s.position.subCell=Na.SUB_CELLS[0]);let r=e.rallyTrait.findRallyPointforUnit(s,this.computeInternalRallyPoint(e,this.type,e.rallyTrait.getRallyPoint(),i.map),i.map),a;var n;a=this.type===Ki.NavalUnitType?r:(n=this.computeExitCoords(e,this.type),i.map.tiles.getByMapCoords(Math.floor(n.rx),Math.floor(n.ry))),s.rules.consideredAircraft&&(r=a);let o;if(e.rallyTrait.getRallyPoint()!==r&&(o=e.rallyTrait.findRallyNodeForUnit(s,i.map)),s.isInfantry()){let t=i.map.tileOccupation.getObjectsOnTileByLayer(o?.tile??r,s.rules.consideredAircraft?fn.Air:fn.Ground).filter(e=>e.isInfantry()&&e.moveTrait.moveState!==Hr.Moving).map(e=>e.position.subCell);s.position.subCell=Na.SUB_CELLS.find(e=>!t.includes(e))??Na.SUB_CELLS[0]}s.direction=270,i.spawnObject(s,a),i.traits.filter(wn).forEach(e=>{e[wn.onProduce](s,i)}),i.events.dispatch(new ho(s)),s.rules.consideredAircraft?(n=o??{tile:r,onBridge:void 0},s.unitOrderTrait.addTask(new ba(i,n.tile,!!n.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))):s.unitOrderTrait.addTask(new ro(i,e,r,o)),this.status=Tn.Delivering,this.deliveringUnit=s}produceAircraftAt(e,t,i){let s=e.traits.find(oo);if(!s)return!1;var r=s.getFirstAvailableDockNumber();if(void 0===r)return!1;let a=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(a.rules)&&a.veteranTrait?.setVeteranLevel(Yr.Veteran);t=s.getDockOffset(r);return a.position.moveToLeptons(e.position.getMapPosition()),a.position.moveByLeptons3(t),i.spawnObject(a,a.position.tile),s.dockUnitAt(a,r),a.isAircraft()&&a.airportBoundTrait&&(a.airportBoundTrait.preferredAirport=e),i.traits.filter(wn).forEach(e=>{e[wn.onProduce](a,i)}),i.events.dispatch(new ho(a)),!0}computeExitCoords(e,t){if(t===Ki.InfantryType)return this.computeBarracksDefaultExitCoords(e);if(t===Ki.UnitType)return this.computeWarFactoryExitCoords(e);throw new Error(`Unsupported factory type ${Ki[t]}`)}computeInternalRallyPoint(e,t,i,s){let r,a;if(t===Ki.NavalUnitType)a=this.computeNavalInternalRallyPoint(e,i,s);else{if(t===Ki.InfantryType)r=this.computeBarracksInternalRallyCoords(e);else{if(t!==Ki.UnitType)throw new Error(`Unsupported factory type ${Ki[t]}`);r=this.computeWarFactoryInternalRallyCoords(e)}a=s.tiles.getByMapCoords(r.rx,r.ry)}return a??this.findTileAdjacentToBuilding(e,s)}computeDefaultRallyPoint(e,t,i){let s,r;if(t===Ki.NavalUnitType)r=this.computeNavalDefaultRallyPoint(e,i);else{if(t===Ki.InfantryType)s=this.computeBarracksInternalRallyCoords(e);else{if(t!==Ki.UnitType)throw new Error(`Unsupported factory type ${Ki[t]}`);s=this.computeWarFactoryDefaultRallyCoords(e)}r=i.tiles.getByMapCoords(s.rx,s.ry)}return r??this.findTileAdjacentToBuilding(e,i)}findTileAdjacentToBuilding(e,t){return new Fs(t.tiles,t.mapBounds,e.tile,e.getFoundation(),1,1,()=>!0).getNextTile()}computeBarracksDefaultExitCoords(e){var t=e.getFoundation();let i,s;return t.width<=2||t.height<=2?(i=t.width-1,s=t.height-1,e.rules.gdiBarracks&&2<t.width&&(i=Math.floor(t.width/2))):(i=0,s=t.height-1),{rx:e.tile.rx+i,ry:e.tile.ry+s}}computeBarracksInternalRallyCoords(e){var t=e.getFoundation();let{rx:i,ry:s}=this.computeBarracksDefaultExitCoords(e);return!(t.width<=2||t.height<=2)||e.rules.gdiBarracks?s+=1:e.rules.nodBarracks&&(i+=t.width<=2?1:0,s+=t.height<=2?1:0),{rx:i,ry:s}}computeWarFactoryExitCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+Math.floor(t.width/2),ry:e.tile.ry+Math.floor(t.height/2)}}computeWarFactoryInternalRallyCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+t.width-1,ry:e.tile.ry+Math.floor(t.height/2)}}computeWarFactoryDefaultRallyCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+t.width,ry:e.tile.ry+Math.floor(t.height/2)}}computeNavalDefaultRallyPoint(e,t){let i=new ao(t.tiles,t.mapBounds,e.centerTile,5,5,e=>e.terrainType===Zt.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 vs(t.rx,t.ry).sub(new vs(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 uo{constructor(e,t,i,s,r,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=s,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=r,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var s=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var r=this.startTile.rx-this.distance,a=this.startTile.ry-this.distance,n=this.startTile.rx+this.foundation.width-1+this.distance,o=this.startTile.ry+this.foundation.height-1+this.distance;let e,t,i;if(0<this.distance){for(t=1+a;t<o;t++)i=s(r,t),i&&(yield i);for(e=r;e<n;e++)i=s(e,a),i&&(yield i);for(t=o-1;t>=a;t--)i=s(n,t),i&&(yield i);for(e=n;e>=r;e--)i=s(e,o),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}class po{[Xr.onSpawn](i,s){let e;if(s.rules.hasObject(i.rules.freeUnit,Ct.Vehicle))e=s.rules.getObject(i.rules.freeUnit,Ct.Vehicle);else{if(!s.rules.hasObject(i.rules.freeUnit,Ct.Infantry))return void console.warn(`Free unit "${i.rules.freeUnit}" is not a vehicle or infantry type.`);e=s.rules.getObject(i.rules.freeUnit,Ct.Infantry)}let r=s.createUnitForPlayer(e,i.owner),a;var t=new uo(s.map.tiles,s.map.mapBounds,i.tile,i.getFoundation(),1,1,e=>{var t=0<s.map.terrain.getPassableSpeed(e,r.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},r).length;return!a&&t&&(a=e),t&&!s.map.getObjectsOnTile(e).find(e=>e.isOverlay())}).getNextTile()??a;if(!t)return i.owner.removeOwnedObject(r),void r.dispose();s.spawnObject(r,t)}}class go{[mn.onSell](e,t){this.spawnSurvivors(e,t)}[Ur.onDestroy](e,t,i,s){s||i?.obj===e&&i.weapon?.rules.suicide||e.isVehicle()&&e.moveTrait.isMoving()||e.crashableTrait||this.spawnSurvivors(e,t)}spawnSurvivors(s,r){var t=r.rules.general.crew,e=s.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(s.rules.cost*t.survivorRate/i);s.isVehicle()&&(n=Math.min(1,n));let o=[];for(let e=0;e<n;e++)(0===e||r.generateRandom()>=t.crewEscape)&&o.push(a);if(s.rules.constructionYard&&(o=[...o,r.rules.general.engineer]),0<o.length){var h,l=r.map.tiles.getInRectangle(s.tile,s.getFoundation()).filter(e=>r.map.isWithinBounds(e));let i=[...l];for(h of o){var c=r.rules.getObject(h,Ct.Infantry);if(r.map.terrain.getPassableSpeed(s.tile,c.speedType,!s.isBuilding()&&s.onBridge,void 0,!0)){let e=r.createUnitForPlayer(c,s.owner),t=i.length?i.splice(r.generateRandomInt(0,i.length-1),1)[0]:void 0;t=t||l[r.generateRandomInt(0,l.length-1)],e.isInfantry()&&(e.position.subCell=Na.SUB_CELLS[0]),e.veteranTrait&&s.owner.canProduceVeteran(e.rules)&&e.veteranTrait.setVeteranLevel(Yr.Veteran),r.spawnObject(e,t),s.isBuilding()&&e.unitOrderTrait.addTask(new Ta(r,void 0,{ignoredBlockers:s.isDestroyed?void 0:[s]}))}}}}}class mo{constructor(e,t){this.gameObject=e,this.bridges=t,this.checkedClosestBridge=!1}canRepairBridge(){var e=this.findClosestBridgeBounds();return e?this.bridges.canBeRepaired(e):(console.warn(`No bridge associated with hut at ${this.gameObject.tile.rx}, ${this.gameObject.tile.ry}.`),!1)}repairBridge(t,i){var s=this.findClosestBridgeBounds();if(!s)throw new Error("No bridge bounds found");var e=this.bridges.findDestroyedPieceTiles(s),r=s.start.rx!==s.end.rx;let a;a=s.isHigh?Wa.calculateHighBridgeOverlayId(s.type,r):Wa.calculateLowBridgeOverlayId(s.type,r);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=s.isHigh?4:0,t.spawnObject(e,n),this.updateUnitsUnderBridgePiece(n,s,t,i)}for(o of this.bridges.findBridgePieces(s))o.obj.bridgeTrait.bridgeSpec=s}updateUnitsUnderBridgePiece(e,i,s,r){var a;for(let t of this.bridges.getPieceTiles(this.bridges.getPieceAtTile(e)))if(i.isHigh){let e=s.map.getGroundObjectsOnTile(t).filter(e=>e.tile===t&&e.isUnit()&&!e.unitOrderTrait.hasTasks()&&e.rules.tooBigToFitUnderBridge);e.forEach(e=>e.unitOrderTrait.addTask(new Ta(s)))}else for(a of s.map.getGroundObjectsOnTile(t))a.isUnit()&&(s.map.terrain.getPassableSpeed(t,a.rules.speedType,!0)?(a.zone=Ts.Ground,a.onBridge=!0):a.isDestroyed||s.destroyObject(a,{player:r}))}demolishBridge(e,t){var i=this.getBridgePieces();if(i)for(var s of i)s.obj.isLowBridge()&&e.map.getTileZone(s.obj.tile,!0)!==Ts.Water||s.obj.isDestroyed||(s.obj.deathType=Wr.Demolish,e.destroyObject(s.obj,t,!0))}getBridgePieces(){var e=this.findClosestBridgeBounds();if(e)return this.bridges.findBridgePieces(e)}findClosestBridgeBounds(){return this.checkedClosestBridge||(this.checkedClosestBridge=!0,this.closestBridge=this.bridges.findClosestBridgeSpec(this.gameObject.tile)),this.closestBridge}dispose(){this.gameObject=void 0}}class fo{constructor(){this.isActive=!1,this.produceCashCooldown=0}[Xr.onSpawn](e){e.owner.isNeutral||(this.isActive=!0)}[qr.onChange](e,t){t.isNeutral&&!e.owner.isNeutral&&(e.owner.credits=Math.max(0,e.owner.credits+e.rules.produceCashStartup),this.isActive=!0,this.produceCashCooldown=e.rules.produceCashDelay)}[Mr.onTick](e){this.isActive&&(this.produceCashCooldown--,this.produceCashCooldown<=0&&(this.produceCashCooldown=e.rules.produceCashDelay,e.owner.credits=Math.max(0,e.owner.credits+e.rules.produceCashAmount)))}}class yo{constructor(){this.linkedDamageHandled=!1}[ha.onDamage](e,t,i,s){if(!this.linkedDamageHandled){var r=Math.floor(i/2);if(r)for(var a of t.map.tiles.getAllNeighbourTiles(e.tile))if(a.landType===Yt.Wall){let e=t.map.getObjectsOnTile(a).find(e=>(e.isBuilding()||e.isOverlay())&&e.wallTrait);e.wallTrait.linkedDamageHandled=!0,e.healthTrait.inflictDamage(r,s,t),e.wallTrait.linkedDamageHandled=!1,e.healthTrait.health||t.destroyObject(e,s)}}}}const wo=e=>void 0!==e.position;class To{constructor(e,t){this.tiles=e,this.tileOccupation=t}hasLineOfSight(e,t,i){var s=i.warhead.rules.wall||!i.projectileRules.subjectToWalls,r=i.projectileRules.subjectToCliffs,a=i.rules.spawner;let n=0,o=!1;if(!s||r||a){var h,l,c=wo(e)?e.tile:e,t=wo(t)?t.tile:t;for({x:h,y:l}of Da(c.rx,c.ry,t.rx,t.ry)){var u=this.tiles.getByMapCoords(h,l);if(!u)return!1;if(!s&&u.landType===Yt.Wall)return!1;if(r)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}}class bo extends ba{constructor(e,t,i,s){super(e,t instanceof Ia?t.isBuilding()?t.centerTile:t.tile:t,i,{pathFinderIgnoredBlockers:t instanceof Ia&&0<s.range?[t]:void 0}),this.target=t,this.weapon=s,this.recalcMinRange=!0,this.cancelRequested=!1,this.bomberInitialLock=!1,this.rangeHelper=new Is(e.map.tileOccupation),this.losHelper=new To(e.map.tiles,e.map.tileOccupation)}onStart(i){let e=this.target,s=this.game.map;if(e instanceof Ia&&e.isBuilding()&&i.rules.movementZone!==ii.Fly){let t=e.tile;var r=e instanceof Ia?e.getFoundation():{width:1,height:1},r=new Fs(s.tiles,s.mapBounds,t,r,1,5,e=>0<s.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-t.z)<2).getNextTile();r&&this.rangeHelper.tileDistance(e,r)>Math.SQRT2&&this.updateTarget(r,!1)}this.bomberInitialLock=this.isCloseEnoughToDest(i,i.tile),super.onStart(i)}cancel(){this.bomberManeuverTile?this.cancelRequested=!0:super.cancel()}shouldAirStrafe(e){return e.rules.movementZone===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 fa(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!==Ts.Air&&this.target instanceof Ia&&this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)&&(!this.target.isUnit()||this.target.tile===e&&this.target.moveTrait.moveState!==Hr.Moving))return!1;if(t.zone!==Ts.Air){if(!super.canStopAtTile(t,e,i))return!1}else if(this.game.map.tileOccupation.getAirObjectsOnTile(e).filter(e=>e.isUnit()&&e.moveTrait.moveState!==Hr.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===Ts.Air?e.position.computeSubCellOffset(e.position.desiredSubCell):e.position.getTileOffset(),{minRange:s,range:r}=this.rangeHelper.computeWeaponRangeVsTarget(t,this.target,this.weapon,this.game.rules),i=Ss.tile3dToWorld(t.rx+i.x/Ss.LEPTONS_PER_TILE,t.ry+i.y/Ss.LEPTONS_PER_TILE,t.z+e.position.tileElevation);return(e.isUnit()&&e.rules.movementZone===ii.Fly?this.rangeHelper.isInRange2(i,this.target,s,r):this.rangeHelper.isInRange3(i,this.target,s,r))&&this.losHelper.hasLineOfSight(t,this.target,this.weapon)}findRelocationTile(t,i,s){if(s.rules.movementZone!==ii.Fly)return super.findRelocationTile(t,i,s);{i=this.game.map;let e=new fa(i.tiles,i.mapBounds,t,1,this.game,e=>this.isCancelling()||this.isCloseEnoughToDest(s,e));return e.getNextTile()}}retarget(e,t){var i=e instanceof Ia?e.isBuilding()?e.centerTile:e.tile:e;this.bomberManeuverTile?this.bomberQueuedTargetTile=i:(this.updateTarget(i,t),this.recalcMinRange=!0),this.target=e,this.options?.ignoredBlockers&&(this.options.ignoredBlockers=e instanceof Ia?[e]:void 0),this.options??(this.options={}),this.options.pathFinderIgnoredBlockers=e instanceof Ia?[e]:void 0}onTick(r){if(this.recalcMinRange){this.recalcMinRange=!1;var e=this.findMinRangeRelocationTile(r,this.targetTile);if(e!==this.targetTile){if(!e)return this.cancel(),!1;this.updateTarget(e,!!e.onBridgeLandType)}}if(this.shouldAirStrafe(r)&&!this.isCancelling()&&(this.updateTarget(this.target instanceof Ia?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target,!1),!this.isAirStrafeCloseEnough(r)||(a=this.findStrafeDestination(r,this.targetTile))&&this.updateTarget(a,!1)),this.isBombingRun(r)&&!this.isCancelling()&&(!r.ammo||this.weapon.getBurstsFired()||this.bomberInitialLock)&&!this.bomberManeuverTile){this.bomberInitialLock=!1;let e=r.position.getMapPosition();var a=this.target instanceof Ia?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target;let t=new vs(a.rx+.5,a.ry+.5).clone().multiplyScalar(Ss.LEPTONS_PER_TILE).sub(e),i=t.length();i||(t.copy(wr.toMapCoords(r.direction)),i=Number.EPSILON);let s=e.clone().add(t.setLength(i+7*Ss.LEPTONS_PER_TILE));a=s.multiplyScalar(1/Ss.LEPTONS_PER_TILE).floor(),a=Da(a.x,a.y,r.tile.rx,r.tile.ry);if(!a.length)throw new Error("Bresenham returned no tiles");a=a[0];this.bomberManeuverTile=this.game.map.tiles.getByMapCoords(a.x,a.y)??this.game.map.tiles.getPlaceholderTile(a.x,a.y),this.options.allowOutOfBoundsTarget=!0,this.updateTarget(this.bomberManeuverTile,!1)}return this.bomberManeuverTile&&this.bomberCanReturn(r.tile)&&(this.bomberManeuverTile=void 0,this.bomberQueuedTargetTile&&(this.updateTarget(this.bomberQueuedTargetTile,!1),this.recalcMinRange=!0,this.bomberQueuedTargetTile=void 0)),this.cancelRequested&&(this.bomberManeuverTile||(this.cancelRequested=!1,this.cancel())),!!(this.isBombingRun(r)&&this.isCancelling()&&this.forceCancel(r))||super.onTick(r)}forceCancel(e){return!this.bomberManeuverTile&&super.forceCancel(e)}findMinRangeRelocationTile(e,t){var{minRange:i,range:s}=this.rangeHelper.computeWeaponRangeVsTarget(e,this.target,this.weapon,this.game.rules);return e.rules.locomotor===ti.Chrono?this.rangeHelper.isInRange(e,this.target,s-1,s,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,s-1,2*s)??t:this.rangeHelper.isInRange(e,this.target,i,Number.POSITIVE_INFINITY,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,2*i,s-i)}findTileInRange(t,e,i,s){let r=this.game.map;var a,i=new vs(t.tile.rx-e.rx,t.tile.ry-e.ry).setLength(i).floor().add(new vs(e.rx,e.ry));let n;for(a of Da(i.x,i.y,e.rx,e.ry))if(n=r.tiles.getByMapCoords(a.x,a.y),n)break;if(n){let e=new Fs(r.tiles,r.mapBounds,n,{width:1,height:1},0,s,e=>this.rangeHelper.isInWeaponRange(t,this.target,this.weapon,this.game.rules,e)&&this.losHelper.hasLineOfSight(e,this.target,this.weapon)&&0<r.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType)&&!r.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).length);return e.getNextTile()}}}class vo{tick(e,t){this.tickChildren(e,t)}startTask(e,t){if(e.status!==Ms.NotStarted)throw new Error(`Attempted to start a task with status ${e.status}`);e.status=Ms.Running,e.onStart(t)}tickTask(e,t){let i=this.tickChildren(e.children,t);var s=e.children.find(e=>e.blocking);if(!i&&s)return!1;if(!t.isSpawned)return!1;if(e.status===Ms.NotStarted)throw new Error("Attempted tick on a non-started task");if(e.isRunning()||e.isCancelling()){var r=e.isCancelling(),a=!!e.waitingForChildrenToFinish||e.onTick(t);e.children.length&&!s&&a&&(i=e.children.every(e=>e.status===Ms.Cancelled||e.status===Ms.Finished),e.waitingForChildrenToFinish=!i);a=a&&i;return a&&(e.onEnd(t),e.status=r?Ms.Cancelled:Ms.Finished),a}return!0}tickChildren(s,r){let a=!0;if(s.length){let t=new Set,i;for(;r.isSpawned&&(i=s.find(e=>!t.has(e)));){let e;if(i.status===Ms.NotStarted&&this.startTask(i,r),i.status===Ms.Running||i.status===Ms.Cancelling)e=!0===this.tickTask(i,r);else{if(i.status!==Ms.Cancelled)throw new Error(`Unhandled task status ${Ms[i.status]}`);e=!0}if(e){var n=s.indexOf(i);-1!==n&&s.splice(n,1)}else{if(a=!1,i.blocking)break;t.add(i)}}}return a}}class So{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:Ss.tile3dToWorld(this.tile.rx+.5,this.tile.ry+.5,this.tile.z+(this.bridge?.tileElevation??0))}isBridge(){return!this.obj&&!!this.bridge}getBridge(){return this.bridge||(this.obj?.isUnit()&&this.obj.onBridge?this.tileOccupation.getBridgeOnTile(this.obj.tile):void 0)}}(r=bn=bn||{})[r.Idle=0]="Idle",r[r.CheckRange=1]="CheckRange",r[r.PrepareToFire=2]="PrepareToFire",r[r.FireUp=3]="FireUp",r[r.Firing=4]="Firing",r[r.JustFired=5]="JustFired";class _o{constructor(e,t){this.disabled=!1,this.attackState=bn.Idle,this.passiveScanCooldownTicks=0,this.taskRunner=new vo,this.distributedFireHistory=new Map,this.rangeHelper=new Is(t),this.losHelper=new To(e,t)}isIdle(){return this.attackState===bn.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,s=!1,r=!1){var a=t.tile;const n=t instanceof So?t.obj:t;t=this.getAvailableWeapons(e,r,n?.isOverlay()||s&&!n);return this.selectWeaponFromList(e,n,a,t,i,s,r,!1)}selectWeaponFromList(e,t,i,s,r,a,n,o){if((!t?.isInfantry()&&!t?.isVehicle()||!t.disguiseTrait||this.canAttackThroughDisguise(e,t,t.disguiseTrait,r,a,n,o))&&(t?.isBuilding()&&t.overpoweredTrait&&t.owner===e.owner&&s.find(e=>e.warhead.rules.electricAssault)&&(s=s.filter(e=>e.warhead.rules.electricAssault)),!(n&&t?.isAircraft()&&t.missileSpawnTrait&&t.zone!==Ts.Air))){var h=t?.isTechno()?t.rules.armor:void 0;for(const l of s)if(l.targeting.canTarget(t,i,r,a,n)&&(void 0===h||this.checkArmor(l.warhead.rules,h,n)))return l}}getAvailableWeapons(e,t,i){let s;var r;return s=(e.isInfantry()||e.isVehicle())&&e.rules.deployFire&&e.armedTrait?(r=e.armedTrait.getDeployFireWeapon(),[e.deployerTrait?.isDeployed()?r.rules.areaFire?void 0:r:r===e.secondaryWeapon?e.primaryWeapon:e.secondaryWeapon]):e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?[e.owner.country.side===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],s.filter(e=>e&&!e.rules.neverUse)}canAttackThroughDisguise(e,t,i,s,r,a,n){if(!r&&i.hasTerrainDisguise()&&!s.areFriendly(e,t)&&!e.owner.sharedDetectDisguiseTrait?.has(t))return!1;if(a){if(n&&t.moveTrait.isIdle()&&!e.rules.detectDisguise&&!s.areFriendly(t,e))return!1;i=i.getDisguise();if(i?.owner&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&(i.owner===e.owner||s.alliances.areAllied(e.owner,i.owner)))return!1}return!0}checkArmor(e,t,i){var s=e.ivanBomb||e.bombDisarm||e.nukeMaker?1:e.verses.get(t);return void 0===s?(console.warn(`Unhandled ArmorType ${si[t]} in warhead ${e.name} verses`),!1):!(100*s<=(i?1:0))}createAttackTask(e,t,i,s,r){return new ko(e,e.createTarget(t,i),s,r)}[Mr.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 ko?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,s;!o&&a.guardMode&&e&&a.owner.isCombatant()&&(t=a.armedTrait?.computeGuardScanRange(e),i=a.guardArea?.tile,s=50);let r=!1;if(e){var h=this.scanForTarget(a,e,n,t,i);if(h.target){let{target:e,weapon:t}=h;var l=this.createAttackTask(n,e,e.tile,t,{holdGround:o||a.rules.movementZone===ii.Fly&&!a.guardMode||a.rules.movementZone!==ii.Fly&&e.isUnit()&&e.zone===Ts.Air||(a.isInfantry()||a.isVehicle())&&!!a.disguiseTrait||!a.owner.isCombatant(),disallowTurning:o,leashTiles:s,passive:!0});o?this.opportunityFireTask=l:a.unitOrderTrait.addTask(l),r=!0,o||!a.guardMode||a.guardArea||(a.guardArea={tile:a.tile,onBridge:!!a.isUnit()&&a.onBridge})}}r||o||!a.secondaryWeapon?.warhead.rules.electricAssault||(e=a.secondaryWeapon,(h=this.scanForTarget(a,e,n,void 0,void 0,!0)).target&&({target:l,weapon:h}=h,h=this.createAttackTask(n,l,l.tile,h,{passive:!0}),a.unitOrderTrait.addTask(h),r=!0)),!r&&!o&&a.guardArea&&a.isUnit()&&a.moveTrait&&!a.moveTrait.isDisabled()&&a.guardArea.tile!==a.tile&&a.unitOrderTrait.addTasks(new ba(n,a.guardArea.tile,a.guardArea.onBridge),new da(()=>{[Gr.Success,Gr.CloseEnough].includes(a.moveTrait.lastMoveResult)||a.resetGuardModeToIdle(),a.guardArea=void 0}))}}}[ha.onDamage](e,t,i,s){this.isDisabled()||!this.retaliateTarget&&!this.opportunityFireTask&&s&&s.obj&&s.weapon&&this.shouldRetaliate(e,t,i,s.obj,s.weapon.warhead)&&(this.retaliateTarget=s.obj)}[jr.onBeforeTeleport](e,t,i,s){s||(this.attackState=bn.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,s,r){return!(i<1||t.areFriendly(e,s)||!e.rules.canRetaliate||!e.primaryWeapon||r.rules.temporal||s.rules.missileSpawn||e.unitOrderTrait.hasTasks()||!t.isValidTarget(s)||(s.isInfantry()||s.isVehicle())&&s.disguiseTrait&&!e.rules.detectDisguise||e.mindControllerTrait?.isAtCapacity()||!this.selectWeaponVersus(e,s,t,!1)||(e.isBuilding()||s.isBuilding()?this.rangeHelper.tileDistance(e,s):this.rangeHelper.distance2(e,s)/Ss.LEPTONS_PER_TILE)>e.sight)}scanForTarget(e,t,i,s,r,a=!1){let n={},o=Number.NEGATIVE_INFINITY;var h=this.getAvailableWeapons(e,!0,!1),t=s??(e.rules.guardRange||t.range)+1+3+i.rules.elevationModel.bonusCap+(t.projectileRules.isAntiAir?e.rules.airRangeBonus:0);for(const u of this.scanTechnosAround(e,t,i)){var l,c=this.selectWeaponFromList(e,u,u.tile,h,i,!1,!0,!0);c&&this.canPassiveAcquire(u,i)&&i.isValidTarget(u)&&(s?this.rangeHelper.isInRange(e,u,c.minRange,s,c.rules.cellRangefinding)&&(!r||this.rangeHelper.isInRange2(r,u,0,s)):this.rangeHelper.isInWeaponRange(e,u,c,i.rules))&&(a||this.losHelper.hasLineOfSight(e,u,c))&&(l=this.rangeHelper.distance3(e,u)/Ss.LEPTONS_PER_TILE,(l=this.computeThreat(u,e,c,l,i.rules.general.threat))>o&&(n={target:u,weapon:c},o=l))}return n.target&&e.rules.distributedFire&&this.updateDistributedFireHistory(n),n}scanTechnosAround(e,t,i){var s=e.getFoundation();const r=new vs(e.tile.rx,e.tile.ry),a=new vs(e.tile.rx+s.width-1,e.tile.ry+s.height-1);r.addScalar(-t),a.addScalar(t);t=new Mn(r,a);return i.map.technosByTile.queryRange(t)}canPassiveAcquire(e,t){return!e.owner.isNeutral&&!e.rules.civilian&&!e.rules.insignificant&&(1<e.rules.threatPosed||0<e.rules.specialThreatValue&&!e.isBuilding()||e.rules.harvester||e.name===t.rules.general.paradrop.paradropPlane)}computeThreat(e,t,i,s,r){let a=[e.primaryWeapon,e.secondaryWeapon].filter(Ma).map(e=>e.warhead.rules.verses.get(t.rules.armor)??0).reduce((e,t)=>Math.max(e,t),0)*r.targetEffectivenessCoefficientDefault;return e.attackTrait?.currentTarget?.obj===t&&(a*=-1),a+=e.rules.specialThreatValue*r.targetSpecialThreatCoefficientDefault,a+=(i.warhead.rules.verses.get(e.rules.armor)??0)*r.myEffectivenessCoefficientDefault,a+=e.healthTrait.health/100*r.targetStrengthCoefficientDefault,a+=s*r.targetDistanceCoefficientDefault,t.rules.distributedFire&&(a-=1e6*(this.distributedFireHistory.get(e)??0)),t.rules.vhpScan===hi.Strong&&e.healthTrait.getProjectedHitPoints()<=0&&(a-=1e6),a}updateDistributedFireHistory(e){if(50!==this.distributedFireHistory.get(e.target)){for(var[t,i]of this.distributedFireHistory)i--,i<=0?this.distributedFireHistory.delete(t):this.distributedFireHistory.set(t,i);this.distributedFireHistory.set(e.target,50)}}dispose(){this.distributedFireHistory.clear()}}class ko extends Vs{constructor(e,t,i,s={}){super(),this.game=e,this.target=t,this.weapon=i,this.options=s,this.moveExecuted=!1,this.moveAttempts=0,this.rangeCheckCooldown=0,this.lastInRangeTargetPosition=new is,this.lastInRangeSelfPosition=new is,this.initialIndirectTarget=!1,this.forceDropTarget=!1,this.rangeHelper=new Is(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,s;t.attackTrait.attackState=bn.CheckRange,this.onTargetChange(t),this.initialSelfPosition={tile:t.tile,onBridge:t.isUnit()&&t.onBridge?e.getBridgeOnTile(t.tile):void 0},this.weapon.rules.limboLaunch&&t.isUnit()&&!this.target.obj&&(this.forceDropTarget=!0,{reachable:i,fallback:s}=this.findReachableMeleePosition(this.target.tile,!!this.target.getBridge(),{width:1,height:1},t),!i&&s&&(this.lastValidTargetPosition=s,this.updateTargetLines(this.game.createTarget(s.onBridge,s.tile),!1))),this.weapon.rules.limboLaunch&&this.target.obj?.isTechno()&&t.isUnit()&&!this.rangeHelper.isInWeaponRange(t,this.target.obj,this.weapon,this.game.rules)&&({reachable:i,fallback:s}=this.findReachableMeleePosition(this.target.obj.tile,this.target.obj.isUnit()&&this.target.obj.onBridge,this.target.obj.getFoundation(),t),i||(1<(t.unitOrderTrait.waypointPath?.waypoints?.length??0)?this.cancel():(this.forceDropTarget=!0,s&&(this.lastValidTargetPosition=s,this.updateTargetLines(this.game.createTarget(s.onBridge,s.tile),!1))))),this.rangeHelper.isInWeaponRange(t,this.target.obj??this.target.tile,this.weapon,this.game.rules)&&t.isUnit()&&t.rules.movementZone===ii.Fly&&t.zone!==Ts.Air&&(t.rules.hoverAttack||t.isAircraft())&&this.children.push(new ba(this.game,t.tile,!1).setCancellable(!1))}else this.cancel()}findReachableMeleePosition(s,e,t,r){let i=this.game.map,a=i.tileOccupation,n=e?a.getBridgeOnTile(s):void 0,o=new $s(i),h=r.rules.movementZone===ii.Fly,l=(e,t)=>h||0<i.terrain.getPassableSpeed(e,r.rules.speedType,!!t)&&o.isEligibleTile(e,t,n,s)&&!i.terrain.findObstacles({tile:e,onBridge:t},r).length,c,u=new Fs(i.tiles,i.mapBounds,s,t,1,Math.ceil(this.weapon.rules.range),e=>{let t=!1;var i;return l(e,void 0)&&(c=c??{tile:e,onBridge:void 0},t=!0),void 0!==e.onBridgeLandType&&(i=a.getBridgeOnTile(e),l(e,i)&&(c=c??{tile:e,onBridge:i},t=!0)),!!t&&this.rangeHelper.isInWeaponRange(r,s,this.weapon,this.game.rules,e)});return{reachable:u.getNextTile(),fallback:c}}onEnd(e){e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction),e.attackTrait.attackState=bn.Idle,e.attackTrait.currentTarget=void 0;var t=this.game.rules.general.prism.type;e.isBuilding()&&e.name===t&&this.weapon.type!==ni.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===Ms.Running||this.status===Ms.Cancelling){if(this.children.filter(e=>e instanceof ba).some(e=>!e.forceCancel(t)))return!1;this.onEnd(t),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!1)}return this.status=Ms.Cancelled,!0}onTick(i){let s=i.attackTrait;(i.isInfantry()||i.isVehicle())&&s.attackState!==bn.Firing&&(i.isFiring=!1);let r=this.target.obj,a=this.children.find(e=>e instanceof bo);if(this.isCancelling()&&s.attackState!==bn.FireUp)return!i.airSpawnTrait?.isLaunchingMissiles()&&(a?.cancel(),!0);let n=!1;if(s.attackState===bn.FireUp){if(s.isDisabled())return!0;s.attackState=bn.Firing,n=!0}if(s.attackState===bn.Firing){if(this.initialIndirectTarget&&!this.game.map.getObjectsOnTile(this.target.tile).find(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()))return this.cancel(),this.onTick(i);if(n){var o=this.target.obj||this.target.tile;if(!this.game.isValidTarget(this.target.obj)||this.shouldDropTarget(this.target.obj)||!this.weapon.targeting.canTarget(this.target.obj,this.target.tile,this.game,!!this.options.force,!!this.options.passive)||!this.rangeHelper.isInWeaponRange(i,o,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,o,this.weapon))return s.attackState=bn.CheckRange,this.onTick(i)}if(this.weapon.rules.limboLaunch){if((r?.isVehicle()||r?.isAircraft())&&r.parasiteableTrait?.isInfested())return!0;if(i.rules.movementZone!==ii.Fly&&r?.isUnit()&&r.zone===Ts.Air)return!0}if(this.target.tile.onBridgeLandType&&i.tile.onBridgeLandType&&i.isUnit()&&(this.game.map.tileOccupation.getBridgeOnTile(this.target.tile)?.isHighBridge()||this.game.map.tileOccupation.getBridgeOnTile(i.tile)?.isHighBridge()))if((r?r.isUnit()&&(r.zone===Ts.Air||r.onBridge):this.target.isBridge())!==(i.zone===Ts.Air||i.onBridge)&&this.game.map.bridges.findHighBridgeBoundary(i.tile)?.tile===this.game.map.bridges.findHighBridgeBoundary(this.target.tile)?.tile)return!0;let e=1;o=this.game.rules.general.prism.type;if(i.isBuilding()&&i.name===o&&this.weapon.type!==ni.Secondary&&(o=this.countSupportBeamsAndFireDownTowers(i,o),e=1+o*this.game.rules.general.prism.supportModifier),this.weapon.rules.spawner&&(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isParalyzed())return!0;if(0===i.ammo)return i.isAircraft()&&(i.rules.fighter||i.rules.spawned)&&a?.cancel(),!0;let t=!1;if(this.weapon.rules.limboLaunch&&a){if(!a.forceCancel(i))return!1;i.moveTrait.lastTargetOffset=void 0,i.moveTrait.lastVelocity=void 0,t=!0}return(this.weapon.fire(this.target,this.game,e),t)?!0:!!this.weapon.rules.fireOnce||(!(!this.options.passive||!i.rules.distributedFire)||(s.attackState=bn.JustFired,!1))}if(s.attackState===bn.JustFired)return s.attackState=bn.PrepareToFire,this.onTick(i);this.needsTargetUpdate&&(this.target=this.needsTargetUpdate,r=this.target.obj,this.needsTargetUpdate=void 0,this.onTargetChange(i),r||a?.retarget(this.target.tile,!!this.target.getBridge())),r?.isTechno()&&r.replacedBy&&(h=this.game.createTarget(r.replacedBy,r.replacedBy.tile),this.target=h,r=r.replacedBy,this.onTargetChange(i));let t=this.game.isValidTarget(r)&&!this.shouldDropTarget(r);if(t){let e=this.weapon.targeting.canTarget(r,this.target.tile,this.game,!!this.options.force,!!this.options.passive);if(!e||!i.armedTrait.isEquippedWithWeapon(this.weapon)){var h=s.selectWeaponVersus(i,this.target,this.game,this.options.force,this.options.passive);if(h){if(this.setWeapon(h),s.attackState!==bn.CheckRange)return s.attackState=bn.CheckRange,this.onTick(i);e=!0}else e=!1}t=e}if(t&&(l=this.lastTargetTpCheck,r?.isUnit()&&l&&r.moveTrait.lastTeleportTick>=l?(t=!1,this.rangeCheckCooldown=0):this.lastTargetTpCheck=this.game.currentTick),t&&r&&(this.lastValidTargetPosition={tile:r.tile,onBridge:this.target.getBridge()}),t||(this.targetLinesConfig.isAttack=!1),s.attackState===bn.CheckRange){if(0<this.rangeCheckCooldown)return this.rangeCheckCooldown--,!1;let e=this.target.obj?t?this.target.obj:this.lastValidTargetPosition.tile:this.target.tile;var l=this.target.obj?t?this.target.obj.isBuilding()?this.target.obj.centerTile:this.target.obj.tile:this.lastValidTargetPosition.tile:this.target.tile;if(!this.rangeHelper.isInWeaponRange(i,e,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,e,this.weapon)||i.isUnit()&&i.rules.balloonHover&&!i.rules.hoverAttack&&!a&&i.tile!==l||i.isAircraft()&&this.weapon.projectileRules.iniRot<=1&&!a){if(i.isUnit()&&!this.options.holdGround&&this.game.map.isWithinBounds(l)){if(a){if(a.target!==this.target.obj||t)if(t&&this.target.obj&&this.rangeHelper.tileDistance(this.target.obj,this.lastSelfMoveTargetTile)>this.weapon.range)a.retarget(this.target.obj,!!this.target.getBridge()),this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=this.target.obj?.tile??this.target.tile;else{if(void 0!==this.options.leashTiles&&this.rangeHelper.tileDistance(this.initialSelfPosition.tile,i.tile)>this.options.leashTiles)return a.cancel(),!0;var c=e instanceof Ia&&e.isUnit()?e.moveTrait.baseSpeed:0,u=Math.ceil((this.rangeHelper.tileDistance(i,e)-(this.weapon.range+1))/((i.moveTrait.baseSpeed+c)/Ss.LEPTONS_PER_TILE));0<u&&(this.rangeCheckCooldown=Math.min(Ls.BASE_TICKS_PER_SECOND,u))}else{let e;e=void 0!==this.options.leashTiles?this.game.createTarget(this.initialSelfPosition.onBridge,this.initialSelfPosition.tile):this.game.createTarget(this.lastValidTargetPosition.onBridge,this.lastValidTargetPosition.tile),s.currentTarget=e,a.retarget(e.tile,e.isBridge()),this.updateTargetLines(e,!1)}return!1}if(!i.moveTrait||i.moveTrait.isDisabled())return!0;if(this.isCancelling())return!0;if(i.tile===this.lastSelfTileBeforeMove||this.moveExecuted&&i.moveTrait.lastMoveResult===Gr.Fail?this.moveAttempts++:this.moveAttempts=0,this.weapon.rules.limboLaunch&&i.defaultToGuardArea&&r&&this.moveExecuted&&i.moveTrait.lastMoveResult===Gr.Fail&&this.rangeHelper.isInRange(i,r,0,i.armedTrait.computeGuardScanRange(this.weapon),!0))return!0;if(3<this.moveAttempts)return!0;0<this.moveAttempts&&this.children.push(new ua(1/60));c=e,u=r&&!t?this.lastValidTargetPosition.onBridge:this.target.getBridge();return a=new bo(this.game,c,!!u,this.weapon),a.blocking=!1,this.children.push(a),this.moveExecuted=!0,this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=c instanceof Ia?c.tile:c,this.onTick(i)}return!0}if(this.moveExecuted=!1,this.moveAttempts=0,a&&(i.rules.balloonHover&&!i.rules.hoverAttack||i.rules.fighter||i.rules.spawned||i.rules.movementZone===ii.Fly&&!this.rangeHelper.isInRange2(i,this.target.obj??this.target.tile,this.weapon.minRange,this.weapon.range-1)||a.cancel()),a&&(i.isInfantry()&&!i.rules.balloonHover||this.weapon.rules.spawner))return!1;if(a?.children.some(e=>!e.cancellable)&&this.weapon.rules.limboLaunch)return!1;if(a&&a.shouldAirStrafe(i)&&this.target.obj?.isUnit()&&this.target.obj.moveTrait.isMoving()&&1<this.weapon.range&&!this.rangeHelper.isInRange2(i,this.target.obj,this.weapon.minRange,this.weapon.range-1))return!1;s.attackState=bn.PrepareToFire}if(s.attackState!==bn.PrepareToFire)return!1;if(!t||s.isDisabled())return a?.cancel(),!0;u=this.target.getWorldCoords(),c=i.position.worldPosition;if(!(this.lastInRangeTargetPosition.length()&&this.lastInRangeTargetPosition.equals(u)&&this.lastInRangeSelfPosition.length()&&this.lastInRangeSelfPosition.equals(c)))return this.lastInRangeTargetPosition.copy(u),this.lastInRangeSelfPosition.copy(c),s.attackState=bn.CheckRange,this.onTick(i);if(!(this.weapon.rules.omniFire||i.rules.omniFire&&i.rules.fighter)){var c=(new is).copy(u).sub(c),e=wr.fromMapCoords(new vs(c.x,c.z)),c=this.weapon.projectileRules.rot?45:11.25;if((i.isVehicle()||i.isBuilding())&&i.turretTrait){if(i.turretTrait.desiredFacing=e,Math.abs(e-i.turretTrait.facing)>=c)return!1}else if(Math.abs(e-i.direction)>=c){if(i.isAircraft())return i.direction=wr.tick(i.direction,e,i.rules.rot).facing,!1;if(a)return!1;if(i.isVehicle())return!!this.options.disallowTurning||(this.children.push(new Tr(e)),!1);i.direction=e}}if(!this.losHelper.hasLineOfSight(i,this.target.obj||this.target.tile,this.weapon))return s.attackState=bn.CheckRange,this.onTick(i);if(s.isOnCooldown(i))return!1;if(this.weapon.warhead.rules.temporal&&i.temporalTrait.getTarget()===this.target.obj)return!1;if(this.weapon.rules.suicide&&this.weapon.type!==ni.DeathWeapon)return this.game.destroyObject(i,{player:i.owner,obj:i,weapon:this.weapon}),!0;e=this.game.rules.general.prism.type;return i.isBuilding()&&i.name===e&&this.weapon.type!==ni.Secondary&&this.fireUpPrismSupportTowers(i,e),(i.isInfantry()||i.isVehicle())&&(i.isFiring=!0),i.art.fireUp?(this.children.push(new Gs(i.art.fireUp).setCancellable(!1)),s.attackState=bn.FireUp,!1):(s.attackState=bn.Firing,this.onTick(i))}shouldDropTarget(e){return this.forceDropTarget||e?.isTechno()&&(this.weapon.rules.limboLaunch&&((e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested()||e.invulnerableTrait.isActive())||e.warpedOutTrait.isInvulnerable()&&!this.weapon.warhead.rules.temporal||this.initialTargetOwner!==e.owner)}fireUpPrismSupportTowers(t,i){var e;for(e of t.owner.getOwnedObjectsByType(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,s=t.owner.getOwnedObjectsByType(Ct.Building).filter(e=>e.name===i&&e.attackTrait?.currentTarget?.obj===t);for(e of s)e.unitOrderTrait.getCurrentTask()?.cancel();return Math.min(this.game.rules.general.prism.supportMax,s.length)}getTargetLinesConfig(){return this.targetLinesConfig}}class Oo{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()}[Mr.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 ko&&((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 Io{constructor(e,t){this.target=e,this.from=t,this.type=ts.UnitRepairFinish}}class Ao{constructor(e){this.target=e,this.type=ts.UnitRepairStart}}(r=vn=vn||{})[r.Idle=0]="Idle",r[r.Repairing=1]="Repairing";class Co{constructor(){this.status=vn.Idle,this.cooldownTicks=0,this.lastRepairTickSuccessful=!1}[Xr.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))}[Mr.onTick](t,i){if(t.dockTrait&&(!t.rules.needsEngineer||!t.owner.isNeutral))if(!t.dockTrait.hasDockedUnits()||t.dockTrait.getDockedUnits().some(e=>e.zone===Ts.Air)||t.poweredTrait&&!t.poweredTrait.isPoweredOn())this.status=vn.Idle;else if(this.cooldownTicks<=0){var s,r,a=i.rules.general.repair,a=t.rules.unitReload?a.reloadRate:a.uRepairRate;this.cooldownTicks+=Ls.BASE_TICKS_PER_SECOND*a*60;let e=!1;for(s of t.dockTrait.getDockedUnits())s.zone!==Ts.Air&&(s.healthTrait.health<100&&i.areFriendly(s,t)?(this.tickRepair(s,i,t)&&(e=!0),!e||this.status!==vn.Idle&&this.lastRepairTickSuccessful||t.helipadTrait||i.events.dispatch(new Ao(s))):((r=t.rallyTrait.findRallyNodeForUnit(s,i.map))&&(t.dockTrait.undockUnit(s),s.unitOrderTrait.addTask(new ba(i,r.tile,!!r.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))),t.helipadTrait||i.events.dispatch(new Io(s,t))));this.lastRepairTickSuccessful=e,this.status=e?vn.Repairing:vn.Idle}else this.cooldownTicks--}tickRepair(e,t,i){var s=t.rules.general.repair,r=Math.floor(s.repairStep),a=s.repairPercent;let n;if(a){s=a*e.purchaseValue/e.healthTrait.maxHitPoints,a=Math.min(i.owner.credits,Math.max(1,Math.floor(s*r)));if(n=s&&a?Math.floor(a/s):r,!a)return!1;i.owner.credits-=a}else n=r;return n=Math.min(n,e.healthTrait.maxHitPoints-e.healthTrait.getHitPoints()),!!n&&(e.healthTrait.healBy(n,i,t),!0)}computeDefaultRallyPoint(e,t){var i=e.getFoundation(),i=new vs(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,s){let t=new Fs(s.tiles,s.mapBounds,e,{width:1,height:1},0,20,e=>i.rules.naval===(e.terrainType===Zt.Water)&&!s.tileOccupation.isTileOccupiedBy(e,i)),r=t.getNextTile();if(!r&&i.factoryTrait?.type===Ki.NavalUnitType){var{width:a,height:n}=i.getFoundation();for(let t=0;t<a;t++)for(let e=0;e<n;e++){var o=s.tiles.getByMapCoords(i.tile.rx+t,i.tile.ry+e);if(!o)break;if(0<s.terrain.getPassableSpeed(o,Kt.Float,!1)){r=o;break}}}return r}findRallyNodeForUnit(e,t){if(this.rallyPoint){var i=this.findRallyPointforUnit(e,this.rallyPoint,t,!0);return{tile:i,onBridge:e.rules.naval?void 0:t.tileOccupation.getBridgeOnTile(i)}}}findRallyPointforUnit(i,e,s,r){let a=i.rules.naval?void 0:s.tileOccupation.getBridgeOnTile(e),n=i.rules.movementZone===ii.Fly,t=new Fs(s.tiles,s.mapBounds,e,{width:1,height:1},0,5,e=>{var t=!a||a.isHighBridge()?s.tileOccupation.getBridgeOnTile(e):void 0;return!((n?[]:s.terrain.findObstacles({tile:e,onBridge:t},i)).length||r&&s.getObjectsOnTile(e).find(e=>e.isBuilding()&&!e.isDestroyed)||!(n||0<s.terrain.getPassableSpeed(e,i.rules.speedType,!!t)))});return t.getNextTile()??e}}class xo{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 Eo{constructor(){this.timer=new xo}hasCharge(){return this.timer.isActive()}setCharge(e,t){this.hasCharge()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Mr.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=Wr.Demolish,t.destroyObject(e,this.attackerInfo,!0))))}}class Po{[qr.onChange](e,t,i){this.checkAircraftsForPlayer(t,i)}[Qr.onUnspawn](e,t){this.checkAircraftsForPlayer(e.owner,t)}checkAircraftsForPlayer(e,t){let i=t.rules.general.padAircraft;var s;for(s of e.getOwnedObjectsByType(Ct.Aircraft).filter(e=>i.includes(e.name)))s.airportBoundTrait&&(s.airportBoundTrait.preferredAirport=void 0)}}class No{[Mr.onTick](t,i){if(t.dockTrait&&t.dockTrait.hasDockedUnits()&&!t.dockTrait.getDockedUnits().every(e=>!this.canReloadUnit(e)))if(void 0===this.cooldownTicks&&(this.cooldownTicks=Ls.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60),this.cooldownTicks<=0){this.cooldownTicks=Ls.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60;let e=t.dockTrait.getDockedUnits();var s;for(s of 0===e[0].ammo?e.slice(0,1):e)this.canReloadUnit(s)&&s.ammoTrait.ammo++}else this.cooldownTicks--}canReloadUnit(e){return!(!e.ammoTrait||!e.rules.manualReload||e.ammoTrait.isFull()||e.zone===Ts.Air)}}class Ro extends La{constructor(e){super(new ua(e),new da(e=>e.buildStatus=kn.Ready)),this.cancellable=!1}}class Do{constructor(e){this.name=e}getSuperWeapon(e){return e.owner.superWeaponsTrait?.get(this.name)}[Xr.onSpawn](e,t){this.addSuperWeaponToPlayerIfNeeded(e.owner,t)}[Qr.onUnspawn](e,t){this.removeSuperWeaponFromPlayerIfNeeded(e.owner)}[qr.onChange](e,t,i){this.removeSuperWeaponFromPlayerIfNeeded(t),this.addSuperWeaponToPlayerIfNeeded(e.owner,i)}addSuperWeaponToPlayerIfNeeded(t,i){if(t.superWeaponsTrait&&!t.superWeaponsTrait.has(this.name)){let e=i.createSuperWeapon(this.name,t);t.superWeaponsTrait.add(e),e.rules.isPowered&&t.powerTrait?.isLowPower()&&e.pauseTimer()}}removeSuperWeaponFromPlayerIfNeeded(e){let t=e.superWeaponsTrait;t&&(e.getOwnedObjectsByType(Ct.Building).some(e=>e.superWeaponTrait?.name===this.name)||(e=t.get(this.name))&&!e.isGift&&t.remove(this.name))}}(r=Sn=Sn||{})[r.Unexplored=0]="Unexplored",r[r.TemporaryReveal=1]="TemporaryReveal",r[r.Explored=2]="Explored",_n=_n||{},_n[_n.Darken=8]="Darken";class Mo{constructor(){this.invalidations=new Map,this.temporaryReveals=new Map,this.fullInvalidation=!1,this._onChange=new io}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(Sn.Unexplored),this.tileElevation=new Uint8Array(i.width*i.height);for(t of e.getAll())this.tileElevation[t.rx+t.ry*i.width]=t.terrainType===Zt.Cliff&&0<t.z?t.z-1:t.z;return this}clone(){let e=new Mo;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)===Sn.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 s=this.invalidations.get(e);s||(s={centerTile:e,elevation:0,radius:0},this.invalidations.set(e,s)),s.elevation=Math.max(s.elevation,t),s.radius=Math.max(s.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,Sn.Unexplored,Sn.Explored),this._onChange.dispatch(this,{type:"incremental",tiles:i})}revealTemporarily(e){this.temporaryReveals.set(e.tile,5*Ls.BASE_TICKS_PER_SECOND)}revealObject(e){this.invalidate(e.tile,Number.POSITIVE_INFINITY,4.25)}toggleFlagsAround(e,t,i,s){var r=[];this.setValueAround(e,t,Number.POSITIVE_INFINITY,r,void 0,void 0,s?{setFlags:i}:{clearFlags:i}),this._onChange.dispatch(this,{type:"incremental",tiles:r})}update(){let i=[];if(this.invalidations.size){for(var e of this.invalidations.values())this.setValueAround(e.centerTile,e.radius,e.elevation,i,Sn.Explored,[Sn.Unexplored,Sn.TemporaryReveal]);this.invalidations.clear()}this.temporaryReveals.size&&this.temporaryReveals.forEach((e,t)=>{e<=0?(this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,Sn.Unexplored,Sn.TemporaryReveal),this.temporaryReveals.delete(t)):(e===5*Ls.BASE_TICKS_PER_SECOND&&this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,Sn.TemporaryReveal,Sn.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(s,r,a,n,o,h=void 0,{setFlags:l,clearFlags:c}={}){var e=Math.ceil(r),t=s.rx-e,u=s.rx+e,d=s.ry-e,p=s.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-s.rx)*(i-s.rx)+(t-s.ry)*(t-s.ry)>r*r+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(Sn.Explored),this._onChange.dispatch(this,{type:"clear"})}reset(){this.tiles.fill(Sn.Unexplored),this._onChange.dispatch(this,{type:"cover"})}}class Lo{constructor(e){this.radiusTiles=e,this.refreshTicks=0}[Mr.onTick](e,t){0<this.refreshTicks&&this.refreshTicks--,this.refreshTicks<=0&&this.update(e,t)}[Xr.onSpawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!0)}[Qr.onUnspawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!1),this.update(e,t)}[qr.onChange](e,t,i){this.markGapTilesForFriendlies(e,t,i,!1),this.markGapTilesForFriendlies(e,e.owner,i,!0),this.update(e,i)}[yn.onChange](e,t,i){this.markGapTilesForFriendlies(e,e.owner,t,!i),i&&this.update(e,t)}markGapTilesForFriendlies(i,e,s,t){let r=[e,...s.alliances.getAllies(e)],a;for(var n of r){let e=s.mapShroudTrait.getPlayerShroud(n);if(e&&(e.toggleFlagsAround(i.tile,this.radiusTiles,_n.Darken,t),!t)){if(!a){let t=new Is(s.map.tileOccupation);a=r.map(e=>[...e.buildings]).flat().filter(e=>e.gapGeneratorTrait&&e!==i&&t.tileDistance(e,i)<=e.gapGeneratorTrait.radiusTiles+this.radiusTiles)}for(var o of a)e.toggleFlagsAround(o.tile,o.gapGeneratorTrait.radiusTiles,_n.Darken,!0)}}}update(t,i){this.refreshTicks=5*Ls.BASE_TICKS_PER_SECOND;let s;var r,a,n,o,h=t.owner.buildings.has(t)&&t.poweredTrait?.isPoweredOn();for(r of i.getCombatants())if(r!==t.owner&&!i.alliances.areAllied(t.owner,r)){let e=i.mapShroudTrait.getPlayerShroud(r);if(e)if(h){e.unrevealAround(t.tile,this.radiusTiles),s||(n=this.radiusTiles+as.MAX_SIGHT,a=new vs(t.tile.rx,t.tile.ry).addScalar(-n),n=new vs(t.tile.rx,t.tile.ry).addScalar(n),s=i.map.technosByTile.queryRange(new Mn(a,n)));for(o of s)o.owner===r||i.alliances.areAllied(o.owner,r)?e.revealFrom(o):o.rules.revealToAll&&e.revealObject(o)}else[...r.buildings].some(e=>e.rules.spySat)&&e.revealAround(t.tile,this.radiusTiles)}}}const Fo=Ls.BASE_TICKS_PER_SECOND;class jo{constructor(e){this.radiusTiles=e,this.detectionLines=[],this.nextScan=Fo}[Mr.onTick](e,t){e.owner.powerTrait?.isLowPower()?this.disable():(0<this.nextScan&&this.nextScan--,this.nextScan<=0&&(this.nextScan=Fo,this.detectionLines=this.scan(e,t)))}[yn.onChange](e,t,i){i&&this.disable()}disable(){this.detectionLines.length&&(this.detectionLines=[],this.nextScan=0)}scan(t,i){var e=i.getCombatants().filter(e=>e!==t.owner&&!i.alliances.areAllied(e,t.owner));let s=[],r=new Is(i.map.tileOccupation);var a,n,o,h=e=>r.distance2(e,t)/Ss.LEPTONS_PER_TILE<=this.radiusTiles;for(a of e)for(var l of a.getOwnedObjects())l.attackTrait?.currentTarget?h((n=l.attackTrait.currentTarget).obj??n.tile)&&s.push({source:l,target:n}):l.isUnit()&&l.unitOrderTrait.targetLinesConfig&&((o=l.unitOrderTrait.targetLinesConfig).target?h(o.target)&&(n=i.createTarget(o.target,o.target.tile),s.push({source:l,target:n})):(o=o.pathNodes[0])&&h(o.tile)&&(o=i.createTarget(o.onBridge,o.tile),s.push({source:l,target:o})));return s}}class Uo{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*Ls.BASE_TICKS_PER_SECOND}[Mr.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 Io(i,e))))}[Ur.onDestroy](e,t,i){this.unit&&(t.destroyObject(this.unit,i,!0),this.unit=void 0)}evacuate(t,i,s){let e;var r={x:i.tile.rx,y:i.tile.ry+i.art.foundation.height},r=s.map.tiles.getByMapCoords(r.x,r.y);r&&s.map.isWithinBounds(r)&&this.canEvacuateTo(r,t,i,s)&&(e=r),e=e||new Fs(s.map.tiles,s.map.mapBounds,i.tile,i.art.foundation,1,1,e=>this.canEvacuateTo(e,t,i,s)).getNextTile(),e?(s.unlimboObject(t,e),t.unitOrderTrait.addTask(new Ta(s))):s.destroyObject(t,{player:t.owner})}canEvacuateTo(e,t,i,s){return 0<s.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length}}(r=kn=kn||{})[r.BuildUp=0]="BuildUp",r[r.Ready=1]="Ready",r[r.BuildDown=2]="BuildDown";class Wo extends Aa{constructor(e,t,i){super(Ct.Building,e,t,i),this.showWeaponRange=!1,this.wallType=[0,0,0,0],this.direction=0,this.buildStatus=kn.BuildUp,this.lastBuildStatus=this.buildStatus}static factory(e,t,i,s,r,a){let n=new this(e,t,s);return t.canBeOccupied&&(n.garrisonTrait=new Xn(n,i.audioVisual.conditionRed,t.maxNumberOccupants),n.traits.add(n.garrisonTrait)),t.canC4&&!t.wall&&(n.c4ChargeTrait=new Eo,n.traits.add(n.c4ChargeTrait)),t.bridgeRepairHut&&(n.cabHutTrait=new mo(n,a),n.traits.add(n.cabHutTrait)),t.crewed&&(n.crewedTrait=new go,n.traits.add(n.crewedTrait)),t.turret&&(n.turretTrait=new Qn,n.traits.add(n.turretTrait)),t.overpowerable&&(n.overpoweredTrait=new Oo(n),n.traits.add(n.overpoweredTrait)),(t.powered&&0!==t.power||t.needsEngineer)&&(n.poweredTrait=new to(n),n.traits.add(n.poweredTrait)),(t.factory||t.cloning)&&(n.factoryTrait=new co(t.cloning?Ki.InfantryType:t.factory,t.cloning),n.traits.add(n.factoryTrait)),t.superWeapon&&(n.superWeaponTrait=new Do(t.superWeapon),n.traits.add(n.superWeaponTrait)),t.numberOfDocks&&(n.dockTrait=new oo(n,r,t.numberOfDocks,s.dockingOffsets),n.traits.add(n.dockTrait),t.helipad&&(n.helipadTrait=new Po,n.traits.add(n.helipadTrait)),(t.unitRepair||t.unitReload)&&(n.unitRepairTrait=new Co,n.traits.add(n.unitRepairTrait)),t.unitReload&&(n.unitReloadTrait=new No,n.traits.add(n.unitReloadTrait))),t.hospital&&(n.hospitalTrait=new Uo,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 po),t.produceCashStartup&&n.traits.add(new fo),t.wall&&(n.wallTrait=new yo,n.traits.add(n.wallTrait)),t.gapGenerator&&(n.gapGeneratorTrait=new Lo(t.gapRadiusInCells),n.traits.add(n.gapGeneratorTrait)),t.psychicDetectionRadius&&(n.psychicDetectorTrait=new jo(t.psychicDetectionRadius),n.traits.add(n.psychicDetectorTrait)),n}isBuilding(){return!0}getFoundation(){return this.art.foundation}getFoundationCenterOffset(){var e=this.getFoundation();return new vs(e.width/2*Ss.LEPTONS_PER_TILE,e.height/2*Ss.LEPTONS_PER_TILE)}update(e){this.buildStatus!==kn.BuildUp||this.unitOrderTrait.hasTasks()||this.unitOrderTrait.addTask(new Ro(e.rules.general.buildupTime)),this.buildStatus!==this.lastBuildStatus&&(this.lastBuildStatus=this.buildStatus,e.events.dispatch(new Zn(this,this.buildStatus))),this.attackTrait?.setDisabled(this.buildStatus!==kn.Ready||!!this.poweredTrait&&!this.poweredTrait.isPoweredOn()),super.update(e)}}class zo extends Ia{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 Vo extends Ia{constructor(e,t,i){super(Ct.Overlay,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){let s=new this(e,t,i);return t.wall&&(s.wallTrait=new yo,s.traits.add(s.wallTrait)),s}isTiberium(){return Ha.getOverlayTibType(this.overlayId)!==ra.NotSpecial}isBridge(){return Wa.isBridge(this.overlayId)}isXBridge(){return Wa.isXBridge(this.overlayId)}isHighBridge(){return Wa.isHighBridge(this.overlayId)}isLowBridge(){return Wa.isLowBridge(this.overlayId)}isBridgePlaceholder(){return Wa.isBridgePlaceholder(this.overlayId)}getFoundation(){let e={width:1,height:1};return this.isBridge()&&(this.isXBridge()?e.height+=2:e.width+=2),e}}class Ho extends Ia{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 Go extends ba{constructor(e,t,i,s){super(e,i??t,!1,{closeEnoughTiles:i?void 0:0,strictCloseEnough:!i}),this.teleportTile=t,this.teleportCondition=s}onStart(e){if(super.onStart(e),!e.harvesterTrait||e.rules.locomotor!==ti.Chrono)throw new Error(`Vehicle ${e.name} is not a chrono miner`)}onTick(e){return!e.moveTrait.isDisabled()&&(!(this.isCancelling()||e.moveTrait.moveState!==Hr.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===Ts.Air&&(e.zone=Ts.Ground,e.position.tileElevation=0),!0))}}class $o extends Vs{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 Is(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=An.MovingToOreSite,e.harvesterTrait.lastGatherExplicit=this.explicitOrder}onEnd(e){e.harvesterTrait.status!==An.LookingForOreSite&&(e.harvesterTrait.status=An.Idle)}onTick(i){if(this.isCancelling())return!0;let s=i.harvesterTrait;if(s.status===An.MovingToOreSite){if(this.target=this.initialTarget?.landType===Yt.Tiberium?this.initialTarget:this.findClosestReachableOreSite(i,s.lastOreSite??i.tile,!0),s.lastOreSite=this.target,!this.target){s.status=An.LookingForOreSite;let e=this.getRefineryOnTile(i.tile);if(e&&1===i.unitOrderTrait.getTasks().length){let t=i.rules.movementZone===ii.Fly;var r=new Fs(this.game.map.tiles,this.game.map.mapBounds,e.tile,e.getFoundation(),1,5,e=>t||0<this.game.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},i).length).getNextTile();r&&i.unitOrderTrait.addTasks(new ba(this.game,r,!1),new da(()=>{[Gr.Success,Gr.CloseEnough,Gr.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new ua(1/60))}))}return!0}var a=this.game.rules.general.closeEnough,r=this.rangeHelper.tileDistance(i.tile,this.target)<=a;if(i.tile!==this.target&&(i.tile.landType!==Yt.Tiberium||!r||this.strictTarget)){if(i.tile!==this.target&&r&&i.tile.landType!==Yt.Tiberium){r=this.findClosestReachableOreSite(i,i.tile,!1,!0);if(r)this.target=r,s.lastOreSite=this.target;else{if(!this.forceMoveTried)return this.forceMoveTried=!0,this.children.push(new ba(this.game,this.target,!1,{closeEnoughTiles:0,strictCloseEnough:!0})),!1;if(this.forceMoveTried=!1,!s.isEmpty())return this.returnOreIfPossible(i),!0;r=this.findClosestReachableOreSite(i,i.tile,!0,!0);if(!r)return s.status=An.LookingForOreSite,!0;this.target=r,s.lastOreSite=this.target}}return this.children.push(new ba(this.game,this.target,!1,{closeEnoughTiles:a}),new da(()=>{[Gr.Success,Gr.CloseEnough,Gr.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new ua(5/60))})),!1}this.target=i.tile,s.lastOreSite=this.target,s.status=An.Harvesting,this.forceMoveTried=!1,this.strictTarget=!1}if(s.status!==An.Harvesting)return!1;{if(s.isFull())return this.returnOreIfPossible(i),!0;let e=this.game.map.getObjectsOnTile(i.tile).find(e=>e.isOverlay()&&e.isTiberium());if(!e)return this.findClosestReachableOreSite(i,s.lastOreSite??i.tile,!1)||s.isEmpty()?(s.status=An.MovingToOreSite,this.onTick(i)):(this.returnOreIfPossible(i),!0);let t=e.traits.get(Ga);a=t.collectBail();if(t.getBailCount()||this.game.unspawnObject(e),a===aa.Ore)s.ore++;else{if(a!==aa.Gems)throw new Error(`Unsupported tiberium type ${a}`);s.gems++}return[...i.owner.buildings].some(e=>e.rules.refinery)||this.explicitOrder?(this.children.push(new ua(1/60)),!1):!0}}findClosestReachableOreSite(t,i,e,s=!1){let r=t.rules.movementZone===ii.Fly;var a=e=>e.landType===Yt.Tiberium&&(!s||(r||!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 fa(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 Fs(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 qo(this.game))}getTargetLinesConfig(e){return{pathNodes:this.initialTarget?[{tile:this.initialTarget,onBridge:void 0}]:[]}}}class qo extends Vs{constructor(e,t,i=!1,s=!1){super(),this.game=e,this.forceTarget=t,this.resetLastOreSite=i,this.explicitOrder=s,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new Is(e.map.tileOccupation)}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=An.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!==An.LookingForRefinery&&(e.harvesterTrait.status=An.Idle)}onTick(s){if(this.isCancelling())return!0;let r=s.harvesterTrait;if(r.status===An.LookingForRefinery)return!0;if(r.status===An.MovingToRefinery){if(!this.target||!this.isValidTargetRefinery(this.target,s)||s.tile!==this.findRefineryDockingTile(this.target)){var a=this.forceTarget??this.findClosestReachableRefinery(s);if(!a)return r.status=An.LookingForRefinery,!0;this.target&&this.target!==a&&this.target.dockTrait.hasReservedDockForUnit(s)&&this.target.dockTrait.unreserveDockForUnit(s),this.target=a}let e=this.target.dockTrait.getFirstAvailableDockNumber(),t=!1;void 0===e&&(e=this.target.dockTrait.getFirstEmptyDockNumber(),void 0!==e&&(t=!this.target.dockTrait.hasReservedDockForUnit(s)));let i=this.findRefineryDockingTile(this.target);var n=this.rangeHelper.tileDistance(s,i);if(void 0===e||t||n>this.game.rules.general.harvesterTooFarDistance&&!this.explicitOrder){var o=this.findReachableQueueingTile(s);return o?(s.tile!==o&&this.children.push(s.rules.teleporter?new Go(this.game,i,o,()=>this.chronoMinerCanTeleport(s,i,this.target)):new ba(this.game,o,!1),new da(()=>{s.moveTrait.lastMoveResult===Gr.Fail?r.status=An.LookingForRefinery:s.moveTrait.lastMoveResult===Gr.CloseEnough&&this.children.push(new ua(5/60))})),!1):!0}if(this.target.dockTrait.hasReservedDockForUnit(s)||this.target.dockTrait.reserveDockAt(s,e),void 0===this.reservedDockNumber&&(this.reservedDockNumber=this.target.dockTrait.getReservedDockForUnit(s)),s.tile!==i)return this.children.push(s.rules.teleporter?new Go(this.game,i,void 0,()=>this.chronoMinerCanTeleport(s,i,this.target)):new ba(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new da(()=>{s.moveTrait.lastMoveResult===Gr.Fail&&(r.status=An.LookingForRefinery)})),!1;r.status=An.Docking}if(!this.isValidTargetRefinery(this.target,s))return r.status=An.MovingToRefinery,this.forceTarget=void 0,this.onTick(s);if(r.status===An.Docking){if(270!==s.direction)return this.children.push(new Tr(270)),!1;this.target.dockTrait.dockUnitAt(s,this.reservedDockNumber),this.reservedDockNumber=void 0,r.status=An.PreparingToUnload}if(r.status===An.PreparingToUnload)return this.preventOpportunityFire=!0,this.children.push(new ua(2/60)),r.status=An.Unloading,!1;if(r.status!==An.Unloading)return!1;a=r.ore*this.game.rules.getTiberium(aa.Ore).value+r.gems*this.game.rules.getTiberium(aa.Gems).value;this.target.owner.credits+=a;n=[...this.target.owner.buildings].filter(e=>e.rules.orePurifier&&(!e.poweredTrait||!this.target.owner.powerTrait?.isLowPower())).length,o=this.game.rules.general.purifierBonus;return this.target.owner.credits+=n*Math.floor(a*o),r.ore=0,r.gems=0,1===s.unitOrderTrait.getTasks().length&&s.unitOrderTrait.addTask(new $o(this.game)),!0}isValidTargetRefinery(e,t){return e.isSpawned&&this.game.areFriendly(e,t)&&!e.warpedOutTrait.isActive()}findClosestReachableRefinery(i){let s=this.rangeHelper,e=[...i.owner.buildings].filter(e=>e.rules.refinery&&e.dockTrait&&!e.warpedOutTrait.isActive()).sort((e,t)=>s.distance2(i,e)-s.distance2(i,t));var t=e[0],r=e.find(e=>0<e.dockTrait.getAvailableDockCount());return!r||t&&s.tileDistance(i,r.centerTile)-s.tileDistance(i,t.centerTile)>this.game.rules.general.harvesterTooFarDistance?t:r}findReachableQueueingTile(t){if(this.target.art.queueingCell){var e=new vs(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 Fs(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===Ts.Air||0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-this.target.tile.z)<2&&!e.onBridgeLandType}findRefineryDockingTile(e){e={x:e.tile.rx+e.getFoundation().width-1,y:e.tile.ry+Math.floor(e.getFoundation().height/2)};return this.game.map.tiles.getByMapCoords(e.x,e.y)}chronoMinerCanTeleport(e,t,i){let s=this.rangeHelper;t=s.tileDistance(e,t);return!(!this.forceTarget&&t>this.game.rules.general.chronoHarvTooFarDistance)&&(!(t<=1)&&(!!this.isValidTargetRefinery(i,e)&&!(0===i.dockTrait.getAvailableDockCount()&&!i.dockTrait.hasReservedDockForUnit(e))))}}(On=On||{}).onPush=Symbol(),(r=In=In||{})[r.Move=0]="Move",r[r.ForceMove=1]="ForceMove",r[r.Attack=2]="Attack",r[r.ForceAttack=3]="ForceAttack",r[r.AttackMove=4]="AttackMove",r[r.Guard=5]="Guard",r[r.GuardArea=6]="GuardArea",r[r.Capture=7]="Capture",r[r.Occupy=8]="Occupy",r[r.Deploy=9]="Deploy",r[r.DeploySelected=10]="DeploySelected",r[r.Stop=11]="Stop",r[r.Cheer=12]="Cheer",r[r.Dock=13]="Dock",r[r.Gather=14]="Gather",r[r.Repair=15]="Repair",r[r.Scatter=16]="Scatter",r[r.EnterTransport=17]="EnterTransport",r[r.PlaceBomb=18]="PlaceBomb",(r=An=An||{})[r.Idle=0]="Idle",r[r.LookingForOreSite=1]="LookingForOreSite",r[r.MovingToOreSite=2]="MovingToOreSite",r[r.Harvesting=3]="Harvesting",r[r.LookingForRefinery=4]="LookingForRefinery",r[r.MovingToRefinery=5]="MovingToRefinery",r[r.Docking=6]="Docking",r[r.PreparingToUnload=7]="PreparingToUnload",r[r.Unloading=8]="Unloading";class Xo{constructor(e){this.storage=e,this.ore=0,this.gems=0,this.status=An.Idle,this.lastGatherExplicit=!1,this.autoGatherOnNextIdle=!1,this.ticksSinceLastRefineryCheck=0,this.ticksSinceLastOreCheck=0}[Xr.onSpawn](e,t){e.owner.isCombatant()&&t.afterTick(()=>{e.unitOrderTrait.addTask(new $o(t))})}[qr.onChange](e,t,i){!t.isCombatant()&&e.owner.isCombatant()&&i.afterTick(()=>{e.unitOrderTrait.addTask(new $o(i))})}[Mr.onTick](e,t){this.status===An.LookingForRefinery?this.ticksSinceLastRefineryCheck++>5*Ls.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastRefineryCheck=0,e.unitOrderTrait.hasTasks()?this.ticksSinceLastRefineryCheck=-25*Ls.BASE_TICKS_PER_SECOND:[...e.owner.buildings].some(e=>e.rules.refinery)||this.lastGatherExplicit?e.unitOrderTrait.addTask(new qo(t)):this.status=An.Idle):this.status===An.LookingForOreSite?this.ticksSinceLastOreCheck++>20*Ls.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastOreCheck=0,e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new $o(t))):this.status===An.Idle&&this.autoGatherOnNextIdle&&e.unitOrderTrait.isIdle()&&e.tile.landType===Yt.Tiberium&&(this.autoGatherOnNextIdle=!1,e.unitOrderTrait.addTask(new $o(t,e.tile,!0)))}[jr.onBeforeTeleport](e,t,i,s){!s&&e.owner.isCombatant()&&(this.status=An.Idle,this.lastOreSite=void 0,i&&e.rules.teleporter&&t.afterTick(()=>{e.unitOrderTrait.addTask(new(this.isFull()?qo:$o)(t))}))}[On.onPush](e,t){this.autoGatherOnNextIdle=[In.AttackMove,In.Move,In.ForceMove,In.Scatter].includes(t),[An.LookingForRefinery,An.LookingForOreSite].includes(this.status)&&(this.status=An.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 Qo{constructor(e){this.target=e,this.type=ts.LeaveTransport}}class Zo{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)}[Mr.onTick](e,t){this.loadQueue=this.loadQueue.filter(e=>!e.isDestroyed&&!e.isCrashing)}[Ur.onDestroy](e,t,i,s){var r=!!e.armedTrait?.deathWeapon,a=i?.weapon?.warhead.rules.parasite;if(s||r||e.zone===Ts.Air||a)for(var n of this.units)r&&n.armedTrait&&(n.armedTrait.deathWeapon=void 0),n.position.tileElevation=e.position.tileElevation,n.zone=e.zone,n.onBridge=e.onBridge,n.position.tile=e.tile,t.destroyObject(n,i,!0);else this.spawnSurvivors(t);this.units=[]}spawnSurvivors(e){var t=this.obj;if(this.units.length){for(var i of this.units)0<e.map.terrain.getPassableSpeed(t.tile,i.rules.speedType,t.onBridge)?(i.owner.addOwnedObject(i),i.position.tileElevation=t.onBridge?e.map.tileOccupation.getBridgeOnTile(t.tile).tileElevation:0,i.onBridge=t.onBridge,i.zone=e.map.getTileZone(t.tile,!t.onBridge),e.unlimboObject(i,t.tile),i.unitOrderTrait.addTask(new Ta(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 Qo(t))}}getHash(){return V(this.units.map(e=>e.getHash()))}debugGetState(){return this.units.map(e=>e.debugGetState())}dispose(){this.obj=void 0}}class Yo{[Mr.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===Yr.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}}}(Cn=Cn||{}).onHeal=Symbol();class Ko{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=sh+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}[Mr.onTick](s,r){if(this.parasite)if(this.parasite.isDestroyed)this.uninfest();else if(0<this.damageTickCooldown)this.damageTickCooldown--;else{let e=this.parasiteWeapon;this.damageTickCooldown=this.parasite.rules.organic?sh+2:e.getCooldownTicks();let t=e.rules.damage;this.parasite.veteranTrait&&(t*=this.parasite.veteranTrait.getVeteranDamageMultiplier());let i=e.warhead.computeDamage(t,s);this.canBeCulled(s,this.parasite,e,r)&&(i=s.healthTrait.getHitPoints()),e.warhead.inflictDamage(i,s,{player:this.parasite.owner,obj:this.parasite,weapon:e},r),s.isCrashing?(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(s,r)):!s.isDestroyed&&s.isVehicle()&&s.zone!==Ts.Air&&e.warhead.rules.rocker&&s.applyRocking(90*(.5<=r.generateRandom()?1:-1),1)}}canBeCulled(e,t,i,s){if(!i.warhead.rules.culling)return!1;s=s.rules.audioVisual,s=t.veteranTrait?.isElite()?s.conditionYellow:s.conditionRed;return e.healthTrait.health<=100*s}[Cn.onHeal](e,t,i,s){var r;!this.parasite||this.parasite.isDestroyed||s===e||e.isAircraft()&&s?.rules.unitReload||(this.parasite.rules.organic?(r=this.parasite,this.evictOrDestroyParasite(e,t),this.stunParasite(r,t)):(this.parasite.deathType=Wr.None,t.destroyObject(this.parasite,s?{player:s.owner,obj:s}:void 0),this.uninfest()))}[ha.onDamage](e,t,i,s){s?.obj!==this.parasite&&(this.lastExternalDamageInflicted=i,this.lastExternalDamageTick=t.currentTick)}[Zr.onAttack](i,s,r){if(this.parasite&&!this.parasite.isDestroyed&&s?.weapon?.warhead.rules.sonic){var a=this.parasite;this.evictOrDestroyParasite(i,r),this.stunParasite(a,r);let e=s.weapon.warhead;e.canDamage(a,a.tile,a.zone)&&(i=e.computeDamage(s.weapon.rules.damage,a),e.inflictDamage(i,a,s,r));let t=s.obj?.unitOrderTrait.getCurrentTask();t instanceof ko&&t.getWeapon().warhead.rules.sonic&&t.cancel()}}[Ur.onDestroy](e,t,i,s){this.parasite&&!this.parasite.isDestroyed&&(s||!this.parasite.invulnerableTrait.isActive()&&this.shouldSupressParasite(t,this.parasite,i)?(this.parasite.deathType=Wr.None,t.destroyObject(this.parasite,i,s),this.uninfest()):(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(e,t)))}shouldSupressParasite(e,t,i){return i?.obj!==t||this.lastExternalDamageInflicted&&this.lastExternalDamageInflicted>t.rules.suppressionThreshold&&e.currentTick-this.lastExternalDamageTick<2*this.lastExternalDamageInflicted}[jr.onBeforeTeleport](e,t,i,s){i&&s&&this.parasite&&!this.parasite.isDestroyed&&(this.parasiteWeapon.expireCooldown(),s=this.parasite,this.evictOrDestroyParasite(e,t,!0),s.isDestroyed||this.stunParasite(s,t))}stunParasite(e,t){e.unitOrderTrait.addTaskToFront(new ua(10/60).setCancellable(!1)),e.isVehicle()&&e.submergibleTrait&&(e.submergibleTrait.emerge(e,t),e.cloakableTrait?.uncloak(t),e.submergibleTrait.setCooldown(10*Ls.BASE_TICKS_PER_SECOND))}evictOrDestroyParasite(s,r,a=!1){if(this.parasite&&!this.parasite.isDestroyed){var e=s.zone===Ts.Air;if(e&&this.parasite.rules.movementZone!==ii.Fly||!e&&!r.map.terrain.getPassableSpeed(s.tile,this.parasite.rules.speedType,s.onBridge)&&!r.map.getObjectsOnTile(s.tile).find(e=>e.isBuilding()))this.parasite.deathType=Wr.None,r.destroyObject(this.parasite,{player:s.owner,obj:s});else{let t=s.tile,i=s.onBridge;if(!a&&!s.isDestroyed||this.parasite.rules.organic){let e=new Fs(r.map.tiles,r.map.mapBounds,t,{width:1,height:1},1,1,e=>0<r.map.terrain.getPassableSpeed(e,this.parasite.rules.speedType,i)&&!r.map.terrain.findObstacles({tile:e,onBridge:i},this.parasite).length);a=e.getNextTile();if(!a)return this.parasite.deathType=Wr.None,r.destroyObject(this.parasite,{player:s.owner,obj:s}),void this.uninfest();t=a}this.parasite.onBridge=i,this.parasite.position.subCell=this.parasite.isInfantry()?s.position.subCell:0,this.parasite.zone=r.map.getTileZone(t,!i),this.parasite.position.tileElevation=i?r.map.tileOccupation.getBridgeOnTile(t).tileElevation:0,this.parasite.resetGuardModeToIdle(),r.unlimboObject(this.parasite,t,!0)}this.uninfest()}}destroyParasite(e,t){this.parasite&&(this.parasite.deathType=Wr.None,t.destroyObject(this.parasite,e),this.uninfest())}dispose(){this.gameObject=void 0}}class Jo{constructor(e){this.target=e,this.type=ts.ShipSubmergeChange}}class eh{constructor(){this.isActive=!1}isSubmerged(){return this.isActive}setCooldown(e){this.cooldownTicks=e}[Mr.onTick](e,t){this.isActive||e.parasiteableTrait?.isInfested()||(e.attackTrait&&e.attackTrait.attackState!==bn.Idle&&!e.moveTrait.isMoving()?this.cooldownTicks=Math.max(this.cooldownTicks??0,5*Ls.BASE_TICKS_PER_SECOND):this.cooldownTicks??(this.cooldownTicks=Math.floor(60*t.rules.general.cloakDelay*Ls.BASE_TICKS_PER_SECOND)),0<this.cooldownTicks&&this.cooldownTicks--,this.cooldownTicks<=0&&(this.isActive=!0,t.events.dispatch(new Jo(e))))}[ha.onDamage](e,t){this.emerge(e,t)}emerge(e,t){this.isActive&&(this.isActive=!1,this.cooldownTicks=void 0,t.events.dispatch(new Jo(e)))}}class th{constructor(){this.prevHoverBobLeptons=0,this.spawnTick=0}[Xr.onSpawn](e,t){this.setBaseElevation(e,t),this.spawnTick=t.currentTick}[Vr.onTileChange](e,t,i,s){s&&(this.prevHoverBobLeptons=0,this.setBaseElevation(e,t))}setBaseElevation(e,t){e.position.tileElevation=(e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile)?.tileElevation??0:0)+Ss.worldToTileHeight(t.rules.general.hover.height)}[Mr.onTick](e,t){var i=this.computeHoverBobLeptons(t.currentTick,t.rules.general.hover),t=i-this.prevHoverBobLeptons;this.prevHoverBobLeptons=i;i=Ss.tileHeightToWorld(e.position.tileElevation);e.position.tileElevation=Ss.worldToTileHeight(i+t)}computeHoverBobLeptons(e,t){e=(e-this.spawnTick)/Ls.BASE_TICKS_PER_SECOND/(60*t.bob);return.1*t.height*Qi.sin(2*e*Math.PI)}}class ih{constructor(){this.tilt={pitch:0,yaw:0}}[Xr.onSpawn](e){this.tilt=this.computeTilt(e.tile.rampType)}[Vr.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 sh=34;class rh extends Aa{constructor(e,t,i){super(Ct.Vehicle,e,t,i),this.direction=0,this.spinVelocity=0,this.crateBonuses=new Pa,this.turretNo=0,this.onBridge=!1,this.isSinker=!1,this.isFiring=!1,this.zone=t.naval?Ts.Water:Ts.Ground}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s,r){let a=new this(e,t,i);return a.isSinker=!t.underwater&&(t.weight>=s.general.shipSinkingWeight||!t.naval),a.moveTrait=new _a(a,r),a.traits.add(a.moveTrait),t.crashable&&(a.crashableTrait=new xa(a),a.traits.add(a.crashableTrait)),t.crewed&&(a.crewedTrait=new go,a.traits.add(a.crewedTrait)),t.harvester&&(a.harvesterTrait=new Xo(t.storage),a.traits.add(a.harvesterTrait)),t.passengers&&(a.transportTrait=new Zo(a),a.traits.add(a.transportTrait),t.gunner&&(a.gunnerTrait=new Yo,a.traits.add(a.gunnerTrait))),t.turret&&(a.turretTrait=new Qn,a.traits.add(a.turretTrait)),t.consideredAircraft&&!t.landable||a.traits.add(new no),t.parasiteable&&(a.parasiteableTrait=new Ko(a),a.traits.add(a.parasiteableTrait)),t.naval&&t.underwater&&(a.submergibleTrait=new eh,a.traits.add(a.submergibleTrait)),t.locomotor===ti.Hover&&a.traits.add(new th),t.isTilter&&!t.consideredAircraft&&(a.tilterTrait=new ih,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??sh,facing:e,factor:t}}}class ah{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 nh{setParent(e){this.parent=e}getParent(){return this.parent}[Mr.onTick](s,r){if(this.parent&&s.attackTrait&&s.primaryWeapon){let e=this.parent.attackTrait?.currentTarget,t=s.unitOrderTrait.getCurrentTask(),i=new Is(r.map.tileOccupation);var a=this.parent.armedTrait?.getWeapons().find(e=>e.rules.spawner);s.ammo&&!(e&&s.attackTrait.currentTarget?e.equals(s.attackTrait.currentTarget):e===s.attackTrait.currentTarget||!e&&this.parent.isUnit()&&(this.parent.unitOrderTrait.getCurrentTask()instanceof ba||this.parent.unitOrderTrait.getCurrentTask()instanceof ko))&&(!e||a&&i.isInWeaponRange(this.parent,e.obj??e.tile,a,r.rules))?e&&s.primaryWeapon.targeting.canTarget(e.obj,e.tile,r,!0,!1)?!t||t instanceof ba?(s.unitOrderTrait.cancelAllTasks(),s.unitOrderTrait.addTask(s.attackTrait.createAttackTask(r,e.obj,e.tile,s.primaryWeapon,{force:!0}))):s.attackTrait.attackState!==bn.Idle&&t.requestTargetUpdate(e):t?t instanceof ba||t.cancel():this.tryMoveToParent(s,this.parent,r):this.tryMoveToParent(s,this.parent,r)}}tryMoveToParent(t,i,s){if(t.tile!==i.tile){let e=t.unitOrderTrait.getCurrentTask();e?e instanceof ba&&e.updateTarget(i.tile,!!i.isUnit()&&i.onBridge):t.unitOrderTrait.addTask(new ba(s,i.tile,!!i.isUnit()&&i.onBridge,{closeEnoughTiles:0,strictCloseEnough:!0}))}}}class oh{setWarhead(e){return this.warhead=e,this}setDamage(e){return this.damage=e,this}setLauncher(e){return this.launcher=e,this}[Ur.onDestroy](e,t){this.warhead&&this.damage&&this.launcher&&this.warhead.detonate(t,this.damage,e.tile,e.tileElevation,e.position.worldPosition,e.zone,ia.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 hh extends Aa{constructor(e,t,i,s){super(Ct.Aircraft,e,t,i),this.pitch=0,this.yaw=0,this.roll=0,this.onBridge=!1,this.zone=Ts.Ground,this.crateBonuses=new Pa,this.generalRules=s}get sight(){return this.rules.spawned?super.sight:super.sight+(this.zone===Ts.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,s,r){let a=new this(e,t,i,s.general);return a.rules.airportBound&&a.rules.dock.length&&(a.airportBoundTrait=new ah(a.rules.dock),a.traits.add(a.airportBoundTrait)),a.rules.missileSpawn||(a.crashableTrait=new xa(a),a.traits.add(a.crashableTrait)),a.rules.spawned&&(a.rules.missileSpawn?(a.missileSpawnTrait=new oh,a.traits.add(a.missileSpawnTrait)):(a.spawnLinkTrait=new nh,a.traits.add(a.spawnLinkTrait))),a.moveTrait=new _a(a,r),a.traits.add(a.moveTrait),t.dock.length&&a.traits.add(new no),t.landable&&e!==s.general.paradrop.paradropPlane||a.traits.add(new Fa),t.parasiteable&&(a.parasiteableTrait=new Ko(a),a.traits.add(a.parasiteableTrait)),a}isUnit(){return!0}isAircraft(){return!0}}class lh{constructor(e){this.gameObject=e,this.orders=[],this.queuedOrders=new Set,this.tasks=[],this.taskRunner=new vo}[Mr.onTick](i,e){if(i.isSpawned){var s=this.hasTasks(),t=this.tasks.find(e=>!e.isCancelling());s&&this.taskRunner.tick(this.tasks,i);var r,a=this.orders.length;if(a&&(!s||!t)){let e,t=!1;for(;e=this.orders[0];)if(e.isValid()&&e.isAllowed()&&((r=e.process())&&(this.queuedOrders.has(e)&&(this.tasks.push(new Gs(5)),this.tasks.push(new da(()=>{i.resetGuardModeToIdle()}))),this.tasks.push(...r),s||this.taskRunner.tick(this.tasks,i)),t=!0),this.orders.shift(),this.queuedOrders.delete(e),this.waypointPath&&(this.currentWaypoint?(this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.currentWaypoint=this.currentWaypoint?.next):this.currentWaypoint=this.waypointPath.waypoints[0],this.currentWaypoint||this.cleanupWaypointPath()),t)break}!a&&!s&&this.waypointPath&&this.currentWaypoint&&(this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.cleanupWaypointPath());let e=t;for(;e?.useChildTargetLines;){var n=e.children.find(e=>!e.isCancelling());if(!n)break;e=n}this.targetLinesTask!==e&&(this.targetLinesTask=e,this.targetLinesConfig=e?.getTargetLinesConfig(this.gameObject))}}[qr.onChange](){this.clearOrders(),this.cancelAllTasks()}[jr.onBeforeTeleport](e,t,i,s){i&&!s&&(this.clearOrders(),this.tasks.length=0)}addOrder(t,e=!1){!1!==t.onAdd(this.tasks,e)?(e||(this.clearOrders(),this.tasks=this.tasks.filter(e=>e.status!==Ms.NotStarted),this.tasks.forEach(e=>e.cancel())),this.orders.push(t),e&&this.queuedOrders.add(t),this.gameObject.traits.filter(On).forEach(e=>{e[On.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 ch=[[0,0,0,0],[0,0,1,1],[1,0,0,1],[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,0,0],[0,1,0,0],[0,0,1,0],[1,0,1,1],[1,1,0,1],[1,1,1,0],[0,1,1,1],[1,0,1,2],[2,1,0,1],[1,2,1,0],[0,1,2,1],[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]];class uh{constructor(e,t){this.tiles=e,this.tileOccupation=t,this._worldPosition=new is,this._tileOffset=new vs,this._centerOffset=new vs,this.desiredSubCell=0,this._tileElevation=0,this._onPositionChange=new io}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/Ss.LEPTONS_PER_TILE-.5),t=Math.sign(this._tileOffset.y/Ss.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 vs(this._tile.rx*Ss.LEPTONS_PER_TILE+this._tileOffset.x+this._centerOffset.x,this._tile.ry*Ss.LEPTONS_PER_TILE+this._tileOffset.y+this._centerOffset.y)}getBridgeBelow(){return this._tile?.onBridgeLandType?this.tileOccupation.getBridgeOnTile(this._tile):void 0}moveToTileCell(e,t=0){if(!this._tile)throw new Error("Tile is not set");var i=e!==this._tile;this._tile=e,this._tileOffset=this.computeSubCellOffset(t),this.desiredSubCell=t,this.updateWorldPosition(e,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:i})}moveToTileCoords(e,t,i=!1){var s=Math.floor(e),r=Math.floor(t),a=!this._tile||this._tile.rx!==s||this._tile.ry!==r;if(a){let e=this.tiles.getByMapCoords(s,r);if(!e){if(!i)throw new RangeError(`Attempted move to a non-existent tile: [${s},${r}]`);e=this.tiles.getPlaceholderTile(s,r)}this._tile=e}this._tileOffset.set((e-s)*Ss.LEPTONS_PER_TILE,(t-r)*Ss.LEPTONS_PER_TILE),this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:a})}moveToLeptons(e,t=!1){this.moveToTileCoords(e.x/Ss.LEPTONS_PER_TILE,e.y/Ss.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)/Ss.LEPTONS_PER_TILE,this._tile.ry+(this._tileOffset.y+t)/Ss.LEPTONS_PER_TILE,i)}moveByLeptons3(e,t=!1){var i=this._worldPosition.y;this.moveByLeptons(e.x,e.z,t),this.setAbsoluteElevationWorld(i+e.y)}setAbsoluteElevationWorld(e){this._absoluteElevation=e,this._tileElevation=void 0,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}computeSubCellOffset(e){let t={width:0,height:0};var i;e&&(i=(e-1)%2*2-1,s=2*Math.floor((e-1)/2)-1,t={width:i*Ss.LEPTONS_PER_TILE/4,height:s*Ss.LEPTONS_PER_TILE/4});var s=Ss.LEPTONS_PER_TILE/2;return new vs(s+t.width,s+t.height)}interpolateRampHeight(e,t,i){var s=ch[i],r=s[1],i=s[0];return r*(1-e)*(1-t)+s[2]*e*(1-t)+i*(1-e)*t+s[3]*e*t}updateWorldPosition(t,i){var e=i.x+this._centerOffset.x,s=i.y+this._centerOffset.y,r=e/Ss.LEPTONS_PER_TILE,i=s/Ss.LEPTONS_PER_TILE;let a;if(void 0!==this._tileElevation){let e=0;0!==t.rampType&&(e=this.interpolateRampHeight(r,i,t.rampType)),a=Ss.tileHeightToWorld(t.z+e+this._tileElevation)}else a=this._absoluteElevation;this._worldPosition.set(t.rx*Ss.LEPTONS_PER_TILE+e,a,t.ry*Ss.LEPTONS_PER_TILE+s),void 0===this._tileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos())}computeTileElevationFromWorldPos(){if(!this._tile)return 0;var e=Ss.worldToTileHeight(this._worldPosition.y),t=(this._tileOffset.x+this._centerOffset.x)/Ss.LEPTONS_PER_TILE,i=(this._tileOffset.y+this._centerOffset.y)/Ss.LEPTONS_PER_TILE;let s=0;return 0!==this._tile.rampType&&(s=this.interpolateRampHeight(t,i,this._tile.rampType)),e-this._tile.z-s}clone(){let e=new uh(this.tiles,this.tileOccupation);return e._worldPosition=this._worldPosition.clone(),e._tile=this._tile,e._tileOffset=this._tileOffset.clone(),e._centerOffset=this._centerOffset.clone(),e._tileElevation=this._tileElevation,e._absoluteElevation=this._absoluteElevation,e._computedTileElevation=this._computedTileElevation,e}}class dh{constructor(e){this.tileOccupation=e}checkCollisions(e,t,i){var s,r=e.tile;let a,n;for(s of this.tileOccupation.getObjectsOnTile(r))s.isOverlay()&&s.isBridge()&&(a=s),s.isBuilding()&&(n=s);if(i.walls){if(e.tileElevation<=2&&r.landType===Yt.Wall)return ia.Wall;if(i.buildings&&n?.tile===r&&e.tileElevation<=1.1&&i.buildings(n.owner))return ia.Wall}if(i.shore&&r.landType!==Yt.Water)return ia.Shore;if(i.ground&&e.tileElevation<0)return ia.Ground;var o=e.tileElevation+r.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?ia.UnderBridge:ia.OnBridge}else if(a?.isLowBridge()&&i.shore)return ia.UnderBridge;if(i.cliffs){t=r.z-t.tile.z;if(e.tileElevation<0&&4<=t)return ia.Cliff}return ia.None}computeDetonationZone(e,t,i){let s=this.tileOccupation.getBridgeOnTile(e);return i===ia.None&&t>1.5+(s?.tileElevation??0)?Ts.Air:s&&1.5<t||e.terrainType!==Zt.Water||s?.isLowBridge()?Ts.Ground:Ts.Water}}(r=Bn=Bn||{})[r.Travel=0]="Travel",r[r.Impact=1]="Impact",r[r.Detonation=2]="Detonation";class ph extends Ia{constructor(e,t,i,s){super(Ct.Projectile,e,t,i),this.tileOccupation=s,this.state=Bn.Travel,this.detonationTimer=0,this.collisionType=ia.None,this.direction=0,this.zone=Ts.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 is,this.sonicVisitedObjects=new Map,this.collisionHelper=new dh(s)}get fromObject(){return this._fromObject}set fromObject(e){(this._fromObject=e)&&e.veteranTrait&&!e.isDestroyed&&(this.veteranDamageMult=e.veteranTrait.getVeteranDamageMultiplier())}get rot(){return this.fromWeapon.rules.isSonic?Oi.iniRotToDegsPerTick(this.iniRot):this.rules.rot}get iniRot(){return this.fromWeapon.rules.isSonic?10:this.rules.iniRot}static factory(e,t,i,s){return new this(e,t,i,s)}onSpawn(a){var e;if(super.onSpawn(a),this.initialSelfPosition=this.position.worldPosition.clone(),!this.target.obj||this.fromWeapon.type===ni.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 Is(this.tileOccupation);var t=e.distance2(this.target.getWorldCoords(),this)/Ss.LEPTONS_PER_TILE;this.initialTileDistToTarget=t,this.maxSpeed=this.computeMaxSpeed(this.fromWeapon.speed,t,a.rules.audioVisual.gravity)}),this.isHoming()){if(1===this.iniRot&&(this.homingMoveDir=this.target.getWorldCoords().clone().sub(this.position.worldPosition)),this.fromObject?.isAircraft()&&this.rules.isAntiGround&&!this.rules.isAntiAir){let e=this.target.obj;!e?.isVehicle()||e.isDestroyed||e.veteranLevel!==Yr.Elite||e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Ta(a))}}else if(this.rules.vertical){let e=this.position.clone();e.tileElevation=this.fromWeapon.warhead.rules.nukeMaker?Ss.worldToTileHeight(this.fromWeapon.projectileRules.detonationAltitude):0,this.aimPoint=e.worldPosition.clone()}else{let r=this.target.getWorldCoords().clone();a.afterTick(()=>{let e=this.target.getWorldCoords().clone().sub(r);var t=e.length()>Ss.LEPTONS_PER_TILE;let i=t?r:this.target.obj?.isUnit()&&this.target.obj.moveTrait.velocity.length()&&isFinite(this.maxSpeed)?this.computeAimPointVersusMovingTarget(this.target.obj,this.maxSpeed,this.position.worldPosition,a.map):this.target.getWorldCoords().clone();this.aimPoint=i,this.snapToTarget=!t&&isFinite(this.maxSpeed)&&!this.fromWeapon.warhead.rules.sonic,(this.rules.inaccurate||this.rules.flakScatter)&&(this.adjustAimForBallisticScatter(a,i),this.snapToTarget=!1),!t&&this.rules.arcing&&(this.rules.inaccurate?(this.overshootTiles=this.calculateInaccurateBallisticOvershoot(a),this.snapToTarget=!1):this.target.obj?.isVehicle()&&this.target.obj.moveTrait.isMoving()&&(this.overshootTiles=this.calculateBallisticOvershootVsMoving(a,this.target.obj),this.overshootTiles&&(this.snapToTarget=!1)));let s=i.clone().sub(this.position.worldPosition);s.length()<this.fromWeapon.speed&&this.update(a)})}}adjustAimForBallisticScatter(e,t){let i=e.rules.combatDamage.ballisticScatter,s;s=this.rules.flakScatter?(this.rules.inviso&&(i*=2),e.generateRandom()*i):i/2+e.generateRandom()*(i/2);let r=s*Ss.LEPTONS_PER_TILE;this.rules.flakScatter&&(n=t.clone().sub(this.initialSelfPosition).length(),r*=n/(this.fromWeapon.range*Ss.LEPTONS_PER_TILE));var a=sr(new vs(r,0),e.generateRandomInt(0,360)),n=Ss.vecWorldToGround(t).add(a).multiplyScalar(1/Ss.LEPTONS_PER_TILE).floor();e.map.tiles.getByMapCoords(n.x,n.y)&&t.add(new is(a.x,0,a.y))}calculateBallisticOvershootVsMoving(e,t){let i=this.target.getWorldCoords().clone().sub(this.initialSelfPosition);var s=nr(Ss.vecWorldToGround(i),Ss.vecWorldToGround(t.moveTrait.velocity)),t=(90<s?180-s:s)/90,s=i.length()/Ss.LEPTONS_PER_TILE,t=t*s/5;return e.generateRandom()<=t?2*Math.min(1,s/5):0}calculateInaccurateBallisticOvershoot(e){return e.generateRandom()<=.5?2:0}update(n){if(void 0!==this.maxSpeed)if(super.update(n),this.state!==Bn.Impact){var s=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()>=Ss.LEPTONS_PER_TILE)?(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*Ss.LEPTONS_PER_TILE))return void this.detonate(n);if(this.homingMoveDir||(c=wr.toMapCoords(this.direction),this.homingMoveDir=new is(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 Is(this.tileOccupation);var l=Math.floor(e.distance2(a,this)/Ss.LEPTONS_PER_TILE),c=2<l&&1<this.iniRot;let t=a.clone().sub(this.position.worldPosition),i=0;this.homingTravelTicks<this.rules.courseLockDuration||(c?(dr(this.homingMoveDir,new is(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=Ss.tileHeightToWorld(Math.sign(u)*Math.min(Math.abs(u),p)))):dr(this.homingMoveDir,t,this.rot)),this.direction=wr.fromMapCoords(new vs(this.homingMoveDir.x,this.homingMoveDir.z));var l=t.length(),u=Math.min(l,h);this.homingTravelDistance+=u,this.homingTravelTicks++;let s=!1,r=ia.None;if(1<=u){let e=this.homingMoveDir.clone().setLength(u);i&&(e.y+=i),u===h&&this.velocity.copy(e);var d=e.clone().add(this.position.worldPosition);n.map.mapBounds.isWithinHardBounds(d)?this.position.moveByLeptons3(e):s=!0,r=this.checkObstacles(o,n),(r||u<h)&&(s=!0)}else this.position.moveByLeptons3(t),s=!0;s&&(this.collisionType=r,this.detonate(n,r))}else{let t=this.aimPoint.clone().sub(this.position.worldPosition);this.rules.vertical||(this.direction=wr.fromMapCoords(new vs(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=Ss.vecWorldToGround(this.position.worldPosition.clone().sub(this.initialSelfPosition).add(t));var l=this.aimPoint.clone().sub(this.initialSelfPosition),r=e.length(),d=Ss.vecWorldToGround(l).length(),u=l.y,l=n.rules.audioVisual.gravity;t.y=(u/d*h+l/2*d/h)*r/h-l*(r/h)*(r/h)/2+this.initialSelfPosition.y-this.position.worldPosition.y}let e=!1;r=t.clone().add(this.position.worldPosition);n.map.isWithinHardBounds(r)?this.position.moveByLeptons3(t):e=!0;let i=ia.None;if(1<=p?(p!==h&&!this.overshootTiles||this.velocity.copy(t),i=this.checkObstacles(o,n),(i||p<h)&&(e=!0)):e=!0,e){if(!i)if(this.overshootTiles){var g=Ss.vecWorldToGround(s).setLength(this.overshootTiles*Ss.LEPTONS_PER_TILE);if(sr(g,n.generateRandomInt(-45,45)),r=Ss.vecGroundToWorld(g).add(this.position.worldPosition),!n.map.isWithinHardBounds(r))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(a.clone().sub(this.position.worldPosition))}this.collisionType=i,this.isNuke?(this.state=Bn.Impact,this.detonationTimer=2.5*Ls.BASE_TICKS_PER_SECOND):this.detonate(n,i)}}let e=this.fromWeapon.warhead;if(e.rules.sonic){var t,i,g=11/30*Ss.LEPTONS_PER_TILE,g=this.position.worldPosition.clone().add(this.velocity.clone().setLength(g)),g=Ss.vecWorldToGround(g).multiplyScalar(1/Ss.LEPTONS_PER_TILE).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)&&t.isSpawned&&(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 s=!0,r=this.target.obj;if(r?.isUnit()&&this.fromObject){let e=new Is(this.tileOccupation);i=e.computeWeaponRangeVsTarget(this.fromObject,r,this.fromWeapon,i.rules).range;this.fromWeapon.rules.limboLaunch?s=e.isInRange3(this.initialSelfPosition,t,0,i+.5):(t=r.moveTrait.velocity.length())&&(this.fromObject.rules.movementZone===ii.Fly?5<this.speed/t&&(s=e.isInRange2(this.initialSelfPosition,this.position.worldPosition,0,i)):isFinite(this.fromWeapon.speed)&&3.5<this.fromWeapon.speed/r.rules.speed&&(s=e.isInRange3(this.initialSelfPosition,this.position.worldPosition,0,i)))}return s}updateSpeed(e){let t;return t=this.isHoming()||this.rules.vertical?void 0===this.speed?Math.min(e,this.rules.acceleration):Math.min(e,this.speed+this.rules.acceleration):e,t}computeMaxSpeed(e,t,i){let s=e*as.MAGIC_SPEED_MULT;return this.rules.arcing&&(s*=(1+i/6)/2,t=Math.floor(t),s*=t<=8?1:1+t/8*.5),this.fromWeapon.warhead.rules.sonic&&(s=Math.ceil(t*Ss.LEPTONS_PER_TILE/21)),s}checkObstacles(e,t){return this.fromWeapon.rules.limboLaunch?ia.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 s=t.rules.damage;t.type===ni.DeathWeapon&&i.rules.ivanBomb&&(s=e.rules.combatDamage.ivanDamage);let r=s*this.baseDamageMultiplier;return t.type===ni.DeathWeapon&&this.fromObject&&(r*=this.fromObject.rules.deathWeaponDamageModifier),r*=this.veteranDamageMult,r}detonate(n,e=ia.None){var i=this.fromWeapon;let s=i.warhead;var t,r=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,e);let o=this.tile;i.type===ni.DeathWeapon&&s.rules.ivanBomb&&(s=new Xa(n.rules.getWarhead(n.rules.combatDamage.ivanWarhead)));let a=this.computeBaseDamage(n);n.destroyObject(this),this.state=Bn.Detonation;let h=this.target.obj,l=!1;if(s.rules.parasite&&h?.isUnit()&&o===h.tile&&s.canDamage(h,o,r))if(h.isInfantry())a=Number.POSITIVE_INFINITY;else if(h.parasiteableTrait&&this.fromObject?.isUnit()){if(!(this.fromWeapon instanceof Ka))throw new Error("Projectile with parasite warhead must have a weapon reference");h.parasiteableTrait.infest(this.fromObject,this.fromWeapon),l=!0}let c=!0;if(l&&(c=!1),s.rules.sonic&&(c=!1),s.rules.ivanBomb&&(c=!1,!h?.isTechno()||!h.tntChargeTrait||h.tntChargeTrait.hasCharge()||h.isDestroyed||h.warpedOutTrait.isInvulnerable()||(t=n.rules.combatDamage.ivanTimedDelay,h.tntChargeTrait.setCharge(t,n.currentTick,{player:this.fromPlayer}))),s.rules.bombDisarm&&(c=!1,h?.isTechno()&&h.tntChargeTrait?.hasCharge()&&!h.isDestroyed&&h.tntChargeTrait.removeCharge()),s.rules.mindControl&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&h.mindControllableTrait&&!h.mindControllableTrait?.isActive()&&!n.areFriendly(h,this.fromObject)&&s.canDamage(h,o,r)&&!h.invulnerableTrait.isActive()&&this.fromObject.mindControllerTrait.control(h,n)),s.rules.temporal&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&s.canDamage(h,o,r)&&!h.invulnerableTrait.isActive()&&(s.inflictDamage(0,h,{player:this.fromPlayer,weapon:i,obj:this.fromObject},n),this.fromObject.temporalTrait.updateTarget(h,i,n))),s.rules.makesDisguise&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&(this.fromObject.isInfantry()||this.fromObject.isVehicle())&&h?.isUnit()&&h.type===this.fromObject.type&&this.fromObject.disguiseTrait?.disguiseAs(h,this.fromObject,n)),s.rules.electricAssault&&(this.fromObject?.isUnit()&&!this.fromObject.isDestroyed&&h?.isBuilding()&&!h.isDestroyed&&h.overpoweredTrait&&h.owner===this.fromPlayer&&h.overpoweredTrait.chargeFrom(this.fromObject),c=!1),c&&s.detonate(n,a,o,this.tileElevation,this.position.worldPosition,r,e,this.target,{player:this.fromPlayer,weapon:i,obj:this.fromObject},this.isShrapnel,!1,this.impactAnim),s.rules.nukeMaker){let e;e=this.fromObject?(u=Ka.factory(Ka.NUKE_PAYLOAD_NAME,ni.Primary,this.fromObject,n.rules),n.createProjectile(u.projectileRules.name,this.fromObject,u,this.target,!1)):n.createLooseProjectile(Ka.NUKE_PAYLOAD_NAME,this.fromPlayer,this.target),e.isNuke=!0,e.impactAnim="NUKEBALL";var u=this.target.tile;e.position.moveToTileCoords(u.rx+.5,u.ry+.5),e.position.tileElevation=this.position.tileElevation,n.spawnObject(e,u)}if(this.rules.shrapnelCount&&this.rules.shrapnelWeapon&&((this.target.obj?!this.target.obj.isBuilding():n.map.getGroundObjectsOnTile(this.target.tile).some(e=>e.isTerrain())&&!i.projectileRules.isAntiAir)||this.isShrapnel)){let t=n.rules.getWeapon(this.rules.shrapnelWeapon);var d,p=n.rules.getProjectile(t.projectile);let i=this.rules.shrapnelCount,s=new Is(n.map.tileOccupation),e=new Fs(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},1,t.range,e=>s.isInTileRange(o,e,t.minimumRange,t.range)),r=new Set;for(;0<Math.floor(i);){var g,m=e.getNextTile();if(!m)break;for(g of n.map.tileOccupation.getObjectsOnTileByLayer(m,p.isAntiAir?fn.Air:fn.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===Ds.Paradrop))))if(!r.has(g)&&(r.add(g),i=Math.max(0,i-1-(g.isTechno()?.5:0)),Math.floor(i)<=0))break}for(d of r){var f=n.createTarget(d.isTerrain()?void 0:d,d.tile);this.createShrapnel(n,f,t.name)}i=Math.floor(i);let a=new fa(n.map.tiles,n.map.mapBounds,o,t.range,n,e=>s.isInTileRange(o,e,t.minimumRange,t.range));for(let e=0;e<i;e++){var y=a.getNextTile();if(!y)break;y=n.createTarget(void 0,y);this.createShrapnel(n,y,t.name)}}if(i.rules.limboLaunch&&!l&&this.fromObject?.isUnit()){let r=this.fromObject;s.rules.parasite&&(this.target.obj.isVehicle()||this.target.obj?.isAircraft())&&this.target.obj.parasiteableTrait&&(this.target.obj.parasiteableTrait.beingBoarded=!1);let t,a;i=r.rules.movementZone===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),s=new $s(n.map),e=new Fs(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},0,1,e=>{var t=n.map.tileOccupation.getBridgeOnTile(e);return 0<n.map.terrain.getPassableSpeed(e,r.rules.speedType,!!t)&&s.isEligibleTile(e,t,i,o)&&(e===o||!n.map.terrain.findObstacles({tile:e,onBridge:i},r).length)});t=e.getNextTile(),a=!!t?.onBridgeLandType}t?(!i&&this.target.obj.isUnit()&&(r.onBridge=a,r.position.tileElevation=a?n.map.tileOccupation.getBridgeOnTile(t)?.tileElevation??0:0),n.unlimboObject(r,t),r.isInfantry()&&(r.position.subCell=this.target.obj.position.subCell),r.direction=this.direction):r.owner.removeOwnedObject(r)}}createShrapnel(e,t,i){let s=e.createLooseProjectile(i,this.fromPlayer,t);s.isShrapnel=!0,s.veteranDamageMult=this.veteranDamageMult,s.position.moveToLeptons(this.position.getMapPosition()),s.position.tileElevation=this.position.tileElevation,e.spawnObject(s,s.position.tile)}computeAimPointVersusMovingTarget(t,i,e,s){let r=t.position.worldPosition,a=r.clone();var n=i,i=t.moveTrait.velocity.length();if(n<3*i)return r.clone();let o=Cr.computeInterceptPoint(e,n,r,t.moveTrait.velocity);if(o.length()){let e=o.clone().sub(r);n=e.length(),i=i,n=i?Math.ceil(n/i):0;if(o=r.clone().add(e.setLength(n*i)),s.isWithinHardBounds(o))if(t.zone!==Ts.Air){o.multiplyScalar(1/Ss.LEPTONS_PER_TILE);let e=t.position.clone();e.moveToTileCoords(o.x,o.z),a=e.worldPosition}else a=o;else a=r}return a.clone()}}(r=xn=xn||{})[r.None=0]="None",r[r.PreparingToFire=1]="PreparingToFire",r[r.FiringUp=2]="FiringUp",r[r.Firing=3]="Firing";class gh{constructor(e){this.gameObject=e,this.deployed=!1,this.deployFireDelay=0,this.deployFireState=xn.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?Ds.Deployed:Ds.None),t?(this.deployFireState=xn.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===xn.FiringUp&&(e.isFiring=!1),this.deployFireState=xn.None,this.deployWeapon=void 0)}}toggleDeployed(){this.setDeployed(!this.isDeployed())}[Mr.onTick](e,t){if(void 0!==this.undeployDelay&&(0<this.undeployDelay&&this.undeployDelay--,this.undeployDelay<=0&&[xn.None,xn.PreparingToFire].includes(this.deployFireState)))return this.undeployDelay=void 0,void this.setDeployed(!1);if(this.deployWeapon&&this.deployFireState!==xn.None){if(this.deployFireState===xn.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=xn.FiringUp}if(this.deployFireState===xn.FiringUp){if(e.isFiring=!0,0<this.fireUpDelay--)return;this.deployFireState=xn.Firing}var i;this.deployFireState===xn.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=xn.None,this.deployWeapon=void 0):this.deployFireState=xn.PreparingToFire)}}computeDeployFireCooldown(t,i){if(t.rules.radLevel&&t.rules.areaFire){var s=this.gameObject.tile,s=i.mapRadiationTrait.getRadSiteLevel(s);if(!s)return 0;i=i.rules.radiation;let e=Math.max(0,s*i.radDurationMultiple-i.radLevelDelay);return 1===this.deployFireCount&&(i=i.radDurationMultiple*t.rules.radLevel,e=Math.max(0,e-Math.floor(.25*i))),e}return t.getCooldownTicks()}getHash(){return this.deployed?1:0}debugGetState(){return{deployed:this.deployed}}dispose(){this.gameObject=void 0}}(En=En||{}).onChange=Symbol();class mh{constructor(e,t,i,s,r){this.target=e,this.attacker=t,this.damageHitPoints=i,this.currentHealth=s,this.prevHealth=r,this.type=ts.InflictDamage}}(Pn=Pn||{}).onChange=Symbol(),(r=Nn=Nn||{})[r.Green=0]="Green",r[r.Yellow=1]="Yellow",r[r.Red=2]="Red";class fh{constructor(e,t,i){this.target=e,this.currentHealth=t,this.prevHealth=i,this.type=ts.HealthChange}}class yh{constructor(e,t,i,s){this.maxHitPoints=e,this.gameObject=t,this.conditionYellow=i,this.conditionRed=s,this.setHitPoints(e),this.projectedHitPoints=this.hitPoints}get health(){return this._computedHealth}set health(e){this.setHitPoints(0<e?Math.max(1,Math.floor(e*this.maxHitPoints/100)):0),this.projectedHitPoints=this.hitPoints}get level(){return this.health>100*this.conditionYellow?Nn.Green:this.health>100*this.conditionRed?Nn.Yellow:Nn.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,s){var e=this.hitPoints,r=this.health;this.applyHitPoints(e-t,s),e!==this.hitPoints&&0<t&&(this.gameObject.traits.filter(ha).forEach(e=>{e[ha.onDamage](this.gameObject,s,t,i)}),s.events.dispatch(new mh(this.gameObject,i,t,this.health,r)))}healBy(e,i,s){if(e<0)throw new Error(`Can't heal by negative value ${e}`);if(this.hitPoints<this.maxHitPoints){var r=this.hitPoints;this.applyHitPoints(this.hitPoints+e,s),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-r;this.gameObject.traits.filter(Cn).forEach(e=>{e[Cn.onHeal]?.(this.gameObject,s,t,i)})}}healToFull(i,s){if(this.hitPoints<this.maxHitPoints){var e=this.hitPoints;this.applyHitPoints(this.maxHitPoints,s),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-e;this.gameObject.traits.filter(Cn).forEach(e=>{e[Cn.onHeal]?.(this.gameObject,s,t,i)})}}applyHitPoints(e,t){let i=this.health;this.setHitPoints(e),i!==this.health&&(t.traits.filter(En).forEach(e=>{e[En.onChange](this.gameObject,t,i)}),this.gameObject.traits.filter(Pn).forEach(e=>{e[Pn.onChange](this.gameObject,t,i)}),t.events.dispatch(new fh(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)}[Mr.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 wh{constructor(e){this.bridges=e,this.needsImageUpdate=!1,this.dominoHandled=!1}[ha.onDamage](){this.needsImageUpdate=!0}[Mr.onTick](e){this.needsImageUpdate&&(this.needsImageUpdate=!1,this.bridges.handlePieceHealthChange(this.bridges.getPieceAtTile(e.tile)))}[Ur.onDestroy](s,r,a){var e=this.bridges.getPieceAtTile(s.tile);this.dominoHandled||this.bridges.findDominoPieces(e).filter(e=>!e.obj.isDestroyed).forEach(e=>{e.obj.traits.get(wh).dominoHandled=!0,r.destroyObject(e.obj,a)});let t=r.map.tileOccupation.calculateTilesForGameObject(s.tile,s);t.forEach(e=>{let t=Vi(e.terrainType),i=r.rules.getLandRules(t);r.map.getGroundObjectsOnTile(e).forEach(e=>{e.isUnit()&&e.onBridge&&!e.isDestroyed&&(s.isLowBridge()&&0<i.getSpeedModifier(e.rules.speedType)||e.isInfantry()&&e.stance===Ds.Paradrop?(e.onBridge=!1,e.zone=_s(t)):(e.isInfantry()&&(e.infDeathType=Jt.None),r.destroyObject(e,a,!0)))})})}}(r=Rn=Rn||{})[r.Idle=0]="Idle",r[r.Spawning=1]="Spawning";class Th{constructor(e){this.rules=e,this.ticksSinceLastSpawn=0,this.cooldownTicks=Math.floor(1/this.rules.animationProbability),this.status=Rn.Idle}[Mr.onTick](e,t){this.status=Rn.Idle,this.ticksSinceLastSpawn++>this.cooldownTicks&&(this.ticksSinceLastSpawn=0,this.status=Rn.Spawning,this.spawnTiberium(e.tile,t))}spawnTiberium(s,r){for(let i=1;i<=2;i++){let e=new Fs(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},i,i,e=>Ga.canBePlacedOn(e,r.map));var a=e.getNextTile();if(a){var n=ln.calculateOverlayId(ra.Ore,a);if(void 0===n)throw new Error("Expected an overlayId");let e=r.createObject(Ct.Overlay,r.rules.getOverlayName(n));return e.overlayId=n,e.value=3,void r.spawnObject(e,a)}e=new Fs(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},i,i,e=>e.landType===Yt.Tiberium);let t;for(;!t;){var o=e.getNextTile();if(!o)break;t=r.map.getObjectsOnTile(o).find(e=>e.isOverlay()&&e.isTiberium()&&e.traits.get(Ga).getBailCount()+1<=Ga.maxBails)}if(t)return void t.traits.get(Ga).spawnBails(1)}}}class bh{constructor(e=!1){this.freeRepair=e,this.disabled=!0,this.cooldownTicks=0,this.healLeftover=0}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}[Mr.onTick](t,i){if(!this.isDisabled())if(100===t.healthTrait.health&&this.setDisabled(!0),this.cooldownTicks<=0){var s=i.rules.general.repair,r=t.isInfantry()?s.iRepairRate:t.isBuilding()?s.repairRate:s.uRepairRate;this.cooldownTicks+=Ls.BASE_TICKS_PER_SECOND*r*60;var a=t.isInfantry()?s.iRepairStep:s.repairStep,r=this.freeRepair?0:s.repairPercent;let e;r?(s=r*t.purchaseValue/t.healthTrait.maxHitPoints,r=Math.min(t.owner.credits,Math.max(1,Math.floor(s*a))),e=s&&r?r/s:a,r?t.owner.credits-=r:this.setDisabled(!0)):e=a,e&&(e+=this.healLeftover,e=Math.min(t.healthTrait.maxHitPoints-t.healthTrait.getHitPoints(),e),e&&(a=Math.floor(e),this.healLeftover=e-a,a&&t.healthTrait.healBy(a,t,i)))}else this.cooldownTicks--}[qr.onChange](){this.setDisabled(!0)}}(Dn=Dn||{}).onDestroy=Symbol();class vh{constructor(e){this.target=e,this.type=ts.UnitPromote}}class Sh{constructor(){this.cooldownTicks=0}[Mr.onTick](e,t){100!==e.healthTrait.health&&(this.cooldownTicks<=0?(this.cooldownTicks+=Ls.BASE_TICKS_PER_SECOND*t.rules.general.repair.repairRate*60,e.healthTrait.healBy(1,e,t)):this.cooldownTicks--)}}class _h{constructor(e,t){this.gameObject=e,this.rules=t,this.specialWeaponIndex=0;t=e.veteranLevel===Yr.Elite;e.rules.weaponCount?(this.selectSpecialWeapon(0,t),this.guardWeaponRangeOverride=this.primaryWeapon?.range):this.selectStandardWeapons(t)}selectStandardWeapons(e=!1){var t=this.gameObject,i=e&&t.rules.elitePrimary||t.rules.primary;i?(r=e?t.art.elitePrimaryFireFlh:t.art.primaryFireFlh,this.primaryWeapon=Ka.factory(i,ni.Primary,t,this.rules,r)):this.primaryWeapon=void 0;var s,r=e&&t.rules.eliteSecondary||t.rules.secondary;r?(s=e?t.art.eliteSecondaryFireFlh:t.art.secondaryFireFlh,this.secondaryWeapon=Ka.factory(r,ni.Secondary,t,this.rules,s)):this.secondaryWeapon=void 0,(t.explodes||t.crashableTrait)&&(s=t.rules.deathWeapon||!!t.crashableTrait&&this.secondaryWeapon?.rules.name||this.primaryWeapon?.rules.name||this.rules.combatDamage.deathWeapon,this.deathWeapon=Ka.factory(s,ni.DeathWeapon,t,this.rules))}selectSpecialWeapon(e,t=!1){let i=this.gameObject;var s=i.rules.weaponCount;if(s<1)throw new Error(`Object "${i.name}" doesn't support special weapons`);if(s-1<e)throw new RangeError(`Weapon index ${e} out of bounds (max ${s}) for object ${i.name}`);s=t&&i.rules.getEliteWeaponAtIndex(e)||i.rules.getWeaponAtIndex(e);if(!s)throw new Error(`Missing weapon at index ${e} for object "${i.name}"`);t=i.art.getSpecialWeaponFlh(e);this.primaryWeapon=Ka.factory(s,ni.Primary,i,this.rules,t),this.secondaryWeapon=void 0,this.specialWeaponIndex=e,this.deathWeapon=this.primaryWeapon.rules.suicide?Ka.factory(i.rules.deathWeapon||this.primaryWeapon.name,ni.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===ni.Primary?this.primaryWeapon:this.secondaryWeapon}isEquippedWithWeapon(e){return[this.primaryWeapon,this.secondaryWeapon].includes(e)}getWeapons(){return[this.primaryWeapon,this.secondaryWeapon].filter(Ma)}[Mr.onTick](){this.primaryWeapon&&this.primaryWeapon.tick(),this.secondaryWeapon&&this.secondaryWeapon.tick()}[Ur.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 kh{}class Oh{constructor(e,t){this.gameObject=e,this.veteranRules=t,this.veteranLevel=Yr.None,this.xp=0,this.promotionThresh=e.rules.cost*t.veteranRatio+1}[Dn.onDestroy](e,t,i,s){e.isDestroyed&&!e.isCrashing||t.isTechno()&&(t.rules.dontScore||t.rules.insignificant||(i&&(i.warhead.rules.temporal||i.warhead.rules.parasite&&e.rules.organic)||!s.areFriendly(e,t))&&(this.veteranLevel>=this.veteranRules.veteranCap||this.gainXP(t.rules.cost*(t.veteranLevel+1))&&this.handlePromotion(e,s)))}setRelativeXP(e){this.gainXP(Math.floor(e*this.promotionThresh))}gainXP(e){if(this.xp+=e,this.xp>=this.promotionThresh){var t=Math.min(this.veteranLevel+Math.floor(this.xp/this.promotionThresh),this.veteranRules.veteranCap),e=t-this.veteranLevel;if(e)return this.xp-=e*this.promotionThresh,this.setVeteranLevel(t),!0}return!1}promote(e,t){e=Math.min(this.veteranLevel+e,this.veteranRules.veteranCap);e-this.veteranLevel&&(this.setVeteranLevel(e),this.handlePromotion(this.gameObject,t))}isMaxLevel(){return this.veteranLevel===this.veteranRules.veteranCap}isElite(){return this.veteranLevel===Yr.Elite}setVeteranLevel(e){this.veteranLevel=e,this.veteranLevel===Yr.Elite&&this.gameObject.armedTrait?.toggleEliteWeapons(!0)}handlePromotion(e,t){this.hasVeteranAbility(oi.SELF_HEAL)&&(e.traits.find(Sh)||t.addObjectTrait(e,new Sh)),this.hasVeteranAbility(oi.CLOAK)&&(e.cloakableTrait||(e.cloakableTrait=new hn(e,t.rules.general.cloakDelay),t.addObjectTrait(e,e.cloakableTrait))),this.hasVeteranAbility(oi.EXPLODES)&&(e.explodes||(e.explodes=!0,e.armedTrait||(e.armedTrait=new _h(e,t.rules),t.addObjectTrait(e,e.armedTrait)))),this.hasVeteranAbility(oi.RADAR_INVISIBLE)&&(e.radarInvisible||(e.radarInvisible=!0)),this.hasVeteranAbility(oi.SENSORS)&&(e.sensorsTrait||(e.sensorsTrait=new kh,t.addObjectTrait(e,e.sensorsTrait))),e.isInfantry()&&this.hasVeteranAbility(oi.FEARLESS)&&e.suppressionTrait?.disable(),this.hasVeteranAbility(oi.C4)&&(e.c4||(e.c4=!0)),this.hasVeteranAbility(oi.GUARD_AREA)&&(e.defaultToGuardArea||(e.defaultToGuardArea=!0,e.unitOrderTrait.isIdle()&&e.resetGuardModeToIdle())),this.hasVeteranAbility(oi.CRUSHER)&&(e.crusher||(e.crusher=!0)),t.events.dispatch(new vh(e))}getVeteranSightMultiplier(){return this.getVeteranAbilityMultiplier(oi.SIGHT)}getVeteranSpeedMultiplier(){return this.getVeteranAbilityMultiplier(oi.FASTER)}getVeteranArmorMultiplier(){return this.getVeteranAbilityMultiplier(oi.STRONGER)}getVeteranDamageMultiplier(){return this.getVeteranAbilityMultiplier(oi.FIREPOWER)}getVeteranRofMultiplier(){return this.getVeteranAbilityMultiplier(oi.ROF)}hasVeteranAbility(e){return this.veteranLevel===Yr.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=Yr.Elite&&this.gameObject.rules.eliteAbilities.has(e)}getVeteranAbilityMultiplier(e){let t=1;return(this.veteranLevel===Yr.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=Yr.Elite&&this.gameObject.rules.eliteAbilities.has(e))&&(t=this.getVeteranRulesMultiplier(e)),t}getVeteranRulesMultiplier(e){switch(e){case oi.FASTER:return this.veteranRules.veteranSpeed;case oi.STRONGER:return this.veteranRules.veteranArmor;case oi.FIREPOWER:return this.veteranRules.veteranCombat;case oi.ROF:return this.veteranRules.veteranROF;case oi.SIGHT:return this.veteranRules.veteranSight;default:throw new Error(`Unhandled VeteranAbility ${e}`)}}dispose(){this.gameObject=void 0}}class Ih{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 Ah{constructor(e){this.target=e,this.type=ts.ObjectDisguiseChange}}class Ch{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 Ah(t))}revealDisguise(e,t){this.cooldownTicks=t.rules.general.infantryBlinkDisguiseTime,this.isActive=!1,t.events.dispatch(new Ah(e))}[Xr.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}}[Mr.onTick](e,t){e.rules.permaDisguise||(e.attackTrait?.attackState===bn.JustFired||e.moveTrait.moveState!==Hr.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 Ah(e))))}[ha.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 Bh{constructor(){this.timer=new xo}isActive(){return this.timer.isActive()}setActiveFor(e,t){this.timer.setActiveFor(e,t)}[Mr.onTick](e,t){this.timer.tick(t.currentTick)}}class xh{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(xs).forEach(e=>{e[xs.onChange](this.gameObject,i,t)}),this.gameObject.traits.filter(yn).forEach(e=>{e[yn.onChange](this.gameObject,i,t)})}expire(e){this.remainingTicks=0,this.notifyChange(!1,e)}isInvulnerable(){return this.isActive()&&this.invulnerable}[Mr.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 xo}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()}[Mr.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))}[Ur.onDestroy](e,t,i){this.timer.isActive()&&!i?.weapon?.warhead.rules.ivanBomb&&e.deathType!==Wr.None&&e.deathType!==Wr.Temporal&&(this.timer.reset(),this.detonateIvanWarhead(t,e))}detonateIvanWarhead(e,t){var i=e.rules.combatDamage.ivanDamage;let s=new Xa(e.rules.getWarhead(e.rules.combatDamage.ivanWarhead));var r=t.tile,a=t.tileElevation,n=t.isUnit()?t.zone:e.map.getTileZone(r),o=!!t.isUnit()&&t.onBridge;s.detonate(e,i,r,a,t.isBuilding()?Ss.tile3dToWorld(r.rx+.5,r.ry+.5,r.z+a):t.position.worldPosition,n,o?ia.OnBridge:ia.None,e.createTarget(t,r),{...this.attackerInfo,weapon:void 0},!1,!1,void 0)}}class Ph{constructor(e){this.gameObject=e}getOriginalOwner(){return this.prevOwner}isActive(){return!!this.controller}getController(){return this.controller}controlBy(e,t){if(this.controller)throw new Error(`Object "${this.gameObject?.name}" is already mind controlled by "${e.name}"`);this.controller=e,this.prevOwner=this.gameObject.owner,t.changeObjectOwner(this.gameObject,e.owner)}restore(e){this.prevOwner&&(e.changeObjectOwner(this.gameObject,this.prevOwner),this.prevOwner=void 0,this.controller=void 0)}[Qr.onUnspawn](e,t){this.controller&&(this.controller.mindControllerTrait.cleanTarget(e),!e.isDestroyed&&e.limboData&&this.restore(t))}dispose(){this.gameObject=void 0}}class Nh{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)}[Qr.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}[Mr.onTick](e,t){if(e.attackTrait&&(e.attackTrait.currentTarget&&!e.warpedOutTrait.isActive()||this.releaseCurrentTarget(t)),void 0!==this.eraseTicks)for(var i of this.attackers){var s=i.temporalTrait.currentWeapon;if(!s)throw new Error(`Attacker "${i.name}" is no longer targeting "${e.name}"`);var r=s.rules.damage;if(this.eraseTicks-=r,this.eraseTicks<=0){e.deathType=Wr.Temporal,t.destroyObject(e,{player:i.owner,obj:i,weapon:s},!0),this.eraseTicks=void 0;break}}}getTarget(){return this.currentTarget}updateTarget(t,e,i){if(this.currentTarget!==t){this.releaseCurrentTarget(i),this.currentTarget=t,this.currentWeapon=e;e=t.temporalTrait.attackers.size;if(t.temporalTrait.attackers.add(this.gameObject),!e){t.warpedOutTrait.setActive(!0,!0,i);let e=t.unitOrderTrait.getCurrentTask();(e&&e instanceof ko||e instanceof ba)&&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}}[Ur.onDestroy](e,t){this.releaseCurrentTarget(t)}dispose(){this.gameObject=void 0,this.attackers.clear()}}class Dh{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}[Xr.onSpawn](t,i){var s=i.rules.getObject(t.rules.spawns,Ct.Aircraft);for(let e=0;e<t.rules.spawnsNumber;e++)this.pushNewSpawn(s,i,t)}[Qr.onUnspawn](e,t){this.destroySpawns(e,t)}[Ur.onDestroy](e,t,i,s){this.destroySpawns(e,t,i,s)}pushNewSpawn(e,t,i){let s=t.createUnitForPlayer(e,i.owner);s.limboData={selected:!1,controlGroup:void 0},e.missileSpawn&&(s.pitch=90*t.rules.general.getMissileRules(e.name).pitchInitial),this.spawns.push(s),this.storage.push(s)}destroySpawns(e,t,i,s){for(var r of this.spawns)r.isDestroyed||(r.isSpawned&&!r.rules.missileSpawn&&r.crashableTrait?r.crashableTrait.crash(i):(r.isSpawned||(r.armedTrait&&(r.armedTrait.deathWeapon=void 0),r.position.tileElevation=e.position.tileElevation,r.zone=e.isUnit()?e.zone:Ts.Ground,r.onBridge=!!e.isUnit()&&e.onBridge,r.position.tile=e.tile),t.destroyObject(r,i,s)));this.spawns.length=0,this.storage.length=0,this.missileLaunches.length=0}[Mr.onTick](r,a){var t;if(this.spawns=this.spawns.filter(e=>!e.isDestroyed),this.missileLaunches=this.missileLaunches.filter(e=>!e.missile.isDestroyed),this.spawns.length<r.rules.spawnsNumber){var i=r.rules.spawnsNumber-this.spawns.length,s=a.rules.getObject(r.rules.spawns,Ct.Aircraft);for(let e=0;e<i;e++)s.missileSpawn&&e&&void 0===this.nextRegenTicks[e]?this.nextRegenTicks[e]=this.nextRegenTicks[0]:((t=this.nextRegenTicks)[e]??(t[e]=r.rules.spawnRegenRate),0<this.nextRegenTicks[e]&&this.nextRegenTicks[e]--),this.nextRegenTicks[e]<=0&&this.pushNewSpawn(s,a,r);this.nextRegenTicks=this.nextRegenTicks.filter(e=>0<e)}if(this.storage.length){if(this.nextReloadTicks??(this.nextReloadTicks=r.rules.spawnReloadRate),0<this.nextReloadTicks&&this.nextReloadTicks--,this.nextReloadTicks<=0){for(var e of this.storage)e.ammoTrait&&e.ammoTrait.ammo<e.ammoTrait.maxAmmo&&e.ammoTrait.ammo++;this.nextReloadTicks=r.rules.spawnReloadRate}}else this.nextReloadTicks=void 0;for(let s of this.missileLaunches.slice()){var n=a.rules.general.getMissileRules(s.missile.name);if(s.pauseFrames??(s.pauseFrames=n.pauseFrames),0<s.pauseFrames&&s.pauseFrames--,s.pauseFrames<=0){var o=90*n.pitchFinal,n=90*(n.pitchFinal-n.pitchInitial)/n.tiltFrames;let i=s.missile;if(i.pitch<o)i.pitch=Math.min(o,i.pitch+n);else{i.unitOrderTrait.addTask(new La(new ba(a,s.targetTile,!!s.targetBridge),new da(()=>{var e,t;i.isDestroyed||(a.unspawnObject(i),i.dispose(),t=Ss.vecGroundToWorld(wr.toMapCoords(i.direction).multiplyScalar(1)),e=s.targetWorldPos.clone().add(t),t=a.map.getTileZone(s.targetTile),s.warhead.detonate(a,s.damage,s.targetTile,s.targetBridge?.tileElevation??0,e,t,s.targetBridge?ia.OnBridge:ia.None,s.target,{player:i.owner,obj:r,weapon:void 0},!1,!1,void 0))})).setCancellable(!1));n=this.spawns.indexOf(i);if(-1===n)throw new Error("Missile not found in spawns list");this.spawns.splice(n,1),this.missileLaunches.splice(this.missileLaunches.indexOf(s),1)}}}}[qr.onChange](e,t,i){for(var s of this.spawns)s.isDestroyed||i.changeObjectOwner(s,e.owner)}[yn.onChange](e,t,i){i&&this.removeMissileLaunches(t)}[jr.onBeforeTeleport](e,t,i,s){s||this.removeMissileLaunches(t)}removeMissileLaunches(e){if(this.missileLaunches.length){for(var t of this.missileLaunches){e.unspawnObject(t.missile),t.missile.dispose();t=this.spawns.indexOf(t.missile);if(-1===t)throw new Error("Missile not found in spawns list");this.spawns.splice(t,1)}this.missileLaunches.length=0}}prepareLaunch(s,r,a){if(this.storage.length){let i=this.storage[0];if(!i.ammo)return;if(this.storage.shift(),i.missileSpawnTrait){let e,t;var n=s.veteranTrait?.isElite(),o=a.rules;if(s.rules.spawns===o.general.v3Rocket.type)e=n?o.combatDamage.v3EliteWarhead:o.combatDamage.v3Warhead,t=n?o.general.v3Rocket.eliteDamage:o.general.v3Rocket.damage;else{if(s.rules.spawns!==o.general.dMisl.type)throw new Error(`Unhandled missile type "${s.rules.spawns}"`);e=n?o.combatDamage.dMislEliteWarhead:o.combatDamage.dMislWarhead,t=n?o.general.dMisl.eliteDamage:o.general.dMisl.damage}a=new Xa(a.rules.getWarhead(e));i.missileSpawnTrait.setDamage(t).setWarhead(a).setLauncher(s),this.missileLaunches.push({missile:i,targetTile:(r.obj?.isUnit()?r.obj:r).tile,targetBridge:r.getBridge(),targetWorldPos:r.getWorldCoords().clone(),target:r,warhead:a,damage:t,pauseFrames:void 0})}else{if(!i.spawnLinkTrait)throw new Error(`Aircraft "${i.name}" must have Spawned=yes to be launchable`);i.spawnLinkTrait.setParent(s)}return i}}storeAircraft(e,t){if(!this.spawns.includes(e))throw new Error(`Object "${e.name}#${e.id}" not found in list of linked spawns`);if(e.limboData)throw new Error(`Object "${e.name}#${e.id}" is already in limbo`);t.limboObject(e,{selected:!1,controlGroup:void 0}),this.storage.push(e)}}class Mh{[Kr.onCrash](e,t){this.handleDestroy(e,t)}[Ur.onDestroy](e,t,i){i?.weapon?.warhead.rules.temporal||e.isCrashing||e.deathType!==Wr.Sink&&e.isSpawned&&this.handleDestroy(e,t)}handleDestroy(e,t){var i,s;(e.isVehicle()||e.isBuilding()||e.isOverlay())&&(i=e.isOverlay()?0:e.rules.minDebris,s=e.isOverlay()?t.rules.general.bridgeVoxelMax:e.rules.maxDebris,0<(s=t.generateRandomInt(i,s))&&this.spawnDebris(e,t,s))}spawnDebris(t,i,s){let r=t.position.getMapPosition();if(i.map.isWithinHardBounds(r)){let e=t.isOverlay()?[]:t.isVehicle()?t.rules.debrisTypes:t.rules.debrisAnims;e.length||(e=i.rules.audioVisual.metallicDebris),e=e.filter(e=>i.rules.hasObject(e,Ct.VoxelAnim)||i.art.hasObject(e,Ct.Animation)),new Array(s).fill(0).map(()=>e[i.generateRandomInt(0,e.length-1)]).map(e=>i.createObject(Ct.Debris,e)).forEach(e=>{e.position.moveToLeptons(r),e.position.tileElevation=t.position.tileElevation,i.spawnObject(e,e.position.tile)})}}}class Lh extends Ia{constructor(e,t,i,s){super(Ct.Debris,e,t,i),this.age=0,this.direction=0,this.rotationAxis=new is,this.angularVelocity=0,this.zone=Ts.Air,this.velocity=new is,this.collisionHelper=new dh(s)}static factory(e,t,i,s){return new this(e,t,i,s)}onSpawn(e){super.onSpawn(e),this.direction=e.generateRandomInt(0,359),this.xySpeed=z(0,this.rules.maxXYVel,e.generateRandom()),this.zSpeed=z(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=z(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=wr.toMapCoords(this.direction).setLength(this.xySpeed);let i=new is(e.x,this.zSpeed,e.y);var s=this.position.clone(),e=i.clone().add(this.position.worldPosition);if(t.map.isWithinHardBounds(e)){this.position.moveByLeptons3(i);let e=!1;s=this.collisionHelper.checkCollisions(this.position,s,{cliffs:!0,ground:!0,shore:!1,walls:!0,buildings:!1});s&&(!([ia.Ground,ia.OnBridge].includes(s)&&0<this.rules.elasticity&&t.map.getTileZone(this.tile)!==Ts.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,s)):this.velocity.copy(i)}else t.unspawnObject(this)}detonate(t,i=ia.None){var e,s=this.rules.warhead?t.rules.getWarhead(this.rules.warhead):void 0,r=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,i);let a;r===Ts.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 $a;if(a&&n.spawnSmudges(a,this.tile,t),t.destroyObject(this),s){let e=new Xa(s);e.detonate(t,this.rules.damage,this.tile,this.tileElevation,this.position.worldPosition,r,i,t.createTarget(void 0,this.tile),void 0,!1,!1,void 0,this.rules.damageRadius||void 0,!0)}}}class Fh{constructor(e,t,i,s){this.tiles=e,this.tileOccupation=t,this.bridges=i,this.nextObjectId=s}create(e,t,i,s){let r,a;e===Ct.Debris?r=i.hasObject(t,Ct.VoxelAnim)?(a=s.getObject(t,Ct.VoxelAnim),i.getObject(t,Ct.VoxelAnim)):(a=s.getAnimation(t),new ls(Ct.Debris,s.getIni().getOrCreateSection(t))):a=e===Ct.Projectile?(r=i.getProjectile(t),r.inviso?new Hn(Ct.Projectile,r,new h(t)):s.getProjectile(t)):(r=i.getObject(t,e),s.getObject(t,e));let n;switch(e){case Ct.Building:n=Wo.factory(t,r,i,a,this.tiles,this.bridges);break;case Ct.Infantry:n=Na.factory(t,r,a,this.tileOccupation);break;case Ct.Vehicle:n=rh.factory(t,r,a,i,this.tileOccupation);break;case Ct.Aircraft:n=hh.factory(t,r,a,i,this.tileOccupation);break;case Ct.Terrain:n=zo.factory(t,r,a);break;case Ct.Overlay:n=Vo.factory(t,r,a);break;case Ct.Smudge:n=Ho.factory(t,r,a);break;case Ct.Projectile:n=ph.factory(t,r,a,this.tileOccupation);break;case Ct.Debris:n=Lh.factory(t,r,a,this.tileOccupation);break;default:throw new Error("Not implemented")}if(n.id=this.nextObjectId.value++,n.position=new uh(this.tiles,this.tileOccupation),n.isUnit()?n.position.subCell=0:n.isBuilding()&&n.position.setCenterOffset(n.getFoundationCenterOffset()),n.isTechno()&&((n.rules.primary||n.rules.secondary||n.rules.weaponCount||n.rules.explodes)&&(n.armedTrait=new _h(n,i),n.traits.add(n.armedTrait)),-1!==n.rules.ammo&&(o=n.rules.initialAmmo,n.ammoTrait=new Ih(n.rules.ammo,-1!==o?o:void 0),n.traits.add(n.ammoTrait)),n.unitOrderTrait=new lh(n),n.traits.addToFront(n.unitOrderTrait),(n.primaryWeapon||n.secondaryWeapon)&&(n.attackTrait=new _o(this.tiles,this.tileOccupation),n.traits.add(n.attackTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.deployer&&(n.deployerTrait=new gh(n),n.traits.add(n.deployerTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.canDisguise&&(n.disguiseTrait=new Ch,n.traits.add(n.disguiseTrait)),n.rules.cloakable&&(n.cloakableTrait=new hn(n,i.general.cloakDelay),n.traits.add(n.cloakableTrait)),n.rules.sensors&&(n.sensorsTrait=new kh,n.traits.add(n.sensorsTrait)),n.autoRepairTrait=new bh(!n.isBuilding()),n.traits.add(n.autoRepairTrait),n.rules.trainable&&(n.veteranTrait=new Oh(n,i.general.veteran),n.traits.add(n.veteranTrait)),n.rules.selfHealing&&n.traits.add(new Sh),n.invulnerableTrait=new Bh,n.traits.add(n.invulnerableTrait),n.warpedOutTrait=new xh(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 Ph(n),n.traits.add(n.mindControllableTrait)),[n.primaryWeapon,n.secondaryWeapon].some(e=>e?.warhead.rules.mindControl)&&(n.mindControllerTrait=new Nh(n),n.traits.add(n.mindControllerTrait)),n.rules.spawns&&(n.airSpawnTrait=new Dh,n.traits.add(n.airSpawnTrait)),n.rules.maxDebris&&n.traits.add(new Mh)),n.isTechno()||n.isOverlay()||n.isTerrain()){var o=n.isOverlay()&&Wa.isBridge(i.getOverlayId(n.name));let e=n.rules.strength;!e&&n.isTerrain()&&(e=i.general.treeStrength),o&&(e=i.combatDamage.bridgeStrength),(e||n.isTechno())&&(n.healthTrait=new yh(e,n,i.audioVisual.conditionYellow,i.audioVisual.conditionRed),n.traits.add(n.healthTrait)),n.isOverlay()&&o&&(n.bridgeTrait=new wh(this.bridges),n.traits.add(n.bridgeTrait),Wa.getOverlayBridgeType(i.getOverlayId(n.name))===ea.Concrete&&n.traits.add(new Mh))}return n.isOverlay()&&n.isOverlay()&&Ha.getOverlayTibType(i.getOverlayId(n.name))!==ra.NotSpecial&&n.traits.add(new Ga(n)),n.isTerrain()&&n.rules.spawnsTiberium&&n.traits.add(new Th(n.rules)),n.cachedTraits.tick.push(...n.traits.filter(Mr)),n}}class jh{constructor(){this.allObjects=new Map,this._onObjectSpawned=new io,this._onObjectRemoved=new io}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 Uh,Wh,zh,Vh,Hh,Gh,$h,qh,Xh,Qh,r=__webpack_require__(495),Zh=__webpack_require__.n(r),Yh=__webpack_require__(45);class Kh{constructor(e,t,i,s,r){this.tiles=e,this.theaterType=t,this.mapBounds=i,this.tileOccupation=s,this.rules=r,this.passabilityGraphs=new Map,this.invalidatedTiles=new Map,this.handleTileOccupationUpdate=({tiles:e,object:i})=>{e=e.filter(e=>{let t=Kt.Foot;return i.isTerrain()&&i.rules.getOccupationBits(this.theaterType)!==Ji.All&&(t=Kt.Wheel),i.isOverlay()&&(i.isBridge()||i.isTiberium())||this.isBlockerObject(i,e,!1,t)||this.isBlockerObject(i,e,!0,t)||i.isBuilding()&&i.rules.leaveRubble});e.length&&this.invalidateTiles(e)},this.handleMapBoundsResize=()=>{this.passabilityGraphs.clear()},s.onChange.subscribe(this.handleTileOccupationUpdate),i.onLocalResize.subscribe(this.handleMapBoundsResize)}invalidateTiles(i){i.length&&[...this.passabilityGraphs.keys()].forEach(e=>{let t=this.invalidatedTiles.get(e);t?i.forEach(e=>t.add(e)):this.invalidatedTiles.set(e,new Set(i))})}computePath(t,e,i,s,r,{maxExpandedNodes:a=Number.POSITIVE_INFINITY,bestEffort:n=!0,excludeTiles:o,ignoredBlockers:h=[]}={}){let l=this.computePassabilityGraph(t);var c=h.map(e=>this.tileOccupation.calculateTilesForGameObject(e.tile,e)).reduce((e,t)=>e.concat(t),[]);if(c.length&&this.updatePassability(c,t,l,h),!this.getPassableSpeed(e,t,i,h))return c.length&&this.updatePassability(c,t,l),[];var u=this.getNodeId(s,r),d=!!l.hasNode(u);d||((h=new Fs(this.tiles,this.mapBounds,s,{width:1,height:1},1,5,e=>0<this.getPassableSpeed(e,t,!1)&&Math.abs(e.z-s.z)<2&&!o?.({tile:e,onBridge:void 0,speed:100})).getNextTile())?(s=h,r=!1):(l.addNode(u,{tile:s,onBridge:void 0,speed:100}),a=Math.min(a,500)));let p=(0,Yh.aStar)(l,{bestEffort:n,maxExpandedNodes:a,distance(e,t){if(o?.(t.data)||!t.data.speed)return Number.POSITIVE_INFINITY;var i=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);return i+t+(Math.SQRT2-2)*Math.min(i,t)},heuristic(e,t,i){if(o?.(t.data)||!t.data.speed)return Number.POSITIVE_INFINITY;var s=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);let r=s+t+(Math.SQRT2-2)*Math.min(s,t);return i?.parent&&(t=(s=i.parent.node).data.tile.rx-e.data.tile.rx,e=s.data.tile.ry-e.data.tile.ry,i.dirX=t,i.dirY=e,t===i.parent.dirX&&e===i.parent.dirY||(r+=.2)),r}}),g=p.find(this.getNodeId(e,i),this.getNodeId(s,r)).map(e=>({tile:e.data.tile,onBridge:e.data.onBridge}));return(g.length<2||o&&g.length&&(!n&&g[0].tile!==s||g[g.length-1].tile!==e))&&(g=[]),!d&&l.hasNode(u)&&l.removeNode(u),c.length&&this.updatePassability(c,t,l),g}computeAllPassabilityGraphs(){Object.keys(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=Zh()({multigraph:!0}),this.passabilityGraphs.set(t,i),this.tiles.forEach(e=>{this.computePassability(e,t,i)});return i}updatePassability(e,t,i,s=[]){let r=new Set;e.forEach(e=>{[e,this.tiles.getNeighbourTile(e,sa.Right),this.tiles.getNeighbourTile(e,sa.BottomRight),this.tiles.getNeighbourTile(e,sa.Bottom),this.tiles.getNeighbourTile(e,sa.BottomLeft)].filter(Ma).forEach(e=>r.add(e))}),e.forEach(e=>{i.removeNode(this.getNodeId(e,!1)),i.removeNode(this.getNodeId(e,!0))}),r.forEach(e=>{this.computePassability(e,t,i,s)})}computePassability(e,t,i,s=[]){var r=[sa.Left,sa.TopLeft,sa.Top,sa.TopRight];let a=this.getPassableSpeed(e,t,!1,s);if(a){var n,o=this.getNodeId(e,!1);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:void 0});for(n of r)this.connectTiles(e,void 0,n,t,i,s)}var h=this.tileOccupation.getBridgeOnTile(e);if(h&&(a=this.getPassableSpeed(e,t,!0,s),a)){var l,o=this.getNodeId(e,!0);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:h});for(l of r)this.connectTiles(e,h,l,t,i,s)}}connectTiles(t,i,s,r,a,n=[]){var o=this.tiles.getNeighbourTile(t,s);if(o){let e=this.tileOccupation.getBridgeOnTile(o);s=i||e?0:1;if(Math.abs(t.z+(i?.tileElevation??0)-(o.z+(e?.tileElevation??0)))>s){if(!e?.isHighBridge()&&!i?.isHighBridge()||0!==Math.abs(t.z-o.z)||!a.hasNode(this.getNodeId(t,!1)))return;i=e=void 0}r=this.getPassableSpeed(o,r,!!e,n);r&&(n=this.getNodeId(o,!!e),a.hasNode(n)||a.addNode(n,{speed:r,tile:o,onBridge:e}),i=this.getNodeId(t,!!i),a.getLink(i,n)||a.addLink(i,n))}}getNodeId(e,t){return e.id+(t?"_bridge":"")}getPassableSpeed(e,t,i,s=[],r=!1){if(!this.mapBounds.isWithinBounds(e))return 0;let a=i?e.onBridgeLandType:e.landType;if(void 0===a)return 0;a===Yt.Wall&&t===Kt.Track&&(a=Vi(e.terrainType));let n=this.rules.getLandRules(a);var o,h=n.getSpeedModifier(t);if(!h)return 0;if(!r)for(o of this.tileOccupation.getObjectsOnTile(e))if(this.isBlockerObject(o,e,i,t)&&!s.includes(o))return 0;return h}isBlockerObject(t,i,e,s){if(t.isTerrain()&&s===Kt.Foot&&t.rules.getOccupationBits(this.theaterType)!==Ji.All)return!1;if(t.isBuilding()){if(t.rules.invisibleInGame)return!1;if(t.isDestroyed&&t.rules.leaveRubble)return!1;if(t.rules.gate)return!1;var r=t.art.foundation;let e=t.rules.numberImpassableRows;return s===Kt.Foot?e=r.width:t.rules.weaponsFactory&&!e&&(e=r.width-1),Er({x:t.tile.rx,y:t.tile.ry,width:(e||r.width)-1,height:r.height-1},{x:i.rx,y:i.ry})}return!(t.isAircraft()||t.isInfantry()||t.isVehicle()||t.isSmudge()||t.isOverlay()&&(e&&t.isBridge()||!e&&t.isHighBridge()||t.isTiberium()||t.rules.crate||t.isBridgePlaceholder())||s===Kt.Track&&t.rules.crushable)}findObstacles(t,e){var i,s,r=e.rules.speedType;let a=[];for(i of this.tileOccupation.getGroundObjectsOnTile(t.tile))i!==e&&(((s=this.isBlockerObject(i,t.tile,!!t.onBridge,r))||i.isUnit()&&(i.tile===t.tile&&i.onBridge===!!t.onBridge||i.moveTrait.reservedPathNodes.find(e=>e.tile===t.tile&&!!e.onBridge==!!t.onBridge))||r===Kt.Track&&i.rules.crushable||r===Kt.Foot&&i.isTerrain()||i.isBuilding()&&i.rules.gate)&&(s={obj:i,static:s},i.isInfantry()&&e.isInfantry()?i.position.desiredSubCell===e.position.desiredSubCell&&a.push(s):i.isTerrain()&&e.isInfantry()&&!i.rules.getOccupiedSubCells(this.theaterType).includes(e.position.desiredSubCell)||a.push(s)));return a}dispose(){this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate),this.mapBounds.onLocalResize.unsubscribe(this.handleMapBoundsResize)}}class Jh{constructor(){this.mapCutoffHeight=0,this.mapBuildableSize={x:0,y:0,width:0,height:0},this.localSize={x:0,y:0,width:0,height:0},this.fullSize={width:0,height:0},this.clampedFullSize={x:0,y:0,width:0,height:0},this.rawLocalSize={x:0,y:0,width:0,height:0},this._onLocalResize=new io}get onLocalResize(){return this._onLocalResize.asEvent()}fromMapFile(e,t){this.fullSize={width:2*e.fullSize.width,height:2*e.fullSize.height},this.clampedFullSize={x:1,y:2,width:2*(e.fullSize.width-1)-1/Ss.ISO_TILE_SIZE,height:2*(e.fullSize.height-1)+1-1/Ss.ISO_TILE_SIZE},this.mapCutoffHeight=t.getCutoffTileHeight();t=Math.max(2,e.localSize.x),e={x:t,y:e.localSize.y,width:Math.min(e.fullSize.width-2-t,e.localSize.width),height:e.localSize.height};return this.updateRawLocalSize(e),this}updateRawLocalSize(e){var t,i;this.rawLocalSize.width&&this.rawLocalSize.height&&!function(e,t){let i=new Br.Box2(new Br.Vector2(e.x,e.y),new Br.Vector2(e.x+e.width,e.y+e.height));return t=new Br.Box2(new Br.Vector2(t.x,t.y),new Br.Vector2(t.x+t.width,t.y+t.height)),i.containsBox(t)}(e,this.rawLocalSize)?console.warn("New map limits must be outside old limits. Skipping."):(t=e,i=this.rawLocalSize,t.x===i.x&&t.y===i.y&&t.width===i.width&&t.height===i.height||(this.localSize=this.computeLocalSize(e,this.fullSize.height/2,this.mapCutoffHeight),this.rawLocalSize={...e},this.mapBuildableSize={x:this.localSize.x,y:this.localSize.y+4,width:this.localSize.width-2,height:this.localSize.height-8},this._onLocalResize.dispatch(this)))}computeLocalSize(e,t,i){return{x:2*e.x,y:2*e.y-4,height:Math.min(2*(e.height+5)-1,2*t-2*(e.y-3)-i),width:2*e.width}}getLocalSize(){return this.localSize}getRawLocalSize(){return this.rawLocalSize}getFullSize(){return this.fullSize}getClampedFullSize(){return this.clampedFullSize}isWithinBounds(e){return Er(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z})}clampWithinBounds(e){let{x:t,y:i}=function(e,t){let i=new Br.Box2(new Br.Vector2(e.x,e.y),new Br.Vector2(e.x+e.width,e.y+e.height));return i.clampPoint(new Br.Vector2(t.x,t.y),new Br.Vector2)}(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z});return i+=t%2-i%2,i>this.mapBuildableSize.y+this.mapBuildableSize.height&&(i-=2),{dx:t,dy:i}}isWithinHardBounds(e){var t=e.x/Ss.LEPTONS_PER_TILE,i=(e.z??e.y)/Ss.LEPTONS_PER_TILE,e=t-i+this.fullSize.width/2-1,i=t+i-this.fullSize.width/2-1;return Er(this.clampedFullSize,{x:++e,y:++i})}}class el{constructor(e,t,i,s,r,a,n,o=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.dirX=a,this.dirY=n,this.predicate=o,this.finished=!1,this.distance=s}getNextTile(){if(!this.finished){let t;do{let e={x:this.startTile.rx,y:this.startTile.ry};e.x+=this.distance*Math.sign(this.dirX),e.y+=this.distance*Math.sign(this.dirY);var i=this.tiles.getByMapCoords(e.x,e.y);if(i&&this.mapBounds.isWithinBounds(i)&&this.predicate(i)&&(t=i),this.maxDistance&&this.distance>=this.maxDistance)return this.finished=!0,t}while(this.distance++,!t);return t}}}(r=Uh=Uh||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.End=2]="End";class tl{constructor(e,t,i,s,r){this.tileSets=e,this.tiles=t,this.tileOccupation=i,this.mapBounds=s,this.rules=r,this.pieces=new Set,this.piecesByTile=new Map,this.handleTileOccupationUpdate=({object:t,type:i})=>{if(t.isOverlay()&&t.isBridge()){var s=t.tile;let e=this.piecesByTile.get(s);if("added"===i){if(e)throw new Error(`A bridge piece already exists at tile (${s.rx},${s.ry})`);var r=this.findBridgeAdjacentTiles(t);e={obj:t,prev:void 0,next:void 0,headType:this.computeHead(t,r.prev,r.next)},this.piecesByTile.set(s,e),this.pieces.add(e),this.connectPiece(e,r.prev,r.next),this.updateOverlayData(e),e.prev&&this.updateOverlayData(e.prev),e.next&&this.updateOverlayData(e.next)}else{if(!e)throw new Error(`Bridge piece was alredy removed at tile (${s.rx},${s.ry})`);t=e.prev,r=e.next;this.disconnectPiece(e),this.piecesByTile.delete(s),this.pieces.delete(e),t&&this.updateOverlayData(t),r&&this.updateOverlayData(r)}}},i.onChange.subscribe(this.handleTileOccupationUpdate)}getPieceAtTile(e){return this.piecesByTile.get(e)}handlePieceHealthChange(e){this.updateOverlayData(e),e.prev&&this.updateOverlayData(e.prev),e.next&&this.updateOverlayData(e.next)}findDominoPieces(t){let i=[],s=!1,e=t.next;if(t.headType===Uh.None||e)for(;e;){if(i.push(e),e.headType!==Uh.None){s=!0;break}e=e.next}else s=!0;if(s){s=!1,i.length=0;let e=t.prev;if(t.headType===Uh.None||e)for(;e;){if(i.push(e),e.headType!==Uh.None){s=!0;break}e=e.prev}else s=!0;if(s)return[]}return i}findBridgeAdjacentTiles(e){var t=e.isXBridge(),t=new vs(Number(t),Number(!t));let i=new vs(e.tile.rx,e.tile.ry);e=i.clone().sub(t),e=this.tiles.getByMapCoords(e.x,e.y),t=i.clone().add(t);return{prev:e,next:this.tiles.getByMapCoords(t.x,t.y)}}connectPiece(e,t,i){t&&(e.prev=this.getPieceAtTile(t),e.prev&&(e.prev.next=e)),i&&(e.next=this.getPieceAtTile(i),e.next&&(e.next.prev=e))}disconnectPiece(e){e.next&&(e.next.prev=void 0,e.next=void 0),e.prev&&(e.prev.next=void 0,e.prev=void 0)}computeHead(e,t,i){var s=e.tile;if(e.isHighBridge()){s=s.z+e.tileElevation;return t?.z===s?Uh.Start:i?.z===s?Uh.End:Uh.None}return Wa.isLowBridgeHead(e.overlayId)?Wa.isLowBridgeHeadStart(e.overlayId)?Uh.Start:Uh.End:Uh.None}updateOverlayData(t){let i=t.obj,s=t.prev,r=t.next,a=!1;var n=i.isXBridge(),o=Wa.getOverlayBridgeType(i.overlayId);if(Wa.isLowBridgeHead(i.overlayId)){let e=0;Wa.isLowBridgeHeadStart(i.overlayId)?(e=n?20:22,r||e++):(e=n?18:24,s||e++),i.overlayId=(o===ea.Wood?Wa.minLowBridgeWoodId:Wa.minLowBridgeConcreteId)+e,i.value=e,a=!0}else{let e;var h,l=(i.healthTrait?.health??100)<=50;e=t.headType!==Uh.None?t.headType===Uh.Start?r?l?6:(r.obj.healthTrait?.health??100)<=50?5:0:n?8:7:s?l?6:(s.obj.healthTrait?.health??100)<=50?4:0:n?7:8:(n||(h=s,s=r,r=h),s||r?s?r?(t=(s.obj.healthTrait?.health??100)<=50,h=(r.obj.healthTrait?.health??100)<=50,l||t&&h?6:t?4:h?5:0):8:7:0),n||(e+=9),i.isHighBridge()?i.value=e:(i.overlayId=(o===ea.Wood?Wa.minLowBridgeWoodId:Wa.minLowBridgeConcreteId)+e,i.value=e,a=!0)}a&&(i.name=this.rules.getOverlayName(i.overlayId))}findClosestBridgeSpec(i){let e=new Fs(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===Uh.None)||!!this.tileSets.isHighBridgeBoundaryTile(e.tileNum)});var o=e.getNextTile();if(o){let s,t,r,a;var h=!this.tileOccupation.getBridgeOnTile(o);let e;if(h){var l=this.findHighBridgeBoundary(o);if(!l)return;s=l.tile,t=ea.Concrete,this.tileSets.getSetNum(o.tileNum)===this.tileSets.getGeneralValue("WoodBridgeSet")&&(t=ea.Wood),r=l.headType===k.TopLeft||l.headType===k.BottomRight,a=l.headType===k.TopLeft||l.headType===k.TopRight,e=l.headType}else{s=this.tileOccupation.getBridgeOnTile(o).tile;let e=this.getPieceAtTile(s);if(!e)throw new Error("Bridge head is not defined");var c=Wa.getOverlayBridgeType(e.obj.overlayId);if(c===ea.NotBridge)throw new Error("Expected a bridge type");t=c,r=e.obj.isXBridge(),a=e.headType===Uh.Start}var u=Number(r)*(a?1:-1),d=Number(!r)*(a?1:-1);let n;if(h){o=new el(this.tiles,this.mapBounds,s,1,100,u,d,e=>e.z===s.z&&this.tileSets.isHighBridgeBoundaryTile(e.tileNum)).getNextTile(),c=this.tileSets.getSetNum(s.tileNum);if(!o||this.tileSets.getSetNum(o.tileNum)!==c)return;o=this.findHighBridgeBoundary(o);if(!o)return;if(e!==this.tileSets.getOppositeHighBridgeHeadType(o.headType))return;n=o.tile}else{let t,i=1;for(var p=s.rx,g=s.ry;!t;){var m=this.tiles.getByMapCoords(p+u*i,g+d*i);if(!m)return;let e=this.getPieceAtTile(m);if(e&&e.obj.isXBridge()!==r)return;e?.headType===(a?Uh.End:Uh.Start)&&(t=e),i++}n=t.obj.tile}return{start:a?s:n,end:a?n:s,type:t,isHigh:h}}}findHighBridgeBoundary(r){var a,e=this.tileSets.getTile(r.tileNum),n=this.tileSets.getHighBridgeHeadType(e.index);if(void 0!==n){let i=0,s=0;switch(n){case k.TopLeft:i=1,s=0;break;case k.BottomRight:i=-1,s=0;break;case k.TopRight:i=0,s=1;break;case k.BottomLeft:i=0,s=-1;break;case k.MiddleTlBr:i=1,s=0;break;case k.MiddleTrBl:i=0,s=1;break;default:throw new Error(`Unhandled head type "${n}"`)}let e=new Fs(this.tiles,this.mapBounds,r,{width:1,height:1},0,5,e=>e.terrainType===Zt.Pavement&&e.z>=r.z&&e.tileNum===r.tileNum),t=[];for(;a=e.getNextTile();)t.push(a);if(t.sort((e,t)=>100*(i?i*(t.rx-e.rx):s*(t.ry-e.ry))+(i?e.ry-t.ry:e.rx-t.rx)),t.length)return{tile:t[0],headType:n}}else console.warn(`Couldn't find a valid bridge type for index "${e.index}" @ ${r.rx},${r.ry}`)}canBeRepaired(i){let e=this.createBridgePieceTileFinder(i,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===i.start.z)),s=!1,r;for(var a=i.start.rx!==i.end.rx?sa.BottomLeft:sa.BottomRight;r=e.getNextTile();){s=!0;let e=this.tiles.getNeighbourTile(r,a),t=this.tiles.getNeighbourTile(e,a);if(i.isHigh){if([r,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.rules.invisibleInGame)))return!1}else if([r,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>!(e.isUnit()||e.isSmudge()||e.isOverlay()&&e.isBridgePlaceholder()))))return!1}return s}getPieceTiles(e){var t=e.obj.tile,i=e.obj.isXBridge()?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 s=this.findHighBridgeBoundary(e);s&&i.add(s.tile)}return i}findBridgeSpecsForHeadTiles(e){let t=new Map;for(var i of e){i=this.findClosestBridgeSpec(i);i&&t.set(i.start.id+":"+i.end.id,i)}return[...t.values()]}findAllBridgeTiles(e){let t=[];var i,s=e.start.rx!==e.end.rx?sa.BottomLeft:sa.BottomRight;for(i of this.findNonBuildablePieceTiles(e)){var r=this.tiles.getNeighbourTile(i,s),a=this.tiles.getNeighbourTile(r,s);t.push(i,r,a)}return t}findBridgePieces(e){let t=this.createBridgePieceTileFinder(e,e=>!!this.getPieceAtTile(e)),i=[];for(var s;s=t.getNextTile();)i.push(this.getPieceAtTile(s));return i}findDestroyedPieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var s;s=e.getNextTile();)i.push(s);return i}findNonBuildablePieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var s;s=e.getNextTile();)i.push(s);return i}createBridgePieceTileFinder(e,t){var i=e.start.rx!==e.end.rx;return new el(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 il=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 s of this.regions)if(s.add(e,t))return!0}return!1}remove(t,e=!0){let i=this.parentMap.get(t);i&&(i===this?(this.parentMap.delete(t),this.objects.splice(this.objects.findIndex(e=>e.value===t),1),e&&this.parent?.update()):i.remove(t,e))}updateObject(t){let i=this.parentMap.get(t);if(i){var e=this.config.getKey(t);if(i.box.containsPoint(e))i.objects.find(e=>e.value===t).key=e;else{i.remove(t,!1);let e=i.parent;for(;e&&!e.add(t,!1);)e=e.parent}}}queryRange(e,t=[]){if(this.box.intersectsBox(e))if(this.regions)for(var i of this.regions)i.queryRange(e,t);else for(var s of this.objects)e.containsPoint(s.key)&&t.push(s.value);return t}update(){let e=0;if(this.regions){for(var t of this.regions)e+=t.update();e<=this.config.joinThreshold&&this.join()}else e=this.objects.length,e>=this.config.splitThreshold&&this.split()&&this.update();return e}split(){if(this.regions||this.config.maxDepth<=1)return!1;var t,e,i={getKey:this.config.getKey,joinThreshold:this.config.joinThreshold,splitThreshold:this.config.splitThreshold,maxDepth:this.config.maxDepth-1},s=this.generateRegions(),r=this.objects;this.objects=[],this.regions=[];for(t of s){let e=new sl(t,i);e.parentMap=this.parentMap,this.regions.push(e),e.parent=this}for(e of r)this.parentMap.delete(e.value),this.add(e.value,!1);return!0}join(){if(!this.regions)return!1;for(var e of this.regions){e.join(),e.parent=void 0;for(var t of e.objects)this.objects.push(t),this.parentMap.set(t.value,this)}return!(this.regions=void 0)}generateRegions(){let i=[this.box.clone()];var s=this.box.getCenter(il);let r=i[0],a=r.clone();r.max.x=s.x,a.min.x=s.x,i.push(a);for(let e=0,t=i.length;e<t;e++)r=i[e],a=r.clone(),r.max.y=s.y,a.min.y=s.y,i.push(a);return i}}class rl{constructor(e){this.tiles=e,this.tileOcclusion=[];let t=this.tileOcclusion;for(var i of e.getAll())t[i.rx]=t[i.rx]||[],t[i.rx][i.ry]=new Set}addOccluder(t){let e=this.calculateTilesForGameObject(t);e.forEach(e=>this.occludeTile(e,t))}removeOccluder(t){let e=this.calculateTilesForGameObject(t);e.forEach(e=>this.unoccludeTile(e,t))}calculateTilesForGameObject(e){var t=e.art.occupyHeight,i=Math.max(0,t-2);let s=[];var r=e.getFoundation();for(let t=1;t<=i;t++)for(let e=0;e<r.width;e++)s.push(new vs(e-t,-t));for(let t=1;t<=i;t++)for(let e=1;e<r.height;e++)s.push(new vs(-t,e-t));s.push(...e.art.addOccupy);for(let{x:t,y:i}of e.art.removeOccupy){var a=s.findIndex(e=>e.x===t&&e.y===i);-1!==a&&s.splice(a,1)}var n,o,h=e.tile;let l=[];for({x:n,y:o}of s){var c=this.tiles.getByMapCoords(h.rx+n,h.ry+o);c&&l.push(c)}return l}occludeTile(e,t){this.tileOcclusion[e.rx][e.ry].add(t),e.occluded=!0}unoccludeTile(e,t){let i=this.tileOcclusion[e.rx][e.ry];i.delete(t),e.occluded=0<i.size}isTileOccluded(e){return 0<this.tileOcclusion[e.rx][e.ry].size}}class al{static calculate(u,d){let p=new Map;u.forEach(e=>{var t=d.getSetNum(e.tileNum);p.set(e,t),d.isCLAT(t)&&(t=d.getLAT(t),p.set(e,t),e.tileNum=d.getTileNumFromSet(t))}),u.forEach(t=>{var i=p.get(t);if(d.isLAT(i)){let e=0;var s=u.getNeighbourTile(t,sa.TopRight),r=u.getNeighbourTile(t,sa.BottomRight),a=u.getNeighbourTile(t,sa.BottomLeft),n=u.getNeighbourTile(t,sa.TopLeft);s&&d.canConnectTiles(i,p.get(s))&&(e+=1),r&&d.canConnectTiles(i,p.get(r))&&(e+=2),a&&d.canConnectTiles(i,p.get(a))&&(e+=4),n&&d.canConnectTiles(i,p.get(n))&&(e+=8),0<e&&(n=d.getCLATSet(i),t.tileNum=d.getTileNumFromSet(n,e))}else if(i===d.getGeneralValue("RampBase")&&!(t.rampType<1||4<t.terrainType)){let e=-1;var o=u.getNeighbourTile(t,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))}})}}class nl{constructor(e,t,i,s){this.mapFile=e,this.tiles=new Va(this.mapFile.tiles,t,i.general,s),this.mapBounds=(new Jh).fromMapFile(this.mapFile,this.tiles),this.tileOccupation=new lo(this.tiles),this.tileOcclusion=new rl(this.tiles),this.terrain=new Kh(this.tiles,this.mapFile.theaterType,this.mapBounds,this.tileOccupation,i),this.bridges=new tl(t,this.tiles,this.tileOccupation,this.mapBounds,i);let r=this.mapFile.tags;for(let t of this.mapFile.cellTags){let e=this.tiles.getByMapCoords(t.coords.x,t.coords.y);e&&(e.tag=r.find(e=>e.id===t.tagId))}s=this.tiles.getMapSize(),i=Math.max(s.width,s.height)/5;this.technosByTile=new sl(new Mn(new vs(0,0),new vs(s.width,s.height)),{getKey:e=>{e=e.isBuilding()?e.centerTile:e.tile;return new vs(e.rx,e.ry)},maxDepth:this.computeQuadDepth(i),splitThreshold:10,joinThreshold:5}),this.mapFile.theaterType!==I.Snow&&al.calculate(this.tiles,t)}get startingLocations(){return this.mapFile.startingLocations}computeQuadDepth(e){if(e<=1)return 1;let t=0;for(;1<=e/2;)e/=2,t++;return t+(1<e?1:0)}getLighting(){return this.mapFile.lighting}getIonLighting(){return this.mapFile.ionLighting}getTheaterType(){return this.mapFile.theaterType}getTags(){return this.mapFile.tags}getTriggers(){return this.mapFile.triggers}getCellTags(){return this.mapFile.cellTags}getVariables(){return this.mapFile.variables}getWaypoint(t){return this.mapFile.waypoints.find(e=>e.number===t)}getTileAtWaypoint(e){e=this.getWaypoint(e);if(e){e=this.tiles.getByMapCoords(e.rx,e.ry);if(e)return e}}isWithinBounds(e){return this.mapBounds.isWithinBounds(e)}clampWithinBounds(e){var t=this.mapBounds.clampWithinBounds(e);let i=this.tiles.getByDisplayCoords(t.dx,t.dy);if(i&&this.mapBounds.isWithinBounds(i)){let e=i;for(;e&&this.mapBounds.isWithinBounds(e);)i=e,e=this.tiles.getByDisplayCoords(e.dx,e.dy+2)}else{let e=0;for(;!i||!this.mapBounds.isWithinBounds(i);){if(30<e)throw new Error("Exceeded max elevation while trying to clamp tile to map bounds");i=this.tiles.getByDisplayCoords(t.dx,t.dy+e),e+=2}}return i}isWithinHardBounds(e){return this.mapBounds.isWithinHardBounds(e)}getInitialMapObjects(){return{terrains:this.mapFile.terrains,overlays:this.mapFile.overlays,smudges:this.mapFile.smudges,technos:[...this.mapFile.structures,...this.mapFile.infantries,...this.mapFile.vehicles,...this.mapFile.aircrafts]}}getObjectsOnTile(e){return this.tileOccupation.getObjectsOnTile(e)}getGroundObjectsOnTile(e){return this.tileOccupation.getGroundObjectsOnTile(e)}getTileZone(e,t=!1){return this.tileOccupation.getTileZone(e,t)}dispose(){this.terrain.dispose(),this.bridges.dispose()}}class ol{constructor(e,t){this.first=e,this.second=t}has(e){return this.first===e||this.second===e}equals(e){return this.first===e.first&&this.second===e.second||this.first===e.second&&this.second===e.first}}(r=Wh=Wh||{})[r.Requested=0]="Requested",r[r.Formed=1]="Formed";class hl{constructor(e){this.playerList=e,this.alliances=[]}findByPlayers(e,t){let i=new ol(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,Wh.Requested)}}cancelRequest(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==Wh.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!==Wh.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=Wh.Formed}}setAlliance(e,t,i){if(!this.canFormAlliance(e,t))throw new Error(`Can't form alliance between players "${e.name}" and "${t.name}"`);var s;if(s=this.findByPlayers(e,t))throw new Error(`An alliance already exists between players ${e.name} and ${t.name}`);return s={players:new ol(e,t),status:i},this.alliances.push(s),s}breakAlliance(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==Wh.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===Wh.Formed}getAllies(t){return this.filterByPlayer(t).filter(e=>e.status===Wh.Formed).map(e=>e.players.first===t?e.players.second:e.players.first)}haveSharedIntel(e,t){return e.isObserver||t.isObserver||e===t||this.areAllied(e,t)}canRequestAlliance(e){return e.isCombatant()&&!e.isAi}canFormAlliance(t,i){let e=this.getHostilePlayers();if(0===e.filter(e=>e.has(t)&&!e.has(i)).length)return!1;if(0===e.filter(e=>e.has(i)&&!e.has(t)).length)return!1;let s=new ol(t,i);return!!e.filter(e=>!e.equals(s)).length}getHostilePlayers(){var i,s=this.playerList.getCombatants();let r=[];for(let t=0;t<s.length;t++)for(let e=t+1;e<s.length;e++)this.getAllies(s[t]).includes(s[e])||(i=new ol(s[t],s[e]),r.push(i));return r}getHash(){return V(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 ll{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}}(r=zh=zh||{})[r.None=0]="None",r[r.Hover=1]="Hover",r[r.Selected=2]="Selected",r[r.SelectedHover=3]="SelectedHover";class cl{constructor(e){this.selectionLevel=zh.None,e.isBuilding()&&e.rules.wall?this.maxSelectionLevel=zh.None:this.maxSelectionLevel=e.rules.selectable?zh.Selected|zh.Hover:zh.Hover}getSelectionLevel(){return this.selectionLevel}setSelectionLevel(e){this.selectionLevel=Math.min(this.maxSelectionLevel,e)}setHover(e){this.setSelectionLevel(e?this.selectionLevel|zh.Hover:this.selectionLevel&~zh.Hover)}setSelected(e){this.setSelectionLevel(e?this.selectionLevel|zh.Selected:this.selectionLevel&~zh.Selected)}isHovered(){return this.selectionLevel>>zh.Hover&1}isSelected(){return this.selectionLevel>=zh.Selected}getControlGroupNumber(){return this.controlGroupNumber}setControlGroupNumber(e){this.controlGroupNumber=e}}class ul{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 cl(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=V([...this.selectedUnits].map(e=>e.id))}getHash(){return this.hashNeedsUpdate&&(this.updateHash(),this.hashNeedsUpdate=!1),this.hash}createGroup(e){this.addUnitsToGroup(e,this.getSelectedUnits())}addUnitsToGroup(e,t,i=!0){this.unassignUnitsFromGroup(t);let s=this.groups.get(e);s||(s=new Set,this.groups.set(e,s)),i&&([...s.values()].forEach(e=>this.selectionModelsByUnit.get(e)?.setControlGroupNumber(void 0)),s.clear());for(var r of t)s.add(r),this.getOrCreateSelectionModel(r).setControlGroupNumber(e)}addGroupToSelection(e){if(this.groups.has(e))for(var t of[...this.groups.get(e)])this.addToSelection(t)}selectGroup(e){this.deselectAll(),this.addGroupToSelection(e)}getGroupUnits(e){return[...this.groups.get(e)??[]]}unassignUnitsFromGroup(e){for(var t of this.groups.values())for(var i of e)t.delete(i)}}class dl{constructor(e){this._onChange=new io,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 pl{constructor(e,t=void 0,i=0,s=new j(255,0,0)){this.name=e,this.country=t,this.startLocation=i,this.color=s,this.isAi=!1,this.defeated=!1,this.resigned=!1,this.dropped=!1,this.objectsByType=new Map,this.objectsById=new Map,this.traits=new Oa,this._credits=0,this.score=0,this.unitsBuiltByType=new Map,this.unitsKilledByType=new Map,this.unitsLostByType=new Map,this.buildingsCaptured=0,this.cratesPickedUp=0,this.cheerCooldownTicks=0,this.isObserver=!t,this.isNeutral=!!t&&!t.isPlayable()}get credits(){return this._credits}set credits(e){if(e<0)throw new RangeError("Can't set credits to a negative value");this._credits=e}getOrCreateObjectsForType(e){let t=this.objectsByType.get(e);return t||(t=new Set,this.objectsByType.set(e,t)),t}addOwnedObject(e){let t=this.getOrCreateObjectsForType(e.type);t.add(e),(e.owner=this).objectsById.set(e.id,e)}removeOwnedObject(e){let t=this.objectsByType.get(e.type);if(!t||!t.has(e))throw new Error(`GameObject ${e.name} does not belong to player ${this.name}`);t.delete(e),this.objectsById.delete(e.id)}getOwnedObjectById(e){return this.objectsById.get(e)}getOwnedObjectsByType(e,t=!1){let i=[];return i=[...this.objectsByType.get(e)||new Set],t||(i=i.filter(e=>!e.limboData)),i}getOwnedObjects(e=!1){let t=[];return[...this.objectsByType.values()].forEach(e=>{e.forEach(e=>t.push(e))}),e||(t=t.filter(e=>!e.limboData)),t}removeAllOwnedObjects(){this.objectsByType.forEach(e=>e.clear()),this.objectsById.clear()}get buildings(){return this.getOrCreateObjectsForType(Ct.Building)}addUnitsBuilt(e,t){this.unitsBuiltByType.set(e,(this.unitsBuiltByType.get(e)??0)+t)}getUnitsBuilt(e){return void 0!==e?this.unitsBuiltByType.get(e)??0:[...this.unitsBuiltByType.values()].reduce((e,t)=>e+t,0)}addUnitsKilled(e,t){this.unitsKilledByType.set(e,(this.unitsKilledByType.get(e)??0)+t)}getUnitsKilled(e){return void 0!==e?this.unitsKilledByType.get(e)??0:[...this.unitsKilledByType.values()].reduce((e,t)=>e+t,0)}addUnitsLost(e,t){this.unitsLostByType.set(e,(this.unitsLostByType.get(e)??0)+t)}getUnitsLost(e){return void 0!==e?this.unitsLostByType.get(e)??0:[...this.unitsLostByType.values()].reduce((e,t)=>e+t,0)}isCombatant(){return!this.isNeutral&&!this.isObserver&&!this.defeated}canProduceVeteran(e){if(!this.production||!this.country)throw new Error("Non-combatants can't produce units");var t=this.production.getQueueTypeForObject(e),t=this.production.getFactoryTypeForQueueType(t);return this.production.hasVeteranType(t)||this.country.hasVeteranUnit(e.type,e.name)}getHash(){return V([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 gl{constructor(){this.disabled=!0,this.activeEvents=[]}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}}const ml=(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 fl{constructor(e,t,i,s,r){this.player=e,this.maxTechLevel=t,this.gameOpts=i,this.rules=s,this.allAvailableObjects=r,this.buildSpeedModifier=1,this.queues=new Map,this._onQueueUpdate=new io,this.primaryFactories=new Map,this.factoryCounts=new Map,this.veteranTypes=new Set,this.stolenTech=new Set}static factory(e,t,i,s){let r=new fl(e,t.mpDialogSettings.techLevel,i,t,s);t=t.general.maximumQueuedObjects+1;return r.addQueue(pn.Structures,new so(pn.Structures,1,1)),r.addQueue(pn.Armory,new so(pn.Armory,1,1)),r.addQueue(pn.Infantry,new so(pn.Infantry,t,t)),r.addQueue(pn.Vehicles,new so(pn.Vehicles,t,t)),r.addQueue(pn.Ships,new so(pn.Ships,t,t)),r.addQueue(pn.Aircrafts,new so(pn.Aircrafts,0,t)),r}get onQueueUpdate(){return this._onQueueUpdate.asEvent()}addQueue(e,t){this.queues.set(e,t),t.onUpdate.subscribe(()=>this._onQueueUpdate.dispatch(this,t))}getQueue(e){var t=this.queues.get(e);if(!t)throw new Error(`No queue found with type ${pn[e]}`);return t}getAllQueues(){return[...this.queues.values()]}getQueueTypeForObject(e){if(e.type===Ct.Building)return e.buildCat===Yi.Combat?pn.Armory:pn.Structures;if(e.type===Ct.Infantry)return pn.Infantry;if(e.type===Ct.Vehicle)return e.naval?pn.Ships:pn.Vehicles;if(e.type===Ct.Aircraft)return pn.Aircrafts;throw new Error(`Unsupported object type ${Ct[e.type]}`)}getQueueForObject(e){return this.getQueue(this.getQueueTypeForObject(e))}getQueueTypeForFactory(e){if(e===Ki.InfantryType)return pn.Infantry;if(e===Ki.UnitType)return pn.Vehicles;if(e===Ki.AircraftType)return pn.Aircrafts;if(e===Ki.NavalUnitType)return pn.Ships;throw new Error(`Unsupported factory type ${Ki[e]}`)}getFactoryTypeForQueueType(e){if(e===pn.Structures||e===pn.Armory)return Ki.BuildingType;if(e===pn.Infantry)return Ki.InfantryType;if(e===pn.Vehicles)return Ki.UnitType;if(e===pn.Aircrafts)return Ki.AircraftType;if(e===pn.Ships)return Ki.NavalUnitType;throw new Error(`Unsupported queue type ${pn[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!==Ki.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?Ki.BuildingType:e.type===Ct.Infantry?Ki.InfantryType:e.type===Ct.Aircraft?Ki.AircraftType:e.naval?Ki.NavalUnitType:Ki.UnitType}meetsPrerequisites(e){let t=[...this.player.buildings].map(e=>e.name);var i;for(i of e.prerequisite)if(i=i.toUpperCase(),ml.has(i)){var s=ml.get(i);if(void 0===s)throw new Error(`Unknown prereqName ${i}`);var r,a=this.rules.general.prereqCategories.get(s);if(void 0===a)throw new Error(`Missing prerequisite category ${s} in rules`);let e=!1;for(r of a)if(-1!==t.indexOf(r)){e=!0;break}if(!e)return!1}else if(-1===t.indexOf(i))return!1;return!0}getPrimaryFactory(e){return this.primaryFactories.get(e)}setPrimaryFactory(e){e.rules.factory&&this.primaryFactories.set(e.rules.factory,e)}isPrimaryFactory(e){return this.getPrimaryFactory(e.rules.factory)===e}incrementFactoryCount(e){this.factoryCounts.set(e,(this.factoryCounts.get(e)??0)+1)}decrementFactoryCount(e){if(!this.factoryCounts.get(e))throw new Error(`Can't decrement factory count ${Ki[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 yl{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 wl{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 Tl{constructor(e,t,i){this.rules=e,this.gameOpts=t,this.allAvailableObjects=i}createCombatant(e,t,i,s,r,a){let n=new pl(e,t,i,s);return n.isAi=r,n.aiDifficulty=a,n.powerTrait=new eo(n),n.traits.add(n.powerTrait),n.radarTrait=new gl,n.traits.add(n.radarTrait),n.superWeaponsTrait=new yl,n.traits.add(n.superWeaponsTrait),n.production=fl.factory(n,this.rules,this.gameOpts,this.allAvailableObjects),n.sharedDetectDisguiseTrait=new wl,n}createObserver(e,t){let i=new pl(e,void 0,void 0,t.colors.get("LightGrey"));return i.radarTrait=new gl,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 $n(i);let s=new pl(t,i,void 0,e.colors.get("LightGrey"));return s.powerTrait=new eo(s),s.traits.add(s.powerTrait),s}}(Vh=Vh||{}).onSpawn=Symbol(),(Hh=Hh||{}).onUnspawn=Symbol(),(Gh=Gh||{}).onChange=Symbol();class bl{[Vh.onSpawn](e,t){e.isTechno()&&e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"add",t)}[Hh.onUnspawn](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"remove",t)}[En.onChange](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"update",t)}[Gh.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))}[xs.onChange](e,t,i){e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,i?"remove":"add",t)}[Bs.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 vl{constructor(e){this.target=e,this.type=ts.BuildingSell}}class Sl{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(mn).forEach(e=>{e[mn.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 vl(e)),e.dispose()}computeRefundValue(e){let t=0;return 0<e.rules.soylent?t=e.rules.soylent:e.rules.cost&&(t=e.purchaseValue,e.owner.isAi||(t=Math.floor(t*this.generalRules.refundPercent))),t}computePurchaseValue(e,t){return e.cost}dispose(){this.game=void 0}}class _l{constructor(e,t){this.target=e,this.radarEnabled=t,this.type=ts.RadarOnOff}}class kl{constructor(e,t,i){this.target=e,this.radarEventType=t,this.tile=i,this.type=ts.RadarEvent}}class Ol{constructor(){this.activeLightningStrikes=new Map}[Vh.onSpawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Hh.onUnspawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Ns.onPowerLow](e,t){this.updateRadarForPlayer(e,t)}[Ns.onPowerRestore](e,t){this.updateRadarForPlayer(e,t)}[Ns.onPowerChange](){}[Gh.onChange](e,t,i){e.rules.radar&&(this.updateRadarForPlayer(t,i),this.updateRadarForPlayer(e.owner,i))}[xs.onChange](e,t){e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Rs.onActivate](e,t,i){if(e===es.LightningStorm){this.activeLightningStrikes.set(t,(this.activeLightningStrikes.get(t)??0)+1);for(var s of i.getCombatants())s===t||i.alliances.areAllied(s,t)||this.updateRadarForPlayer(s,i)}}[oa.onDeactivate](e,t,i){if(e===es.LightningStorm){e=(this.activeLightningStrikes.get(t)??0)-1;if(0<e?this.activeLightningStrikes.set(t,e):this.activeLightningStrikes.delete(t),e<=0)for(var s of i.getCombatants())this.updateRadarForPlayer(s,i)}}updateRadarForPlayer(i,s){var e,t;i.radarTrait&&(e=i.radarTrait?.isDisabled(),t=![...i.buildings].find(e=>e.rules.radar&&!e.warpedOutTrait.isActive())||i.powerTrait.level===dn.Low||[...this.activeLightningStrikes.entries()].some(([e,t])=>t&&e!==i&&!s.alliances.areAllied(e,i)),i.radarTrait.setDisabled(t),e!==t&&s.events.dispatch(new _l(i,!t)))}[ta.onAttack](e,t,i){e.isTechno()&&(!e.isBuilding()||e.rules.canBeOccupied||e.rules.needsEngineer?e.isVehicle()&&e.harvesterTrait&&this.addEventForPlayer(Xt.HarvesterUnderAttack,e.owner,e.tile,i):this.addEventForPlayer(Xt.BaseUnderAttack,e.owner,e.tile,i))}addEventForPlayer(s,e,r,a){let n=e.radarTrait;if(n){let t=a.rules.general.radar;n.activeEvents=n.activeEvents.filter(e=>a.currentTick-e.startTick<t.getEventDuration(e.type));let i=new Is(a.map.tileOccupation);!!n.activeEvents.find(e=>e.type===s&&i.isInTileRange(r,e.tile,0,t.getEventSuppresionDistance(e.type)))||(n.activeEvents.push({startTick:a.currentTick,tile:r,type:s}),a.events.dispatch(new kl(e,s,r)))}}}class Il{constructor(e){this.target=e,this.type=ts.InsufficientFunds}}class Al{constructor(e,t){this.rules=e,this.speedCheat=t,this.availableObjectRules=new Set;t=60*e.general.buildSpeed*Ls.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)})}[Bs.onTick](e){for(var t of e.getCombatants())for(var i of t.production.getAllQueues())this.tickQueue(i,t,e)}[Vh.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===Ki.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t)):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Hh.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===Ki.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t))):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Gh.onChange](e,t,i){var s;e.isBuilding()?(this.ensurePrerequisites(t),(s=e.rules.factory)&&(t.production?.getPrimaryFactory(s)===e&&t.production.crownPrimaryFactoryHeir(s),e.owner.production&&!e.owner.production.getPrimaryFactory(s)&&e.owner.production.setPrimaryFactory(e),t.production?.decrementFactoryCount(s),e.owner.production?.incrementFactoryCount(s),s===Ki.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))}[Ns.onPowerLow](e){e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}[Ns.onPowerRestore](e){e.production&&(e.production.buildSpeedModifier=1)}[Ns.onPowerChange](e){e.powerTrait?.level===dn.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,s){i.production&&s.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=>s.rules.general.padAircraft.includes(e.name)).length;i.production.getQueueForFactory(Ki.AircraftType).maxSize=Math.max(0,e-t)})}tickQueue(s,r,a){if(s.status===gn.Active){let e=!1,t=s.getFirst();var n=r.production.getFactoryTypeForQueueType(s.type),o=r.production.getFactoryCount(n),h=r.production.buildSpeedModifier,n=1/Qi.pow(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*Ls.BASE_TICKS_PER_SECOND,n=t.creditsEach?t.creditsEach/i:h;n/(60*Ls.BASE_TICKS_PER_SECOND)<.06&&(i=t.creditsEach/h);var l,o=r.credits,h=t.creditsEach-t.creditsSpent,h=Math.min(r.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,r.credits-=l,e=!0)):t.creditsEach||(l=t.progress*n,t.progress=Math.min(1,(1+l)/n),e=!0),e&&1===t.progress&&(s.status=gn.Ready),0<o&&!r.credits&&a.events.dispatch(new Il(r)),e&&s.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]}}($h=$h||{}).onChange=Symbol();class Cl{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 Mo).fromTiles(this.map.tiles);for(var s of t.getCombatants()){let e=i.clone();this.shroudByPlayer.set(s,e),this.revealObjects(e,s,t),e.update()}}[Bs.onTick](e){for(var[t,i]of this.shroudByPlayer)t.defeated&&!t.isObserver?this.shroudByPlayer.delete(t):i.update()}[Gh.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 s of[e.owner,...i.alliances.getAllies(e.owner)])this.shroudByPlayer.get(s)?.revealFrom(e)}[$h.onChange](t,e,i){if(e){let e=this.getPlayerShroud(t.players.first);var s,r,t=i.alliances.getAllies(t.players.first).map(e=>this.getPlayerShroud(e)).filter(Ma);for(s of t)e.merge(s);e.invalidateFull();for(r of t)r.copy(e),r.invalidateFull()}}[Vh.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(Ol).addEventForPlayer(Xt.EnemyObjectSensed,i,e.centerTile,t))}e.gapGeneratorTrait&&this.gapGenerators.add(e)}}[Hh.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))}[Ns.onPowerLow](e,t){this.updateGaps(t,e)}[Ns.onPowerRestore](e,t){this.updateGaps(t,e)}[Ns.onPowerChange](e,t){}revealMap(e,t){this.shroudByPlayer.get(e)?.revealAll(),this.markOwnGapTiles(t,e),this.updateGaps(t)}resetShroud(e,t){let i=this.shroudByPlayer.get(e);i&&(i.reset(),this.markOwnGapTiles(t,e),this.revealObjects(i,e,t))}revealObjects(t,e,i){var s;for(s of[...e.getOwnedObjects(),...i.alliances.getAllies(e).map(e=>e.getOwnedObjects()).flat()])t.revealFrom(s);this.revealedToAll.forEach(e=>t.revealObject(e))}updateGaps(e,t){for(var i of this.gapGenerators)t&&i.owner!==t||i.gapGeneratorTrait.update(i,e)}markOwnGapTiles(e,t){for(var i of this.gapGenerators)i.owner!==t&&!e.alliances.areAllied(i.owner,t)||this.getPlayerShroud(t)?.toggleFlagsAround(i.tile,i.gapGeneratorTrait.radiusTiles,_n.Darken,!0)}dispose(){this.map.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class Bl extends Vs{onTick(e){return!(e.buildStatus!==kn.BuildDown&&(e.buildStatus=kn.BuildDown,!e.rules.wall))||(this.children.push(new ua(.035)),!1)}}class xl{constructor(e,t,i,s,r){this.player=e,this.rules=t,this.art=i,this.map=s,this.game=r}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 s={x:t.tile.rx,y:t.tile.ry},r=this.rules.getBuilding(t.name),a=this.art.getObject(t.name,Ct.Building).foundation;r.baseNormal&&i.push(this.getAdjacentRect(s,a,e))}return i}meetsAdjacency(e,t){var i,s,r;for(i of this.getAdjacencyMap(t))if(s=e,r=i,s.x<=r.x+r.width&&r.x<=s.x+s.width&&s.y<=r.y+r.height&&r.y<=s.y+s.height)return!0;return!1}canBuildAt(e,t,i,s=!1){var r=this.rules.getBuilding(e),a=this.art.getObject(e,Ct.Building);let n=[];var o=a.foundation,h=s?t:this.normalizePlacementTileCoords(e,t);let l=!0;t={x:h.rx,y:h.ry,width:o.width,height:o.height};r.constructionYard||this.meetsAdjacency(t,r.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,r,i)&&!this.game.mapShroudTrait.getPlayerShroud(this.player)?.isShrouded(u))})}if(r.wall&&n[0].buildable){let e=this.getWallConnectingTiles(h,r);e.forEach(e=>{n.push({rx:e.rx,ry:e.ry,buildable:!0})})}return n}placeAt(e,t,i=!1){let s=[],r=this.rules.getBuilding(e),a=i?t:this.normalizePlacementTile(e,t);if(r.wall){let t=[[a,r]],e=this.getWallConnectingTiles(a,r);e.forEach(e=>{e!==a&&t.push([e,r])});for(var n of t)s.push(this.executePlacement(n[0],n[1]));e.forEach(e=>{e=this.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.name===r.name&&e.owner===this.player);this.connectWall(e)})}else{var o,t=this.executePlacement(a,r);s.push(t);for(o of this.map.tileOccupation.calculateTilesForGameObject(a,t)){var h=this.map.getObjectsOnTile(o).find(e=>e.isSmudge());h&&this.game.unspawnObject(h)}}return s}normalizePlacementTileCoords(e,t){e=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 La(new Bl,new da(()=>{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,s){var r,a=s.guardRange+1;let n=[];for(r of[[0,1],[0,-1],[1,0],[-1,0]]){let t=[];for(let e=0;e<a;++e){var o={x:i.rx+r[0]*e,y:i.ry+r[1]*e},o=this.map.tiles.getByMapCoords(o.x,o.y);if(!o)break;if(this.map.getObjectsOnTile(o).find(e=>e.isBuilding()&&e.name===s.name&&e.owner===this.player)){n=n.concat(t);break}if(!this.isTileBuildable(o,s))break;t.push(o)}}return n}getAdjacentBuildingData(e,t){var i;let s=[];for(i of[[0,1],[0,-1],[1,0],[-1,0]]){var r={x:e.rx+i[0],y:e.ry+i[1]},a=this.map.tiles.getByMapCoords(r.x,r.y);a&&((r=this.map.getObjectsOnTile(a).find(e=>e.isBuilding()&&e.name===t&&e.owner===this.player))&&s.push({direction:i,tile:a,building:r}))}return s}updateAdjacentWalls(t){let e=new ao(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 El{static generate(e,t,i,s){var r,a=i.reduce((e,t)=>e+t.cost,0)/i.length*e;let n=[],o=a,h=(i=i.filter(e=>e.isAvailableTo(s)&&e.hasOwner(s))).filter(e=>t.includes(e.name));for(r of h){if(o<=0)break;var l=2/3/h.length,l=Math.ceil(l*a/r.cost);o-=l*r.cost,n.push({name:r.name,type: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 Pl{constructor(){this.dispatcher=new io,this.dispatchersByType=new Map}dispatch(e){this.dispatcher.dispatch(void 0,e),this.dispatchersByType.get(e.type)?.dispatch(void 0,e)}subscribe(e,t){let i=void 0,s;return s="function"==typeof e?e:(i=e,t),void 0===i?(this.dispatcher.subscribe(s),()=>this.unsubscribe(s)):this.subscribeType(i,s)}unsubscribe(e,t){let i=void 0,s;s="function"==typeof e?e:(i=e,t),void 0===i?this.dispatcher.unsubscribe(s):this.unsubscribeType(i,s)}subscribeType(e,t){let i=this.dispatchersByType.get(e);return i||(i=new io,this.dispatchersByType.set(e,i)),i.subscribe(t),()=>this.unsubscribeType(e,t)}unsubscribeType(e,t){this.dispatchersByType.get(e)?.unsubscribe(t)}}class Nl{constructor(e,t,i){this.target=e,this.attackerInfo=t,this.incidental=i,this.type=ts.ObjectDestroy}}class Rl{constructor(e){this.target=e,this.type=ts.PlayerDefeated}}(qh=qh||{}).onDestroy=Symbol();class Dl{constructor(e,t){this.target=e,this.prevOwner=t,this.type=ts.ObjectOwnerChange}}class Ml{constructor(e){this.gameObject=e,this.type=ts.ObjectUnspawn}}class Ll{constructor(e){this.gameObject=e,this.type=ts.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}}(r=Xh=Xh||{})[r.NoAction=0]="NoAction",r[r.DropPlayer=1]="DropPlayer",r[r.ObserveGame=2]="ObserveGame",r[r.ResignGame=3]="ResignGame",r[r.PlaceBuilding=4]="PlaceBuilding",r[r.SellBuilding=5]="SellBuilding",r[r.ToggleRepair=6]="ToggleRepair",r[r.SelectUnits=7]="SelectUnits",r[r.OrderUnits=8]="OrderUnits",r[r.UpdateQueue=9]="UpdateQueue",r[r.ToggleAlliance=10]="ToggleAlliance",r[r.ActivateSuperWeapon=11]="ActivateSuperWeapon",r[r.PingLocation=12]="PingLocation";class jl{constructor(e){this.actionType=e}unserialize(e){}serialize(){return[]}print(){return""}}(r=Qh=Qh||{})[r.Add=0]="Add",r[r.Cancel=1]="Cancel",r[r.Pause=2]="Pause",r[r.Resume=3]="Resume";class Ul extends jl{constructor(e){super(Xh.UpdateQueue),this.game=e}unserialize(e){this.queueType=Number(e[0]),this.updateType=Number(e[1]),this.updateType!==Qh.Add&&this.updateType!==Qh.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!==Qh.Add&&this.updateType!==Qh.Cancel||e.push(""+this.item.name,""+this.item.type,""+this.quantity),e}print(){return this.updateType===Qh.Resume?`Resume queue ${pn[this.queueType]}`:this.updateType===Qh.Add?`Add to queue ${this.item.name} x ${this.quantity}`:this.updateType===Qh.Pause?`Put queue ${pn[this.queueType]} on hold.`:this.updateType===Qh.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,s=t.production.getQueue(this.queueType);if(this.updateType===Qh.Resume)s.status===gn.OnHold&&(s.status=gn.Active);else if(this.updateType===Qh.Add){let e=s.find(i);var r;(s.status===gn.Active||s.status===gn.Idle||s.status===gn.OnHold&&e[0]!==s.getFirst()||s.status===gn.Ready&&i.type!==Ct.Building)&&(r=e.reduce((e,t)=>e+t.quantity,0),Number.isFinite(i.buildLimit)&&t.getOwnedObjectsByType(i.type,!0).filter(e=>e.name===i.name).length+r>=i.buildLimit||t.production.isAvailableForProduction(i)&&(a=Math.min(s.maxSize-s.currentSize,s.maxItemQuantity-r),0<(n=Math.min(this.quantity,a))&&s.push(i,n,i.cost)))}else if(this.updateType===Qh.Cancel){if([gn.Ready,gn.OnHold,gn.Active].includes(s.status)){let e=s.find(i);var a,n;e.length&&(a=e.reduce((e,t)=>e+t.quantity,0),0<(n=Math.min(a,this.quantity))&&(s.pop(i,n),n===a&&(t.credits+=e[0].creditsSpent)))}}else this.updateType===Qh.Pause&&s.status===gn.Active&&(s.status=gn.OnHold)}}var Wl=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},zl=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Vl{constructor(e,t,i,s){Ql.add(this),Gl.set(this,void 0),$l.set(this,void 0),ql.set(this,void 0),Xl.set(this,void 0),Wl(this,Gl,t,"f"),Wl(this,$l,i,"f"),Wl(this,ql,e,"f"),Wl(this,Xl,s,"f")}placeBuilding(t,i,s){zl(this,Ql,"m",Zl).call(this,Xh.PlaceBuilding,e=>{e.name=t,e.tile={x:i,y:s}})}sellBuilding(t){zl(this,Ql,"m",Zl).call(this,Xh.SellBuilding,e=>{e.buildingId=t})}toggleRepairWrench(t){zl(this,Ql,"m",Zl).call(this,Xh.ToggleRepair,e=>{e.buildingId=t})}toggleAlliance(t,i){zl(this,Ql,"m",Zl).call(this,Xh.ToggleAlliance,e=>{e.toPlayerName=t,e.toggle=i})}pauseProduction(t){zl(this,Ql,"m",Zl).call(this,Xh.UpdateQueue,e=>{e.queueType=t,e.updateType=Qh.Pause})}resumeProduction(t){zl(this,Ql,"m",Zl).call(this,Xh.UpdateQueue,e=>{e.queueType=t,e.updateType=Qh.Resume})}queueForProduction(t,e,i,s){let r=zl(this,ql,"f").rules.getObject(e,i);zl(this,Ql,"m",Zl).call(this,Xh.UpdateQueue,e=>{e.queueType=t,e.updateType=Qh.Add,e.item=r,e.quantity=s})}unqueueFromProduction(t,e,i,s){let r=zl(this,ql,"f").rules.getObject(e,i);zl(this,Ql,"m",Zl).call(this,Xh.UpdateQueue,e=>{e.queueType=t,e.updateType=Qh.Cancel,e.item=r,e.quantity=s})}activateSuperWeapon(t,i,s){zl(this,Ql,"m",Zl).call(this,Xh.ActivateSuperWeapon,e=>{e.superWeaponType=t,e.tile={x:i.rx,y:i.ry},e.tile2=s?{x:s.rx,y:s.ry}:void 0})}orderUnits(t,i,s,r,a){zl(this,Ql,"m",Zl).call(this,Xh.SelectUnits,e=>{e.unitIds=t});let n;if(s){let e,t;if(r){e=void 0;var o=zl(this,ql,"f").map.tiles.getByMapCoords(s,r);if(!o)throw new Error(`No tile found at rx,ry=${s},${r}`);t=o,a&&(e=zl(this,ql,"f").map.tileOccupation.getBridgeOnTile(o))}else e=zl(this,ql,"f").getObjectById(s),t=e.tile;n=zl(this,ql,"f").createTarget(e,t)}zl(this,Ql,"m",Zl).call(this,Xh.OrderUnits,e=>{e.orderType=i,e.target=n})}quitGame(){zl(this,Ql,"m",Zl).call(this,Xh.ResignGame)}}var Hl,Gl=new WeakMap,$l=new WeakMap,ql=new WeakMap,Xl=new WeakMap,Ql=new WeakSet,Zl=function(e,t){if(!zl(this,Xl,"f"))throw new Error("Player name must be set before issuing any actions");let i=zl(this,Gl,"f").create(e);i.playerName=zl(this,Xl,"f"),t?.(i),zl(this,$l,"f").push(i)},Yl=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Kl=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};(r=Hl=Hl||{})[r.ObjectOwnerChange=0]="ObjectOwnerChange",r[r.ObjectSpawn=1]="ObjectSpawn",r[r.ObjectUnspawn=2]="ObjectUnspawn",r[r.ObjectDestroy=3]="ObjectDestroy";class Jl{constructor(e){ic.add(this),ec.set(this,void 0),tc.set(this,[]),Yl(this,ec,e,"f")}subscribe(e,t){let i=void 0,s;s="function"==typeof e?e:(i=e,t);t=Kl(this,ec,"f").subscribe(e=>{e=Kl(this,ic,"m",sc).call(this,e);!e||void 0!==i&&i!==e.type||s(e)});return Kl(this,tc,"f").push(t),t}dispose(){for(var e of Kl(this,tc,"f"))e();Kl(this,tc,"f").length=0}}var ec=new WeakMap,tc=new WeakMap,ic=new WeakSet,sc=function(t){switch(t.type){case ts.ObjectOwnerChange:return{type:Hl.ObjectOwnerChange,prevOwnerName:t.prevOwner.name,newOwnerName:t.target.owner.name,target:t.target.id};case ts.ObjectSpawn:return{type:Hl.ObjectSpawn,target:t.gameObject.id};case ts.ObjectUnspawn:return{type:Hl.ObjectUnspawn,target:t.gameObject.id};case ts.ObjectDestroy:{let e=t;return e.target.isProjectile()?void 0:{type:Hl.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}},rc=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},ac=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class nc{constructor(e){lc.add(this),oc.set(this,void 0),hc.set(this,void 0),rc(this,oc,e,"f"),rc(this,hc,e.map,"f")}getStartingLocations(){return ac(this,hc,"f").startingLocations}getTheaterType(){return ac(this,hc,"f").getTheaterType()}getTile(e,t){t=ac(this,hc,"f").tiles.getByMapCoords(e,t);if(t&&ac(this,hc,"f").mapBounds.isWithinBounds(t))return t}getTilesInRect(e,t){return ac(this,hc,"f").tiles.getInRectangle(e,t).filter(e=>ac(this,hc,"f").mapBounds.isWithinBounds(e))}getObjectsOnTile(e){return ac(this,hc,"f").getObjectsOnTile(e).map(e=>e.id)}hasBridgeOnTile(e){return!!e.onBridgeLandType}hasHighBridgeOnTile(e){return!!ac(this,hc,"f").tileOccupation.getBridgeOnTile(e)?.isHighBridge()}isPassableTile(e,t,i){return 0<ac(this,hc,"f").terrain.getPassableSpeed(e,t,i)}isVisibleTile(e,t){var i=ac(this,oc,"f").getPlayerByName(t);if(!i)throw new Error(`Player "${t}" doesn't exist`);return!ac(this,oc,"f").mapShroudTrait.getPlayerShroud(i)?.isShrouded(e)}getTileResourceData(e){e=ac(this,hc,"f").getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium()||e.isTerrain()&&e.rules.spawnsTiberium);return e?ac(this,lc,"m",cc).call(this,e):void 0}getAllTilesResourceData(){var e;let t=[];for(e of ac(this,oc,"f").getWorld().getAllObjects()){var i=ac(this,lc,"m",cc).call(this,e);i&&t.push(i)}return t}}var oc=new WeakMap,hc=new WeakMap,lc=new WeakSet,cc=function(t){let i;if(t.isOverlay()&&t.isTiberium()){let e=t.traits.get(Ga);var s=e.getTiberiumType(),r=e.getBailCount();i={tile:t.tile,ore:s===aa.Ore?r:0,gems:s===aa.Gems?r:0,spawnsOre:!1}}else t.isTerrain()&&t.rules.spawnsTiberium&&(i={tile:t.tile,ore:0,gems:0,spawnsOre:!0});return i},uc=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},dc=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class pc{constructor(e){gc.set(this,void 0),uc(this,gc,e,"f")}get allObjectRules(){return dc(this,gc,"f").allObjectRules}get buildingRules(){return dc(this,gc,"f").buildingRules}get infantryRules(){return dc(this,gc,"f").infantryRules}get vehicleRules(){return dc(this,gc,"f").vehicleRules}get aircraftRules(){return dc(this,gc,"f").aircraftRules}get terrainRules(){return dc(this,gc,"f").terrainRules}get overlayRules(){return dc(this,gc,"f").overlayRules}get countryRules(){return dc(this,gc,"f").countryRules}get general(){return dc(this,gc,"f").general}get ai(){return dc(this,gc,"f").ai}get crateRules(){return dc(this,gc,"f").crateRules}get combatDamage(){return dc(this,gc,"f").combatDamage}get radiation(){return dc(this,gc,"f").radiation}hasObject(e,t){return dc(this,gc,"f").hasObject(e,t)}getObject(e,t){return dc(this,gc,"f").getObject(e,t)}getBuilding(e){return dc(this,gc,"f").getBuilding(e)}getWeapon(e){return dc(this,gc,"f").getWeapon(e)}getWarhead(e){return dc(this,gc,"f").getWarhead(e)}getProjectile(e){return dc(this,gc,"f").getProjectile(e)}getOverlayName(e){return dc(this,gc,"f").getOverlayName(e)}getOverlayId(e){return dc(this,gc,"f").getOverlayId(e)}getOverlay(e){return dc(this,gc,"f").getOverlay(e)}getCountry(e){return dc(this,gc,"f").getCountry(e)}getMultiplayerCountries(){return dc(this,gc,"f").getMultiplayerCountries()}getIni(){return dc(this,gc,"f").getIni()}}var gc=new WeakMap,mc=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},fc=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class yc{constructor(e,t){_c.add(this),vc.set(this,void 0),Sc.set(this,void 0),mc(this,vc,e,"f"),mc(this,Sc,t,"f"),this.mapApi=new nc(e),this.rulesApi=new pc(e.rules)}isPlayerDefeated(e){return fc(this,vc,"f").getPlayerByName(e).defeated}areAlliedPlayers(e,t){var i=fc(this,vc,"f").getPlayerByName(e);if(!i)throw new Error(`Player "${e}" doesn't exist`);e=fc(this,vc,"f").getPlayerByName(t);if(!e)throw new Error(`Player "${t}" doesn't exist`);return fc(this,vc,"f").alliances.areAllied(i,e)}canPlaceBuilding(e,t,i){var s=fc(this,vc,"f").getPlayerByName(e);if(!s)throw new Error(`Player "${e}" doesn't exist`);let r=fc(this,vc,"f").getConstructionWorker(s).canBuildAt(t,i,void 0,!0);return!r.some(e=>!e.buildable)}getBuildingPlacementData(e){e=fc(this,vc,"f").art.getObject(e,Ct.Building);return{foundation:e.foundation,foundationCenter:e.foundationCenter}}getPlayers(){return fc(this,vc,"f").getNonNeutralPlayers().map(e=>e.name)}getPlayerData(e){let t=fc(this,vc,"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===dn.Low},radarDisabled:!!t.radarTrait?.isDisabled()}}getAllTerrainObjects(){return fc(this,vc,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}getAllUnits(){return fc(this,vc,"f").getWorld().getAllObjects().filter(e=>e.isTechno()).map(e=>e.id)}getVisibleUnits(e,t,i=()=>!0){const s=fc(this,vc,"f").getPlayerByName(e);if(!s)throw new Error(`Player "${e}" doesn't exist`);if("self"===t)return s.getOwnedObjects().filter(e=>i(e.rules)).map(e=>e.id);let r;if("allied"===t)r=e=>e.owner===s||fc(this,vc,"f").alliances.areAllied(e.owner,s);else{if("hostile"!==t)throw new Error(`Unexpected type ${t}`);{let t=fc(this,vc,"f").mapShroudTrait.getPlayerShroud(s);r=e=>!t?.isShrouded(e.tile)&&e.owner!==s&&!fc(this,vc,"f").alliances.areAllied(e.owner,s)}}return fc(this,vc,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&r(e)&&i(e.rules)).map(e=>e.id)}getGameObjectData(t){if(fc(this,vc,"f").getWorld().hasObjectId(t)){let e=fc(this,vc,"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=fc(this,vc,"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?fc(this,_c,"m",kc).call(this,e.primaryWeapon):void 0,secondaryWeapon:e.secondaryWeapon?fc(this,_c,"m",kc).call(this,e.secondaryWeapon):void 0,deathWeapon:e.armedTrait?.deathWeapon?fc(this,_c,"m",kc).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 fc(this,vc,"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 fc(this,vc,"f").rules.general}getRulesIni(){return fc(this,vc,"f").rules.getIni()}getArtIni(){return fc(this,vc,"f").art.getIni()}generateRandomInt(e,t){if(fc(this,Sc,"f"))return fc(this,vc,"f").generateRandomInt(e,t);var i=this.generateRandom();return Math.round(i*(t-e))+e}generateRandom(){return fc(this,Sc,"f")?fc(this,vc,"f").generateRandom():Math.random()}getTickRate(){return fc(this,vc,"f").speed.value*Ls.BASE_TICKS_PER_SECOND}getCurrentTick(){return fc(this,vc,"f").currentTick}}var wc,Tc,bc,vc=new WeakMap,Sc=new WeakMap,_c=new WeakSet,kc=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()}},Oc=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Ic=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Ac{constructor(e){wc.set(this,void 0),Oc(this,wc,e,"f")}isAvailableForProduction(e){return Ic(this,wc,"f").isAvailableForProduction(e)}getAvailableObjects(t){let e=Ic(this,wc,"f").getAvailableObjects();return void 0!==t&&(e=e.filter(e=>this.getQueueTypeForObject(e)===t)),e}getQueueTypeForObject(e){return Ic(this,wc,"f").getQueueTypeForObject(e)}getQueueData(e){let t=Ic(this,wc,"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}))}}}wc=new WeakMap;class Cc{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){}}(r=Tc=Tc||{})[r.Initial=0]="Initial",r[r.Deployed=1]="Deployed",r[r.Attacking=2]="Attacking",r[r.Defeated=3]="Defeated";class Bc extends Cc{constructor(){super(...arguments),this.botState=Tc.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 Tc.Initial:{const i=e.getGeneralRules().baseUnit;if(e.getVisibleUnits(this.name,"self",e=>e.constructionYard).length){this.botState=Tc.Deployed;break}var t=e.getVisibleUnits(this.name,"self",e=>i.includes(e.name));t.length&&this.actionsApi.orderUnits([t[0]],In.DeploySelected);break}case Tc.Deployed:break;case Tc.Attacking:e.getVisibleUnits(this.name,"self",e=>e.isSelectableCombatant).length||(this.botState=Tc.Defeated,this.actionsApi.quitGame())}}}(r=bc=bc||{})[r.Requested=0]="Requested",r[r.Formed=1]="Formed",r[r.Broken=2]="Broken";class xc{constructor(e,t,i){this.alliance=e,this.changeType=t,this.from=i,this.type=ts.AllianceChange}}var Ec,Pc,Nc,Rc,Dc,Mc,Lc,Fc,jc,Uc,r=__webpack_require__(948),Wc=__webpack_require__.n(r);class zc{constructor(e){this.prng=new(Wc())(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 Vc{constructor(e,t){this.action=e,this.trigger=t}getDebugName(){return`${this.action.triggerId}[${this.action.index}] (${this.trigger.name}).`}}class Hc extends Vc{constructor(e,t,i){super(e,t),this.oneTimeOnly=i,this.superWeaponIdx=Number(e.params[1])}execute(i){var s=[...i.rules.superWeaponRules.values()].find(e=>e.index===this.superWeaponIdx);if(s){let t=i.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(t&&t.superWeaponsTrait&&!t.superWeaponsTrait.has(s.name)){let e=i.createSuperWeapon(s.name,t,this.oneTimeOnly);e.isGift=!0,t.superWeaponsTrait.add(e)}}else console.warn(`No superweapon found with index "${this.superWeaponIdx}". `+`Skipping action ${this.getDebugName()}.`)}}class Gc extends Vc{constructor(e,t,i){super(e,t),this.damage=i}execute(t){var e=Number(this.action.params[1]),i=t.map.getTileAtWaypoint(e);if(i){var s=t.rules.getWarhead(Xa.HE_WARHEAD_NAME);let e=new Xa(s);var r=t.map.tileOccupation.getBridgeOnTile(i),a=r?.tileElevation??0,s=t.map.getTileZone(i);e.detonate(t,this.damage,i,a,Ss.tile3dToWorld(i.rx+.5,i.ry+.5,i.z+a),s,r?ia.OnBridge:ia.None,t.createTarget(r,i),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class $c extends Vc{execute(e){let i=e.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(i){let t=Number(this.action.params[1]);var s=e.getAllPlayers().find(e=>e.country?.id===t);if(s)for(var r of i.getOwnedObjects(!0))e.changeObjectOwner(r,s)}}}class qc extends Vc{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e,t){var i=e.getAllPlayers().find(e=>e.country?.id===this.houseId);if(i)for(var s of t)s instanceof Ia&&s.isSpawned&&e.changeObjectOwner(s,i)}}class Xc extends Vs{constructor(){super(),this.executed=!1,this.cancellable=!1}onTick(e){return this.executed?(e.stance=Ds.None,!0):!e.isInfantry()||!e.art.sequences.has(cn.Cheer)||(e.stance!==Ds.None&&e.stance!==Ds.Guard||(e.stance=Ds.Cheer,this.children.push(new ua(1/60).setCancellable(!1)),!(this.executed=!0)))}}class Qc extends Vc{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 Xc)}}const Zc=new Map([[0,e=>{e=e.rules.powerups.powerups.find(e=>e.type===Cs.Money);return e?{...e,data:"5000"}:void 0}],[1,Cs.Unit],[2,Cs.HealBase],[3,Cs.Cloak],[4,Cs.Explosion],[5,Cs.Napalm],[6,Cs.Money],[7,Cs.Darkness],[8,Cs.Reveal],[9,Cs.Armor],[10,Cs.Speed],[11,Cs.Firepower],[12,Cs.ICBM],[13,void 0],[14,Cs.Veteran],[15,void 0],[16,Cs.Gas],[17,Cs.Tiberium],[18,void 0]]);class Yc extends Vc{execute(e){var t=Number(this.action.params[1]),i=this.action.params[6],s=e.map.getTileAtWaypoint(i);if(s)if(Zc.has(t)){const r=Zc.get(t);t="function"==typeof r?r(e):e.rules.powerups.powerups.find(e=>e.type===r);t&&e.crateGeneratorTrait.spawnCrateAt(s,t,e)}else e.crateGeneratorTrait.spawnRandomCrateAt(s,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}}class Kc extends Vc{execute(e){var t=Number(this.action.params[1])-1;if(Object.values(Xt).includes(t)){var i=this.action.params[6],s=e.map.getTileAtWaypoint(i);if(s)for(var r of e.getCombatants())e.traits.get(Ol).addEventForPlayer(t,r,s,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}else console.warn(`Unknown radar event type "${1+t}". Skipping action ${this.getDebugName()}.`)}}class Jc extends Vc{execute(e,t){for(var i of t)i instanceof Ia&&i.isSpawned&&e.destroyObject(i)}}class eu extends Vc{execute(e){var t=this.action.params[1];e.triggers.destroyTag(t)}}class tu extends Vc{execute(e){var t=this.action.params[1];e.triggers.destroyTrigger(t)}}class iu extends Vc{execute(s){var r=Number(this.action.params[1]),e=this.action.params[6],a=s.map.getTileAtWaypoint(e);if(a){let t;try{t=s.rules.getWeaponByInternalId(r)}catch(e){if(e instanceof RangeError)return void console.warn(`Weapon with internal ID "${r}" not found. `+`Skipping action ${this.getDebugName()}.`);throw e}let e;try{e=s.rules.getWarhead(t.warhead)}catch(e){return void console.warn(`Warhead "${t.warhead}" not found. `+`Skipping action ${this.getDebugName()}.`)}let i=new Xa(e);var n=s.map.tileOccupation.getBridgeOnTile(a),o=n?.tileElevation??0,r=s.map.getTileZone(a);i.detonate(s,t.damage,a,o,Ss.tile3dToWorld(a.rx+.5,a.ry+.5,a.z+o),r,n?ia.OnBridge:ia.None,s.createTarget(n,a),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class su extends Vc{execute(e,t){for(var i of t)i instanceof Ia&&i.isBuilding()&&i.garrisonTrait&&!i.isDestroyed&&i.garrisonTrait.evacuate(e)}}class ru extends Vc{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 au extends Vc{execute(e){var t=this.action.params[1];e.triggers.forceTrigger(t,e)}}class nu extends Vc{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 ou extends Vc{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===es.IronCurtain))&&e.traits.get(nn).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class hu extends Vc{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===es.LightningStorm))&&e.traits.get(nn).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class lu extends Vc{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 cu extends Vc{execute(){}}class uu extends Vc{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===es.MultiMissile))&&e.traits.get(nn).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class du{constructor(e,t){this.name=e,this.tile=t,this.type=ts.TriggerAnim}}class pu extends Vc{execute(e){var t,i=this.action,s=Number(i.params[1]),r=e.rules.getAnimationName(s);void 0!==r?(t=i.params[6],(i=e.map.getTileAtWaypoint(t))?e.events.dispatch(new du(r,i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)):console.warn(`No animation found for index "${s}". Skipping action ${this.getDebugName()}`)}}class gu{constructor(e,t){this.soundId=e,this.tile=t,this.type=ts.TriggerSoundFx}}class mu extends Vc{execute(e){var t=this.action,i=t.params[1],s=t.params[6],t=e.map.getTileAtWaypoint(s);t?e.events.dispatch(new gu(i,t)):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class fu extends Vc{execute(e){e.events.dispatch(new gu(this.action.params[1]))}}class yu{constructor(e){this.soundId=e,this.type=ts.TriggerEva}}class wu extends Vc{execute(e){e.events.dispatch(new yu(this.action.params[1]))}}class Tu extends Vc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.resetShroud(t,e)}}class bu extends Vc{execute(e){var[t,i,s,r]=this.action.params.slice(2,6).map(Number);e.map.mapBounds.updateRawLocalSize({x:t,y:i,width:s,height:r})}}class vu extends Vc{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var s of e.getCombatants())e.mapShroudTrait.getPlayerShroud(s)?.revealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Su extends Vc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.revealMap(t,e)}}class _u extends Vc{execute(e,t){for(var i of t)i instanceof Ia&&i.isBuilding()&&!i.isDestroyed&&e.sellTrait.sell(i)}}class ku extends Vc{execute(e){var t=Number(this.action.params[1])/100;e.mapLightingTrait.setTargetAmbientIntensity(t)}}function Ou(e){let t=new DataView(new ArrayBuffer(4));return t.setInt32(0,e),t.getFloat32(0)}class Iu extends Vc{execute(e){var t=Ou(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeRate(t)}}class Au extends Vc{execute(e){var t=Ou(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeStep(t)}}class Cu{constructor(e){this.tile=e,this.type=ts.TriggerStopSoundFx}}class Bu extends Vc{execute(e){var t=this.action.params[6],i=e.map.getTileAtWaypoint(t);i?e.events.dispatch(new Cu(i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class xu{constructor(e){this.label=e,this.type=ts.TriggerText}}class Eu extends Vc{execute(e){e.events.dispatch(new xu(this.action.params[1]))}}class Pu extends Vc{execute(e){e.countdownTimer.addSeconds(Number(this.action.params[1]))}}class Nu extends Vc{execute(e){e.countdownTimer.setSeconds(Number(this.action.params[1]))}}class Ru extends Vc{execute(e){e.countdownTimer.addSeconds(-Number(this.action.params[1]))}}class Du extends Vc{execute(e){e.countdownTimer.start()}}class Mu extends Vc{execute(e){e.countdownTimer.stop()}}class Lu extends Vc{execute(e){e.countdownTimer.text=this.action.params[1]}}class Fu extends Vc{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 ju extends Vc{constructor(e,t,i){super(e,t),this.turnOn=i}execute(e,t){for(var i of t)i instanceof Ia&&i.isBuilding()&&i.poweredTrait?.setTurnedOn(this.turnOn)}}class Uu extends Vc{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var s of e.getCombatants())e.mapShroudTrait.getPlayerShroud(s)?.unrevealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Wu{create(e,t){switch(e.type){case $t.NoAction:return new cu(e,t);case $t.FireSale:return new ru(e,t);case $t.TextTrigger:return new Eu(e,t);case $t.DestroyTrigger:return new tu(e,t);case $t.ChangeHouse:return new qc(e,t);case $t.RevealMap:return new Su(e,t);case $t.RevealAroundWaypoint:return new vu(e,t);case $t.PlaySoundFx:return new fu(e,t);case $t.PlaySpeech:return new wu(e,t);case $t.ForceTrigger:return new au(e,t);case $t.TimerStart:return new Du(e,t);case $t.TimerStop:return new Mu(e,t);case $t.TimerExtend:return new Pu(e,t);case $t.TimerShorten:return new Ru(e,t);case $t.TimerSet:return new Nu(e,t);case $t.GlobalSet:return new nu(e,t,!0);case $t.GlobalClear:return new nu(e,t,!1);case $t.DestroyObject:return new Jc(e,t);case $t.AddOneTimeSuperWeapon:return new Hc(e,t,!0);case $t.AddRepeatingSuperWeapon:return new Hc(e,t,!1);case $t.AllChangeHouse:return new $c(e,t);case $t.ResizePlayerView:return new bu(e,t);case $t.PlayAnimAt:return new pu(e,t);case $t.DetonateWarhead:return new iu(e,t);case $t.ReshroudMap:return new Tu(e,t);case $t.EnableTrigger:return new Fu(e,t,!0);case $t.DisableTrigger:return new Fu(e,t,!1);case $t.CreateRadarEvent:return new Kc(e,t);case $t.LocalSet:return new lu(e,t,!0);case $t.LocalClear:return new lu(e,t,!1);case $t.SellBuilding:return new _u(e,t);case $t.TurnOffBuilding:return new ju(e,t,!1);case $t.TurnOnBuilding:return new ju(e,t,!0);case $t.ApplyOneHundredDamage:return new Gc(e,t,100);case $t.DestroyTag:return new eu(e,t);case $t.SetAmbientStep:return new Au(e,t);case $t.SetAmbientRate:return new Iu(e,t);case $t.SetAmbientLight:return new ku(e,t);case $t.NukeStrike:return new uu(e,t);case $t.PlaySoundFxAt:return new mu(e,t);case $t.UnrevealAroundWaypoint:return new Uu(e,t);case $t.LightningStrike:return new hu(e,t);case $t.TimerText:return new Lu(e,t);case $t.CreateCrate:return new Yc(e,t);case $t.IronCurtainAt:return new ou(e,t);case $t.EvictOccupiers:return new su(e,t);case $t.Cheer:return new Qc(e,t);case $t.StopSoundsAt:return new Bu(e,t);default:throw new Error(`Unhandled action type "${$t[e.type]}"`)}}}class zu{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 Vu extends zu{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 Hu extends zu{check(e){return!0}}class Gu extends zu{check(s,e){return e.filter(e=>{if(e.type!==ts.ObjectAttacked)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attacker?.player;return(!i||!s.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class $u extends zu{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==ts.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 qu extends zu{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 Xu extends zu{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===ts.ObjectSpawn&&e.gameObject.type===this.objectType&&e.gameObject.rules.index===this.objectIndex)}}class Qu extends zu{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===ts.EnterTile&&i.source.owner===this.player){let e=new Is(t.map.tileOccupation);if(e.tileDistance(i.target,this.waypointTile)<2)return!0}return!1}}class Zu extends zu{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits<this.threshold}}class Yu extends zu{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits>this.threshold}}class Ku extends zu{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!==ts.ObjectDestroy)return!1;let t=e.target;return!(!t.isBuilding()||t.owner.country?.id!==this.houseId)&&!t.owner.buildings.size})&&(this.allDestroyed=!0)}}class Ju extends zu{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!==ts.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 ed extends zu{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!==ts.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 td extends zu{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!==ts.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 id extends zu{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!==ts.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 sd extends zu{check(s,e){return e.filter(e=>{if(e.type!==ts.ObjectDestroy)return!1;let t=e.target;if(!t.isOverlay()||!t.isBridge())return!1;e=t.bridgeTrait?.bridgeSpec;if(!e)return!1;let i=s.map.bridges.findAllBridgeTiles(e);return i.find(e=>this.targets.includes(e))}).map(e=>e.target.tile)}}class rd extends zu{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===ts.ObjectDestroy){let e=i.target;e.isBuilding()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class ad extends zu{check(s,e){return e.filter(e=>{if(e.type!==ts.ObjectDestroy)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attackerInfo?.player;return(!i||!s.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class nd extends zu{check(e,t){return t.filter(e=>{if(e.type!==ts.ObjectDestroy&&e.type!==ts.ObjectOwnerChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class od extends zu{constructor(){super(...arguments),this.eventsFilter=[ts.ObjectDestroy,ts.ObjectOwnerChange,ts.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 hd extends zu{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===ts.ObjectDestroy){let e=i.target;e.isUnit()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class ld extends zu{constructor(e,t){super(e,t),this.timerTicks=Number(this.event.params[1])*Ls.BASE_TICKS_PER_SECOND}check(e){return e.currentTick>this.timerTicks}}class cd extends zu{constructor(e,t){super(e,t),this.elapsedTicks=0,this.timerTicks=Number(this.event.params[1])*Ls.BASE_TICKS_PER_SECOND}check(e){return this.elapsedTicks++>this.timerTicks}reset(){this.elapsedTicks=0}}class ud extends zu{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>(e.type===ts.EnterObject||e.type===ts.EnterTile)&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class dd extends zu{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 pd extends zu{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==ts.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 gd extends zu{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==ts.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 md extends zu{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 fd extends zu{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 yd extends zu{check(e){return!1}}class wd extends zu{check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.factoryTrait)return!1;return!0}}class Td extends zu{check(e,t){return t.some(e=>e.type===ts.CratePickup)}}class bd extends zu{check(e,t){return t.filter(e=>e.type===ts.CratePickup&&this.targets.includes(e.source)).map(e=>e.source)}}class vd extends zu{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]))*Ls.BASE_TICKS_PER_SECOND),this.elapsedTicks++>this.timerTicks}reset(){this.timerTicks=void 0,this.elapsedTicks=0}}class Sd extends zu{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>e.type===ts.BuildingInfiltration&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class _d extends zu{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==ts.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 kd extends zu{constructor(e,t){super(e,t),this.infantryIdx=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==ts.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 Od extends zu{check(e,t){return t.some(e=>e.type===ts.TimerExpire)}}class Id{create(e,t){switch(e.type){case Gt.NoEvent:return new yd(e,t);case Gt.EnteredBy:return new ud(e,t);case Gt.SpiedBy:return new Sd(e,t);case Gt.AttackedByAny:return new Gu(e,t);case Gt.DestroyedByAny:return new ad(e,t);case Gt.AnyEvent:return new Hu(e,t);case Gt.DestroyedAllUnits:return new ed(e,t);case Gt.DestroyedAllBuildings:return new Ku(e,t);case Gt.DestroyedAll:return new Ju(e,t);case Gt.CreditsExceed:return new Yu(e,t);case Gt.ElapsedTime:return new cd(e,t);case Gt.MissionTimerExpired:return new Od(e,t);case Gt.DestroyedBuildings:return new rd(e,t);case Gt.DestroyedUnits:return new hd(e,t);case Gt.NoFactoriesLeft:return new wd(e,t);case Gt.BuildBuilding:return new Xu(e,t,Ct.Building);case Gt.BuildUnit:return new Xu(e,t,Ct.Vehicle);case Gt.BuildInfantry:return new Xu(e,t,Ct.Infantry);case Gt.BuildAircraft:return new Xu(e,t,Ct.Aircraft);case Gt.GlobalIsSet:return new dd(e,t,!0);case Gt.GlobalIsCleared:return new dd(e,t,!1);case Gt.DestroyedOrCaptured:return new nd(e,t);case Gt.LowPower:return new fd(e,t);case Gt.DestroyedBridge:return new sd(e,t);case Gt.BuildingExists:return new qu(e,t);case Gt.ComesNearWaypoint:return new Qu(e,t);case Gt.LocalIsSet:return new md(e,t,!0);case Gt.LocalIsCleared:return new md(e,t,!1);case Gt.FirstDamagedCombat:return new gd(e,t,100);case Gt.HalfHealthCombat:return new gd(e,t,50);case Gt.QuarterHealthCombat:return new gd(e,t,25);case Gt.FirstDamagedAny:return new pd(e,t,100);case Gt.HalfHealthAny:return new pd(e,t,50);case Gt.QuarterHealthAny:return new pd(e,t,25);case Gt.AttackedByHouse:return new $u(e,t);case Gt.AmbientLightBelow:return new Vu(e,t,"below");case Gt.AmbientLightAbove:return new Vu(e,t,"above");case Gt.ElapsedScenarioTime:return new ld(e,t);case Gt.DestroyedOrCapturedOrInfiltrated:return new od(e,t);case Gt.PickupCrate:return new bd(e,t);case Gt.PickupCrateAny:return new Td(e,t);case Gt.RandomDelay:return new vd(e,t);case Gt.CreditsBelow:return new Zu(e,t);case Gt.SpyEnteringAsHouse:return new _d(e,t);case Gt.SpyEnteringAsInfantry:return new kd(e,t);case Gt.DestroyedAllUnitsNaval:return new id(e,t);case Gt.DestroyedAllUnitsLand:return new td(e,t);case Gt.BuildingNotExists:return new qu(e,t,!0);default:throw new Error(`Unhandled trigger event type "${Gt[e.type]}"`)}}}class Ad{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 Cd{constructor(){this.disposables=new Ad,this.triggerInstances=new Map,this.targetsByTag=new Map,this.conditionFactory=new Id,this.executorFactory=new Wu,this.pendingGameEvents=[],this.globalVariables=new Map,this.localVariables=new Map}init(i){var t,e,s,r,a=i.map.getInitialMapObjects()["technos"];for(let t of a)if(t.tag){let e=this.targetsByTag.get(t.tag);e||(e=[],this.targetsByTag.set(t.tag,e));var n=i.map.tiles.getByMapCoords(t.rx,t.ry);!n||(n=i.map.getObjectsOnTile(n).find(e=>e.name===t.name&&e.type===t.type))&&e.push(n)}for(t of i.map.getCellTags()){var o=i.map.tiles.getByMapCoords(t.coords.x,t.coords.y);if(o){let e=this.targetsByTag.get(t.tagId);e||(e=[],this.targetsByTag.set(t.tagId,e)),e.push(o)}else console.warn(`CellTag out of bounds at (${t.coords.x}, ${t.coords.y}). Skipping.`)}for([e,s]of i.map.getVariables())this.localVariables.set(e,s.clone());for(r of i.map.getTriggers())this.triggerInstances.set(r.id,this.createTriggerInstance(r,i));this.disposables.add(i.events.subscribe(e=>this.pendingGameEvents.push(e)))}createTriggerInstance(i,s){let r=this.targetsByTag.get(i.tag.id)??[];return{trigger:i,conditions:i.events.map(e=>{let t=this.conditionFactory.create(e,i);return t.setTargets(r),t.init(s),t}).sort((e,t)=>Number(t.blocking)-Number(e.blocking)),targets:r,remainingTargets:new Set(i.tag.repeatType===Ht.OnceAll?r:[]),disabled:i.disabled,finished:!1}}update(i){var s,r=this.pendingGameEvents.splice(0,this.pendingGameEvents.length);for(s of this.triggerInstances.values())if(!s.finished&&!s.disabled){let e=!0,t=[];for(var a of s.conditions){var n=a.check(i,r);if("boolean"==typeof n?n||(e=!1):n.length?t.push(...n):e=!1,a.blocking&&!e)break}if(e){var o=s.trigger;s.conditions.forEach(e=>e.reset?.());let e=[];if(o.tag.repeatType===Ht.OnceAll){for(var h of t)s.remainingTargets.delete(h);if(s.remainingTargets.size)continue;e=t.length?[t[t.length-1]]:[]}else e=s.targets;this.executeActions(o,e,i),o.tag.repeatType!==Ht.Repeat&&(s.finished=!0)}}}executeActions(t,i,s){for(var r of t.actions){let e=this.executorFactory.create(r,t);e.execute(s,i)}}setTriggerEnabled(e,t){let i=this.triggerInstances.get(e);i&&(i.disabled=!t)}forceTrigger(e,t){e=this.triggerInstances.get(e);e&&this.executeActions(e.trigger,e.targets,t)}destroyTrigger(e){this.triggerInstances.delete(e)}destroyTag(e){let t=[];for(var[i,s]of this.triggerInstances)s.trigger.tag.id===e&&t.push(i);for(var r of t)this.destroyTrigger(r)}getGlobalVariable(e){return!!this.globalVariables.get(e)?.value}toggleGlobalVariable(e,t){let i=this.globalVariables.get(e);void 0===i?this.globalVariables.set(e,new Ti("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 Ti("No name",t)):i.value=t}dispose(){this.disposables.dispose()}}class Bd{constructor(e){this.target=e,this.type=ts.TimerExpire}}class xd{constructor(){this.ticks=0,this.running=!1}getSeconds(){return Math.floor(this.ticks/Ls.BASE_TICKS_PER_SECOND)}setSeconds(e){this.ticks=Math.max(0,Math.floor(Ls.BASE_TICKS_PER_SECOND*e))}addSeconds(e){this.ticks=Math.max(0,this.ticks+Math.floor(Ls.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 Bd(this))))}}(Ec=Ec||{}).onAdd=Symbol(),(r=Pc=Pc||{})[r.NotStarted=0]="NotStarted",r[r.Started=1]="Started",r[r.Ended=2]="Ended";class Ed{constructor(e,t,i,s,r,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 xd,this._onEnd=new io,this.afterTickCallbacks=[],this.events=new Pl,this.traits=new Oa,this.world=e,this.map=t,this.rules=i,this.art=s,this.id=r,this.startTimestamp=a,this.prng=new zc(Number(r+""+a)),this.gameOpts=n,this.gameModeType=o,this.playerList=h,this.unitSelection=l,this.alliances=c,this.desiredSpeed=new dl(Ls.computeGameSpeed(n.gameSpeed)),this.speed=new dl(this.desiredSpeed.value),this.nextObjectId=u,this.objectFactory=d,this.botManager=class{constructor(e,t,i,s,r){this.game=e,this.actionFactory=t,this.actionQueue=i,this.gameApi=s,this.eventsApi=r,this.bots=new Map}static factory(e,t){return new this(e,t,new Fl,new yc(e,!0),new Jl(e.events))}init(){var e,t;for(e of this.game.getCombatants().filter(e=>e.isAi))this.bots.set(e,new Bc(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),this.triggers=new Cd}get onEnd(){return this._onEnd.asEvent()}addPlayer(e){this.playerList.addPlayer(e),this.constructionWorkers.set(e,this.createConstructionWorker(e))}getPlayer(e){return this.playerList.getPlayerAt(e)}getPlayerByName(e){return this.playerList.getPlayerByName(e)}getAiPlayerName(e){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){return new xl(e,this.rules,this.art,this.map,this)}getConstructionWorker(e){var t=this.constructionWorkers.get(e);if(!t)throw new Error(`No construction worker found for player "${e.name}"`);return t}getUnitSelection(){return this.unitSelection}init(e){this.localPlayer=e,this.createMapObjects(),this.createPlayerInitialUnits(),this.map.terrain.computeAllPassabilityGraphs(),this.mapShroudTrait.init(this),this.crateGeneratorTrait.init(this),this.playerList.getAll().forEach(e=>e.credits=this.gameOpts.credits),this.rules.mpDialogSettings.alliesAllowed&&this.createInitialTeams()}start(){this.status=Pc.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=>As(e)?e.name:this.getAiPlayerName(e));if(1<i.length)for(let t=0;t<i.length-1;t++)for(let e=t+1;e<i.length;e++){var s=this.getPlayerByName(i[t]),r=this.getPlayerByName(i[e]),r=this.alliances.setAlliance(s,r,Wh.Formed);this.onAllianceChange(r,s,!0)}}}createMapObjects(){var e=this.rules.general.harvesterUnit.every(e=>!W(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 s,r,a=i.name;this.validateMapObjectRulesAndArt(a,Ct.Terrain)&&((s=this.map.tiles.getByMapCoords(i.rx,i.ry))?(r=this.rules.getObject(a,Ct.Terrain),t&&r.spawnsTiberium||(a=this.createObject(Ct.Terrain,a),this.spawnObject(a,s))):console.warn(`Invalid map object location (${i.rx},${i.ry})`,i))}}createInitialMapOverlays(e,s){let r=new Map,a=new Map;for(var n of e){var o=this.rules.getOverlayName(n.id);if(this.validateMapObjectRulesAndArt(o,Ct.Overlay)){let e=this.createObject(Ct.Overlay,o);e.overlayId=n.id,e.value=n.value;let t=n.rx,i=n.ry;e.isBridge()&&e.isHighBridge()&&(e.position.tileElevation=4,t+=e.isXBridge()?0:-1,i+=e.isXBridge()?-1:0);var h=this.map.tiles.getByMapCoords(t,i);if(h)if(e.rules.tiberium&&(o=Ha.getOverlayTibType(n.id),void 0!==(o=ln.calculateOverlayId(o,h))&&o!==n.id&&(e.dispose(),e=this.createObject(Ct.Overlay,this.rules.getOverlayName(o)),e.overlayId=o,e.value=n.value)),Wa.isLowBridge(n.id))Wa.isBridgePlaceholder(n.id)||(r.set(h,n.value),1===n.value?a.set(h,e):e.dispose());else{if(e.isTiberium()){if(![ra.Ore,ra.Gems,ra.Vinifera].includes(Ha.getOverlayTibType(e.overlayId))){console.warn(`Found unsupported TS tiberium overlay ${e.overlayId} @${h.rx},${h.ry}. Skipping.`);continue}if(this.map.getObjectsOnTile(h).find(e=>e.isTerrain())){e.dispose();continue}}s&&e.isTiberium()?e.dispose():this.spawnObject(e,h)}else console.warn(`Invalid map object location (${t},${i})`,n),e.dispose()}}for(var[t,i]of a){var l=i.isXBridge(),c=this.map.tiles.getByMapCoords(t.rx+(l?0:-1),t.ry+(l?-1:0)),l=this.map.tiles.getByMapCoords(t.rx+(l?0:1),t.ry+(l?1:0));c&&l&&(0===r.get(c)||2===r.get(l))?(i.value=0,this.spawnObject(i,c)):(i.dispose(),console.warn(`Invalid bridge segment @${t.rx},${t.ry}. Skipping.`))}var u,d=[...a.keys()].filter(e=>this.map.bridges.getPieceAtTile(e)?.headType!==Uh.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=Wa.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,s=this.map.tiles.getByMapCoords(t.rx,t.ry);s?(i=this.createObject(Ct.Smudge,i),this.spawnObject(i,s)):console.warn(`Invalid map object location (${t.rx},${t.ry})`,t)}}createInitialMapTechnos(e){let t=new Map(this.playerList.getAll().filter(e=>!!e.country).map(e=>[e.country.name,e])),s=this.map.getTags();for(let i of e){var r=i.name;if(this.validateMapObjectRulesAndArt(r,i.type)){var a=this.map.tiles.getByMapCoords(i.rx,i.ry);if(a){var n=t.get(i.owner);if(n){if(n.isNeutral){let t=this.createObject(i.type,r);i.tag&&(t.tag=s.find(e=>e.id===i.tag)),t.healthTrait.health=i.health/256*100;let e=!1;if(!t.healthTrait.health){if(!t.isBuilding()||!t.rules.leaveRubble){t.dispose();continue}e=!0}if(i.isInfantry()||i.isVehicle()||i.isAircraft()){t.direction=(-i.direction/256*360+360)%360,i.isInfantry()&&(t.position.subCell=i.subCell);let e=!1;i.onBridge&&(void 0===a.onBridgeLandType?console.warn(`Cannot place unit "${i.name}" on a bridge because `+`no bridge was found at ${a.rx}, ${a.ry}`):e=!0),t.onBridge=e,t.zone=_s(e?a.onBridgeLandType:a.landType),e&&(t.position.tileElevation+=this.map.tileOccupation.getBridgeOnTile(a)?.tileElevation??0),i.veterancy&&t.veteranTrait?.setRelativeXP(i.veterancy)}else t.poweredTrait?.setTurnedOn(i.poweredOn);this.changeObjectOwner(t,n),this.spawnObject(t,a),e&&this.destroyObject(t,void 0,!0)}}else console.warn(`Invalid owner "${i.owner}" for map object`,i)}else console.warn(`Invalid map object location (${i.rx},${i.ry})`,i)}}}validateMapObjectRulesAndArt(e,t){return this.rules.hasObject(e,t)?!!this.art.hasObject(e,t)||(console.warn(`Map object '${e}' has no art section. Skipping.`),!1):(console.warn(`Map object '${e}' has no rules section. Skipping.`),!1)}createPlayerInitialUnits(){let e=this.playerList.getCombatants().map(e=>e.country);var i=[...this.rules.infantryRules.values(),...this.rules.vehicleRules.values()].filter(t=>t.allowedToStartInMultiplayer&&!t.naval&&-1!==t.techLevel&&t.techLevel<=this.rules.mpDialogSettings.techLevel&&!this.rules.general.baseUnit.includes(t.name)&&e.some(e=>t.isAvailableTo(e)&&t.hasOwner(e)));for(let h of this.playerList.getCombatants()){var l=this.map.startingLocations[h.startLocation],c=this.map.tiles.getByMapCoords(l.x,l.y);let t=this.rules.general.baseUnit.find(e=>{let t=this.rules.getObject(e,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=El.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 s=[],r=!1,a=new ao(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(r||(t=a.getNextTile(),t?s.push(t):r=!0),r&&s.length){var g=s[o];let e=n.get(g);e||(e=new ao(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)%s.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 Na.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(Yr.Elite):t.country.hasVeteranUnit(e.type,e.name)&&e.veteranTrait.setVeteranLevel(Yr.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,s,r){let a=this.createObject(Ct.Projectile,e);return a.fromWeapon=i,a.fromObject=t,a.fromPlayer=t.owner,a.target=s,a.isShrapnel=r,a}createLooseProjectile(e,t,i){var s=this.rules.getWeapon(e),r=s.projectile,a=this.rules.getProjectile(r),e=this.rules.getWarhead(s.warhead),e={minRange:0,projectileRules:a,range:Number.POSITIVE_INFINITY,rules:s,speed:Ka.computeSpeed(s,a),type:ni.Primary,warhead:new Xa(e)};let n=this.createObject(Ct.Projectile,r);return n.fromWeapon=e,n.fromObject=void 0,n.fromPlayer=t,n.target=i,n}createSuperWeapon(e,t,i=!1){var s=this.rules.getSuperWeapon(e);return new Us(e,s,t,i)}createTarget(e,t){return new So(e,t,this.map.tileOccupation)}isValidTarget(e){if(e){if(!e.isSpawned||e.isCrashing)return!1;if(!(e.rules.legalTarget||e.isBuilding()&&e.rules.hospital))return!1;if(e.isBuilding()&&e.rules.invisibleInGame)return!1}return!0}spawnObject(e,t){if(e.isTechno()&&e.limboData)throw new Error(`Object ${e.name}#${e.id} is in limbo. Use unlimboObject instead or clear limboData first`);this.doSpawnObject(e,t)}unspawnObject(e){e.isTechno()&&e.owner&&e.owner.removeOwnedObject(e),this.doUnspawnObject(e)}limboObject(e,t){e.limboData=t,this.doUnspawnObject(e)}unlimboObject(e,t,i=!1){var s=e.limboData;if(!s)throw new Error(`Object ${e.name}#${e.id} has no limboData attached`);e.limboData=void 0,this.doSpawnObject(e,t);let r=this.getUnitSelection();s.selected&&!i&&r.addToSelection(e),void 0!==s.controlGroup&&r.addUnitsToGroup(s.controlGroup,[e],!1)}doSpawnObject(t,e){var i,s;t.position.tile=e,t.isBuilding()&&(s=t.art.foundationCenter,i=e.rx+s.x,s=e.ry+s.y,t.centerTile=this.map.tiles.getByMapCoords(i,s)??this.map.tiles.getPlaceholderTile(i,s)),this.world.spawnObject(t),(t.cachedTraits.tick.length||t.isProjectile()||t.isDebris()||t.isTechno())&&this.updatableObjects.add(t),t.isTechno()&&this.map.technosByTile.add(t),t.isProjectile()||t.isDebris()||this.map.tileOccupation.occupyTileRange(e,t),t.art.canHideThings&&this.map.tileOcclusion.addOccluder(t),t.onSpawn(this),this.traits.filter(Vh).forEach(e=>{e[Vh.onSpawn](t,this)}),this.events.dispatch(new Ll(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(Hh).forEach(e=>{e[Hh.onUnspawn](t,this)}),this.events.dispatch(new Ml(t))}destroyObject(t,i,e=!1,s=!1){if(t.isDestroyed)throw new Error(`Object with ID "${t.id}" is already destroyed`);if(t.isTechno()){let e=t.mindControllableTrait?.getOriginalOwner()??t.owner;!i||t.isBuilding()&&!e.isCombatant()||(i.player.addUnitsKilled(t.type,1),i.player===e||this.alliances.areAllied(i.player,e)||(i.player.score+=t.rules.points)),e.isNeutral||e.addUnitsLost(t.type,1)}if(t.isDestroyed=!0,t.healthTrait&&(t.healthTrait.health=0),t.onDestroy(this,i,e),this.traits.filter(qh).forEach(e=>{e[qh.onDestroy](t,this,i)}),i?.obj?.traits.filter(Dn).forEach(e=>{e[Dn.onDestroy](i.obj,t,i.weapon,this)}),this.events.dispatch(new Nl(t,i,s)),t.isBuilding()&&t.rules.leaveRubble&&t.deathType!==Wr.Temporal){t.owner.removeOwnedObject(t),this.unitSelection.cleanupUnit(t);s=this.map.tileOccupation.calculateTilesForGameObject(t.tile,t);this.map.terrain.invalidateTiles(s),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(Hh).forEach(e=>{e[Hh.onUnspawn](t,this)}),this.events.dispatch(new Ml(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(Gh).forEach(e=>{e[Gh.onChange](t,i,this)}),t.onOwnerChange(i,this),this.events.dispatch(new Dl(t,i)))}addObjectTrait(t,i){t.addTrait(i),this.traits.filter(Ec).forEach(e=>{e[Ec.onAdd](t,i,this)})}onAllianceChange(t,e,i){this.events.dispatch(new xc(t,i?bc.Formed:bc.Broken,e)),this.traits.filter($h).forEach(e=>{e[$h.onChange](t,i,this)})}update(){if(this.status!==Pc.NotStarted){this.botManager.update(),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(Bs).forEach(e=>{e[Bs.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/Ls.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=Pc.Ended,this._onEnd.dispatch(this,void 0))}updateDefeatedPlayers(e){let s=this.stalemateDetectTrait?.isStale()&&0===this.stalemateDetectTrait.getCountdownTicks(),r=this.gameOpts.shortGame;e.forEach(t=>{let i;if(s)i=!0;else{let e;e=r?(e=[...t.getOwnedObjectsByType(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 Rl(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 V([...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()}}class Pd{constructor(e){this.map=e,this.radSites=new Map,this.radLevelByTile=new Map,this._onChange=new io}get onChange(){return this._onChange.asEvent()}getRadLevel(e){return this.radLevelByTile.get(e)}[Bs.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 Xa(a.rules.getWarhead(n.radSiteWarhead));this.radLevelByTile.forEach((e,t)=>{var i,s,r=Math.min(n.radLevelMax,e)*n.radLevelFactor;for(i of a.map.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&!(e.isInfantry()&&e.stance===Ds.Paradrop&&1<e.tileElevation)))o.canDamage(i,t,i.zone)&&(0<(s=o.computeDamage(r,i))&&o.inflictDamage(s,i,void 0,a,!0))})}applyDecay(s){var e=new Set(this.radLevelByTile.keys());this.radLevelByTile.clear(),this.radSites.forEach(({radLevel:e,radius:t},i)=>{e-=s;e<=0?this.radSites.delete(i):(this.radSites.set(i,{radLevel:e,radius:t}),this.setRadLevelAround(i,t,e))}),this._onChange.dispatch(this,e)}createRadSite(e,t,i){(t-=this.radSites.get(e)?.radLevel??0)<=0||(this.radSites.set(e,{radLevel:(this.radSites.get(e)?.radLevel??0)+t,radius:i}),(t=this.setRadLevelAround(e,i,t)).size&&this._onChange.dispatch(this,t))}setRadLevelAround(e,t,i){let s=new Is(this.map.tileOccupation),r=new Fs(this.map.tiles,this.map.mapBounds,e,{width:1,height:1},0,t,e=>!!e,!1);var a;let n=new Set;for(;a=r.getNextTile();){var o=s.tileDistance(e,a);o<=t&&(o=Math.ceil(z(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 Nd{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 Rd{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 Dd{constructor(){this.unitSelectionByPlayer=new Map}getOrCreateSelection(e){let t=this.unitSelectionByPlayer.get(e);return t||(t=new Rd(e),this.unitSelectionByPlayer.set(e,t)),t}}class Md extends jl{constructor(){super(Xh.NoAction)}process(){}}class Ld{create(){return new Md}}class Fd{constructor(e){this.target=e,this.type=ts.BuildingPlace}}class jd{constructor(e,t,i){this.name=e,this.player=t,this.tile=i,this.type=ts.BuildingFailedPlace}}(Nc=Nc||{}).onPlace=Symbol();class Ud extends jl{constructor(e){super(Xh.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(Nc).forEach(e=>{e[Nc.onPlace](i,this.game)}),this.game.events.dispatch(new Fd(i))):this.game.events.dispatch(new jd(this.name,t,e))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}tryPlaceBuilding(s,r){var a=this.game.rules.getBuilding(this.name);if(s.production){let i=s.production.getQueueForObject(a);if(i.status===gn.Ready&&i.getFirst().rules===a){let t=this.game.getConstructionWorker(s);if(s.production.isAvailableForProduction(a)){let e=t.canBuildAt(this.name,r,void 0,!0);if(!e.filter(e=>!e.buildable).length){r=t.placeAt(this.name,r,!0);s.addUnitsBuilt(Ct.Building,1),i.shift(a,1);let e=s.production.getPrimaryFactory(Ki.BuildingType);return e&&(e.factoryTrait.status=Tn.Delivering),r[0]}}}}}}class Wd{constructor(e){this.game=e}create(){return new Ud(this.game)}}class zd extends jl{constructor(e){super(Xh.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!==kn.Ready||e.warpedOutTrait.isActive()||this.game.sellTrait.sell(e))}}}class Vd{constructor(e){this.game=e}create(){return new zd(this.game)}}class Hd extends jl{constructor(e,t){super(Xh.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 Gd{constructor(e,t){this.game=e,this.orderActionContext=t}create(){return new Hd(this.game,this.orderActionContext)}}const $d=[In.Occupy,In.Dock,In.Attack,In.Capture,In.Repair,In.EnterTransport,In.PlaceBomb,In.Deploy,In.Gather];(r=Rc=Rc||{})[r.Default=0]="Default",r[r.Mini=1]="Mini",r[r.Scroll=2]="Scroll",r[r.NoScroll=10]="NoScroll",r[r.Select=18]="Select",r[r.Move=31]="Move",r[r.NoMove=41]="NoMove",r[r.MoveMini=42]="MoveMini",r[r.NoActionMini=52]="NoActionMini",r[r.AttackRange=53]="AttackRange",r[r.AttackNoRange=58]="AttackNoRange",r[r.AttackMini=63]="AttackMini",r[r.Guard=68]="Guard",r[r.GuardMini=73]="GuardMini",r[r.Unknown1=78]="Unknown1",r[r.Unknown2=88]="Unknown2",r[r.Occupy=89]="Occupy",r[r.NoOccupy=99]="NoOccupy",r[r.OccupyMini=100]="OccupyMini",r[r.Deploy=110]="Deploy",r[r.NoDeploy=119]="NoDeploy",r[r.Unknown3=120]="Unknown3",r[r.Sell=129]="Sell",r[r.SellMini=139]="SellMini",r[r.NoSell=149]="NoSell",r[r.RepairMove=150]="RepairMove",r[r.SideRepair=170]="SideRepair",r[r.NoRepair=190]="NoRepair",r[r.Unknown4=191]="Unknown4",r[r.Unknown5=199]="Unknown5",r[r.Dynamite=204]="Dynamite",r[r.Unknown6=209]="Unknown6",r[r.Unknown7=214]="Unknown7",r[r.Unknown8=219]="Unknown8",r[r.Unknown9=224]="Unknown9",r[r.Unknown10=229]="Unknown10",r[r.Unknown11=234]="Unknown11",r[r.Unknwon12=239]="Unknwon12",r[r.Unknown13=249]="Unknown13",r[r.Para=259]="Para",r[r.Unknown14=269]="Unknown14",r[r.Storm=279]="Storm",r[r.Unknown15=299]="Unknown15",r[r.C4=309]="C4",r[r.Nuke=319]="Nuke",r[r.Unknown16=329]="Unknown16",r[r.Power=339]="Power",r[r.Unknown17=345]="Unknown17",r[r.Iron=346]="Iron",r[r.Unknown18=351]="Unknown18",r[r.Unknown19=356]="Unknown19",r[r.Chrono=357]="Chrono",r[r.DefuseBomb=369]="DefuseBomb",r[r.NoAction=384]="NoAction",r[r.Pan=385]="Pan",r[r.Unknown21=394]="Unknown21",r[r.AttackMove=404]="AttackMove",r[r.Unknown23=413]="Unknown23",r[r.Unknown24=422]="Unknown24",r[r.Unknown25=431]="Unknown25",r[r.Unknown26=432]="Unknown26",r[r.Unknown27=433]="Unknown27",r[r.Unknown28=434]="Unknown28",r[r.Beacon=435]="Beacon",(r=Dc=Dc||{})[r.None=0]="None",r[r.Move=1]="Move",r[r.Attack=2]="Attack",r[r.Enter=3]="Enter",r[r.Capture=4]="Capture",r[r.SpecialAttack=5]="SpecialAttack";class qd{constructor(e){this.orderType=e,this.targetOptional=!0,this.minimapAllowed=!0,this.singleSelectionRequired=!1,this.terminal=!1,this.feedbackType=Dc.None}getPointerType(e,t){return e?Rc.Mini:Rc.Default}set(e,t){return this.sourceObject=e,this.target=t,this}isValid(){return!0}isAllowed(){return!0}onAdd(e,t){return!0}}class Xd{constructor(e,t){this.from=e,this.to=t,this.type=ts.ObjectMorph}}class Qd extends Vs{constructor(e){super(),this.game=e}onStart(e){if(!this.morphInto)throw new Error("morphInto not set");e.isBuilding()&&e.buildStatus!==kn.BuildDown&&this.morphInto.type!==Ct.Building&&this.children.push(new Bl),e.isVehicle()&&this.morphInto.type===Ct.Building&&this.children.push(new Tr(180))}onTick(s){if(!this.morphInto)throw new Error("morphInto not set");let e=this.game.getUnitSelection();var t=e.isSelected(s),i=e.getOrCreateSelectionModel(s).getControlGroupNumber(),r=this.morphInto;let a;if(r.type===Ct.Building){if(s.isVehicle()&&s.parasiteableTrait?.isInfested())return!0;let t=s.tile,e=this.game.getConstructionWorker(s.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(s),s.dispose(),[a]=e.placeAt(this.morphInto.name,t),a.healthTrait.health=s.healthTrait.health}else{let e=s.unitOrderTrait.getTasks().filter(e=>e instanceof ba);this.game.unspawnObject(s),s.dispose(),a=this.game.createUnitForPlayer(this.morphInto,s.owner),a.direction=180,a.healthTrait.health=s.healthTrait.health;r=s.art.foundationCenter;this.game.spawnObject(a,this.game.map.tiles.getByMapCoords(s.tile.rx+r.x,s.tile.ry+r.y)),e.forEach(e=>a.unitOrderTrait.addTask(e))}return a.purchaseValue=s.purchaseValue,s.replacedBy=a,t&&e.addToSelection(a),void 0!==i&&e.addUnitsToGroup(i,[a],!1),this.game.events.dispatch(new Xd(s,a)),!0}}class Zd extends Qd{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 Yd{constructor(e){this.target=e,this.type=ts.RallyPointChange}}class Kd extends qd{constructor(e,t,i,s=!1){super(s?In.ForceMove:In.Move),this.game=e,this.map=t,this.unitSelection=i,this.forceMove=s,this.targetOptional=!1,this.feedbackType=Dc.Move}getPointerType(e){let t=this.isAllowed();var i,s,r,a;return!t||this.sourceObject.isBuilding()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)||(i=!!this.target.getBridge(),s=this.sourceObject.rules.speedType,r=this.sourceObject.rules.movementZone===ii.Fly,a=this.map.getObjectsOnTile(this.target.tile).some(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()),t=r?this.sourceObject.rules.balloonHover||0<this.map.terrain.getPassableSpeed(this.target.tile,Kt.Amphibious,i)&&!a:0<this.map.terrain.getPassableSpeed(this.target.tile,s,i)&&!a&&!(this.target.obj?.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))),e?t?Rc.MoveMini:Rc.NoActionMini:t?Rc.Move:Rc.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 Zd(this.game),new ba(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t})]:e.isUnit()?[new ba(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===kn.BuildUp)return this.sourceObject.unitOrderTrait.getTasks().find(e=>e instanceof Ro)?.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 Yd(this.sourceObject)),!1;if(!e&&this.isValid()&&this.isAllowed()){this.sourceObject.attackTrait?.cancelOpportunityFire();let e=t.find(e=>e.constructor===ba&&!e.isCancelling());if(e)return e.updateTarget(this.target.tile,!!this.target.getBridge()),e.children.length&&e.children[0]instanceof ko&&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===ko&&!e.isCancelling());e&&e.forceCancel(this.sourceObject)&&t.splice(t.indexOf(e))}}return!0}}class Jd extends Qd{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 ep{constructor(e,t){this.unit=e,this.deployType=t,this.type=ts.UnitDeployUndeploy}}class tp{constructor(e){this.target=e,this.type=ts.PrimaryFactoryChange}}(r=Mc=Mc||{})[r.None=0]="None",r[r.OnlyPassengers=1]="OnlyPassengers",r[r.All=2]="All";class ip extends Vs{constructor(e,t){super(),this.game=e,this.soft=t,this.evacState=Mc.None,this.evacTries=0,this.turnPerformed=!1,this.preventLanding=!1}forceEvac(){this.evacState=Mc.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!==Mc.OnlyPassengers&&1!==t.units.length||!e.rules.gunner?Mc.OnlyPassengers:Mc.All)}onTick(e){if(this.isCancelling()||this.evacState===Mc.None)return!0;if(e.zone===Ts.Air)return this.children.push(new da(()=>e.zone!==Ts.Air)),!1;let t=e.transportTrait.units;if(!t.length||e.rules.gunner&&1===t.length&&this.evacState!==Mc.All)return!0;var i=t[t.length-1],s=this.findValidEvacTarget(e,i);if(s&&!this.turnPerformed){this.turnPerformed=!0;var r=(s.dir+180)%360;if(e.direction!==r)return this.children.push(new Tr(r)),!1}return this.evacuateUnit(i,e,s)?(t.pop(),this.children.push(new ua(1/60)),!1):!(++this.evacTries<=3)||(this.children.push(new ua(.05)),!1)}evacuateUnit(e,t,i){if(!i)return!this.soft&&(e.position.tile=t.tile,e.position.tileElevation=t.tileElevation,e.onBridge=t.onBridge,e.zone=t.zone,this.game.destroyObject(e,{player:e.owner}),!0);var{spawnNode:s,moveNode:i}=i;return e.position.tileElevation=s.onBridge?.tileElevation??0,e.onBridge=!!s.onBridge,e.zone=this.game.map.getTileZone(s.tile,!s.onBridge),this.game.unlimboObject(e,s.tile),e.unitOrderTrait.unmarkNextQueuedOrder(),i?e.unitOrderTrait.addTask(new ba(this.game,i.tile,!!i.onBridge)):e.unitOrderTrait.addTask(new Ta(this.game)),this.game.events.dispatch(new Qo(t)),!0}findValidEvacTarget(a,n){let o=this.game.map,h=new $s(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=wr.toMapCoords(l);let i=a.tile,s=t,r;for(let t=1;t<=2;t++){if(2===t){if(!r)break;i=r.tile,s=r.onBridge}var f,y=a.tile.rx+Math.sign(m.x)*t,w=a.tile.ry+Math.sign(m.y)*t,T=o.tiles.getByMapCoords(y,w);if(!T||!o.mapBounds.isWithinBounds(T))break;let e=[o.tileOccupation.getBridgeOnTile(T)];e[0]&&e.push(void 0);for(f of e)if(c=T,u=f,d=s,p=i,0<o.terrain.getPassableSpeed(c,n.rules.speedType,!!u)&&h.isEligibleTile(c,u,d,p)&&!o.terrain.findObstacles({tile:c,onBridge:u},n).length){if(1!==t)return{spawnNode:r,moveNode:{tile:T,onBridge:f},dir:l};r={tile:T,onBridge:f},g={spawnNode:r,moveNode:void 0,dir:l}}}}if(g)return g}}class sp extends qd{constructor(e,t){super(t?In.Deploy:In.DeploySelected),this.game=e,this.targeted=t,this.minimapAllowed=!1,this.getPointerType=()=>this.isAllowed()?Rc.Deploy:Rc.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&&![Ds.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 s=i.moveTrait.currentWaypoint?.tile??i.tile;let t=e.canBuildAt(i.rules.deploysInto,s,[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 ip(this.game,!0)]:e.isBuilding()&&e.rules.factory?void 0:e.isVehicle()&&e.rules.deploysInto?[new Jd(this.game)]:(e.isInfantry()||e.isVehicle())&&e.deployerTrait?[new da(()=>{e.deployerTrait.toggleDeployed(),this.game.events.dispatch(new ep(e,e.deployerTrait.isDeployed()?"undeploy":"deploy"))})]:e.isBuilding()&&e.garrisonTrait?.units.length?[new da(()=>{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 tp(i)),!1;if(i.isVehicle()&&i.transportTrait&&!e&&this.isValid()&&this.isAllowed()){let e=t.find(e=>e.constructor===ip&&!e.isCancelling());if(e)return e.forceEvac(),!1}return!0}}class rp{constructor(e){this.player=e,this.type=ts.Cheer}}class ap{constructor(e){this.target=e,this.type=ts.DeployNotAllowed}}class np extends jl{constructor(e,t,i,s){super(Xh.OrderUnits),this.game=e,this.map=t,this.orderActionContext=i,this.orderFactory=s,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[s,i]=t[2].split(","),i=this.map.tiles.getByMapCoords(Number(s),Number(i));i?(this.target=this.game.createTarget(e,i),this.queue=Boolean(Number(t[3]||"0"))):this.isInvalid=!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?"":`${In[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=[],s=[],i=[],r=[];if(e.forEach(e=>{(e instanceof Kd?t:e.orderType===In.Scatter?s:e.orderType===In.DeploySelected?i:e.orderType===In.Cheer?r:a).push(e)}),t.length&&this.target){let s=this.target.getBridge();var o=t.map(e=>e.sourceObject);let r=new $s(this.map).findPositions(o,this.target.tile,s);t.forEach(e=>{var t=r.get(e.sourceObject),i=!s||s.isHighBridge()?this.map.tileOccupation.getBridgeOnTile(t):s,t=this.game.createTarget(i,t);e.target=t,a.push(e)})}if(s.length){o=s.map(e=>e.sourceObject).filter(e=>e.isInfantry()||e.isVehicle());let i=new wa(this.game).findPositions(o);s.forEach(e=>{var t=i.get(e.sourceObject);t&&(t=this.game.createTarget(t.onBridge,t.tile),e.target=t,a.push(e))})}if(i.length){let t=[];i.forEach(e=>{((e.sourceObject.isInfantry()||e.sourceObject.isVehicle())&&e.sourceObject.deployerTrait?t:a).push(e)});let e=t.filter(e=>!e.sourceObject.deployerTrait.isDeployed());e.length?e.forEach(e=>a.push(e)):t.forEach(e=>a.push(e))}r.length&&(n.cheerCooldownTicks||(n.cheerCooldownTicks=this.game.rules.general.maximumCheerRate,a.push(...r),this.game.events.dispatch(new rp(n)))),a.forEach(e=>e.sourceObject.unitOrderTrait.addOrder(e,this.queue)),this.updateWaypointPaths(a)}}}validateOrders(e){let i=this.orderActionContext.getOrCreateSelection(e);var s,r=i.getSelectedUnits();let t=this.orderFactory.create(this.orderType,i);t.target=this.target;let a=[];for(s of r)if(!(s.owner!==e||s.rules.spawned||s.isDestroyed||s.isCrashing||s.isDisposed||s.warpedOutTrait.isActive()||(t.sourceObject=s,t instanceof sp&&t.isValid()&&!t.isAllowed()&&this.game.events.dispatch(new ap(s)),t.singleSelectionRequired&&1<r.length)))if(t.isValid()&&t.isAllowed()){let e=this.orderFactory.create(this.orderType,i);e.set(s,this.target),a.push(e)}else{let t=!1;for(var n of $d){let e=this.orderFactory.create(n,i);if(e.set(s,this.target),!(e.singleSelectionRequired&&1<r.length)&&(e.targetOptional===!this.target&&e.isValid()&&e.isAllowed())){a.push(e),t=!0;break}}if(!t&&this.target&&this.orderType!==In.Deploy){let e=this.orderFactory.create(In.Move,i);e.set(s,this.target),e.isValid()&&e.isAllowed()&&a.push(e)}}return a}updateWaypointPaths(i){if(this.queue&&this.target){let e=i.map(e=>e.sourceObject);var t=[...new Set(e.map(e=>e.unitOrderTrait.waypointPath).filter(Ma))];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 op extends ba{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 hp extends ba{constructor(e,t){super(e,hp.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 lp{constructor(e){this.target=e,this.type=ts.BuildingGarrison}}class cp{constructor(e,t){this.target=e,this.source=t,this.type=ts.EnterObject}}class up extends Vs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&this.target.garrisonTrait?.canBeOccupied()&&this.target.garrisonTrait.units.length<this.target.garrisonTrait.maxOccupants&&!(this.target.garrisonTrait.units.length&&this.target.garrisonTrait.units[0].owner!==e.owner)&&!e.mindControllableTrait?.isActive()}onTick(e){if(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())return!0;let t=this.target.garrisonTrait;return this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new op(this.game,this.target)),!(this.aborted=!0)):(this.game.limboObject(e,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(e).getControlGroupNumber()}),t.units.length||(e.owner.buildingsCaptured++,this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new lp(this.target))),this.game.events.dispatch(new cp(this.target,e)),t.units.push(e),!0):!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class dp{constructor(e){this.target=e,this.type=ts.UnitRecycle}}class pp extends Vs{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===kn.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 op(this.game,this.target)),!(this.aborted=!0)):(this.game.sellTrait.sell(e),this.game.events.dispatch(new dp(e)),this.game.events.dispatch(new cp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class gp{constructor(e,t){this.target=e,this.source=t,this.type=ts.BuildingInfiltration}}class mp extends Vs{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!==kn.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 op(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.agentTrait?.infiltrate(e,this.target,this.game),this.game.events.dispatch(new gp(this.target,e)),this.game.events.dispatch(new cp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}(r=Lc=Lc||{})[r.MoveToQueueingTile=0]="MoveToQueueingTile",r[r.WaitForTurn=1]="WaitForTurn",r[r.MoveToTarget=2]="MoveToTarget",r[r.EnterTarget=3]="EnterTarget",r[r.ClearTarget=4]="ClearTarget";class fp extends Vs{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=Lc.MoveToQueueingTile:this.state=Lc.MoveToTarget}onEnd(e){!this.target.isDestroyed&&e.isSpawned&&this.target.hospitalTrait.removeFromHealQueue(e)}onTick(i){if(this.isCancelling()&&this.state!==Lc.EnterTarget||this.state===Lc.ClearTarget||i.moveTrait.isDisabled())return!0;if(this.state===Lc.MoveToQueueingTile){let t=new $s(this.game.map);var e=new Fs(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 ba(this.game,e,!1,{closeEnoughTiles:5})),this.children.push(new da(()=>{[Gr.Success,Gr.CloseEnough].includes(i.moveTrait.lastMoveResult)||this.cancel()})),this.state=Lc.WaitForTurn,this.queueingTile=e,!1)}if(this.state===Lc.WaitForTurn){if(!this.target.hospitalTrait.unitIsFirstInHealQueue(i))return!1;this.queueingTile=void 0,this.state=Lc.MoveToTarget}if(this.state===Lc.MoveToTarget){if(!this.isAllowed(i))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(i.tile,this.target))return!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),!(this.movePerformed=!0));this.state=Lc.EnterTarget}return this.state===Lc.EnterTarget&&(!this.isAllowed(i)||this.isCancelling()?(this.children.push(new op(this.game,this.target)),this.state=Lc.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 cp(this.target,i)),!0))}getTargetLinesConfig(e){return{target:this.queueingTile?void 0:this.target,pathNodes:this.queueingTile?[{tile:this.queueingTile,onBridge:void 0}]:[]}}}class yp extends qd{constructor(e){super(In.Occupy),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Dc.Capture}getPointerType(e){return e?this.isAllowed()?Rc.OccupyMini:Rc.NoActionMini:this.isAllowed()?Rc.Occupy:Rc.NoOccupy}isValid(){return!!(this.target.obj?.isSpawned&&this.target.obj?.isBuilding()&&this.sourceObject.isInfantry())&&(!!this.isInfantryRecycle(this.sourceObject,this.target.obj)||(this.target.obj.isBuilding()&&this.target.obj.hospitalTrait?this.game.areFriendly(this.sourceObject,this.target.obj)&&this.sourceObject.isInfantry():this.target.obj.garrisonTrait?this.target.obj.garrisonTrait.canBeOccupied()&&this.sourceObject.rules.occupier&&!(this.target.obj.garrisonTrait.units.length&&this.target.obj.garrisonTrait.units[0].owner!==this.sourceObject.owner)&&!this.sourceObject.mindControllableTrait?.isActive()&&!this.sourceObject.mindControllerTrait?.isActive():!(!this.target.obj.rules.spyable||!this.sourceObject.rules.infiltrate||this.game.areFriendly(this.sourceObject,this.target.obj))))}isInfantryRecycle(e,t){return t.rules.cloning&&e.owner===t.owner}isAllowed(){var e=this.target.obj,t=this.sourceObject;return this.isInfantryRecycle(t,e)?t.rules.movementZone!==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 pp(this.game,e)]:e.hospitalTrait?[new fp(this.game,e)]:e.garrisonTrait?[new up(this.game,e)]:[new mp(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof up||e instanceof mp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Is(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class wp extends Vs{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 hp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));if(!this.isAllowed(e)||this.isCancelling())return this.children.push(new op(this.game,this.target)),!(this.aborted=!0);var t=Math.floor(60*this.game.rules.combatDamage.c4Delay*Ls.BASE_TICKS_PER_SECOND);return this.target.c4ChargeTrait.setCharge(t,{player:e.owner,obj:e}),this.game.events.dispatch(new cp(this.target,e)),this.children.push(new op(this.game,this.target)),!(this.aborted=!0)}getTargetLinesConfig(e){return{target:this.target,pathNodes:[],isAttack:!0}}}class Tp extends qd{constructor(e,{forceAttack:t,noIvanBomb:i}={}){super(t?In.ForceAttack:In.Attack),this.game=e,this.isC4=!1,this.forceAttack=!!t,this.ivanBombAllowed=!i||!!t,this.targetOptional=!1,this.feedbackType=Dc.None,this.rangeHelper=new Is(this.game.map.tileOccupation),this.losHelper=new To(this.game.map.tiles,e.map.tileOccupation)}getPointerType(e,t){if(!this.isAllowed())return e?Rc.NoActionMini:Rc.NoAction;if(this.isC4)return Rc.C4;var i=this.sourceObject.attackTrait?.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);if(i?.rules.sabotageCursor)return Rc.C4;if(this.ivanBombAllowed&&this.sourceObject.rules.ivan&&i?.warhead.rules.ivanBomb)return Rc.Dynamite;if(i?.warhead.rules.bombDisarm)return Rc.DefuseBomb;if(i&&i.rules.damage<0)return Rc.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?Rc.AttackMini:t?Rc.AttackRange:Rc.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=Dc.SpecialAttack,!0;if(this.isC4=!1,this.feedbackType=Dc.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===Ts.Air))return!1;if(e===this.sourceObject)return!1;t=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return!!t&&(!(!this.ivanBombAllowed&&t.warhead.rules.ivanBomb)&&(!(e?.isBuilding()&&e.cabHutTrait&&!t.warhead.rules.ivanBomb&&!t.warhead.rules.bombDisarm)&&(!!(this.sourceObject.isUnit()&&this.sourceObject.moveTrait&&!this.sourceObject.moveTrait.isDisabled()||this.rangeHelper.isInWeaponRange(this.sourceObject,e||this.target.tile,t,this.game.rules))&&(!(this.sourceObject.airSpawnTrait&&t.rules.spawner&&!this.game.map.isWithinBounds(this.target.tile))&&(!!this.forceAttack||(!e?.isBuilding()||!e.hospitalTrait)&&(!(!e||!e.healthTrait)&&(!e.isDestroyed&&!e.isCrashing&&(!(!e.isOverlay()||!(t.warhead.rules.wall||t.warhead.rules.wood&&e.rules.armor===si.Wood))||e.isTechno()))))))))}isAllowed(){return!this.sourceObject.attackTrait.isDisabled()}process(){if(this.isC4)return[new wp(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return[new ko(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===ba||e.constructor===ko)&&!e.isCancelling());e&&(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor===ko)&&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===ko&&!e.isCancelling());if(e?.getWeapon().warhead.rules.temporal)return e.setForceAttack(this.forceAttack),e.requestTargetUpdate(this.target),!1}return!0}}class bp extends qd{constructor(e){super(In.Stop),this.game=e,this.getPointerType=()=>Rc.NoAction}isValid(){return this.sourceObject.isTechno()}isAllowed(){return!0}process(){return[new da(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 vp extends qd{constructor(){super(In.Cheer),this.getPointerType=()=>Rc.NoAction}isValid(){return this.sourceObject.isInfantry()&&[Ds.None,Ds.Guard].includes(this.sourceObject.stance)}isAllowed(){return!0}process(){return[new Xc]}}class Sp extends qd{constructor(e){super(In.Dock),this.game=e,this.targetOptional=!1,this.feedbackType=Dc.Move}getPointerType(e){return e?this.isAllowed()?Rc.OccupyMini:Rc.NoActionMini:this.isAllowed()?Rc.Occupy:Rc.NoOccupy}isValid(){if(!this.target.obj?.isBuilding()||this.target.obj.isDestroyed||!this.target.obj.dockTrait||this.target.obj.buildStatus!==kn.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 qo(this.game,e,!0,!0)]:e.unitRepairTrait||this.sourceObject.rules.dock.includes(e.name)?[new pa(this.game,e)]:[]}}class _p extends qd{constructor(e){super(In.Gather),this.game=e,this.targetOptional=!1,this.feedbackType=Dc.Move}getPointerType(e){return e?Rc.AttackMini:Rc.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 $o(this.game,this.target.tile,!0)]}}class kp extends ba{constructor(){super(...arguments),this.attackPerformed=!1,this.passedFirstWaypoint=!1}onTick(i){if(i.moveTrait.moveState===Hr.Moving&&(this.passedFirstWaypoint=!0),i.moveTrait.moveState===Hr.ReachedNextWaypoint&&i.attackTrait&&!i.attackTrait.isDisabled()&&!this.isCancelling()){let e=i.attackTrait.selectDefaultWeapon(i);if(e&&(this.passedFirstWaypoint||e&&!e.getCooldownTicks())){var s=i.attackTrait.scanForTarget(i,e,this.game);if(s.target){let{target:e,weapon:t}=s;if(!t.getCooldownTicks()){s=i.attackTrait.createAttackTask(this.game,e,e.tile,t,{holdGround:!0,passive:!0});return this.children.push(s),this.useChildTargetLines=!0,this.attackPerformed=!0,i.moveTrait.velocity.set(0,0,0),i.moveTrait.currentWaypoint=void 0,i.moveTrait.collisionState=$r.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=$r.Resolved,this.updateTarget(this.targetTile,this.toBridge)}}return super.onTick(i)}}class Op extends qd{constructor(e,t){super(In.AttackMove),this.game=e,this.map=t,this.targetOptional=!1,this.feedbackType=Dc.Attack}getPointerType(e){let t=this.isAllowed();var i,s,r;return t&&(i=!!this.target.getBridge(),s=this.sourceObject.rules.speedType,r=this.sourceObject.rules.movementZone===ii.Fly,t=r||0<this.map.terrain.getPassableSpeed(this.target.tile,s,i)||!!this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)),e?t?Rc.AttackMini:Rc.NoActionMini:t?Rc.AttackMove:Rc.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 kp(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})]}}class Ip{constructor(e,t){this.target=e,this.source=t,this.type=ts.BuildingRepairFull}}class Ap{constructor(e,t){this.source=e,this.tile=t,this.type=ts.BridgeRepair}}class Cp extends Vs{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 op(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 Ap(e.owner,this.target.centerTile))):(this.target.healthTrait.healToFull(e,this.game),this.game.events.dispatch(new Ip(this.target,e.owner))),this.game.events.dispatch(new cp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Bp extends qd{constructor(e){super(In.Repair),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Dc.Capture}getPointerType(e){return e?this.isAllowed()?Rc.OccupyMini:Rc.NoActionMini:this.isAllowed()?Rc.RepairMove:Rc.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 Cp(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Cp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Is(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class xp extends qd{constructor(e,t){super(t?In.GuardArea:In.Guard),this.game=e,this.targeted=t,this.getPointerType=e=>e?this.isAllowed()?Rc.GuardMini:Rc.NoActionMini:this.isAllowed()?Rc.Guard:Rc.NoMove,this.terminal=!0,this.targetOptional=!t,this.minimapAllowed=t,this.feedbackType=t?Dc.Move:Dc.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 da(()=>e.harvesterTrait.lastOreSite=void 0),new $o(this.game,void 0,!0)];let i=[];return t&&i.push(new ba(this.game,t,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})),i.push(new da(e=>{t&&![Gr.Success,Gr.CloseEnough].includes(this.sourceObject.moveTrait?.lastMoveResult)||(this.sourceObject.guardMode=!0)})),i}}class Ep extends qd{constructor(e){super(In.Scatter),this.game=e,this.getPointerType=()=>Rc.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 Ta(this.game,{tile:this.target.tile,toBridge:!!this.target.getBridge()})]}}class Pp{constructor(e){this.target=e,this.type=ts.EnterTransport}}(r=Fc=Fc||{})[r.MoveToQueueingTile=0]="MoveToQueueingTile",r[r.WaitForTurn=1]="WaitForTurn",r[r.MoveToTransport=2]="MoveToTransport",r[r.EnterTransport=3]="EnterTransport",r[r.ClearTransport=4]="ClearTransport";class Np extends Vs{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!==Ts.Air&&this.target.zone!==Ts.Air&&this.target.transportTrait.unitFitsInside(e)&&this.target.moveTrait.moveState===Hr.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=Fc.MoveToQueueingTile:this.state=Fc.MoveToTransport}onEnd(e){this.target.isDestroyed||this.target.transportTrait?.removeFromLoadQueue(e)}onTick(n){if(this.isCancelling()&&this.state!==Fc.EnterTransport||this.state===Fc.ClearTransport||n.moveTrait.isDisabled())return!0;if(this.target.tile!==this.initialTargetTile||this.target.moveTrait.moveState!==Hr.Idle)return!0;if(this.state===Fc.MoveToQueueingTile){let s=new $s(this.game.map),r=this.target.onBridge?this.game.map.tileOccupation.getBridgeOnTile(this.target.tile):void 0,a;var e=new Fs(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>{let t=[this.game.map.tileOccupation.getBridgeOnTile(e)];t[0]&&t.push(void 0);for(var i of t)if(0<this.game.map.terrain.getPassableSpeed(e,n.rules.speedType,!!i)&&s.isEligibleTile(e,i,r,this.target.tile))return a=i,!0;return!1}).getNextTile();return!e||(this.children.push(new ba(this.game,e,!!a,{closeEnoughTiles:5})),this.children.push(new da(()=>{[Gr.Success,Gr.CloseEnough].includes(n.moveTrait.lastMoveResult)||this.cancel()})),this.queueingNode={tile:e,onBridge:a},this.state=Fc.WaitForTurn,!1)}if(this.state===Fc.WaitForTurn){if(!this.target.transportTrait.unitIsFirstInLoadQueue(n))return!1;this.queueingNode=void 0,this.state=Fc.MoveToTransport}if(this.state===Fc.MoveToTransport){if(!this.isAllowed(n))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(n.tile,this.target))return!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));this.state=Fc.EnterTransport}return this.state===Fc.EnterTransport&&(!this.isAllowed(n)||this.isCancelling()?(this.children.push(new op(this.game,this.target)),this.state=Fc.ClearTransport,!1):(this.game.limboObject(n,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(n).getControlGroupNumber(),inTransport:!0}),this.game.events.dispatch(new Pp(this.target)),this.game.events.dispatch(new cp(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 Rp extends qd{constructor(e){super(In.EnterTransport),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Dc.Enter}getPointerType(e){return e?this.isAllowed()?Rc.OccupyMini:Rc.NoActionMini:this.isAllowed()?Rc.Occupy:Rc.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!==Ts.Air&&e.zone!==Ts.Air&&e.transportTrait.unitFitsInside(t)&&e.moveTrait.moveState===Hr.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 Np(this.game,t)]:[new da(()=>{t.unitOrderTrait.addTask(new ba(this.game,e.tile,e.onBridge)),t.unitOrderTrait.addTask(new da(()=>{this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)&&e.unitOrderTrait.addTask(new Np(this.game,t))}))})]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Np);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Is(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Dp{constructor(e){this.target=e,this.type=ts.BuildingCapture}}class Mp extends Vs{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!==kn.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 op(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.owner.buildingsCaptured++,this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Dp(this.target)),this.game.events.dispatch(new cp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new hp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Lp extends qd{constructor(e){super(In.Capture),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Dc.Capture}getPointerType(e){return e?this.isAllowed()?Rc.OccupyMini:Rc.NoActionMini:this.isAllowed()?Rc.Occupy:Rc.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 Mp(this.game,this.target.obj)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Mp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Is(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Fp{constructor(e,t){this.game=e,this.map=t}create(e,t){switch(e){case In.Deploy:return new sp(this.game,!0);case In.DeploySelected:return new sp(this.game,!1);case In.ForceMove:return new Kd(this.game,this.map,t,!0);case In.Move:return new Kd(this.game,this.map,t);case In.ForceAttack:return new Tp(this.game,{forceAttack:!0});case In.Attack:return new Tp(this.game,{noIvanBomb:!0});case In.PlaceBomb:return new Tp(this.game);case In.AttackMove:return new Op(this.game,this.map);case In.Capture:return new Lp(this.game);case In.Occupy:return new yp(this.game);case In.Stop:return new bp(this.game);case In.Cheer:return new vp;case In.Dock:return new Sp(this.game);case In.Gather:return new _p(this.game);case In.Repair:return new Bp(this.game);case In.Guard:return new xp(this.game,!1);case In.GuardArea:return new xp(this.game,!0);case In.Scatter:return new Ep(this.game);case In.EnterTransport:return new Rp(this.game);default:throw new Error(`Unhandled order type ${In[e]}`)}}}class jp{constructor(e,t,i){this.game=e,this.map=t,this.orderActionContext=i}create(){return new np(this.game,this.map,this.orderActionContext,new Fp(this.game,this.map))}}class Up{constructor(e){this.game=e}create(){return new Ul(this.game)}}class Wp{constructor(e){this.target=e,this.type=ts.PlayerDropped}}class zp extends jl{constructor(e,t){super(Xh.DropPlayer),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.playerName){let e=this.game.getPlayerByName(this.playerName);e.defeated||(this.game.removeAllPlayerAssets(e),e.dropped=!0,this.game.events.dispatch(new Wp(e)))}}}class Vp{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new zp(this.game,this.localPlayerName)}}class Hp{constructor(e){this.target=e,this.type=ts.BuildingRepairStart}}class Gp extends jl{constructor(e){super(Xh.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(bh);e.setDisabled(!e.isDisabled()),e.isDisabled()||this.game.events.dispatch(new Hp(t))}}}}class $p{constructor(e){this.game=e}create(){return new Gp(this.game)}}class qp extends jl{constructor(e){super(Xh.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,s=t,r=this.game.alliances;if(!n.defeated&&r.canRequestAlliance(s)){let t=r.findByPlayers(i,s);t?t.status===Wh.Formed?e||(r.breakAlliance(i,s),this.game.onAllianceChange(t,i,!1)):t.status===Wh.Requested&&(t.players.first===s?e&&r.canFormAlliance(i,s)&&(r.acceptRequest(s,i),this.game.onAllianceChange(t,i,!0),1!==(n=this.game.getCombatants().filter(e=>e!==i&&!r.areAllied(i,e))).length||(a=r.findByPlayers(n[0],i))&&r.cancelRequest(a.players.first,a.players.second),1!==(a=this.game.getCombatants().filter(e=>e!==s&&!r.areAllied(s,e))).length||(a=r.findByPlayers(a[0],s))&&r.cancelRequest(a.players.first,a.players.second)):e||(r.cancelRequest(i,s),this.game.events.dispatch(new xc(t,bc.Broken,i)),this.game.traits.filter($h).forEach(e=>{e[$h.onChange](t,!1,this.game)}))):e&&r.canFormAlliance(i,s)&&((e=r.request(i,s))&&this.game.events.dispatch(new xc(e,bc.Requested,i)))}}}}class Xp{constructor(e){this.game=e}create(){return new qp(this.game)}}class Qp extends jl{constructor(e){super(Xh.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 ${es[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(nn).activateSuperWeapon(this.superWeaponType,t,this.game,i,e)):console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class Zp{constructor(e){this.game=e}create(){return new Qp(this.game)}}class Yp{constructor(e,t){this.tile=e,this.player=t,this.type=ts.PingLocation}}class Kp extends jl{constructor(e){super(Xh.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 Yp(t,e));for(var i of[e,...this.game.alliances.getAllies(e)])this.game.events.dispatch(new kl(i,Xt.GenericNonCombat,t))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class Jp{constructor(e){this.game=e}create(){return new Kp(this.game)}}class eg{constructor(e){this.target=e,this.type=ts.PlayerResigned}}class tg extends jl{constructor(e){super(Xh.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 eg(e)),this.game.events.dispatch(new Rl(e)),this.game.mapShroudTrait.getPlayerShroud(e)?.revealAll(),t=e.radarTrait.isDisabled(),e.radarTrait.setDisabled(!1),t&&this.game.events.dispatch(new _l(e,!0)))}}class ig{constructor(e){this.game=e}create(){return new tg(this.game)}}class sg extends jl{constructor(e,t){super(Xh.ResignGame),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 eg(e)))}}}class rg{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new sg(this.game,this.localPlayerName)}}class ag{register(e,t,i){var s=new Dd;e.registerFactory(Xh.NoAction,new Ld),e.registerFactory(Xh.PlaceBuilding,new Wd(t)),e.registerFactory(Xh.SellBuilding,new Vd(t)),e.registerFactory(Xh.ToggleRepair,new $p(t)),e.registerFactory(Xh.SelectUnits,new Gd(t,s)),e.registerFactory(Xh.OrderUnits,new jp(t,t.map,s)),e.registerFactory(Xh.UpdateQueue,new Up(t)),e.registerFactory(Xh.ToggleAlliance,new Xp(t)),e.registerFactory(Xh.ActivateSuperWeapon,new Zp(t)),e.registerFactory(Xh.PingLocation,new Jp(t)),e.registerFactory(Xh.DropPlayer,new Vp(t,i)),e.registerFactory(Xh.ObserveGame,new ig(t)),e.registerFactory(Xh.ResignGame,new rg(t,i))}}class ng{constructor(){this.detectors=new Set}[Vh.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.detect(e,t)}[Hh.onUnspawn](e,t){e.isTechno()&&(this.isGlobalDetector(e)&&(this.detectors.delete(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.undetect(e,t))}[Gh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isDisguisable(e)&&(this.undetect(e,i),this.detect(e,i))}[zr.onTileChange](e,t,i){this.isGlobalDetector(e)&&(this.updateAroundDetector(e,t,i),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&(this.undetect(e,t),this.detect(e,t))}[Ns.onPowerLow](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait&&!e.poweredTrait.isPoweredOn());this.updateAroundDetectors(i,e)}[Ns.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ns.onPowerChange](e,t){}updateAroundDetectors(e,t){let i=new Set;for(var s of e)for(var r of this.findTechnosAroundDetector(s,t,s.tile))i.add(r);for(var a of i)this.isDisguisable(a)&&(this.undetect(a,t),this.detect(a,t))}updateAroundDetector(e,t,i=e.tile){var s;for(s of this.findTechnosAroundDetector(e,t,i))this.isDisguisable(s)&&(this.undetect(s,t),this.detect(s,t))}findTechnosAroundDetector(e,t,i){var s=e.getFoundation(),s=Math.max(s.width,s.height),e=e.rules.detectDisguiseRange+s,s=new vs(i.rx,i.ry).addScalar(-e),e=new vs(i.rx,i.ry).addScalar(e);return t.map.technosByTile.queryRange(new Mn(s,e))}detect(e,t){let i=new Set,s=new Is(t.map.tileOccupation);for(var r of this.detectors)if(!t.areFriendly(r,e)){var a=r.owner,n=r.rules.detectDisguiseRange;if(!i.has(a))if(!(r.isBuilding()&&r.poweredTrait&&!r.poweredTrait.isPoweredOn())&&s.tileDistance(e,r.tile)<=n)for(var o of[a,...t.alliances.getAllies(a)])i.add(o)}for(var h of i)h.sharedDetectDisguiseTrait?.add(e)}undetect(e,t){for(var i of t.getCombatants())i.sharedDetectDisguiseTrait?.delete(e)}isGlobalDetector(e){return!(!e.isTechno()||!e.rules.detectDisguiseRange)}isDisguisable(e){return!(!e.isInfantry()&&!e.isVehicle()||!e.disguiseTrait)}}class og{constructor(){this.detectors=new Set}[Vh.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isCloakable(e)&&this.detect(e,t)}[Hh.onUnspawn](e,t){e.isTechno()&&this.isGlobalDetector(e)&&this.detectors.delete(e)}[Gh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isCloakable(e)&&this.detect(e,i)}[zr.onTileChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,t),this.isCloakable(e)&&this.detect(e,t)}[Ec.onAdd](e,t,i){e.isTechno()&&(t instanceof hn?this.isCloakable(e)&&this.detect(e,i):t instanceof kh&&this.isGlobalDetector(e)&&this.updateAroundDetector(e,i))}[Ns.onPowerLow](e,t){}[Ns.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ns.onPowerChange](e,t){}[Bs.onTick](e){for(var t of e.getCombatants()){var i;for(i of t.getOwnedObjects())i.cloakableTrait&&!i.cloakableTrait.isCloaked()&&this.detect(i,e)}}updateAroundDetectors(e,t){let i=new Set;for(var s of e)for(var r of this.findTechnosAroundDetector(s,t))i.add(r);for(var a of i)this.isCloakable(a)&&this.detect(a,t)}updateAroundDetector(e,t){var i;for(i of this.findTechnosAroundDetector(e,t))this.isCloakable(i)&&this.detect(i,t)}findTechnosAroundDetector(e,t){var i=e.getFoundation(),s=Math.max(i.width,i.height),i=e.rules.sensorsSight+s,s=new vs(e.tile.rx,e.tile.ry).addScalar(-i),i=new vs(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new Mn(s,i))}detect(e,t){let i=new Is(t.map.tileOccupation);for(var s of this.detectors)if(!t.areFriendly(s,e)){var r=s.rules.sensorsSight;if(!(s.isBuilding()&&s.poweredTrait&&!s.poweredTrait.isPoweredOn())&&i.tileDistance(e,s.tile)<=r){r=e.cloakableTrait?.isCloaked();if(e.cloakableTrait.uncloak(t),r)for(var a of[s.owner,...t.alliances.getAllies(s.owner)])t.traits.get(Ol).addEventForPlayer(Xt.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 hg{constructor(){this.type=ts.StalemateDetect}}class lg{constructor(){this.stale=!1,this.allPlayersCredits=new Map,this.resetCountdown()}isStale(){return this.stale}getCountdownTicks(){return this.countdownTicks}resetCountdown(){this.countdownTicks=Math.floor(60*lg.graceMinutes*Ls.BASE_TICKS_PER_SECOND)}clearStale(){this.stale=!1,this.resetCountdown()}[Bs.onTick](e){0<this.countdownTicks?this.countdownTicks--:this.stale||(this.stale=!0,this.resetCountdown(),e.events.dispatch(new hg));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())}}[wn.onProduce](){this.clearStale()}[Nc.onPlace](e){e.wallTrait||this.clearStale()}[qh.onDestroy](e,t,i){!e.isBuilding()||e.owner.isNeutral||e.wallTrait||e.rules.insignificant||i?.obj&&t.areFriendly(e,i.obj)||this.clearStale()}[Gh.onChange](e,t,i){e.isBuilding()&&!t.isNeutral&&(i.alliances.areAllied(e.owner,t)||this.clearStale())}}lg.graceMinutes=5;class cg{constructor(e){this.prng=e}static factory(e,t){return new this(new zc(Number(e+""+t)))}generateColors(e){let t=[...e.humanPlayers,...e.aiPlayers].filter(Ma),i=t.map(e=>e.colorId).filter(e=>-2!==e);e=Un.length;let s=new Array(e).fill(0).map((e,t)=>t).filter(e=>!i.includes(e)),r=new Map;return t.forEach(e=>{if(-3!==e.countryId&&-2===e.colorId){if(s.length<1)throw new Error("Out of available colors to choose from");var t=this.prng.generateRandomInt(0,s.length-1);r.set(e,s[t]),s.splice(t,1)}}),r}generateCountries(e,t){let i=t.getMultiplayerCountries().length,s=[...e.humanPlayers,...e.aiPlayers].filter(Ma),r=new Map;return s.forEach(e=>{-2===e.countryId&&r.set(e,this.prng.generateRandomInt(0,i-1))}),r}generateStartLocations(i,s){let e=[...i.humanPlayers,...i.aiPlayers].filter(Ma),t=e.filter(e=>-2!==e.startPos).map(e=>e.startPos),r=[...s.keys()].filter(e=>!t.includes(e)),a=[];for(;r.length;){var n=r.length?this.prng.generateRandomInt(0,r.length-1):0;a.push(...r.splice(n,1))}if(a.unshift(...t),3<=a.length)for(var o of[1,2])if(!(t.length-1>=o)){let e=a.map(e=>s[e]),t=this.findFarthestPointFrom(e.slice(0,o),e.slice(o));var h=e.findIndex(e=>e.x===t.x&&e.y===t.y);a.splice(o,0,...a.splice(h,1))}if(4<=a.length)if(t.length-1<3){let e=a.map(e=>s[e]),t=this.findFarthestPointFrom(e.slice(2,3),e.slice(3));i=e.findIndex(e=>e.x===t.x&&e.y===t.y);a.splice(3,0,...a.splice(i,1))}a.splice(0,t.length);let l=new Map,c=-1;return e.forEach(e=>{if(-3!==e.countryId&&-2===e.startPos){if(c>=a.length-1)throw new RangeError("Map has fewer starting locations than players");l.set(e,a[++c])}}),l}findFarthestPointFrom(e,t){let s=e.map(e=>new vs(e.x,e.y)),r,a=0;if(!t.length)throw new Error("Search array must have at least one element");for(var n of t){let i=new vs(n.x,n.y);var o=s.reduce((e,t)=>e+i.distanceTo(t),0);o>=a&&(r=n,a=o)}return r}}class ug{constructor(e,t){this.mapLighting=new yi,this._onChange=new io,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}[Bs.onTick](){var e;void 0!==this.targetAmbient&&(this.ambientUpdateTicks??(this.ambientUpdateTicks=Math.floor(60*Ls.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 dg{constructor(e,t,i,s,r,a){this.game=e,this.inputActions=t,this.replayRecorder=i,this.actionSerializer=s,this.actionFactory=r,this.actionLogger=a,this.errorState=!1}init(){this.gameTurnMillis=1e3/(this.game.speed.value*Ls.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 s=new Map;for(t of e){var i=this.actionSerializer.getActionPayload(t);let e=s.get(t.playerName);e||(e=[],s.set(t.playerName,e)),e.push(i)}this.replayRecorder.recordActions(this.game.currentTick,s),s.forEach((t,i)=>{if(!t.length){let e=new Md;e.playerName=i,t.push(this.actionSerializer.getActionPayload(e))}}),this.processActions(s)}this.game.update()}}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.playerName=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i}): ${e}`)}))}dispose(){}}(r=jc=jc||{})[r.Closed=0]="Closed",r[r.Open=1]="Open",r[r.OpenObserver=2]="OpenObserver",r[r.Player=3]="Player",r[r.Ai=4]="Ai";class pg{encode(e){let s=[],r=0;return e.split("").forEach((e,t)=>{var i=e.charCodeAt(0)<<2*t-7*r,e=127&i,t=i>>7&127,i=i>>14&127;i&&r++,s.push(e,t),i&&s.push(i)}),s.push(0,0),2<=e.length&&s.push(0),s=s.map(e=>128^e),s.map(e=>String.fromCharCode(e)).join("")}decode(e){let i=e.split("").map(e=>e.charCodeAt(0));for(i=i.map(e=>128^e);0===i[i.length-1];)i.pop();let s=[],r=0,a=0;for(;i.length;){var n=s.length,o=i.shift(),h=i.shift();let e=0,t=!1;(-1!==[1,2,3].indexOf(i[0])||n>r+3)&&(e=i.shift(),r=n,t=!0);n=(e<<14|h<<7|o)>>2*n-7*a;s.push(127&n),t&&a++}return s.map(e=>String.fromCharCode(e)).join("")}}class gg{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 mg{serializeOptions(e){let t=e.gameMode,i=(new pg).encode(e.mapTitle),s=(new gg).encode(e.mapName);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,Number(e.hostTeams),i,e.maxSlots,Number(e.mapOfficial),e.mapSizeBytes,s,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===jc.Closed)return"@Closed@";if(e.type===jc.Open)return"@Open@";if(e.type===jc.OpenObserver)return"@OpenObserver@";if(e.type===jc.Ai){if(e.difficulty===bs.Easy)return"@EasyAI@";if(e.difficulty===bs.Medium)return"@MediumAI@";if(e.difficulty===bs.Brutal)return"@HardAI@"}else if(e.type===jc.Player)return e.name;throw new Error(`Unexpected slot info with type ${jc[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 fg{parseOptions(e){let i={},[t,s,,r]=e.split(":"),a=t.split(",");if(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()),i.hostTeams=Boolean(Number(a.shift())),i.mapTitle=(new pg).decode(a.shift()),i.maxSlots=Number(a.shift()),i.mapOfficial=Boolean(Number(a.shift())),i.mapSizeBytes=Number(a.shift()),i.mapName=(new gg).decode(a.shift()),i.mapDigest=a.shift(),i.humanPlayers=this.parsePlayerOpts(s),i.aiPlayers=[],r){var n=r.slice(0,-1).split(",");if(n.length%5!=0)throw new Error(`Couldn't parse gameopt: unexpected ai data length ${n.length}`);for(let e=0,t=Math.floor(n.length/5);e<t;++e){var o={difficulty:Number(n[5*e]),countryId:Number(n[5*e+1]),colorId:Number(n[5*e+2]),startPos:Number(n[5*e+3]),teamId:Number(n[5*e+4])};i.aiPlayers.push(-1!==o.countryId?o:void 0)}}return i}parsePlayerOpts(e){var i=e.split(",");if(i.length%8!=0)throw new Error(`Couldn't parse gameopt: unexpected players data length ${i.length}`);let s=[];for(let e=0,t=Math.floor(i.length/8);e<t;++e){var r={name:i[8*e],countryId:Number(i[8*e+1]),colorId:Number(i[8*e+2]),startPos:Number(i[8*e+3]),teamId:Number(i[8*e+4])};s.push(r)}return s}parsePingData(e){var i=e.split(",").slice(1);if(i.length%2)throw new Error(`Couldn't parse gameopt: unexpected ping data length ${i.length}`);let s=[];for(let e=0,t=Math.floor(i.length/2);e<t;++e)s.push({playerName:i[2*e],ping:Number(i[2*e+1])});return s}parseSlotData(e){var i;let s=[];for(i of e.slice(1,-1).split(",")){let t={};if("@Closed@"===i)t.type=jc.Closed;else if("@Open@"===i)t.type=jc.Open;else if("@OpenObserver@"===i)t.type=jc.OpenObserver;else if(-1!==["@EasyAI@","@MediumAI@","@HardAI@"].indexOf(i)){t.type=jc.Ai;let e;if("@EasyAI@"===i)e=bs.Easy;else if("@MediumAI@"===i)e=bs.Medium;else{if("@HardAI@"!==i)throw new Error(`Couldn't parse gameopt: unknown slot type ${i}`);e=bs.Brutal}t.difficulty=e}else t.type=jc.Player,t.name=i;s.push(t)}return s}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,s]=e.split("=");return s.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 yg{constructor(e,t){this.type=e,this.tickNo=t}}(r=Uc=Uc||{})[r.TurnActions=0]="TurnActions",r[r.ChatMessage=1]="ChatMessage",r[r.Taunt=2]="Taunt";class wg extends yg{constructor(e){super(Uc.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 Tg extends yg{constructor(e){super(Uc.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 bg extends yg{constructor(e,t,i){super(Uc.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[s,i]=i.split(":"),i=this.gameOptsParser.parsePlayerActions(i);t.push([Number(s),i])}this.payload=t}}class vg{constructor(e,t){this.gameOptsParser=e,this.gameOptsSerializer=t}create(e,t){switch(e){case Uc.TurnActions:return new bg(this.gameOptsParser,this.gameOptsSerializer,t);case Uc.ChatMessage:return new wg(t);case Uc.Taunt:return new Tg(t);default:throw new Error(`Unsupported replay event type "${e}" at game tick "${t}"`)}}}const Sg=[3,4];class _g{constructor(){this.name="",this.events=[]}static sanitizeFileName(e,t="_"){return e.replace(/[\/\?<>\\:\*\|"]/g,t).replace(/[\x00-\x1f\x7f\x80-\x9f]/g,t).slice(0,this.maxNameLength)}init(e,t,i,s,r){this.gameId=e,this.gameTimestamp=t,this.gameOpts=i,this.engineVersion=s,this.modHash=r,this.name=_g.sanitizeFileName(this.gameOpts.mapTitle+" "+(new Date).toISOString().replace(/(\.|,)\d+Z$/,"Z")),this.timestamp=Date.now()}writeEvent(...e){this.events.push(...e)}finish(e){this.endTick=e}getEvents(){return this.events}*flush(){if(!this.gameOpts)throw new Error("Game options must be set first");if(!this.engineVersion)throw new Error("Engine version is not set");if(void 0===this.modHash)throw new Error("Mod hash is not set");let e=new mg,t=this.getHeaderTag()+"\n";for(t+=`ENGINE ${this.engineVersion} ${this.modHash}\n`,t+=[this.gameId,this.gameTimestamp,P.encode(e.serializeOptions(this.gameOpts))].join(" ")+"\n",yield t,t="";void 0===this.endTick||this.events.length;){for(var i of this.events)t+=i.tickNo+"="+i.type+"|"+i.serialize()+"\n";this.events.length=0,yield t,t=""}t+=this.getEndTag()+" "+this.endTick+"\n",this.debugInfo&&(t+=P.encode(L(this.debugInfo))+"\n"),yield t}serialize(){if(void 0===this.endTick)throw new Error("Replay is not finished");let e="";var t,i=this.events.slice();for(t of this.flush())e+=t;return this.events=i,e}async parseHeader(e){let t=0,i,s,r,a,n,o;var h;for await(h of"string"==typeof e?e.split("\n"):async function*(e){const t=new TextDecoder("utf-8");let i=e.stream().getReader(),{value:s,done:r}=await i.read();s=s?t.decode(s,{stream:!0}):"";let a=/\r\n|\n|\r/gm,n=0;for(;;){var o=a.exec(s);if(o)yield s.substring(n,o.index),n=a.lastIndex;else{if(r)break;o=s.substr(n);({value:s,done:r}=await i.read()),s=o+(s?t.decode(s,{stream:!0}):""),n=a.lastIndex=0}}n<s.length&&(yield s.substr(n))}(e)){if(0===t)i=this.readReplayVersion(h);else if(1===t){if(!h.match(_g.engineLineRegex))throw new Error("Missing or invalid game engine version line");var l=h.split(" ");s=l[1],r=Number(i<4?"0":l[2])}else{if(2!==t)break;if(!h.match(/^\d+ \d+ .*$/))throw new Error("Missing or invalid game id/time/opts line");var[c,u,l]=h.split(" ");a=Number(c),n=Number(u),o=P.decode(l)}t++}if(t<3)throw new Error("Bad replay header");return{replayVersion:i,engineVersion:s,modHash:r,gameId:a,gameTimestamp:n,gameOptsSerialized:o}}unserialize(e,t){let i=e.split("\n");var s=this.readReplayVersion(i.shift()||"");if(!Sg.includes(s))throw new Error("Unsupported replay version");let r=new fg,a=i.shift();if(!a||!a.match(_g.engineLineRegex))throw new Error("Missing or invalid game engine version line");let[,n,o]=a.split(" ");s<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,s]=h.split(" "),s=r.parseOptions(P.decode(s));this.init(Number(l),Number(e),s,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 vg(r,new mg).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"}}_g.extension=".rpl",_g.maxNameLength=128,_g.engineLineRegex=/^ENGINE \d+\.\d+( \d+)?$/;class kg{constructor(e,t,i,s){this.replay=e,this.playerId=t,this.humanPlayers=i,this.actionSerializer=s}recordActions(t,i){if(Array.isArray(i)){let e=new bg(new fg,new mg,t);e.payload=[[this.playerId,i.map(e=>this.actionSerializer.getActionPayload(e))]],this.replay.writeEvent(e)}else if(this.hasActualActions(i)){let e=new bg(new fg,new mg,t);e.payload=[...i].map(([t,e])=>[this.humanPlayers.findIndex(e=>e.name===t),e]),this.replay.writeEvent(e)}}recordChatMessage(e,t,i){let s=new wg(e);s.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),message:i},this.replay.writeEvent(s)}recordTaunt(e,t,i){let s=new Tg(e);s.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),tauntNo:i},this.replay.writeEvent(s)}hasActualActions(e){return!![...e.values()].find(e=>e.find(e=>e.id!==Xh.NoAction))}}class Og{getActionPayload(e){return{id:e.actionType,params:e.serialize()}}}class Ig{constructor(e,t){this.options=e,this.logger=t,this.timeout=5,this._onMessage=new io,this._onError=new io,this._onClose=new io,this.messageBuffer=""}get onMessage(){return this._onMessage.asEvent()}get onError(){return this._onError.asEvent()}get onClose(){return this._onClose.asEvent()}async connect(s){return new Promise((e,t)=>{this.socket=new WebSocket(s),"binary"===this.options.mode&&(this.socket.binaryType="blob");let i=e=>{this.socket.removeEventListener("error",i),t(new Ig.ConnectError(`Connection to "${s}" failed`))};this.socket.addEventListener("open",()=>{this.socket.removeEventListener("error",i),this.handleOpen(),e()}),this.socket.addEventListener("error",i),this.socket.addEventListener("error",e=>this.handleError(e)),this.socket.addEventListener("close",e=>this.handleClose(e)),this.socket.addEventListener("message",e=>{globalThis.Blob&&e.data instanceof Blob?this.parseData(e.data).then(e=>{this.handleMessage(e)}).catch(e=>{console.error("Failed to decode socket message.",e)}):this.handleMessage(e.data)})})}handleOpen(){this.logger.info("Connection open to "+this.socket.url)}handleError(e){this.logger.error("Connection error",e),this._onError.dispatch(this,e)}handleClose(e){this.logger.info(`Connection closed (${this.socket.url})`,e),this._onClose.dispatch(this,e)}handleMessage(e){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(s){return new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(i.result),i.onerror=()=>t(),i.readAsBinaryString(s)})}sendCommand(d,p){if(p.replyStartCode&&!p.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=!1,a,n=e=>{clearTimeout(a),t(e)},o=e=>{this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",h),clearTimeout(a),a=void 0,i(e)};let h=async()=>{for(;s;)await async function(t){return new Promise(e=>{setTimeout(()=>e(),t)})}(10);c||o(new Ig.SocketError("Connection was closed prematurely"))},l=(e,t)=>p.replyRawText?(n(e.split(/\r?\n/).map(e=>({raw:e,time:t}))),!0):e.split(/\r?\n/).filter(e=>!!e).some(e=>((e,t)=>{if(p.replyMatch)return!!p.replyMatch.exec(e)&&(n([{raw:e,time:t}]),!0);if(!p.replyEndCode&&!p.replyCodes)return n([{raw:e,time:t}]),!0;var[,i,...s]=e.split(" "),i=parseInt(i,10),t={raw:e,code:i,params:s,time:t};if(p.replyEndCode)return p.replyCodes&&-1!==p.replyCodes.indexOf(i)?(n([t]),!0):((i===p.replyStartCode||p.replyBodyCodes&&-1!==p.replyBodyCodes.indexOf(i)||i===p.replyEndCode)&&r.push(t),i===p.replyEndCode&&(n(r),!0));if(void 0===p.replyCodes)throw new Error("List of replyCodes must be specified when not using start/end codes");return-1!==p.replyCodes.indexOf(i)&&(n([t]),!0)})(e,t)),c=!1,u=e=>{if(!c){let t=performance.now();globalThis.Blob&&e.data instanceof Blob?(s=!0,this.parseData(e.data).then(e=>{s=!1,c||l(e,t)&&(c=!0,this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",h))}).catch(e=>{s=!1,console.error("Failed to decode socket message.",e)})):l(e.data,t)&&(c=!0,this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",h))}};if(this.socket&&this.socket.readyState===WebSocket.OPEN){var e=(void 0!==p.timeout?p:this).timeout;a=setTimeout(()=>{o(new Ig.NoReplyError(`Timeout reached for command ${d}`))},1e3*e),this.socket.addEventListener("message",u),this.socket.addEventListener("close",h);try{this.sendMessage(d)}catch(e){o(e)}}else o(new Ig.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 Ig.SocketError(`Socket is not open${this.socket?` (readyState = ${this.socket.readyState})`:""}`);this.logger.debug("Sent message:",e),"string"==typeof e&&(e+="\r\n");let t;t="binary"===this.options.mode&&"string"==typeof e?D(e):e,this.socket.send(t)}async ping(e){var t=performance.now();return(await this.sendCommand("PING",{replyMatch:/^:[^ ]+ PONG/i,timeout:e}))[0].time-t}close(){this.socket&&this.socket.close()}isOpen(){return this.socket&&this.socket.readyState===WebSocket.OPEN}}Ig.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 s extends Error{constructor(e){super(e)}}e.ConnectError=s}(Ig=Ig||{});class Ag extends Error{constructor(e,t){super(e),this.code=t}}(r=(r=Ag=Ag||{}).Code||(r.Code={}))[r.InstanceNonExistent=0]="InstanceNonExistent",r[r.InstanceAlreadyExists=1]="InstanceAlreadyExists";var Cg;(r=Cg=Cg||{})[r.Public=0]="Public",r[r.Private=1]="Private";class Bg{constructor(e,t,i,s,r,a,n,o,h,l,c,u){this.game=e,this.gservCon=t,this.gameoptParser=i,this.gameoptSerializer=s,this.actionSerializer=r,this.actionFactory=a,this.inputActions=n,this.onDesync=o,this.actionLogger=h,this.debugLogger=l,this.replayRecorder=c,this.debugGameState=u,this.debugGameStateHistory=[],this.queuedRateChanges=[],this.errorState=!1,this.passiveMode=!1,this.receivedActions=new Map,this.lagState=!1,this._onLagStateChange=new io,this._onActionsSent=new io,this._onActionsProcessed=new io,this._onActionsReceived=new io,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*Ls.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(Bg.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();e.length||e.push(new Md);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)}}Bg.PREFERRED_HASH_CHECK_MILLIS=1e3;const xg=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");class Eg{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=xg.performance.now(),s=this.updateDeltaGameFrames(i);if(0<s)if(!(!1===this.gameTurnMgr.doGameTurn(i)))return void e();setImmediate(()=>this.doWaitForTick(e,t))}catch(e){t(e)}}updateDeltaGameFrames(e){var t=this.gameTurnMgr.getTurnMillis(),i=t!==this.lastGameTurnMillis;this.lastGameTurnMillis=t,i&&(this.lastGameFrame=0,this.startTime=e);let s=0;return this.startTime?(i=e-this.startTime,t=Math.round(i/t),s=t-this.lastGameFrame,this.lastGameFrame=t):this.startTime=e,s}stop(){this.isStarted&&(this.isStarted=!1)}destroy(){this.stop()}}const Pg=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");var Ng,Rg,Dg,Mg,Lg,Fg,jg,Ug,Wg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},zg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Vg{constructor(e,t,i,s,r,a,n,o){Ng.set(this,void 0),Rg.set(this,void 0),Dg.set(this,void 0),Mg.set(this,void 0),Lg.set(this,void 0),Fg.set(this,void 0),jg.set(this,void 0),Ug.set(this,void 0),Wg(this,Ng,e,"f"),Wg(this,Rg,t,"f"),Wg(this,Dg,new yc(t,!1),"f"),Wg(this,Mg,new Jl(t.events),"f"),Wg(this,Lg,i,"f"),Wg(this,Fg,a,"f"),Wg(this,jg,n,"f"),Wg(this,Ug,o,"f"),zg(this,Mg,"f").subscribe(t=>e.forEach(e=>e.onGameEvent(t,zg(this,Dg,"f")))),e.forEach(e=>{e.setGameApi(zg(this,Dg,"f")),e.setActionsApi(new Vl(t,s,r,e.name)),e.setProductionApi(new Ac(t.getPlayerByName(e.name).production)),e.onGameStart(zg(this,Dg,"f"))})}isFinished(){return zg(this,Rg,"f").status===Pc.Ended||zg(this,Fg,"f").getErrorState()}async update(){if(zg(this,jg,"f"))await zg(this,jg,"f").waitForTick();else{if(!(zg(this,Fg,"f")instanceof dg))throw new Error("Missing animation loop or turn manager");zg(this,Fg,"f").doGameTurn()}zg(this,Ng,"f").forEach(e=>e.onGameTick(zg(this,Dg,"f")))}getCurrentTick(){return zg(this,Dg,"f").getCurrentTick()}getTickRate(){return zg(this,Dg,"f").getTickRate()}getPlayerStats(){return zg(this,Rg,"f").getNonNeutralPlayers().filter(e=>!e.isObserver).map(t=>({name:t.name,country:t.country,ai:t.isAi||zg(this,Ng,"f").some(e=>e.name===t.name),defeated:t.defeated,credits:t.credits,startLocation:t.startLocation}))}saveReplay(e){let t=zg(this,Lg,"f");t.finish(zg(this,Rg,"f").currentTick);var i=`${zg(this,Rg,"f").gameOpts.mapName}_${Date.now()}${_g.extension}`,s=t.serialize(),i=a.resolve(e??process.cwd(),i);Pg.writeFileSync(i,s,"utf-8"),process.stdout.write(`Replay saved to "${i}"\n`)}dispose(){zg(this,Mg,"f").dispose(),zg(this,Ng,"f").length=0,zg(this,Ug,"f")?.call(this)}}Ng=new WeakMap,Rg=new WeakMap,Dg=new WeakMap,Mg=new WeakMap,Lg=new WeakMap,Fg=new WeakMap,jg=new WeakMap,Ug=new WeakMap;var Hg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},Gg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};const $g=a.resolve((0,e.default)(),"./res");class qg{constructor(){em.add(this),Xg.set(this,void 0),Qg.set(this,void 0),Zg.set(this,void 0),Yg.set(this,void 0),Kg.set(this,!1),Jg.set(this,void 0)}async init(e){Hg(this,em,"m",tm).call(this);var t=await(0,n.getOriginPrivateDirectory)(o.default,a.resolve(e)),i=await(0,n.getOriginPrivateDirectory)(o.default,$g),e=await(0,n.getOriginPrivateDirectory)(o.default,process.cwd());Et.initGameResSource(bt.Local);let s=await Et.initRfs(t);s.addDirectoryHandle(i),s.addDirectoryHandle(e);let r=await Et.initVfs(s,fr.get("vfs"));await r.loadStandaloneFiles(),await r.loadExtraMixFiles(Et.getActiveEngine()),await r.addMixFile("ra2cd.mix"),await r.loadImplicitMixFiles(Et.getActiveEngine()),Et.loadRules(),Gg(this,Jg,await Et.loadMapList(),"f"),Gg(this,Xg,Et.getMpModes(),"f"),Gg(this,Kg,!0,"f")}getAvailableMaps(){if(!Hg(this,Kg,"f"))throw new Error("API is not initialized. Call init() first.");return Hg(this,Jg,"f").getAll().map(e=>e.fileName.toLowerCase())}getAvailableGameModes(e){if(!Hg(this,Kg,"f"))throw new Error("API is not initialized. Call init() first.");let t=Hg(this,Jg,"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?Hg(this,em,"m",sm):Hg(this,em,"m",im)).call(this,e)}}var Xg=new WeakMap,Qg=new WeakMap,Zg=new WeakMap,Yg=new WeakMap,Kg=new WeakMap,Jg=new WeakMap,em=new WeakSet,tm=function(){fr.useDefaults(),fr.setLevel(fr.ERROR);const e=process.env.DEBUG_LOGGING;var t;if(e)if(isNaN(e))for(t of e.split(","))fr.get(t).setLevel(fr.DEBUG);else fr.setLevel(Boolean(Number(e))?fr.DEBUG:fr.ERROR);Gg(this,Qg,fr.get("ini"),"f"),Gg(this,Zg,fr.get("action"),"f"),Gg(this,Yg,fr.get("net"),"f")},im=async function(e){if(!Hg(this,Kg,"f"))throw new Error("API is not initialized. Call init() first.");var t=Hg(this,em,"m",am).call(this,e),i=e.agents.filter(e=>e instanceof Cc),s=new vi(Et.vfs.openFile(t.mapName)),r=await Hg(this,em,"m",rm).call(this,0,0,t,s,void 0),a=new Fl,e=new Nd;(new ag).register(e,r,void 0);let n=new _g;n.init(r.id,r.startTimestamp,t,Et.getVersion(),Et.getModHash());s=new Og,t=new kg(n,0,r.gameOpts.humanPlayers,s);let o=new dg(r,a,t,s,e,Hg(this,Zg,"f"));return o.init(),new Vg(i,r,n,e,a,o)},sm=async function(e){if(!Hg(this,Kg,"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 Cc&&t.push(i)}if(!(e.agents[0]instanceof Cc))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 Cc))throw new Error("Only the first player in the agents array can be a bot in online mode");var s=Hg(this,em,"m",am).call(this,e);let r=class{constructor(e){this._onLoadInfo=new io,this._onGameStart=new io,this._onGameActions=new io,this._onGameDesync=new io,this._onRateChange=new io,this._onChatMessage=new io,this._onTaunt=new io,this._onPlayerDisconnect=new io,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):"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(/^:/,""))}):"804"===t[1]&&this._onPlayerDisconnect.dispatch(this,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()}get onPlayerDisconnect(){return this._onPlayerDisconnect.asEvent()}static factory(e){return new this(new Ig({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,s,r){let a=await this.con.sendCommand(`create ${e} ${t} ${P.encode(i)} ${s} ${r}`,{replyCodes:[200,201]});if(201===a[0].code){r=a[0].params?a[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new Ag(`Create error: ${r}`,Ag.Code.InstanceAlreadyExists)}}async joinGame(e,t,i){let s=await this.con.sendCommand(`join ${e} ${t} ${i}`,{replyCodes:[400,401]});if(401===s[0].code){i=s[0].params?s[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new Ag(`Join error: ${i}`,Ag.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.ping(e)}sendPlayerActions(e,t){this.con.sendMessage(`a ${e} ${t}`)}sendMap(e){this.con.sendMessage(`putmap :${(new mg).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 fg).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 s;"#all"===e?s={type:Cg.Public,from:i,text:t}:e===this.currentUser&&(s={type:Cg.Private,from:i,text:t}),s&&this._onChatMessage.dispatch(this,s)}}.factory(Hg(this,Yg,"f"));await r.connect(e.serverUrl),await r.login(e.agents[0].name);let a=new mg;var n=a.serializeOptions(s),o=Date.now(),h=Number(o+"0");await r.createGame(h,0,n,Et.getVersion(),Et.getModHash()),await r.joinGame(h,Et.getVersion(),Et.getModHash());let l=new fg;var c=l.parseOptions(await r.gameOpts());let u=Et.vfs.openFile(s.mapName);var d=new vi(u);s.mapOfficial||r.sendMap(u.readAsString());n=e.agents[0].name;let p=await Hg(this,em,"m",rm).call(this,h,0,c,d,n);s=new Og,h=new Fl,d=new Nd;(new ag).register(d,p,n);let g=new _g;g.init(p.id,p.startTimestamp,c,Et.getVersion(),Et.getModHash());var m,c=new kg(g,0,p.gameOpts.humanPlayers,s);let f=new Bg(p,r,l,a,s,d,h,()=>{console.error("Desync detected."),process.exit(1)},Hg(this,Zg,"f"),void 0,c,!1);f.init();let y=new Eg(f);r.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)=>{r.onGameStart.subscribeOnce(()=>{r.onClose.unsubscribe(t),y.start(),e()}),r.onClose.subscribeOnce(t),r.sendLoadedPercent(100)}),process.stdout.write("Game started.\n");return r.onClose.subscribeOnce(()=>f.dispose()),new Vg(t,p,g,d,h,f,y,()=>{y.destroy(),Hg(this,Yg,"f").setLevel(fr.OFF),r.close()})},rm=async function(e,t,i,s,r){if(!Hg(this,Kg,"f"))throw new Error("API is not initialized. Call init() first.");var a=Et.getIni(Hg(this,Xg,"f").getById(i.gameMode).rulesOverride);await Et.loadTheater(s.theaterType);var n=Et.getActiveEngine(),o=Et.getTheaterSettings(n,s.theaterType),n=Et.getTheaterIni(n,s.theaterType);let h=new Q(n);h.loadTileData(Et.getTileData(),o.Extension);let l=class{static create(e,t,i,s,r,a,n,o,h,l,c,u){var d=i.clone().mergeWith(r).mergeWith(e);let p=new Wn(d,c);var g=new Gn(p,s,c);p.applySpecialFlags(e.specialFlags),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 Wn(i),f=m.getMultiplayerCountries(),y=[...m.getMultiplayerColors().values()],w=new zc(Number(a+""+n)),T=new nl(e,t,p,w.generateRandomInt.bind(w));r=new jh,d=h.getById(o.gameMode).type,s=new ll,c=new hl(s),i=new ul,e=new dl(1),t=new Fh(T.tiles,T.tileOccupation,T.bridges,e),h=new Nd;let b=new Ed(r,T,p,g,a,n,o,d,s,i,c,e,t,h);(new ag).register(h,b,void 0),b.traits.add(new bl),b.sellTrait=new Sl(b,p.general),b.traits.add(b.sellTrait),b.traits.add(new Ol);let v=new Al(p,u);b.traits.add(v),b.mapShroudTrait=new Cl(T,c),b.traits.add(b.mapShroudTrait),b.mapRadiationTrait=new Pd(T),b.traits.add(b.mapRadiationTrait),b.mapLightingTrait=new ug(p.audioVisual,T.getLighting()),b.traits.add(b.mapLightingTrait),b.traits.add(new nn),b.traits.add(new ng),b.traits.add(new og),b.crateGeneratorTrait=new Fn(o.cratesAppear),b.traits.add(b.crateGeneratorTrait),l||(b.stalemateDetectTrait=new lg,b.traits.add(b.stalemateDetectTrait));let S=new Tl(p,o,v.getAvailableObjects()),_=cg.factory(a,n),k=_.generateColors(o),O=_.generateCountries(o,m),I=_.generateStartLocations(o,T.startingLocations),A=[...o.humanPlayers,...o.aiPlayers].filter(Ma);return A.forEach(e=>{let t,i,s;if(As(e)?(t=e.name,i=!1):(t=b.getAiPlayerName(e),i=!0,s=e.difficulty),-3!==e.countryId){var r=O.get(e)??e.countryId,a=k.get(e)??e.colorId,e=I.get(e)??e.startPos;if(-2===r)throw new Error("Random country should have been resolved by now");if(-2===a)throw new Error("Random color should have been resolved by now");if(-2===e)throw new Error("Random start location should have been resolved by now");r=f[r].name,r=$n.factory(r,p),a=y[a];b.addPlayer(S.createCombatant(t,r,e,a,i,s))}else b.addPlayer(S.createObserver(t,p))}),b.addPlayer(S.createNeutral(p,"@@NEUTRAL@@")),b}}.create(s,h,Et.getRules(),Et.getArt(),a,e,t,i,Hg(this,Xg,"f"),!1,Hg(this,Qg,"f"),new dl(!1));return l.init(r?l.getPlayerByName(r):void 0),l.start(),l},am=function(t){let e=Hg(this,Jg,"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=Et.vfs.openFile(t.mapName),s=new Wn(Et.getRules()).getMultiplayerCountries();return{gameMode:t.gameMode,shortGame:t.shortGame,mcvRepacks:t.mcvRepacks,cratesAppear:t.cratesAppear,superWeapons:t.superWeapons,gameSpeed:t.gameSpeed,credits:t.credits,unitCount:t.unitCount,buildOffAlly:t.buildOffAlly,humanPlayers:t.agents.map((t,e)=>({name:t.name,countryId:s.findIndex(e=>e.name===t.country),colorId:e,startPos:-2,teamId:-2})),aiPlayers:new Array(8).fill(void 0),mapName:e.fileName,mapDigest:class{static compute(e){return ne.calculateCrc(e.getBytes()).toString(16)}}.compute(i),mapSizeBytes:i.getSize(),mapTitle:e.fileName,maxSlots:e.maxSlots,mapOfficial:e.official}},r=__webpack_require__(949);class nm extends r.Euler{constructor(){super(...arguments),this.isEuler=!0}setFromRotationMatrix(e,t,i){var s=e.elements,r=s[0],a=s[4],n=s[8],o=s[1],h=s[5],l=s[9],c=s[2],e=s[6],s=s[10];return"XYZ"===(t=t||this._order)?(this._y=Qi.asin(U(n,-1,1)),Math.abs(n)<.99999?(this._x=Qi.atan2(-l,s),this._z=Qi.atan2(-a,r)):(this._x=Qi.atan2(e,h),this._z=0)):"YXZ"===t?(this._x=Qi.asin(-U(l,-1,1)),Math.abs(l)<.99999?(this._y=Qi.atan2(n,s),this._z=Qi.atan2(o,h)):(this._y=Qi.atan2(-c,r),this._z=0)):"ZXY"===t?(this._x=Qi.asin(U(e,-1,1)),Math.abs(e)<.99999?(this._y=Qi.atan2(-c,s),this._z=Qi.atan2(-a,h)):(this._y=0,this._z=Qi.atan2(o,r))):"ZYX"===t?(this._y=Qi.asin(-U(c,-1,1)),Math.abs(c)<.99999?(this._x=Qi.atan2(e,s),this._z=Qi.atan2(o,r)):(this._x=0,this._z=Qi.atan2(-a,h))):"YZX"===t?(this._z=Qi.asin(U(o,-1,1)),Math.abs(o)<.99999?(this._x=Qi.atan2(-l,h),this._y=Qi.atan2(-c,r)):(this._x=0,this._y=Qi.atan2(n,s))):"XZY"===t?(this._z=Qi.asin(-U(a,-1,1)),Math.abs(a)<.99999?(this._x=Qi.atan2(e,h),this._y=Qi.atan2(n,r)):(this._x=Qi.atan2(-l,s),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+t),this._order=t,!1!==i&&this.onChangeCallback(),this}reorder(e){return om.setFromEuler(this),this.setFromQuaternion(om,e)}toVector3(e){return e?e.set(this._x,this._y,this._z):new is(this._x,this._y,this._z)}}const om=new Zi;r=__webpack_require__(949);class hm extends r.Spherical{setFromVector3(e){return this.radius=e.length(),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Qi.atan2(e.x,e.z),this.phi=Qi.acos(U(e.y/this.radius,-1,1))),this}}r=__webpack_require__(949);class lm extends r.Cylindrical{setFromVector3(e){return this.radius=Qi.sqrt(e.x*e.x+e.z*e.z),this.theta=Qi.atan2(e.x,e.z),this.y=e.y,this}}class cm{}const um=new qg})();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__Cylindrical=__webpack_exports__.Cylindrical,__webpack_exports__DMislRules=__webpack_exports__.DMislRules,__webpack_exports__Euler=__webpack_exports__.Euler,__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__Matrix4=__webpack_exports__.Matrix4,__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__Quaternion=__webpack_exports__.Quaternion,__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__Spherical=__webpack_exports__.Spherical,__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__Vector3=__webpack_exports__.Vector3,__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__Cylindrical as Cylindrical,__webpack_exports__DMislRules as DMislRules,__webpack_exports__Euler as Euler,__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__Matrix4 as Matrix4,__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__Quaternion as Quaternion,__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__Spherical as Spherical,__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__Vector3 as Vector3,__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};