;
;
/* ============================================================
MAIN β game setup, loop, win/lose, wiring
============================================================ */
let running=false, paused=false, demoMode=false, gameEnded=false;
/* Declared with the rest of the match state rather than beside
mfReportSimFailure further down: resetWorld() clears it and sits above that
point in the file, so keeping the binding here means a future top-level
caller cannot hit the temporal dead zone. */
let mfSimFailure=null;
let matchLive=false; // false during the carrier drop / deploy phase
let difficulty=1;
let defenseFocus=0; // 0 combined arms, 1 fortress / tower-defence cadence
let infestationOn=true; // neutral map nests, guards, spread, eruptions and tides
let deploymentPackage='prepared'; // supported opening for newcomers; classic start remains selectable
/* The Galactic strategic layer is the game's primary career shell. This
callback is assigned during UI wiring; tactical battles stay in this
document and the strategic shell hands deployments back through the bridge. */
let mfOpenExploration=null,mfExplorationMenuSync=null,mfExplorationLaunching=false;
let hudDeck='orders'; // one secondary command row at a time on phones
/* OTA source can run inside an older packaged HTML shell. Upgrade the two new
HUD surfaces before binding controls so the patch remains usable without an
APK reinstall. New packages already contain this markup, making these no-ops. */
function ensureCommanderLocatorShell(){
const bar=$('heroBar');if(!bar||$('heroPortraitImg'))return;
bar.innerHTML='Cπ'
+'COMMANDERLV 1'
+'FIELD COMMANDHP100%'
+'XP0%';
}
function ensureBuildingsDeckShell(){
const tabs=$('hudDeckTabs');if(!tabs)return;
tabs.setAttribute('role','tablist');
let b=tabs.querySelector('[data-deck="buildings"]');
if(!b){
b=document.createElement('button');b.className='hudDeckBtn';b.dataset.deck='buildings';b.innerHTML='βBUILDINGS';
tabs.insertBefore(b,tabs.querySelector('[data-deck="abilities"]')||tabs.lastElementChild);
}
for(const tab of tabs.querySelectorAll('.hudDeckBtn')){
tab.setAttribute('role','tab');tab.setAttribute('aria-selected',tab.dataset.deck===hudDeck?'true':'false');
}
/* Old shells still carry the ambiguous BASE action. The first-class tab owns
navigation now; leaving both visible would make the same feature appear to
behave two different ways. */
const legacy=$('baseFindBtn');if(legacy){legacy.hidden=true;legacy.setAttribute('aria-hidden','true');}
}
/* Phone command dock is platoon-first (4 groups, deck tabs). Army/box/rings
still treat the army as one blob. Stage A HUD (after Stage 0 screenshots,
not this slice): ring LOD, hologram sampling, box-select via spatial hash.
Army select does not auto-split into P1βP4. selInfo lists 3 unit types. */
let activeWarMode='standard'; // Standard, Co-op and MMO share one planetary catalogue
/* First Contact is deliberately NOT the Tutorial. Training owns KEEL,
objectives, highlights and its own mode; Standard gets only a short series
of ordinary notice-rail prompts during a new career's first three prepared
landings. Keeping this at the battle boundary stops Training state ever
leaking into a normal session again. */
let firstContactTimers=[];
function clearFirstContactGuide(){
for(const t of firstContactTimers) clearTimeout(t);
firstContactTimers.length=0;
}
function startFirstContactGuide(){
clearFirstContactGuide();
if(activeWarMode!=='standard'||!assistedOpeningActive()||deploymentPackage!=='prepared') return;
if(typeof TUT!=='undefined'&&TUT.trainingMode) return;
const battle=(META.standardMatches|0)+1;
const say=(delay,msg)=>firstContactTimers.push(setTimeout(()=>{
if(running&&matchLive&&activeWarMode==='standard'&&!(typeof TUT!=='undefined'&&TUT.trainingMode)) toast(msg);
},delay));
if(battle===1) say(900,'β FIRST CONTACT 1/3 β HQ online. Locked systems stay on the Galaxy map.');
else say(900,'β FIRST CONTACT '+battle+'/3 β Base online. Build your economy next.');
say(11000,'β CLAIM MASS β Build an Extractor on a nearby deposit, then defend it.');
say(28500,'β FORM A SCREEN β Queue units. Tap to attack-move; double-tap to retreat.');
say(56000,'β HOLD TERRITORY β Targeting Arrays extend your construction range.');
}
function setHudDeck(deck,quiet){
const valid=['orders','platoons','buildings','abilities','view'];
hudDeck=valid.includes(deck)?deck:'orders';
if(hudDeck!=='abilities'&&typeof hotUtilityClose==='function')hotUtilityClose(true);
document.body.classList.toggle('hudViewDeck',hudDeck==='view');
let activeTab=null;
document.querySelectorAll('.hudDeckBtn').forEach(b=>{
const on=b.dataset.deck===hudDeck;b.classList.toggle('on',on);b.setAttribute('aria-selected',on?'true':'false');
if(on)activeTab=b;
});
/* Scaled labels can make the tab row horizontally scrollable. Keep the
newly selected tab inside that scroller instead of leaving its hit target
painted under the battlefield canvas at the clipped edge. */
if(activeTab)requestAnimationFrame(()=>activeTab.scrollIntoView({block:'nearest',inline:'nearest'}));
for(const id of ['camRow','tacRow','grpRow','hotSlots']){
const row=$(id); if(row) row.style.display='none';
}
const rowId={orders:'tacRow',platoons:'grpRow',abilities:'hotSlots',view:'camRow'}[hudDeck];
const row=$(rowId);
if(row) row.style.display=hudDeck==='abilities'?(row.children.length?'flex':'none'):'flex';
if(hudDeck==='buildings'){
if(typeof openBaseFinder==='function')openBaseFinder();
}else if(typeof closeBaseFinder==='function')closeBaseFinder(false);
if(hudDeck==='abilities'&&typeof hotSlotSync==='function') hotSlotSync(true);
if(typeof updateSelInfo==='function') updateSelInfo();
if(typeof hotSlotPlace==='function') requestAnimationFrame(hotSlotPlace);
if(!quiet){sfx('ui');buzz(8);}
}
function showHudDock(on,deck){
document.body.classList.toggle('hudTacticalDock',!!on);
const tabs=$('hudDeckTabs'); if(tabs) tabs.style.display=on?'flex':'none';
const primary=$('primaryRow'); if(primary) primary.style.display=on?'flex':'none';
if(on) setHudDeck(deck||hudDeck,true);
else {
if(typeof hotUtilityClose==='function')hotUtilityClose(true);
if(typeof closeBaseFinder==='function')closeBaseFinder(false);
for(const id of ['tacRow','grpRow','hotSlots']){const row=$(id);if(row)row.style.display='none';}
}
}
/* Nine authored deployment plateaus. They are deliberately inset rather
than sitting on the border: the camera can frame them, builders have room to
expand, and every zone can be raised to dry land by the terrain generator. */
const START_ZONES=[
{id:'nw',n:'1',x:.18,y:.18},{id:'n', n:'2',x:.50,y:.15},
{id:'ne',n:'3',x:.82,y:.18},{id:'e', n:'4',x:.85,y:.50},
{id:'se',n:'5',x:.82,y:.82},{id:'s', n:'6',x:.50,y:.85},
{id:'sw',n:'7',x:.18,y:.82},{id:'w', n:'8',x:.15,y:.50},
{id:'c', n:'9',x:.50,y:.50}
];
/* MAP is baked into terrain, pathfinding, fog and shaders. Resizing that buffer
at runtime would desynchronise all four, so map size defines a playable
theatre inside the fixed 2.6 km terrain. Spawn separation, neutral resource
bounds and resource counts all use the same theatre scale; this produces a
genuinely faster Compact match without allocating a second terrain stack. */
const BATTLEFIELD_PRESETS={
compact:{nm:'COMPACT',km:'2.2 KM',dur:'10\u201314 MIN',world:.6875,start:.72,spread:.90,nodes:16,geysers:1,site:.90,haz:.92,
ds:'Close spawns, concentrated resource fields and quick clashes.'},
standard:{nm:'STANDARD',km:'2.6 KM',dur:'15\u201322 MIN',world:.8125,start:.86,spread:1.08,nodes:20,geysers:2,site:1.06,haz:1.04,
ds:'More breathing room for expansion, scouting and multi-front defence.'},
large:{nm:'LARGE',km:'3.2 KM',dur:'20\u201330 MIN',world:1,start:1,spread:1.20,nodes:24,geysers:3,site:1.22,haz:1.14,
ds:'Maximum separation, additional fields and room for multi-front wars.'}
};
let battlefieldPreset='standard';
const DEPLOYMENT_PACKAGES={
prepared:{nm:'PREPARED LANDING',em:'\u25c8',ds:'HQ, Reactor, Factory and Constructor deploy together. Recommended while learning.'},
expedition:{nm:'EXPEDITION LANDING',em:'\u25c7',ds:'HQ and Constructor only. Classic build-from-zero RTS opening.'}
};
function deploymentPackageDef(){return DEPLOYMENT_PACKAGES[deploymentPackage]||DEPLOYMENT_PACKAGES.prepared;}
function deploymentGraceSeconds(diff){return [180,120,75][clamp(diff|0,0,2)];}
function assistedOpeningActive(){return ((META&&META.standardMatches)||0)<3;}
function openingContactRemaining(){
if(!matchLive||typeof AI==='undefined'||AI.openingGrace==null)return 0;
return Math.max(0,AI.openingGrace-(AI.t||0));
}
function battlefieldPresetKey(key){ return key==='grand'?'large':(BATTLEFIELD_PRESETS[key]?key:'standard'); }
function battlefieldPresetDef(){ return BATTLEFIELD_PRESETS[battlefieldPresetKey(battlefieldPreset)]; }
function battlefieldPresetHint(){
const P=battlefieldPresetDef();
return P.km+' \u00b7 '+battlefieldFactionCap()+' FACTIONS MAX \u00b7 EST. '+P.dur+' \u2014 '+P.ds;
}
function battlefieldPlayBounds(pad){
const P=battlefieldPresetDef(),span=MAP*(P.world||1),inset=(MAP-span)*.5;
const lo=inset+(pad||0),hi=MAP-inset-(pad||0);
return lo=1.28?3:(curTheme==='ashland'?2:curTheme==='arctic'?3:0)));
}
function battlefieldShapeRadius(angle,pad){
const B=battlefieldPlayBounds(0),half=Math.max(45,(B.hi-B.lo)*.5-(pad||0));
const style=battlefieldShapeStyle(),ca=Math.abs(Math.cos(angle)),sa=Math.abs(Math.sin(angle));
const power=style===1?3.15:style===2?6.25:style===3?4.15:5.0;
const base=half/Math.pow(Math.pow(ca,power)+Math.pow(sa,power),1/power);
let shape;
if(style===1) shape=.945+.024*Math.sin(angle*3+.65)+.016*Math.sin(angle*7-1.10);
else if(style===2) shape=.958+.020*Math.sin(angle*5+.30)+.012*Math.sin(angle*9+1.20);
else if(style===3) shape=.948+.025*Math.sin(angle*2-.80)+.016*Math.sin(angle*6+.45);
else shape=.966+.014*Math.sin(angle*4+.35)+.010*Math.sin(angle*7-.55);
return Math.max(36,base*shape);
}
function battlefieldSignedDistance(x,y,pad){
const B=battlefieldPlayBounds(0),cx=(B.lo+B.hi)*.5,cy=cx,dx=x-cx,dy=y-cy;
const r=Math.hypot(dx,dy),a=r>0.001?Math.atan2(dy,dx):0;
return battlefieldShapeRadius(a,pad)-r;
}
function battlefieldContains(x,y,pad){ return battlefieldSignedDistance(x,y,pad)>=0; }
function battlefieldClampPoint(x,y,pad){
const B=battlefieldPlayBounds(0),cx=(B.lo+B.hi)*.5,cy=cx,dx=x-cx,dy=y-cy,r=Math.hypot(dx,dy);
const a=r>0.001?Math.atan2(dy,dx):0,limit=battlefieldShapeRadius(a,pad);
if(r<=limit)return [x,y];
const q=limit/Math.max(.001,r);return [cx+dx*q,cy+dy*q];
}
function battlefieldBoundaryPoint(angle,pad){
const B=battlefieldPlayBounds(0),c=(B.lo+B.hi)*.5,r=battlefieldShapeRadius(angle,pad);
return [c+Math.cos(angle)*r,c+Math.sin(angle)*r];
}
/* Max orthographic span for THIS theatre.
SPAN_MAX=3400 is the engine ceiling, sized for the 3.2 km Large mesh. Compact
and Standard are smaller playable discs inside that same mesh, so a single
ceiling lets the view run into exclusion haze, the heightfield rim, and the
skirt void. Pan stays inside the playable square (red rungs). FAR zoom is
allowed to spend Compact/Standard's unused MAP inset so infantry can finish
converting to icons (~2196 span at VH=915) without Large seeing the mesh
skirt (MAP-88 still wins there). Pitch and aspect both change the ground
footprint β a tilted portrait view is tall, a landscape view is wide β so
this is not a per-preset constant. */
function battlefieldViewInner(){
const B=typeof battlefieldPlayBounds==='function'?battlefieldPlayBounds(0):{lo:0,hi:MAP,span:MAP};
const play=Math.max(80,B.span||(B.hi-B.lo));
/* play-24 keeps a hair inside the theatre square so the red rungs sit on
the visible edge. MAP-88 keeps Large's heightfield rim off-screen without
cropping the rungs (they sit ~60wu inside MAP). Compact/Standard are
already inset from MAP, so the theatre wins there. Pan/look-at uses this
tight square; FAR zoom uses battlefieldZoomInner() so icons can engage. */
return Math.min(play-24,MAP-88);
}
function battlefieldZoomInner(){
const inner=battlefieldViewInner();
const B=typeof battlefieldPlayBounds==='function'?battlefieldPlayBounds(0):{lo:0,hi:MAP,span:MAP};
const play=Math.max(80,B.span||(B.hi-B.lo));
/* Compact FAR used to sit at ~2020 span β below the infantry icon-out
crossing (~2196 at VH=915), so the strategic tier never fully took over.
Spend some of Compact/Standard's unused MAP inset as border haze (already
fog-coloured) so FAR zoom reaches that band. 560 wu is past infantry
full-convert with margin; MAP-88 still blocks Large's heightfield rim.
Pan stays on the tight inner. */
const haze=Math.min(560,Math.max(0,(MAP-play)*0.56));
return Math.min(inner+haze,MAP-88);
}
function spanMaxNow(){
const inner=battlefieldZoomInner();
const pitch=clamp(typeof camPitch==='number'?camPitch:1.19,
typeof PITCH_MIN==='number'?PITCH_MIN:1.05,
typeof PITCH_MAX==='number'?PITCH_MAX:1.50);
const sinP=Math.max(0.30,Math.sin(pitch));
/* Fit the pitched ground HEIGHT inside `inner`. The previous formula used
max(width,height) of the ground AABB, so a landscape window was capped
at inner/aspect (~1748 at 1080p) β below the infantry icon crossing.
Screen-right may hang into border haze; shaders already fade that to
fog colour. Portrait phones were already height-limited, so their cap
only moves by battlefieldZoomInner(). Yaw is left out on purpose:
turning used to shrink span and fight the icon band. */
const k=1/sinP;
const hi=typeof SPAN_MAX==='number'?SPAN_MAX:3400;
const lo=spanMinNow();
return clamp(inner/Math.max(0.35,k),lo,hi);
}
/* mesh.js SPAN_MIN=420 is a company view. On a 412Γ900 phone that floor never
reaches commander/unit tactical mesh (~200β270). Icon fade is footprint-
based and still off at 200; the old floor just hid the mesh band. */
function spanMinNow(){ return 200; }
/* mesh.js owns clampCam / zoomBy / camTick. Do not edit that file for this β
FS3D/AO work lives there. Takeover keeps the pitch clamp and rewrites span
+ look-at against the current theatre. distTarget must be clamped too:
camTick lerps orthoSpan toward it, so leaving it at SPAN_MAX would fight
the cap every frame. */
const _mfClampCamMesh=clampCam;
clampCam=function(){
const lo=spanMinNow(), mx=spanMaxNow();
if(orthoSpan>mx) orthoSpan=mx;
if(distTarget>mx) distTarget=mx;
const want=orthoSpan;
_mfClampCamMesh();
/* mesh clampCam raises anything under 420. Restore the tactical floor. */
if(wantmx) orthoSpan=mx;
if(orthoSpan=0&&typeof camAutoAllowed==='function'&&!camAutoAllowed()) camFollow=-1;
_mfCamTickMesh(dt);
};
/* MEDIUM/LOW scissor projects the ground AABB. A pitched portrait view
leaves fog-clear strips (the grey border). Full frame on tall phones. */
if(typeof mfGfxScissor==='function'){
const _mfGfxScissorMesh=mfGfxScissor;
mfGfxScissor=function(on){
if(!on){ _mfGfxScissorMesh(false); return; }
if(typeof VH==='number'&&typeof VW==='number'&&VH>VW){
if(typeof gl!=='undefined'&&gl) gl.disable(gl.SCISSOR_TEST);
return;
}
_mfGfxScissorMesh(true);
};
}
let playerStartZone='sw', spawnPick='player';
let aiSlots=[
{on:true, diff:1,zone:'ne',ally:false,behavior:'balanced'},
{on:false,diff:1,zone:'nw',ally:false,behavior:'balanced'},
{on:false,diff:1,zone:'se',ally:false,behavior:'balanced'},
{on:false,diff:1,zone:'c', ally:false,behavior:'balanced'}
];
/* Theatre size owns participant density while every participant owns one hard
500-unit Commander-seat cap. Authored seats: Compact duel SWβNE; second
enemy SE never NW; ally NW; Large 1v3 uses all four corners. The Brood may
appear as a fifth system force, but never consumes a participant seat. */
const BATTLEFIELD_FACTION_CAP={compact:2,standard:3,large:4};
const SPAWN_CORNERS=['nw','ne','se','sw'];
const SPAWN_LARGE_FIFTH='c';
const SPAWN_FAIR_MIN_M=1400;
function battlefieldFactionCap(){return BATTLEFIELD_FACTION_CAP[populationTheatre()]||3;}
function battlefieldAiCap(){return Math.max(1,battlefieldFactionCap()-1);}
function spawnZoneIsCorner(id){ return SPAWN_CORNERS.indexOf(id)>=0; }
function spawnZoneAllowed(id){return spawnZoneIsCorner(id)||(populationTheatre()==='large'&&id===SPAWN_LARGE_FIFTH);}
function normalizeAiSlotsForBattlefield(){
const max=battlefieldAiCap();
for(const A of aiSlots)A.behavior=typeof aiBehaviorKey==='function'?aiBehaviorKey(A.behavior):'balanced';
for(let i=max;iA.on))aiSlots[0].on=true;
/* A skirmish still needs an opponent. Compact therefore cannot spend its
only AI slot on an ally; larger theatres can trade any additional slot. */
if(!aiSlots.slice(0,max).some(A=>A.on&&!A.ally)){
const first=aiSlots.findIndex((A,i)=>i=0)aiSlots[first].ally=false;
}
if(spawnPick!=='player'){
const i=+spawnPick.slice(2);if(i>=max||!aiSlots[i]||!aiSlots[i].on)spawnPick='player';
}
reseatSpawnPlanner(max);
}
function reseatSpawnPlanner(max){
/* Stage 0 MAP contract. Compact is a SWβNE duel; extras are already off.
On Standard/Large, allies claim NW, the second enemy is SE (never NW β
that is the ally chair / west-edge crush vs player SW), and a third enemy
takes the leftover corner so Large 1v3 is four corners. Brood nests use
neutral placement and do not claim the retired fifth center seat. */
if(max==null) max=battlefieldAiCap();
if((typeof populationTheatre==='function'?populationTheatre():'standard')==='compact'){
playerStartZone='sw';
aiSlots[0].on=true; aiSlots[0].ally=false; aiSlots[0].zone='ne';
return;
}
if(!spawnZoneIsCorner(playerStartZone)) playerStartZone='sw';
let allyN=0;
for(let i=0;i=max||!aiSlots[i].on||!aiSlots[i].ally) continue;
if(allyN===0){
if(playerStartZone==='nw') playerStartZone='sw';
aiSlots[i].zone='nw';
}
allyN++;
}
const taken=new Set([playerStartZone]);
for(let i=0;i=4?['ne','se','nw','c','sw']:(nE>=3?['ne','se','nw','sw']:['ne','se','sw']);
for(const i of enemyIdx){
const A=aiSlots[i];
const nwBanned=A.zone==='nw'&&(i===1||nE<3);
const ok=spawnZoneAllowed(A.zone)&&!taken.has(A.zone)&&!nwBanned;
if(!ok){
const pick=prefer.find(z=>!taken.has(z)&&!(i===1&&z==='nw'))||SPAWN_CORNERS.concat(SPAWN_LARGE_FIFTH).find(z=>spawnZoneAllowed(z)&&!taken.has(z));
if(pick) A.zone=pick;
}
taken.add(A.zone);
}
allyN=0;
for(let i=0;i=max||!aiSlots[i].on||!aiSlots[i].ally) continue;
allyN++;
if(allyN===1){ taken.add(aiSlots[i].zone); continue; }
if(spawnZoneIsCorner(aiSlots[i].zone)&&!taken.has(aiSlots[i].zone)){ taken.add(aiSlots[i].zone); continue; }
const pick=SPAWN_CORNERS.find(z=>!taken.has(z));
if(pick){ aiSlots[i].zone=pick; taken.add(pick); }
}
}
function startZone(id){
const Z=START_ZONES.find(z=>z.id===id)||START_ZONES[0],s=battlefieldPresetDef().start;
return {id:Z.id,n:Z.n,x:.5+(Z.x-.5)*s,y:.5+(Z.y-.5)*s};
}
function activeAiSlots(){ return aiSlots.map((s,i)=>({...s,slot:i})).filter(s=>s.on); }
function activeEnemySlots(){return activeAiSlots().filter(S=>!S.ally);}
function activeAllySlots(){return activeAiSlots().filter(S=>S.ally);}
function spawnAiRosterPick(fac, used){
/* Identity only. Chassis stays FACTIONS[fac].hero (4 / 28 / 29 / 30).
applyCommanderChoice is the player's doctrine stack β never run it here
or three AI seats would multiply player perks. */
const key=typeof commanderFactionKey==='function'?commanderFactionKey(fac):fac;
const roster=(typeof COMMANDER_ROSTERS!=='undefined'&&COMMANDER_ROSTERS[key])||[];
let pick=null;
for(let i=0;iA.slot+':'+(A.ally?'ally':'enemy')+':'+A.zone).join(',');
return theatre+'|player:'+playerStartZone+'|ai:'+seats;
}
function farFromStartZones(x,y,d){
for(const S of skirmishSpawnPoints()) if(dist2(x,y,S.x,S.y)A.diff===live[0].diff);
const conquestFloor=typeof mfConquestDifficultyFloor==='function'?mfConquestDifficultyFloor(curMap):0;
let gdiff=$('globalDiffRow');
if(!gdiff){
gdiff=document.createElement('div'); gdiff.id='globalDiffRow'; gdiff.className='optRow';
list.parentNode.insertBefore(gdiff,list);
}
gdiff.innerHTML=['EASY','NORMAL','HARD'].map((n,d)=>'').join('');
gdiff.querySelectorAll('.globalDiff').forEach(b=>b.addEventListener('pointerdown',e=>{
e.stopPropagation();
if(+b.dataset.d{b.classList.toggle('on',same&&+b.dataset.d===live[0].diff);b.classList.toggle('mapFloor',+b.dataset.d({key:'ai'+i,nm:'AI '+(i+1),on:s.on})));
pick.innerHTML=targets.map(T=>{
const Z=startZone(spawnTargetZone(T.key));
return '';
}).join('');
pick.querySelectorAll('.spawnTarget').forEach(b=>b.addEventListener('pointerdown',e=>{
e.stopPropagation(); const k=b.dataset.sp;
if(k!=='player'){
const i=+k.slice(2);
if(i>=aiMax){toast('LARGER THEATRE REQUIRED \u2014 '+battlefieldFactionCap()+' factions maximum here');sfx('deny');return;}
if(!aiSlots[i].on) aiSlots[i].on=true;
}
spawnPick=k; renderSpawnPlanner(); sfx('ui');
}));
list.innerHTML=aiSlots.map((A,i)=>{
const Z=startZone(A.zone),locked=i>=aiMax,behavior=aiBehaviorKey(A.behavior),BD=aiBehaviorDef(behavior);
const behaviorOptions=Object.keys(AI_BEHAVIOR_TYPES).map(k=>'').join('');
return '
';
}).join('');
list.querySelectorAll('.aiSlot').forEach(row=>{
const i=+row.dataset.ai,locked=i>=aiMax;
row.querySelector('.aiSlotName').addEventListener('pointerdown',()=>{ if(aiSlots[i].on){spawnPick='ai'+i;renderSpawnPlanner();sfx('ui');} });
row.querySelector('.aiRole').addEventListener('pointerdown',()=>{
if(locked){toast('LARGER THEATRE REQUIRED');sfx('deny');return;}
if(!aiSlots[i].ally&&activeEnemySlots().length===1){toast('At least one enemy faction is required');sfx('deny');return;}
aiSlots[i].on=true;aiSlots[i].ally=!aiSlots[i].ally;spawnPick='ai'+i;
normalizeAiSlotsForBattlefield();difficulty=Math.max(...activeEnemySlots().map(A=>A.diff));renderSpawnPlanner();sfx('confirm');
});
row.querySelector('.aiBehavior').addEventListener('change',e=>{
if(locked){renderSpawnPlanner();sfx('deny');return;}
const k=e.target.value;if(!aiBehaviorAvailable(k)){toast('NAVAL AI REQUIRES A CONNECTED OCEAN OR RIVER');renderSpawnPlanner();sfx('deny');return;}
aiSlots[i].behavior=k;aiSlots[i].on=true;spawnPick='ai'+i;renderSpawnPlanner();sfx('confirm');
});
row.querySelector('.aiToggle').addEventListener('pointerdown',()=>{
if(locked){toast('LARGER THEATRE REQUIRED \u2014 choose '+(i===1?'Standard':'Large')+' for this faction slot');sfx('deny');return;}
if(aiSlots[i].on&&!aiSlots[i].ally&&activeEnemySlots().length===1){ toast('At least one enemy faction is required'); return; }
aiSlots[i].on=!aiSlots[i].on;
if(!aiSlots[i].on&&spawnPick==='ai'+i) spawnPick='player';
else if(aiSlots[i].on) spawnPick='ai'+i;
normalizeAiSlotsForBattlefield();difficulty=Math.max(...activeEnemySlots().map(A=>A.diff)); renderSpawnPlanner(); sfx('ui');
});
row.querySelectorAll('.aiDiff').forEach(b=>b.addEventListener('pointerdown',()=>{
if(locked){toast('LARGER THEATRE REQUIRED');sfx('deny');return;}
if(+b.dataset.adA.diff)); renderSpawnPlanner(); sfx('ui');
}));
});
const fair=$('spawnFairness');
if(fair){
const S=skirmishSpawnPoints(); let md=1e9;
for(let a=0;a\u26A0 CRUSH '+Math.round(md)+'mNearest commanders under '+SPAWN_FAIR_MIN_M+'m β use separated corners or the Large center seat'
:'\u2713 1 PLAYER Β· '+activeAllySlots().length+' AI ALLY Β· '+activeEnemySlots().length+' ENEMY3 mass + 1 energy site each Β· nearest commanders '+Math.round(md)+'m apart';
}
drawSpawnPlanner();
}
function initSpawnPlanner(){
const cv3=$('spawnMap'); if(!cv3||cv3.dataset.wired) return;
cv3.dataset.wired='1';
cv3.addEventListener('pointerdown',e=>{
e.stopPropagation(); const r=cv3.getBoundingClientRect(),u=previewPx2Frac((e.clientX-r.left)/r.width,battlefieldPreset),v=previewPx2Frac((e.clientY-r.top)/r.height,battlefieldPreset);
let best=START_ZONES[0],bd=1e9;
for(const Z0 of START_ZONES){ const Z=startZone(Z0.id),d=(u-Z.x)*(u-Z.x)+(v-Z.y)*(v-Z.y);if(dr.maps&&r.maps.indexOf(curMap)>=0);
const med=R&&theatreMapId(R.maps,'standard');
if(med) syncBattlefieldFromMap(med);
}
const ons=[...document.querySelectorAll('#facRow .fbtn.on')];
const specific=ons.find(b=>b.dataset.f&&b.dataset.f!=='random');
if(specific&&(typeof FACTIONS!=='undefined'&&FACTIONS[specific.dataset.f])) aiFactionSel=specific.dataset.f;
else if(!(aiFactionSel&&(aiFactionSel==='random'||(typeof FACTIONS!=='undefined'&&FACTIONS[aiFactionSel])))){
const fac=ons[0];
if(fac&&fac.dataset.f&&(fac.dataset.f==='random'||(typeof FACTIONS!=='undefined'&&FACTIONS[fac.dataset.f]))) aiFactionSel=fac.dataset.f;
else if(typeof META!=='undefined'&&META&&META.setup&&META.setup.f
&&(META.setup.f==='random'||(typeof FACTIONS!=='undefined'&&FACTIONS[META.setup.f])))
aiFactionSel=META.setup.f;
}
if(typeof persistEnemyFacPick==='function') persistEnemyFacPick();
const pf=setupOnBtn('#pfacRow .fbtn.on');
if(pf&&pf.dataset.f&&typeof playableFactions==='function'&&playableFactions().includes(pf.dataset.f))
playerFaction=pf.dataset.f;
const cmd=setupOnBtn('#commanderRow .commanderCard.on')||setupOnBtn('#mfQuickCommanders .mfQuickCommander.on');
if(cmd) playerCommanderId=cmd.dataset.commander||cmd.dataset.mfCommander||playerCommanderId;
const gl=setupOnBtn('#goalRow .glbtn.on'); if(gl&&gl.dataset.g) goalSel=gl.dataset.g;
const tm=setupOnBtn('#timeRow .tmbtn.on'); if(tm) timeLimit=+tm.dataset.t||0;
const pc=setupOnBtn('#paceRow .pcbtn.on'); if(pc) resPace=+pc.dataset.p;
const cr=setupOnBtn('#crRow .crbtn.on'); if(cr) crateRate=crateRateBase=+cr.dataset.c;
const inf=setupOnBtn('#infestRow .ifbtn.on'); if(inf) infestationOn=!!+inf.dataset.i;
const df=setupOnBtn('#defFocusRow .dfbtn.on'); if(df) defenseFocus=+df.dataset.df;
const pkg=setupOnBtn('#deployPkgRow .pkgbtn.on');
if(pkg&&DEPLOYMENT_PACKAGES[pkg.dataset.pkg]) deploymentPackage=pkg.dataset.pkg;
const gd=setupOnBtn('#globalDiffRow .globalDiff.on')||setupOnBtn('.globalDiff.on');
if(gd){
difficulty=+gd.dataset.d;
for(const A of aiSlots) if(A.on&&!A.ally) A.diff=difficulty;
} else if(typeof activeEnemySlots==='function'&&activeEnemySlots().length)
difficulty=Math.max(...activeEnemySlots().map(A=>A.diff));
const wc=setupOnBtn('#wcRowSel .wbtn.on'); if(wc) wcChoice=+wc.dataset.w;
const th=setupOnBtn('#threatRow .thBtn.on');
if(th&&typeof META!=='undefined'&&META) META.threatSel=+th.dataset.t||META.threatSel;
}
let matchSetupArmed=false;
function armMatchSetup(){ commitSetupFromDom(); matchSetupArmed=true; }
function consumeMatchSetup(){ if(!matchSetupArmed) return; matchSetupArmed=false; commitSetupFromDom(); }
function mfRescueHiddenSetupCards(){
/* Galaxy flow hides leftover .setupScroll > .setupCard. Landing package was
never moved into Advanced, so Prepared/Expedition never reached the match.
Rescue without touching the GALAXYβSYSTEMβPLANET stage machine. */
const body=$('mfAdvancedBody'); if(!body) return;
const el=$('deployPkgRow'), card=el&&el.closest('.setupCard');
if(card&&!body.contains(card)){ card.removeAttribute('data-setup-tab'); body.appendChild(card); }
}
function newSkirmish(){
const networkSetup=window.__MF_NETWORK_SETUP__&&window.__MF_NETWORK_SETUP__.schema===1;
const recovering=typeof sessPending!=='undefined'&&!!sessPending;
if(typeof invAbandonReadied==='function')invAbandonReadied();
_mfMatchCons=[];_mfMatchGear=[];
/* Game speed is a per-match control, not a profile setting. It was never
reset here, so one tap to 1.5x or 2x silently carried into every later
match in the session - and since it multiplies the whole simulation
accumulator, everything simply ran fast with no indication why. */
gameSpeed=1; try{ const _b=document.getElementById('spdBtn'); if(_b) _b.textContent='1Γ'; }catch(e){}
if(!networkSetup)consumeMatchSetup();
if(!networkSetup&&typeof sessBindMatchProfile==='function')
sessBindMatchProfile(recovering?sessPending.profileId:
typeof PROFILES!=='undefined'&&PROFILES&&PROFILES.active);
/* Pull the player faction's radio bank now, while the loading screen is up,
so the first order of the match speaks instead of falling back to whatever
the OS narrator happens to be. */
try{ if(typeof voPrewarm==='function'&&typeof radioFaction==='function') voPrewarm((radioFaction()||{}).id||'nova'); }catch(e){}
stopAttract(); // the menu diorama gives way to the real match
normalizeAiSlotsForBattlefield(); // final contract gate before any ally can spawn
resetWorld();
demoMode=false;
fogOn=networkSetup||META.settings.fog!==false;
if(networkSetup){
/* Online peers share a neutral match profile. Armory, modules and ready
consumables belong to local accounts and cannot alter a common world or
spend items in an unverified match. The account state is left untouched. */
WC={};wcActive=[];crateRate=crateRateBase;
if(typeof AB_CD!=='undefined'&&typeof AB_BASE!=='undefined')for(let i=0;ix.id===_b.equipped[s]); if(g) _mfMatchGear.push(g); }
_mfMatchCons=invApplyLoadout();
}
if(typeof applyCommanderChoice==='function')applyCommanderChoice();
if(typeof applyFactionDoctrineChoice==='function')applyFactionDoctrineChoice();
if(WC.meteor||(typeof mapHazardKey==='function'&&mapHazardKey(curMap)==='meteor')) stormTimer=40+mfSimRandom()*30;
renderWcRow();
/* ---- orbital drop ----------------------------------------------------
Spawns are inset from the map corners. The camera clamps its VIEW to the
battlefield, so a ship parked at 16% of the map sat in a corner the
camera physically could not centre β you could neither see it properly
nor fly it. 26% keeps both starts comfortably reachable while leaving
plenty of ground between them. */
const starts=skirmishSpawnPoints(), PS=starts[0];
const pxs=PS.x, pys=PS.y;
matchLive=false;
carrier.active=true; carrier.phase=0; carrier.alt=980; carrier.clearance=0;
/* The drop is the FIRST thing anyone sees of their own army, and it was
always Nova β "Nova is the current playable army" stopped being true once
the faction picker went into battle setup. It now arrives in the colours
and hardware of whatever the player actually chose. The query override
stays, ahead of the choice, so QA can still inspect any registered
deployer without touching progression. */
const carrierFacQa=(location.search.match(/[?&]carrierfac=(nova|terran|frontline|federation|legion|ascendancy|red|syndicate|machine|coalition|horde|brood|swarm|infestation)/)||[])[1]||'';
const carrierFacOwn=(typeof playerKitKey==='function')?playerKitKey():'nova';
carrier.fac=typeof dropFactionKey==='function'?dropFactionKey(carrierFacQa||carrierFacOwn):'nova';
carrier.x=pxs; carrier.y=pys; carrier.tx=pxs; carrier.ty=pys; carrier.ang=0; carrier.dust=0;
// AI start (mirrored)
/* The enemy fields its FACTION'S hero, not a mirror of yours. The Legion
walks a siege battery, the Syndicate a shielded hover platform, the Horde a
brood hive that keeps spawning β so "kill the enemy Commander" is a
different fight depending on who you drew. */
aiPickFaction(); // must precede the hero spawn AND setupNests()
/* Upload only this match's enemy architecture kit. Deferring the other two
avoids keeping three unused structure libraries resident on phones. */
if(typeof ensureBldFactionMeshes==='function'){
ensureBldFactionMeshes(AI.fac);
/* The player's own architecture too. bldMeshFor() would fault it in lazily,
but that lands on the frame the first structure finishes rather than
here in the carrier phase where an allocation is invisible. */
if(typeof playerKitKey==='function') ensureBldFactionMeshes(playerKitKey());
/* Neutral nests use Horde architecture even when another faction owns the
enemy base. Upload it during the carrier/deployment phase, where a short
allocation is invisible, instead of hitching the first frame a nest
enters view. If infestation is disabled no second kit is resident. */
if(infestationOn&&AI.fac!=='horde') ensureBldFactionMeshes('horde');
}
const FH=FACTIONS[AI.fac]||FACTIONS.legion;
const ownFH=(typeof FACTIONS!=='undefined'&&FACTIONS[playerFaction])||null;
const aiBases=[],allyBases=[];
const enemyRosterUsed=[], allyRosterUsed=playerCommanderId?[playerCommanderId]:[];
for(const S of starts.slice(1)){
const exs=S.x,eys=S.y,egx=Math.round(exs/SNAP_GRID)*SNAP_GRID,egy=Math.round(eys/SNAP_GRID)*SNAP_GRID;
const ally=!!S.ally,team=ally?0:1,fac=ally?carrierFacOwn:AI.fac;
/* Chassis is the faction hero type. Identity is a distinct roster id so
Large 1v3 is not three Vexes / Renns / Sovereigns. */
const heroType=ally?(ownFH&&ownFH.hero!=null?ownFH.hero:4):(FH.hero!=null?FH.hero:4);
const rosterFac=ally?(typeof commanderFactionKey==='function'?commanderFactionKey(playerFaction):playerFaction)||'nova':AI.fac;
const cmd=spawnAiRosterPick(rosterFac, ally?allyRosterUsed:enemyRosterUsed);
const h=spawnUnit(heroType,team,exs,eys,S.slot);
if(h>=0){if(ally)uAllyBase[h]=S.slot;else enemyHeroIdxs.push(h);}
const a=Math.atan2(MAP*.5-eys,MAP*.5-exs),fx=Math.cos(a),fy=Math.sin(a),rx=-fy,ry=fx;
/* B.allyAI had FOUR readers and ZERO writers. Ally bases stamped only
aiBaseSlot, so: the ally-factory lookup in aiAllyTick never matched and
allies NEVER produced a unit after their opening guard squad; the
econTick guard never fired, so ally reactors donated their income to
the player bank - the exact thing its own comment forbids; and
commanderSlotForBuilding billed every ally structure to the player
population seat. One missing stamp, three shipped bugs. */
const baseB=(type,x,y)=>{const B=addBld(type,team,x,y,true);B.fac=fac;B.aiBaseSlot=S.slot;if(ally)B.allyAI=S.slot;B.aiBehavior=aiBehaviorKey(S.behavior);if(ally)B.allyAI=S.slot;return B;};
baseB('pgen',egx+fx*105+rx*45,egy+fy*105+ry*45);
baseB('fac',egx+fx*105-rx*70,egy+fy*105-ry*70);
if(S.diff>=1)baseB('turret',egx+fx*178,egy+fy*178);
if(S.diff>=2){
baseB('turret',egx+fx*125+rx*155,egy+fy*125+ry*155);
baseB('pgen',egx+fx*45-rx*145,egy+fy*45-ry*145);
}
const guard=[1,3,5][S.diff];
for(let k=0;k=2&&k>2?1:0;
const u=spawnUnit(ty,team,egx+fx*(210+mfSimRange(-30,45))+rx*mfSimRange(-100,100),egy+fy*(210+mfSimRange(-30,45))+ry*mfSimRange(-100,100),S.slot);
if(u>=0){ustate[u]=1;utx[u]=egx;uty[u]=egy;if(ally)uAllyBase[u]=S.slot;}
}
let bd=1e12,bi=-1;
for(let d=0;d=0){ deposits[bi].taken=true; baseB('mex',deposits[bi].x,deposits[bi].y); }
/* Store the generation alongside the slot so ai.js can tell "still the same
Commander" from "that slot was recycled into somebody else's unit". */
const base={x:egx,y:egy,diff:S.diff,slot:S.slot,behavior:aiBehaviorKey(S.behavior),commander:h,fac,
commanderId:cmd&&cmd.id,commanderNm:cmd&&cmd.nm,
commanderGen:(h>=0&&typeof ugen!=='undefined')?ugen[h]:null,spawnT:18,orderT:4,mass:220,energy:900};
(ally?allyBases:aiBases).push(base);
aiDeployArrivals.push({x:egx,y:egy,fac,ang:a+Math.PI,depart:0});
}
livingEnemyCommanders();
setupNests();
setupRelics();
/* Deterministic device/browser QA scene. It is inert in every normal game;
the query hook lets release checks reproduce a roof crossing or a city
landing without relying on a lucky random camera route. */
const carrierQa=(location.search.match(/[?&]carrierqa=(fly|land)/)||[])[1]||'';
let carrierQaFocus=null;
if(carrierQa&&relics.length){
const R=relics.find(o=>o.alive&&o.kind===0)||relics.find(o=>o.alive);
if(R){
carrier.phase=1; carrier.alt=0; carrier.ang=0;
if(carrierQa==='fly'){
carrier.x=clamp(R.x-220,70,MAP-70); carrier.y=R.y;
carrier.tx=clamp(R.x+220,70,MAP-70); carrier.ty=R.y;
carrier.clearance=0;
} else {
carrier.x=R.x; carrier.y=R.y; carrier.tx=R.x; carrier.ty=R.y;
carrier.clearance=carrierObstacleClearanceAt(R.x,R.y,0);
}
carrierQaFocus=R;
window.__carrierQa={mode:carrierQa,roofX:R.x,roofY:R.y,roofKind:R.kind,
blocksBefore:carrierLandingBlockCount(),deployed:false};
}
}
aiSetup(difficulty,aiBases,allyBases);
/* Open framed on the ship, close enough to fly it. */
cam.x=carrierQaFocus?carrierQaFocus.x:pxs;
cam.y=carrierQaFocus?carrierQaFocus.y:pys;
orthoSpan=distTarget=carrierQaFocus?520:680; clampCam(); camUpdateMatrices();
camFollow=-1;
running=true; paused=false;
updateFog();
showHudDock(false); $('camRow').style.display='flex';
toast('β ORBITAL DROP β your super carrier is coming down');
sfx('flyby',carrier.x,carrier.y,0.72);
}
/* ---------- deploy the carrier: this is what actually starts the match ---------- */
function deployCarrier(){
/* LANDING HAPPENS ONCE.
Resuming a session arms the carrier through newSkirmish() and then polls
every 250ms to land it automatically, because a player nine minutes into a
fight should not be asked to pick a drop site again. Meanwhile the DEPLOY
button is still on screen - this function is what hides it - and its
handler calls straight in with no check of its own.
So there are two callers racing, and the only thing between them was the
poll's own `if(matchLive) return`. matchLive is not set until partway
through the landing, well after the HQ, the commander and the constructor
have been spawned, so a tap inside that window ran the whole sequence a
second time: two drops, two HQs, two starting armies.
carrierCanDeploy() cannot catch this - it asks whether the GROUND is
landable, not whether you have already landed on it. The guard belongs
here rather than on either caller, so every future entry point inherits it.
Silent on purpose: a duplicate is not a player error to report. */
if(typeof matchLive!=='undefined'&&matchLive) return;
if(!carrierCanDeploy()){
toast('β Cannot deploy here β need solid, flat ground clear of active structures');
sfx('alarm'); return;
}
if(!window.__MF_NETWORK_SETUP__&&!(typeof sessPending!=='undefined'&&sessPending)&&
typeof invCommitReadied==='function'&&!invCommitReadied()){
toast('Supply save failed β deployment paused. Retry when account storage is available');
sfx('alarm'); return;
}
/* Snap the landing point to the build grid. The HQ anchors every later
placement β structures axis-align to their neighbours β so an off-grid HQ
silently pushed the whole base half a cell out of alignment forever. */
const snap=carrierSnapPosition();
const cx2=snap[0], cy2=snap[1];
carrier.x=cx2; carrier.y=cy2;
const landing=carrierClearLandingZone(cx2,cy2);
if(window.__carrierQa){
window.__carrierQa.deployed=true;
window.__carrierQa.blocksCleared=landing.blocks;
window.__carrierQa.tanksCleared=landing.tanks;
window.__carrierQa.overlapsAfter=carrierLandingRelics(cx2,cy2).length;
}
carrier.phase=2; carrier.active=false;
const departNow=performance.now()/1000;
for(const A of aiDeployArrivals) A.depart=departNow;
/* You land with a Carrier HQ, your Commander and ONE constructor β nothing
else. Handing the player a pre-built reactor, factory and extractor made
the opening a formality; the layout that matters most is the one you lay
down yourself, and it should be yours from the first structure. The HQ
generates enough on its own to fund that first move. */
const hq=addBld('hq',0,cx2,cy2,true);
/* Visual-only unfolding window. The HQ exists immediately for simulation
and placement rules, while the renderer grows it out of the landing site
instead of making the dropship vanish and a finished base pop into view. */
hq.deployT=performance.now()/1000;
/* You field YOUR faction's hero, the same way the enemy fields theirs. The
Dominion walks Lord Darion Vex, the Syndicate a shielded hover platform,
the Brood its Sovereign β and Nova keeps the Commander. Until now only the
AI got this, so choosing a faction changed who you fought as everywhere
except the one unit you spend the whole match looking at.
No hero builds anything β `builder:1` belongs to the Constructor, which
lands beside you regardless β so this swaps a fighter, not an economy. */
const PH=(typeof FACTIONS!=='undefined'&&FACTIONS[playerFaction])||null;
heroIdx=spawnUnit(PH&&PH.hero!=null?PH.hero:4,0,cx2+52,cy2+44);
spawnUnit(UT_ENGINEER,0,cx2-52,cy2+44);
/* PREPARED LANDING is explicit onboarding support, not a hidden economy
bonus. The AI already owns these two structures. addBld deliberately owns
the placement so prefab ground is graded through the normal foundation
path instead of hovering over the landing plateau. */
if(deploymentPackage==='prepared'){
const snapB=(v)=>Math.round(v/SNAP_GRID)*SNAP_GRID;
const sites=[['pgen',snapB(cx2-102),snapB(cy2+4)],['fac',snapB(cx2+112),snapB(cy2+6)]];
for(const S of sites){
const B=addBld(S[0],0,S[1],S[2],true);
B.deployT=performance.now()/1000+0.14;
}
}
AI.base.x=AI.base.x; // (AI base already placed)
matchLive=true; stats.t=0; matchClock=timeLimit;
if(typeof commanderVoicePrewarm==='function') commanderVoicePrewarm(playerCommanderId);
/* The HUD drains gameplay dialogue on the fixed-step match clock, not page
time. This cue is raised at the same zero boundary as stats.t so a slow
boot cannot age it before the first simulated battle frame. */
if(typeof commanderCue==='function') commanderCue('objective','assigned',{
subject:(typeof goalDef==='function'&&goalDef().id)||'match',now:0,force:true
});
/* The setup modifier strip is useful before launch but becomes a duplicate
of the compact MOD chip once the battle begins. Hide it at the state
transition instead of waiting for another setup render that never comes. */
if(typeof renderWcRow==='function')renderWcRow();
if(typeof storyCampaignOnDeploy==='function')storyCampaignOnDeploy();
/* A dropped session is laid down here, AFTER the world has regenerated from
the same setup and seed β so we are restoring a fight onto a battlefield
that came back identically, not trying to persist the battlefield itself. */
if(typeof sessPending!=='undefined'&&sessPending){
const snap=sessPending; sessPending=null;
window.__mfSessionFallback=null;
const restored=typeof sessRestoreInto==='function'&&sessRestoreInto(snap);
if(restored){
toast('β SESSION RECOVERED β '+Math.round((snap.t||0)/60)+' minutes restored');
if(typeof sfx==='function') sfx('deploy');
}else{
/* The restore owns a destructive replay after its preflight. If an
unexpected replay invariant still fails, regenerate immediately and
return before this abandoned landing emits effects into the clean
world. The rejected snapshot was already cleared by session.js. */
const code=window.__mfSessionReject||'SESSION_RESTORE_FAILED';
if(typeof newSkirmish==='function')newSkirmish();
window.__mfSessionFallback={code,fresh:true};
toast('β SESSION COULD NOT BE RECOVERED Β· FRESH DEPLOYMENT READY');
return;
}
}
shake=Math.max(shake,16); flashScreen();
addParticle(3,cx2,cy2,0,0,1.2,420, 140,220,255);
for(let k=0;k<34;k++){
const a=Math.random()*TAU, sp=110+Math.random()*220;
addParticle(1,cx2,cy2,Math.cos(a)*sp,Math.sin(a)*sp,1.7,30, 150,142,124);
}
/* Landing destroys the surroundings, not the ground the new HQ already
occupies. The old single crater ran AFTER addBld() flattened and paved the
foundation, excavating a lake directly beneath the base. Four shallow
exhaust scars sit outside the HQ footprint and leave its engineered pad
intact while preserving the violent deployment event. */
for(let q=0;q<4;q++){
const a=q*TAU/4+Math.PI*.25,rx=cx2+Math.cos(a)*118,ry=cy2+Math.sin(a)*118;
deformTerrain(rx,ry,42,0.012);
if(typeof addGroundBurn==='function')addGroundBurn(rx,ry,58,0);
}
sfx('carrier_deploy',cx2,cy2,1.18); buzz(45);
showHudDock(true,'orders');
startFirstContactGuide();
$('deployBtn').style.display='none';
updateFog();
if(wcActive.length) toast('β '+wcActive.length+' modifiers active Β· +'+Math.round((wcRewardMult()-1)*100)+'% payout β tap MOD for details');
else if(landing.blocks||landing.tanks) toast('π LANDING ZONE CLEARED β '+landing.blocks+' city block'+(landing.blocks===1?'':'s')+' demolished');
else toast('π BASE DEPLOYED β your HQ powers itself. Build β Extractors on β deposits');
if(typeof showModSplash==='function') showModSplash();
setTimeout(()=>{ if(running&&matchLive) toast('⬑ BUILD GRID β establish inside HQ range; research a Targeting Array to extend territory'); },5200);
}
function newDemo(){
/* The 10,000-unit Mega / SANDBOX bench is GONE. It was a player-facing
stress toy that no longer represented the game, and it sat on the front
strip beside CAREER and INTEL as if it were a mode. newDemo() now serves
only the three hidden QA capture labs; with no lab token in the URL there
is nothing to enter, so bail before touching world or HUD state. */
const cannonLab=location.search.indexOf('cannonshow=1')>=0;
const defenseLab=location.search.indexOf('defenseshow=1')>=0;
const ammoLab=location.search.indexOf('ammoshow=1')>=0;
if(!cannonLab&&!defenseLab&&!ammoLab) return;
stopAttract();
resetWorld();
demoMode=true; matchLive=true;
carrier.active=false; carrier.phase=2;
WC={}; wcActive=[]; renderWcRow();
showHudDock(true,'powers');
$('deployBtn').style.display='none';
fogOn=false;
/* Hidden device-QA layout. `?cannonshow=1` keeps the real combat simulation
but brings smaller opposing lines into cannon range for readable captures. */
if(defenseLab){
const cx=MAP/2, cy=MAP/2+45, g=v=>Math.round(v/SNAP_GRID)*SNAP_GRID;
const base=[
['hq',0,215],['techlab',0,120],['sgen',-125,135,3],['uplink',130,140,3],
['bunker',-250,35,3],['turret',-155,35,3],['rail',-55,25],['bastion',55,25,3],
['aatower',155,35],['hellstorm',250,35,3],
['minelaser',-205,-85,3],['arc',-100,-90,3],['plasma',0,-90,3],
['missilebastion',110,-90,3],['nova',220,-85,3],
['wall',-200,-195],['wall',-145,-195],['wall',-90,-195],['gate',-30,-195],
['gate',30,-195],['wall',90,-195],['wall',145,-195],['wall',200,-195]
];
for(const [ty,dx,dy,lvl] of base){ const B=addBld(ty,0,g(cx+dx),g(cy+dy),true,0); if(lvl) B.lvl=lvl; }
for(let k=0;k<22;k++){
const a=(k-10.5)*.105, d=280+(k%4)*28;
const ty=[0,1,2,4,9,20,21,23][k%8];
let i=spawnUnit(ty,1,cx+Math.sin(a)*d,cy-190-Math.cos(a)*d*.35);
if(i>=0){ ustate[i]=2; utx[i]=cx+mfSimRange(-90,90); uty[i]=cy+40; }
}
for(let k=0;k<12;k++){
const ty=[0,1,2,9,11,19][k%6];
const i=spawnUnit(ty,0,cx-130+k%6*52,cy+105+(k>5?38:0));
if(i>=0){ ustate[i]=3; utx[i]=ux[i]; uty[i]=uy[i]; }
}
cam.x=cx; cam.y=cy-5; orthoSpan=distTarget=860; camPitch=pitchTarget=1.12; camYaw=yawTarget=.08;
clampCam(); camUpdateMatrices(); running=true; paused=false;
toast('π‘ DEFENSIVE NETWORK β 10 contact-sheet structure families live-fire');
return;
}
if(ammoLab){
/* One mirrored duel per armed chassis. A dense army turns every munition
into the same white explosion; separated lanes let the player actually
read the launch, flight and impact language of each weapon family. */
const roster=[0,1,2,3,4,6,7,8,9,10,14,15,16,17,18,20,21,22,23,25,26,27,28,29];
const cx=MAP/2, cy=MAP/2;
for(let k=0;k=0&&b>=0){
/* Showcase durability only: keep both emitters alive long enough to
compare several volleys instead of capturing 23 simultaneous deaths. */
uhpm[a]*=10; uhp[a]=uhpm[a]; uhpm[b]*=10; uhp[b]=uhpm[b];
utgt[a]=b; utgtg[a]=ugen[b]; ustate[a]=2; utx[a]=ux[b]; uty[a]=uy[b];
utgt[b]=a; utgtg[b]=ugen[a]; ustate[b]=2; utx[b]=ux[a]; uty[b]=uy[a];
}
}
cam.x=cx; cam.y=cy; orthoSpan=distTarget=800; camPitch=pitchTarget=1.08; camYaw=yawTarget=.05;
clampCam(); camUpdateMatrices(); running=true; paused=false;
toast('β‘ AMMUNITION LAB β 24 mirrored weapon duels running live');
return;
}
/* 72 a side, not 5000: the only caller left is the cannon capture lab. */
const perSide=72, cols=12;
for(let k=0;k=0){ ustate[i]=2; utx[i]=ux[i]; uty[i]=MAP*farY; }
i=spawnUnit(t,1, MAP/2+(col-cols/2)*22+mfSimRange(-6,6), MAP*farY-row*16+mfSimRange(-5,5));
if(i>=0){ ustate[i]=2; utx[i]=ux[i]; uty[i]=MAP*nearY; }
}
cam.x=MAP/2; cam.y=MAP/2; orthoSpan=distTarget=cannonLab?720:3200; clampCam(); camUpdateMatrices();
running=true; paused=false;
toast('π₯ COMMANDER CANNON QA β live damage and effects');
}
function mfResolveBattlefieldOutcome(win,reason){
const C=typeof window!=='undefined'&&window.MFMatchCommandConsumer;
/* The relay does not yet verify ordinary victories. Do not pass a local win
to downstream victory wrappers, which could offer the next paid map. */
const online=!!(C&&typeof C.sessionActive==='function'&&C.sessionActive());
endGame(online?false:win,online?'Local battlefield stopped; the relay has not confirmed the outcome.':reason);
}
function checkVictory(){
if(gameEnded||!running||(!matchLive&&!demoMode)) return;
if(demoMode){
if(teamCount[0]===0||teamCount[1]===0){
mfResolveBattlefieldOutcome(teamCount[1]===0,'Simulation complete');
}
return;
}
// losing your Commander always ends the run
if(heroIdx<0){ mfResolveBattlefieldOutcome(false,'Your Commander was destroyed'); return; }
const g=goalDef();
if(g.id==='annihilate'){
if(livingEnemyCommanders().length===0){ mfResolveBattlefieldOutcome(true,'Enemy commanders destroyed'); return; }
} else if(g.id==='purge'){
if(liveNests().length===0){ mfResolveBattlefieldOutcome(true,'Every hive purged from the surface'); return; }
if(livingEnemyCommanders().length===0&&liveNests().length===0){ mfResolveBattlefieldOutcome(true,'Planet cleansed'); return; }
} else if(g.id==='survival'){
/* Last Stand at UNLIMITED had a defeat condition and no victory condition
at all: the kill-the-commander win is excluded for survival, and the
timed resolver below is gated on timeLimit>0. A player could wipe the
enemy off the map and the match would simply keep running. Breaking the
siege outright is a win by any honest reading. */
if(timeLimit<=0&&livingEnemyCommanders().length===0){ mfResolveBattlefieldOutcome(true,'The siege was broken'); return; }
} else {
if(livingEnemyCommanders().length===0){ mfResolveBattlefieldOutcome(true,'Enemy commanders destroyed'); return; }
}
/* NOTHING ON A PHONE MAY RUN FOREVER. "Unlimited" means no SCHEDULED end, not
no end β and against an AI commander parked inside a fortified base, an
unlimited match could run until the player force-quit. A force-quit never
reaches endGame(), so it also paid nothing. Forty minutes is past any
honest match and short of a dead battery. */
if(timeLimit<=0&&stats.t>=MATCH_HARD_CAP){
const a=territoryScore(0), b=territoryScore(1);
mfResolveBattlefieldOutcome(a>=b,'Stalemate β decided on territory'); return;
}
// timed goals resolve on the clock
if(timeLimit>0&&matchClock<=0){
if(g.id==='domination'){
const a=territoryScore(0), b=territoryScore(1);
mfResolveBattlefieldOutcome(a>=b, a>=b?'Time β you held the most territory':'Time β the enemy held more territory');
} else if(g.id==='survival') mfResolveBattlefieldOutcome(true,'Time β you survived the siege');
else if(g.id==='purge') mfResolveBattlefieldOutcome(false,'Time β hives still stand');
else mfResolveBattlefieldOutcome(territoryScore(0)>=territoryScore(1),'Time β decided on territory');
}
}
let mfResultPresentationEpoch=0,mfLastResultCanRestart=false;
function endGame(win,reason){
const C=typeof window!=='undefined'&&window.MFMatchCommandConsumer,
online=!!(C&&typeof C.sessionActive==='function'&&C.sessionActive()),
networkStatus=online&&window.MFMatchRuntime&&typeof MFMatchRuntime.status==='function'?MFMatchRuntime.status():null,
localSeat=networkStatus&&networkStatus.seat||0,
localAuthority=online&&C&&typeof C.seatAuthority==='function'?C.seatAuthority(localSeat):null,
localTeam=localAuthority&&localAuthority.team===1?1:0,hostileTeam=localTeam===0?1:0;
if(online&&gameEnded)return;
/* Weekly and authored missions give their borrowed plan back while scoring
the result. Capture retry eligibility before that cleanup changes mode
flags; a defeated UGA ticket or online seat must never be replayed here. */
const bridge=typeof window!=='undefined'&&window.__MF_GALACTIC_BRIDGE;
mfLastResultCanRestart=!win&&!online&&!demoMode&&activeWarMode==='standard'
&&!(typeof weeklyMode!=='undefined'&&weeklyMode)
&&!(typeof storyCampaignActiveId!=='undefined'&&storyCampaignActiveId)
&&!(typeof trainingMissionActive==='function'&&trainingMissionActive())
&&!window.__MF_NETWORK_SETUP__
&&!(bridge&&(bridge.active||bridge.isolation&&bridge.isolation.active));
const presentationEpoch=++mfResultPresentationEpoch;
/* Emit the terminal commander line before gameEnded hides the battlefield
rail. Audio may be absent, but the deterministic event still reaches the
transcript and any active presentation listener exactly once. */
if(!online&&!gameEnded&&typeof commanderCue==='function'){
const cueNow=Math.max(0,(Number(stats.t)||0)*1000);
commanderCue('outcome',win?'victory':'defeat',{subject:String(reason||'match'),now:cueNow,force:true});
if(typeof commanderDialogueDrain==='function') commanderDialogueDrain(cueNow);
}
gameEnded=true;
if(online){
/* This is a local or relay terminal, not a verified payable outcome. Stop
immediately and release the socket so the room cannot tick forever. The
consumer keeps match ownership latched until explicit menu cleanup. */
running=false;paused=false;
if(window.MFMatchRuntime&&typeof MFMatchRuntime.close==='function')MFMatchRuntime.close();
}
// report match result to a hosting shell (Base44 app) if embedded
try{if(!online){
if(window.parent!==window) window.parent.postMessage({
type:'massfront-result', win:!!win, demo:!!demoMode,
difficulty, theme:curTheme, duration:stats.t|0,
kills:stats.kills[0]|0, losses:stats.kills[1]|0,
heroLevel:heroLvl|0, built:stats.built[0]|0
},'*');
}}catch(e){}
const rw=demoMode||online?null:metaGrant(win); // cross-game rewards (persisted immediately)
/* The endgame layer scores the run, advances the threat ladder, ticks the
mastery grid and records a weekly best β all from what actually happened. */
const dv=demoMode||online?null:(typeof developRecord==='function'?developRecord({
win:!!win, kills:stats.kills[0]|0, built:(stats.built[0])|0, nests:stats.nests|0,
fieldMass:Math.max(0,Math.floor(resM[0]||0)),fieldEnergy:Math.max(0,Math.floor(resE[0]||0)),
reclaimed:Math.max(0,Math.round(stats.reclaimed||0))}):null);
const eg=demoMode||online?null:(typeof endgameRecord==='function'?endgameRecord({
win:!!win, kills:stats.kills[0]|0, built:(stats.built[0])|0,
seconds:stats.t|0, difficulty:difficulty|0}):null);
/* The dispatch waits for the results screen to be dismissed β a story beat
landing on top of a victory screen reads as an interruption. */
setTimeout(()=>{
if(presentationEpoch!==mfResultPresentationEpoch)return;
running=false;
$('goTitle').textContent=online?'ONLINE RESULT UNVERIFIED':win?'MISSION COMPLETE':'MISSION FAILED';
$('goTitle').style.color=online?'#f4cf86':win?'#9fffc4':'#ff8d7a';
const mins=(stats.t/60)|0, secs=(stats.t%60)|0;
const outcome=$('goOutcome');
if(outcome) outcome.textContent=(online?'NO PROGRESSION REWARD Β· ':'')+goalDef().nm.toUpperCase()+' Β· '+reason;
$('goStats').innerHTML='
The relay has not verified this battlefield result. No XP, Cores, loot, or campaign progress was awarded.
':'';
/* The previous result may have exposed CONTINUE. Hide and disarm it before
the mode-specific painter runs, or a rapid defeat tap can activate the
stale victory action for a few frames. */
const cont=$('goContinueBtn');
if(cont){cont.style.display='none';cont.disabled=true;cont.dataset.action='';}
if(online){
if(typeof mfDepart!=='undefined')mfDepart.fromVictory=false;
}
if(online){const chart=$('goChart');if(chart)chart.style.display='none';}
else drawMatchChart();
if(!online&&typeof adShowPostMatchAd==='function') adShowPostMatchAd(win);
$('gameOver').style.display='flex';
if(!online)sfx(win?'level':'alarm');
},1400);
}
window.addEventListener('massfront-match:matchEnd',event=>{
const C=window.MFMatchCommandConsumer;if(!C||typeof C.sessionActive!=='function'||!C.sessionActive()||gameEnded)return;
const detail=event&&event.detail||{},seat=Number(detail.winnerSeat),winner=Number.isInteger(seat)&&seat>0?' Β· winning seat '+seat:'';
endGame(false,'Relay ended the match: '+String(detail.reason||'unknown')+winner);
});
window.addEventListener('massfront-match:protocolError',event=>{
const C=window.MFMatchCommandConsumer;if(!C||typeof C.sessionActive!=='function'||!C.sessionActive())return;
const code=String(event&&event.detail&&event.detail.code||'unknown');
/* A failed bootstrap can occur before newSkirmish clears the previous
operation's gameEnded flag. It still needs a visible no-reward result. */
if(gameEnded){if(!/^bootstrap_/.test(code))return;gameEnded=false;}
endGame(false,'Match connection failed: '+code);
});
// ---------- main loop ----------
let acc=0, lastT=0, fpsN=0, fpsT=0, fpsShow=60;
const MF_SIM_DT=1/30,MF_SIM_MAX_STEPS=3,MF_SIM_DEBT_TICKS=8;
let mfSimDebtClamped=0,mfSimNetworkWaitFrames=0;
function mfMatchConsumer(){return typeof window!=='undefined'&&window.MFMatchCommandConsumer||null;}
/* Mobile panels commonly refresh at 90/120/144 Hz, but this renderer targets
a stable 60 Hz presentation. Keep the authoritative 30 Hz simulation on
every RAF callback while suppressing only duplicate presentation work. A
short consecutive-sample gate avoids mistaking one early 60 Hz callback for
a high-refresh display, and the deadline accumulator gives 90 Hz panels the
correct alternating 1/2-callback cadence instead of collapsing to 45 Hz. */
const MF_PRESENT_MS=1000/60;
let mfRafSampleT=0,mfFastRafStreak=0,mfPresentationCapped=false;
let mfPresentNext=0,mfPresentDt=0,mfPresentationSkips=0,mfPresentationFrames=0;
function mfPresentationDue(ts){
if(!mfRafSampleT){mfRafSampleT=ts;mfPresentNext=ts;mfPresentationFrames++;return true;}
const gap=ts-mfRafSampleT;mfRafSampleT=ts;
if(gap>=4&&gap<13.5)mfFastRafStreak++;
else if(gap>=13.5)mfFastRafStreak=0;
if(!mfPresentationCapped&&mfFastRafStreak>=8){
mfPresentationCapped=true;mfPresentNext=ts;
}
if(!mfPresentationCapped){mfPresentationFrames++;return true;}
if(ts+0.750 && (window.__MF_OTA_RAN|0)!==expect){
/* main.js is not the final OTA artifact. On Android the first rAF can land
while the tail scripts are still executing. Latching bootConfirmed here
made that harmless timing window permanent: probation survived, and the
next launch rolled the update back to the old APK. Leave the latch open
so the frame loop retries; log only when the observed count changes. A
genuinely throwing/missing artifact still never reaches `expect`, so the
existing rollback safety remains intact. */
const ran=window.__MF_OTA_RAN|0;
if(bootIncompleteCount!==ran){
bootIncompleteCount=ran;
try{ console.warn('boot: OTA payload still loading - '+ran+' of '+expect+
' artifacts ran; boot confirmation will retry'); }catch(e){}
}
return;
}
bootConfirmed=true;
if(window.__MASSFRONT_RELEASE_INPUT_GUARD)
window.__MASSFRONT_RELEASE_INPUT_GUARD();
if(window.__bootOk) window.__bootOk();
}
/* ============================================================================
ATTRACT MODE β the menu is a window onto the game, not a picture of it
----------------------------------------------------------------------------
The start screen used to be a gradient. Everything needed to make it a live
scene was already built and idle: terrain, models, lighting, the day cycle.
So the menu now sits over a real battlefield with a real base on it, lit by
the real sun, with the camera making a slow orbit β and the panels float in
front of it in perspective rather than lying flat on top.
It is deliberately small: a few dozen units and a handful of structures, a
slow sim tick, no AI and no fog. A menu should never be the most expensive
thing the game does. */
let attractOn=false, attractT=0, attractCX=0, attractCY=0;
/* Lower bound the frame-rate scaler may not go below. Zero on every preset but
CINEMATIC, which exists precisely to stop the automatic backing-off. */
let perfFloor=0;
/* A snapshot waiting to be laid down once the world has regenerated. */
let sessPending=null;
/* THE PLAYER'S OWN FACTION.
src/audio.js has been reading `playerFaction` since the radio system landed,
but nothing ever declared it β so it was permanently undefined and the player
always spoke with Nova's voice no matter what they were fielding. The setup
screen let you pick your OPPONENT's faction and not your own, which is an odd
thing for a game whose four armies have genuinely different chassis kits.
'nova' is the Terran line and stays the default. */
let playerFaction='nova';
let playerCommanderId='nova_kai';
function menuBg(){ return (META&&META.settings&&META.settings.menubg)||'dim'; }
/* Off keeps the menu chrome β the HUD must still be hidden β but skips building
and ticking the diorama entirely. menuMode is what suppresses the in-match
HUD, so it stays on either way; only attractOn changes. */
function applyMenuBackdrop(){
const ss=document.getElementById('startScreen');
const training=typeof trainingMissionActive==='function'&&trainingMissionActive();
/* Training owns the carrier/loading transition before `running` flips true.
Treating that short window as a menu let applySettings() restart the
attract scene and re-add menuMode over the live tutorial HUD. */
if(training){ document.body.classList.remove('menuMode'); return; }
const onMenu=!running && ss && ss.style.display!=='none';
if(!onMenu) return;
document.body.classList.add('menuMode');
if(menuBg()==='off'){ attractOn=false; return; }
if(!attractOn) setupAttract();
}
function setupAttract(){
/* Cold launch now passes through the visual updater before the main menu.
Building the terrain diorama behind a download wastes memory, heat and GPU
time, so the launcher keeps this function dormant until PLAY hands off. */
if(typeof mfLauncherShouldDeferAttract==='function'&&mfLauncherShouldDeferAttract()){
attractOn=false;document.body.classList.add('menuMode');return;
}
if(typeof trainingMissionActive==='function'&&trainingMissionActive()){
stopAttract();
return;
}
if(!terrVerts) return;
if(menuBg()==='off'){ document.body.classList.add('menuMode'); attractOn=false; return; }
resetWorld();
/* A completed match leaves albedo scars and Brood relief behind. Clear the
old entities first, then rebuild only dirty terrain before the diorama
paints its own foundations; clearing creepF alone leaves purple albedo. */
if(mmDirty) applyTheme();
if(typeof materialV2SetupAttract==='function'&&materialV2SetupAttract())return;
demoMode=false; matchLive=false; fogOn=false;
/* Somewhere scenic and reachable: the map's own player start, which is
guaranteed to be buildable ground. */
const bx=MAP*SP_LO, by=MAP*SP_HI;
attractCX=bx; attractCY=by;
const g=v=>Math.round(v/SNAP_GRID)*SNAP_GRID;
addBld('hq',0,g(bx),g(by),true,0);
for(const [ty,dx,dy] of [['fac',150,-90],['pgen',-140,-70],['pgen',-140,30],
['turret',60,170],['techlab',150,80],['silo',-140,130],
['aatower',-40,-190],['uplink',180,0]]){
const x=g(bx+dx), y=g(by+dy);
if(!footBlocked(ty,x,y,0)&&footOnLand(ty,x,y,0)) addBld(ty,0,x,y,true,0);
}
/* A patrol worth watching: a mixed column walking a slow circuit past the
base, so there is movement, dust and walk cycles rather than a still life. */
for(let k=0;k<34;k++){
const ty=[0,1,2,9,11,19,22,20][k%8];
const a=k/34*TAU, d=190+Math.random()*160;
const i=spawnUnit(ty,0,bx+Math.cos(a)*d,by+Math.sin(a)*d);
if(i>=0){
ustate[i]=5; // patrol
upx1[i]=ux[i]; upy1[i]=uy[i];
upx2[i]=bx+Math.cos(a+2.2)*d; upy2[i]=by+Math.sin(a+2.2)*d;
utx[i]=upx2[i]; uty[i]=upy2[i];
}
}
orthoSpan=distTarget=880; camPitch=pitchTarget=1.16;
cam.x=bx; cam.y=by; camYaw=yawTarget=0.4;
clampCam(); camUpdateMatrices();
attractOn=true; attractT=0;
/* The in-match HUD has no business showing through the menu. */
document.body.classList.add('menuMode');
}
function attractTick(dt){
if(typeof materialV2TickAttract==='function'&&materialV2TickAttract(dt))return;
attractT+=dt;
/* A slow orbit with a gentle breathing zoom. Slow enough to read as
cinematic; never so slow that it looks frozen on a first glance.
Dimmed halves every rate again: the eye tracks change, not brightness, so
slowing the motion does more for legibility than darkening alone. */
const m = menuBg()==='dim' ? 0.45 : 1;
camYaw=yawTarget=0.4+attractT*0.055*m;
orthoSpan=distTarget=880+Math.sin(attractT*0.17*m)*150;
camPitch=pitchTarget=1.18+Math.sin(attractT*0.11*m)*0.06;
cam.x=attractCX+Math.cos(attractT*0.09*m)*40;
cam.y=attractCY+Math.sin(attractT*0.07*m)*40;
clampCam(); camUpdateMatrices();
/* One slow sim step: the patrol walks, guns idle, dust drifts. */
const sd=1/24;
unitTick(sd); projTick(sd); bldTick(sd); beamTick(sd); envTick(sd);
updParticles(sd); shardTick(sd);
/* Parallax: the UI leans against the orbit, so the panels feel like they are
standing in the scene rather than pasted over it. */
const ss=document.getElementById('startScreen');
if(ss&&ss.style.display!=='none'){
const lx=Math.sin(attractT*0.055)*5.0*m, ly=Math.cos(attractT*0.041)*3.0*m;
ss.style.setProperty('--px',lx.toFixed(2)+'deg');
ss.style.setProperty('--py',ly.toFixed(2)+'deg');
}
}
function stopAttract(){
attractOn=false; document.body.classList.remove('menuMode');
/* #gl is display:none under menuMode.bgOff. Remeasure after it is shown
so a landscape desktop window is not stuck with the hidden-canvas size. */
if(typeof resize==='function') resize();
}
/* A FROZEN MATCH MUST SAY SO.
frame() schedules its own next frame on its FIRST line, then runs the whole
simulation step unguarded. One exception anywhere in that step - a bad unit,
a null structure, a malformed order - and the rest of the frame never runs,
while requestAnimationFrame keeps firing forever. The result is the worst
shape a failure can take: the canvas holds its last good frame, HUD CSS
animations and audio keep playing so the game looks alive, pause does nothing
because `paused` is only read inside the body that is throwing, and queued
abilities are never consumed. The player reports "it froze" and there is
nothing in the log, because the same error is thrown and discarded sixty
times a second with no one listening.
This does not swallow the error and carry on - continuing a deterministic
simulation past an exception is how you turn a crash into a desync. It stops
the match deliberately, once, and names the cause: console, a visible toast,
and window.mfSimFailure so a probe or a bug report can read it back. A halted
match that explains itself can be diagnosed; a silent freeze cannot. */
function mfReportSimFailure(error,phase){
if(mfSimFailure) return;
const detail={
phase:phase||'sim',
message:String(error&&error.message||error),
stack:String(error&&error.stack||''),
tick:typeof tick==='number'?tick:null,
clock:typeof matchClock==='number'?matchClock:null,
when:new Date().toISOString()
};
mfSimFailure=detail;
try{window.mfSimFailure=detail;}catch(e){}
try{console.error('MASSFRONT '+detail.phase+' failure at tick '+detail.tick,error);}catch(e){}
/* Halt rather than repeat. The next frame would throw in the same place. */
try{paused=true;}catch(e){}
try{if(typeof toast==='function')toast('Simulation halted: '+detail.message.slice(0,80));}catch(e){}
}
function frame(ts){
requestAnimationFrame(frame);
if(typeof mfPerfFrameBegin==='function') mfPerfFrameBegin();
if(!bootConfirmed) confirmBoot();
if(!lastT) lastT=ts;
let dt=(ts-lastT)/1000; lastT=ts;
if(dt>0.25) dt=0.25;
mfPresentDt=Math.min(0.25,mfPresentDt+dt);
const presentDue=mfPresentationDue(ts);
const presentDt=presentDue?mfPresentDt:0;
if(presentDue)mfPresentDt=0;
// fps
if(presentDue)fpsN++;
fpsT+=dt;
if(fpsT>=0.6){
fpsShow=Math.round(fpsN/fpsT); fpsN=0; fpsT=0;
const total=teamCount[0]+teamCount[1]+teamCount[2];
/* HYSTERESIS. Dozens of effects gate or scale on this value; a bare
threshold on a noisy fps signal flipped it 0.55<->1.0 twice a second at
36-44 fps and strobed all of them at once β glows, beams, dust, water
sparkle. Drop instantly to protect the frame, rise only with headroom.
(This block also used to EASE the visible value "so changes arrive as
fades, not steps". That reintroduced the very strobe it sits above β see
the note on the assignment below β and has been removed.) */
const band=fpsShow<28?0.25:fpsShow<42?0.55:1;
if(bandperfBand&&fpsShow>(perfBand<0.5?34:48)) perfBand=band;
/* QUANTISED, NOT EASED β this is the fix for the half-second FX strobe.
About seventy effects gate on perfScale, and their thresholds sit in one
tight cluster between 0.30 and 0.56: water sparkle, shadow decals, tread
dust, debris, rubble, repair beams, muzzle flashes, and ambient occlusion
at 0.50. Easing the value dragged it through EVERY threshold in that
cluster on a single band change, so all of those effects switched off and
came back over about half a second. Measured on a real GPU: one 1.00 ->
0.25 ramp crossed all six sampled gates (tools/verify-perfscale-gates.mjs).
perfBand above is ALREADY the anti-strobe mechanism β drop instantly,
rise only with headroom. Reading it directly gives one deliberate step
per genuine performance change. The ease this replaces existed so
particle COUNTS would fade rather than step, but a count going from 5 to
3 is invisible while a shadow pass vanishing is not. */
perfScale=perfBand;
/* These were 7000 and 18000 β thresholds inherited from the 10,000-unit
Mega demo, which no longer exists. A real match caps at FACTION_POP_CAP
(500) per commander seat, so four participants top out at 2000 real
units; a Hard Brood system force may add 500 more. Both old thresholds
sat above even that maximum and could never fire. Re-scaled so a heavy
fight is protected before the frame is already gone. */
if(total>1300) perfScale=Math.min(perfScale,0.55);
if(total>1700) perfScale=Math.min(perfScale,0.3);
if(META.settings.perf==='low') perfScale=Math.min(perfScale,0.45);
/* CINEMATIC sets a floor under the automatic scaler, so a heavy fight
cannot quietly strip the frame back to the low preset β which is the
whole reason someone picks it. */
if(typeof perfFloor!=='undefined'&&perfFloor>0) perfScale=Math.max(perfScale,perfFloor);
/* Density is a SETTING, not an observation, so it is applied on the way out
of a value recomputed from perfBand each sample β never folded back into
an accumulator. It used to compound: `perfScale *= GFX.particles` ran
after the ease, so its own output was re-eased and re-multiplied every
sample. Measured on a real GPU it settled at 3.63-3.86 on CINEMATIC
(x1.5) against an intended ceiling of 1.0 β roughly 4x the particles it
was asked for β and at 0.31 on LOW (x0.5) at a locked 60fps, which
silently disabled every effect gated above 0.32. */
if(typeof GFX!=='undefined'&&GFX.particles) perfScale*=GFX.particles;
}
/* A halt is STICKY. Reporting is one-shot, so without this gate the pause
menu's RESUME clears `paused`, the sim re-enters the same throwing code,
and mfReportSimFailure returns early with nothing on screen β the player
is back in the original silent freeze, having been told once that it was
explained. resetWorld() clears the latch, so a new match still starts. */
if(running&&!paused&&!gameEnded&&!mfSimFailure){
if(typeof mfPerfBegin==='function') mfPerfBegin('sim');
const simDt=MF_SIM_DT;
try{
acc+=dt*gameSpeed;
const debtCap=simDt*MF_SIM_DEBT_TICKS;
if(acc>debtCap){mfSimDebtClamped+=Math.floor((acc-debtCap)/simDt);acc=debtCap;}
let steps=0;
while(acc>=simDt&&stepsorthoSpan*0.55)
carrierFollow();
if(typeof mfPerfBegin==='function')mfPerfBegin('simUnits');
unitTick(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simUnits');
if(typeof mfPerfBegin==='function')mfPerfBegin('simProjectiles');
projTick(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simProjectiles');
if(typeof mfPerfBegin==='function')mfPerfBegin('simStructures');
bldTick(simDt);
fortTick(simDt);
buildZoneTick(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simStructures');
if(typeof mfPerfBegin==='function')mfPerfBegin('simEconomy');
reclaimTick(simDt);
econTick(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simEconomy');
if(typeof mfPerfBegin==='function')mfPerfBegin('simCombatEffects');
abilTick(simDt);
beamTick(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simCombatEffects');
if(typeof mfPerfBegin==='function')mfPerfBegin('simWorld');
envTick(simDt);
crateTick(simDt);
sceneryTick(simDt);
shardTick(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simWorld');
if(typeof mfPerfBegin==='function')mfPerfBegin('simParticles');
updParticles(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simParticles');
if(typeof mfPerfBegin==='function')mfPerfBegin('simDeformation');
processDeforms();
if(typeof waterFloodTick==='function') waterFloodTick(simDt);
deformMaintain(simDt);
if(typeof mfPerfEnd==='function')mfPerfEnd('simDeformation');
if(!demoMode&&!matchLive){ // keep vision live while flying the carrier in
fogAcc+=simDt;
if(fogAcc>=0.4){
if(typeof mfPerfBegin==='function')mfPerfBegin('fog');
updateFog();fogAcc=0;
if(typeof mfPerfEnd==='function')mfPerfEnd('fog');
}
}
if(matchLive&&!demoMode&&timeLimit>0&&matchClock>0) matchClock=Math.max(0,matchClock-simDt);
if(!demoMode&&matchLive){ // the war only runs once you've planted your base
aiAcc+=simDt;
if(aiAcc>=0.5){
if(typeof mfPerfBegin==='function')mfPerfBegin('ai');
aiTick(aiAcc);aiAcc=0;
if(typeof mfPerfEnd==='function')mfPerfEnd('ai');
}
fogAcc+=simDt;
/* Fog also records explored terrain and discovered entities. Preserve
its authority cadence; profile the pulse before splitting it. */
if(fogAcc>=0.5){
if(typeof mfPerfBegin==='function')mfPerfBegin('fog');
updateFog();fogAcc=0;
if(typeof mfPerfEnd==='function')mfPerfEnd('fog');
}
if(stats.t-tlLast>=5){tlLast=stats.t;tlRecord();}
}
if(consumer&&typeof consumer.commitTick==='function')consumer.commitTick(nextTick);
if(typeof mfDeterminismEndStep==='function')mfDeterminismEndStep();
/* Resolve the same terminal tick on fast and stalled clients. Waiting
until a whole render catch-up batch finishes allowed extra combat and
rewards during the result screen's 1.4-second presentation delay. */
checkVictory();
if(gameEnded){acc=0;break;}
}
}catch(error){ mfReportSimFailure(error,'sim'); }
if(typeof mfPerfEnd==='function') mfPerfEnd('sim');
}
if(!running && attractOn && attractVisible){
attractTick(dt);
if(presentDue){
processDeforms();
render(presentDt);
}
musicTickFrame(dt);
if(typeof mfPerfFrameEnd==='function') mfPerfFrameEnd();
return;
}
camTick(dt);
if(running){
if(!paused&&perfScale>0.4) weatherTick(dt);
if(presentDue){
render(presentDt);
floatTextTick(presentDt);
if(typeof mfPerfBegin==='function') mfPerfBegin('minimap');
renderMinimap();
if(typeof mfPerfEnd==='function') mfPerfEnd('minimap');
if(typeof mfPerfBegin==='function') mfPerfBegin('hud');
updateHUD(fpsShow);
if(typeof mfPerfEnd==='function') mfPerfEnd('hud');
}
}
musicTickFrame(dt);
if(typeof mfPerfFrameEnd==='function') mfPerfFrameEnd();
}
/* Mid-tier CPU at 500 pop per commander seat. GPU fillrate is the quality preset; this is
sim/HUD/pathfinding. Takeover, not edits to the renderer files. */
function mfCpuBind(){
/* Pathfinding is simulation authority. Replacing computeField/requestField
here made runtime behavior depend on boot order and silently discarded
blocker, clearance and replay fixes made in src/game/sim.js. Keep CPU
tuning on the authoritative implementation instead of shadowing it. */
mfCpuBindMinimap();
mfCpuBindIcons();
mfCpuBindFx();
}
/* mfGfxKey() lives in src/engine/gl.js (manifest index 3). This file is index
79, so a duplicate here silently overwrote that one β editing the documented
definition in gl.js would have had no effect. Do not re-add it.
tools/verify-global-scope.mjs fails the build on this class of shadowing. */
function mfCpuBindSep(){
if(typeof unitSeparation!=='function') return;
const orig=unitSeparation;
unitSeparation=function(i,T,isBug,swarmLOD,total){
/* HIGH keeps the original 800/every-other skip. MEDIUM starts earlier and
strides harder so 400β800 pop does not pay HIGH-class pair tests. */
const q=mfGfxKey();
const gate=q==='low'?280:q==='medium'?420:800;
const stride=q==='low'?3:q==='medium'?(total>900?3:2):2;
if(total>gate && ((i+tick)%stride) && !usel[i] && T.cat!=='hero'){
sepVX=0; sepVY=0; sepHits=0; sepVisited=0;
return;
}
return orig(i,T,isBug,swarmLOD,total);
};
}
function mfCpuBindMinimap(){
if(typeof renderMinimap!=='function') return;
const orig=renderMinimap;
let keep=null, keepT=0, skip=0, keepGen=-1;
renderMinimap=function(){
const tot=(teamCount[0]+teamCount[1]+teamCount[2])|0;
const now=performance.now();
const q=mfGfxKey();
/* Deform stamps null mmBg on every crater. The 2048β256 civic downsample
(drawImage of terrainCanvas) is the #2 CPU hotspot at 500 pop per seat.
HIGH/CINEMATIC refresh scars sooner; MEDIUM holds the last bake longer. */
const hold=q==='low'?1600:q==='medium'?1100:q==='cinematic'?320:520;
/* Hold only a bake from this map gen. Restoring a black/stale keep
after applyTheme nulls mmBg is why MEDIUM phones kept a black square. */
if(keep && keepGen===mmBgGen && now-keepT280?2:1):(tot>700?2:1);
if(keep && keepGen===mmBgGen && skipN>1 && (++skip%skipN)) return;
orig();
if(typeof mmBg!=='undefined'&&mmBg){ keep=mmBg; keepT=now; keepGen=mmBgGen; }
else { keep=null; keepGen=-1; }
};
}
function mfCpuBindIcons(){
/* Screen-footprint handover already lives in tacticons.js (24β15 px).
MEDIUM/LOW convert a few pixels earlier so infantry drop meshes sooner.
HIGH/CINEMATIC keep the authored ramp β do not make the flagship cheaper. */
if(typeof mfIconQ!=='function') return;
const orig=mfIconQ;
mfIconQ=function(worldSpan){
const q=mfGfxKey();
if(q==='high'||q==='cinematic') return orig(worldSpan);
const px=worldSpan/(typeof mfWorldPx==='function'?mfWorldPx():Math.max(.24,orthoSpan/Math.max(1,VH)));
if(q==='medium') return clamp((28-px)/(28-17),0,1);
return clamp((34-px)/(34-20),0,1);
};
}
function mfCpuBindFx(){
/* GPUFX already scales burst counts via GFX.particles. This only thins the
CPU sprite ring (MAXPART=9000) for atmosphere/dust β combat flashes stay. */
if(typeof addParticle!=='function') return;
const orig=addParticle;
let dustN=0;
addParticle=function(type,x,y,vx,vy,life,size,r,g,b){
const q=mfGfxKey();
if(q==='medium'||q==='low'){
/* Thin atmosphere, do not delete it β LOW keeps a quarter, MEDIUM half. */
if(type===9 && ((++dustN)&(q==='low'?3:1))) return;
if(type===10 && (dustN&(q==='low'?3:1))) return;
if(type===1 && q==='medium' && size<9 && (dustN&1)) return;
}
return orig(type,x,y,vx,vy,life,size,r,g,b);
};
}
// ---------- UI wiring ----------
let builtTheme='verdant', builtMap='aelos_north_medium', builtTopology='';
function applyTheme(){
/* setupDeposits and spawn normalization happen before buildTerrain reaches
its exact-plan gate. Keep the previous live world by identity so a rejected
destination cannot leave fresh economy or selector state attached to the
prior terrain texture. buildTerrain owns the matching CPU-terrain rollback. */
const own=k=>Object.prototype.hasOwnProperty.call(window,k);
const prop=k=>({had:own(k),value:window[k]});
const before={
aiRefs:aiSlots.slice(),aiRows:aiSlots.map(A=>({...A})),playerStartZone,spawnPick,
deposits:deposits.slice(),geysers:geysers.slice(),seed:_seed,
civicKitSeq:typeof civicKitSeq==='number'?civicKitSeq:null,
depPts:prop('__depPts'),relocation:prop('__mfResourceRelocation'),
cityAt:prop('__cityAt'),reclaimTip:prop('__reclaimTip')
};
const restoreProp=(key,S)=>{if(S.had)window[key]=S.value;else delete window[key];};
const restoreSetup=()=>{
aiSlots.length=0;for(const A of before.aiRefs)aiSlots.push(A);
for(let i=0;i400) tl.shift();
}
function drawMatchChart(){
const cv3=$('goChart'); if(!cv3||tl.length<3){ if(cv3) cv3.style.display='none'; return; }
cv3.style.display='block';
const c=cv3.getContext('2d'), W=cv3.width, H=cv3.height;
c.clearRect(0,0,W,H);
c.fillStyle='rgba(10,18,30,.85)'; c.fillRect(0,0,W,H);
let mx=10; for(const p of tl) mx=Math.max(mx,p.a0,p.a1);
const X=i2=>8+(W-16)*i2/(tl.length-1), Y=v=>H-10-(H-24)*v/mx;
c.lineWidth=1; c.strokeStyle='rgba(120,160,190,.25)';
for(let g2=1;g2<4;g2++){ c.beginPath(); c.moveTo(8,Y(mx*g2/4)); c.lineTo(W-8,Y(mx*g2/4)); c.stroke(); }
const line=(key,col)=>{
c.strokeStyle=col; c.lineWidth=2; c.beginPath();
tl.forEach((p,i2)=>{ i2? c.lineTo(X(i2),Y(p[key])) : c.moveTo(X(0),Y(p[key])); });
c.stroke();
};
line('a1','rgba(255,110,84,.95)');
line('a0','rgba(96,200,255,.95)');
c.font='700 9px Rajdhani,sans-serif';
c.fillStyle='#8fd8ff'; c.fillText('YOUR ARMY',10,12);
c.fillStyle='#ffab98'; c.fillText('ENEMY',70,12);
c.fillStyle='#7fa8c4'; c.fillText('ARMY VALUE OVER TIME',W-118,12);
}
/* An OTA patch replaces the SCRIPTS, not the shell: a device patched over an
older APK still has the old index.html (no #planetRow) and the old ui.css.
So the planet section is created on demand and its styles are injected here
too β the same rules that ui.css ships for fresh builds. */
function mfPlanetRowStyles(){
if(document.getElementById('mfPlanetRowCss')) return;
const st=document.createElement('style');
st.id='mfPlanetRowCss';
st.textContent='#planetRow{display:flex;flex-direction:column;width:100%;box-sizing:border-box;gap:8px}'
+'.warTableCard{overflow:hidden}.regionMissionDeck{margin-top:10px;padding-top:10px;border-top:1px solid rgba(120,205,255,.2)}'
+'.regionMissionHead{display:flex;justify-content:space-between;gap:8px;align-items:end;margin-bottom:8px}'
+'.regionMissionHead span{font:900 11px/1 var(--fT);letter-spacing:.14em;color:#eaf8ff}'
+'.regionMissionHead small{font:800 8px/1 var(--fT);letter-spacing:.1em;color:#6e9bb7}';
(document.head||document.documentElement).appendChild(st);
}
function ensurePlanetRow(){
mfPlanetRowStyles();
let row=$('planetRow');
if(!row){
const host=document.querySelector('#setupScr [data-setup-tab="map"]');
if(!host||!host.parentNode) return null;
const sec=document.createElement('section');
sec.className='setupCard warTableCard';
sec.setAttribute('data-setup-tab','map');
sec.innerHTML='
PLANETARY WAR TABLE
';
host.parentNode.insertBefore(sec,host); row=$('planetRow');
}
/* OTA patches run inside old APK shells. Move their separate map row into
the War Table once, and retire the independent size card: each site now
carries its Small/Medium/Large theatre contract. */
const card=row.closest('.setupCard'),maps=$('mapRow');
if(card&&maps&&!card.contains(maps)){
const old=maps.closest('.setupCard'),deck=document.createElement('div');
deck.className='regionMissionDeck';
deck.innerHTML='
';
const cv = document.getElementById('planetSphereCanvas');
row.querySelectorAll('.orbitWorld').forEach(b=>{
const choose=e=>{e.preventDefault();e.stopPropagation();selectPlanetKey(b.dataset.planet);};
if(typeof mfBindTap==='function')mfBindTap(b,choose);else b.addEventListener('pointerdown',choose);
});
if(!cv) return;
const draw = () => {
draw3DPlanetSphere(cv, activeKey, planetYaw, planetPitch, curRegionId);
};
draw();
cv.onpointerdown = (e) => {
isDraggingPlanet = true;
lastDragX = e.clientX; lastDragY = e.clientY;
planetDragDx = 0; planetDragDy = 0;
cv.style.cursor = 'grabbing';
cv.setPointerCapture(e.pointerId);
};
cv.onpointermove = (e) => {
if(!isDraggingPlanet) return;
const dx = e.clientX - lastDragX, dy = e.clientY - lastDragY;
planetDragDx = (planetDragDx||0) + Math.abs(dx);
planetDragDy = (planetDragDy||0) + Math.abs(dy);
lastDragX = e.clientX; lastDragY = e.clientY;
planetYaw += dx * 0.01;
planetPitch = Math.max(-0.8, Math.min(0.8, planetPitch - dy * 0.01));
draw();
};
cv.onpointerup = cv.onpointercancel = (e) => {
isDraggingPlanet = false;
cv.style.cursor = 'grab';
};
cv.onclick = (e) => {
const rect = cv.getBoundingClientRect();
const mx = e.clientX - rect.left, my = e.clientY - rect.top;
/* Ignore clicks that dragged more than a few pixels; the globe is rotatable,
and without a threshold every tap ends up nudging the planet. */
if(typeof planetDragDx==='number' && (Math.abs(planetDragDx)>4 || Math.abs(planetDragDy)>4)) return;
/* Globe taps select one of the four surface regions, never another world. */
const W = cv.width, H = cv.height, R = Math.min(W,H)*0.32, cx = W*0.5, cy = H*0.53;
for(const reg of P.regions){
const rLat=reg.lat, rLon=reg.lon+planetYaw;
const cosLat=Math.cos(rLat), sinLat=Math.sin(rLat);
const cosLon=Math.cos(rLon), sinLon=Math.sin(rLon);
const px=cx + R * cosLat * sinLon;
const py=cy - R * (sinLat * Math.cos(planetPitch) - cosLat * cosLon * Math.sin(planetPitch));
const pz=cosLat * cosLon * Math.cos(planetPitch) + sinLat * Math.sin(planetPitch);
const sectorHitRadius = Math.max(38, (reg.rad || 0.38) * R * 1.1);
if(pz > -0.15 && Math.hypot(mx - px, my - py) < sectorHitRadius){
if(typeof mfConquestRegionOpen==='function'&&!mfConquestRegionOpen(activeKey,reg.id)){
if(typeof toast==='function') toast('π LIBERATE THE PREVIOUS REGION FIRST');
if(typeof sfx==='function') sfx('deny');
break;
}
curRegionId = reg.id;
if(reg.maps && reg.maps.length > 0) syncBattlefieldFromMap(theatreMapId(reg.maps,'standard'));
if(typeof sfx==='function') sfx('ui');
renderPlanetRow(); renderMapRow(); renderSpawnPlanner();
break;
}
}
};
}
/* Bounded, least-recently-used. Square backing stores took each entry from
0.37 MB to 0.59 MB; all 48 sites would be ~28 MB of canvases on a device
whose heightfield family already costs ~76 MB. 12 covers a browsing session
without the tail sitting in memory for the rest of the match. */
const mapPrevCache={}; const mapPrevOrder=[]; const MAP_PREV_MAX=12;
function mapPrevTouch(k){
const at=mapPrevOrder.indexOf(k); if(at>=0) mapPrevOrder.splice(at,1);
mapPrevOrder.push(k);
while(mapPrevOrder.length>MAP_PREV_MAX){
const old=mapPrevOrder.shift();
if(old!==k) delete mapPrevCache[old];
}
}
function syncBattlefieldFromMap(key){
const def=MAPDEFS[key]; if(!def) return false;
if(typeof mfConquestMapOpen==='function'&&!mfConquestMapOpen(key))return false;
curMap=key;
/* Every picker (War Table, galaxy UI, conquest advance) funnels through here,
so this is the one place the region can be kept in step with the site. */
if(def.region) curRegionId=def.region;
if(def.theme&&typeof THEMES!=='undefined'&&THEMES[def.theme]) curTheme=def.theme;
if(def.size) battlefieldPreset=battlefieldPresetKey(def.size);
document.querySelectorAll('.bsbtn').forEach(b=>b.classList.toggle('on',b.dataset.bs===battlefieldPreset));
const h=$('battleScaleHint'); if(h) h.textContent=battlefieldPresetHint();
return true;
}
function renderMapRow(){
const row=$('mapRow'); if(!row) return;
const planet=typeof planetForMap==='function'?planetForKey(planetForMap(curMap)):planetForKey(planetForTheme(curTheme));
const reg=(planet.regions && planet.regions.find(r => r.id === curRegionId)) || (planet.regions && planet.regions[0]);
const regionKeys=(reg && reg.maps) || getPlanetMaps(planet);
const rn=$('regionMissionName'); if(rn) rn.textContent=(reg&®.nm)||'REGION';
row.innerHTML='';
for(const key of regionKeys){
const def=MAPDEFS[key];
if(!def) continue;
const card=document.createElement('div');
const conquestOpen=typeof mfConquestMapOpen!=='function'||mfConquestMapOpen(key),conquestWon=typeof mfConquestWon==='function'&&mfConquestWon(key);
card.className='mapCard'+(curMap===key?' sel':'')+(conquestOpen?'':' locked')+(conquestWon?' conquered':'');
card.dataset.map=key;
const ck=key+'_'+(def.theme||curTheme);
let cv3=mapPrevCache[ck];
if(!cv3){
/* 96Γ72 was acceptable while these were icon-sized thumbnails. The War
Table makes one site nearly phone-wide, where that source becomes a
visibly blocky stamp. 192Γ120 stays under five MB even if every one of
the 48 sites is browsed and cached, but keeps rivers, roads and city
footprints legible during map choice. */
cv3=document.createElement('canvas'); cv3.width=384; cv3.height=384;
drawMapPreview(cv3,def,def.theme||curTheme);
mapPrevCache[ck]=cv3;
mapPrevTouch(ck);
}
card.appendChild(cv3);
const hz=(typeof mapHazardDef==='function')?mapHazardDef(key):((typeof MAPHAZ!=='undefined'&&MAPHAZ[key])?MAPHAZ[key]:null);
const sz={compact:'COMPACT Β· 2.2 KM',standard:'STANDARD Β· 2.6 KM',large:'LARGE Β· 3.2 KM'}[def.size]||'BATTLEFIELD';
const CQ=typeof mfConquestLocate==='function'?mfConquestLocate(key):null;
const firstClear=CQ&&typeof mfConquestReward==='function'?mfConquestReward(key):null;
const contract=typeof modeRewardContract==='function'?modeRewardContract('standard'):null;
const rewardXp=firstClear?Math.round(firstClear.xp*(contract?contract.xp:1)):0;
const rewardItem=contract&&contract.item&&typeof INV_CONSUMABLES!=='undefined'?INV_CONSUMABLES.find(x=>x.id===contract.item):null;
card.insertAdjacentHTML('beforeend','
'+sz+'
'+def.nm+'
'+def.ds+'
'
+(CQ?'
FRONT '+CQ.tier+' / 48'+(conquestWon?'SECURED':conquestOpen?['EASY','NORMAL','HARD'][CQ.mi]+' THREAT':'LOCKED')+'
':'')
+(firstClear?'
FIRST CLEAR Β· +'+rewardXp+' XP Β· +'+firstClear.cores+' CORES'+(rewardItem?rewardItem.em+' '+rewardItem.nm+' Β· ONE MATCH':'')+'
':'')
+(hz?'
'+hz.em+' '+hz.nm+''+hz.ds+'
':''));
card.addEventListener('pointerdown',()=>{if(!conquestOpen){toast('π SECURE THE PREVIOUS BATTLEFIELD FIRST');sfx('deny');return;}window._mfTheatrePick=def.size;syncBattlefieldFromMap(key); if(typeof sfx==='function') sfx('ui'); renderMapRow(); renderSpawnPlanner();
/* The region's threat/weather dossier is map-specific. Keep it in sync
when a site changes without recursively rebuilding the card row. */
if($('setupScr')?.classList.contains('galaxyStage-region')&&typeof mfGalaxyRenderRegion==='function')mfGalaxyRenderRegion(false);
});
row.appendChild(card);
}
if(typeof drawSpawnPlanner==='function') drawSpawnPlanner();
}
let settingsFrom='menu';
let inboxFromMatch=false;
const FRONT_SCREEN_IDS=['startScreen','warScr','setupScr','devScr','opsScr','dailyScr','dossierScr','inboxScr','socialScr','updScr','profileScr','settingsScr','armory'];
/* STAGE8_FRONT_FOCUS_BEGIN
Front screens replace one another instead of using browser navigation, so
the browser cannot infer either the new reading start or where Back should
return focus. Keep a tiny route stack: opening records the focused trigger;
returning to an existing route restores that trigger. Modal focus traps stay
authoritative and block delayed front-screen focus from stealing it. */
const mfFrontFocusPath=[];
const mfFrontFocusOrigins=new Map();
const MF_PAUSE_MODAL_EXEMPT=new Set(['pauseOverlay','accDlg','apConfirmOverlay','apOverlay','dispatch']);
const mfPauseInertRestore=[];
let mfFrontFocusTicket=0,mfPauseFocusOrigin=null,mfPauseModalActive=false;
function mfFrontElementVisible(el){
if(!el||el.isConnected===false)return false;
try{const s=getComputedStyle(el);return s.display!=='none'&&s.visibility!=='hidden';}catch(e){return true;}
}
function mfFrontFocusBlocked(){
for(const id of ['apConfirmOverlay','apOverlay','accDlg','dispatch','pauseOverlay']){
const el=$(id);if(mfFrontElementVisible(el))return true;
}
return false;
}
function mfFrontFocusCandidate(el){
if(!el)return null;
if(el.id==='startScreen')return $('startBtn')||el;
const explicit=el.querySelector&&el.querySelector('[data-front-focus]');if(explicit)return explicit;
const heading=el.querySelector&&el.querySelector('h1,h2,[role="heading"]');
if(heading){heading.tabIndex=-1;return heading;}
return el.querySelector&&el.querySelector('button:not(:disabled),input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex]:not([tabindex="-1"])')||el;
}
function mfFrontFocusRebind(target,root){
if(!target||!root)return null;
if(target.isConnected!==false&&root.contains(target))return target;
/* Several front screens rebuild their cards with innerHTML before Back.
Preserve the control's semantic identity so focus lands on the replacement
instead of falling back to the screen heading. */
if(target.id){
const current=$(target.id);
if(current&¤t.isConnected!==false&&root.contains(current))return current;
}
const data=target.dataset||{};
for(const key of ['mode','set','tab','deck','map','fac','char']){
if(data[key]==null||!root.querySelectorAll)continue;
for(const current of root.querySelectorAll('[data-'+key+']')){
if(current.dataset&¤t.dataset[key]===data[key])return current;
}
}
return null;
}
function mfFrontFocusLater(el,preferred){
const ticket=++mfFrontFocusTicket;
requestAnimationFrame(()=>{
if(ticket!==mfFrontFocusTicket||!el||document.body.dataset.frontScreen!==el.id||!mfFrontElementVisible(el)||mfFrontFocusBlocked())return;
let target=mfFrontFocusRebind(preferred,el);
if(!target||!mfFrontElementVisible(target))target=mfFrontFocusCandidate(el);
if(!target||typeof target.focus!=='function')return;
try{target.focus({preventScroll:true});}catch(e){target.focus();}
});
}
function mfFrontFocusRoute(from,id,el){
if(!mfFrontFocusPath.length&&from)mfFrontFocusPath.push(from);
const active=document.activeElement,backAt=mfFrontFocusPath.lastIndexOf(id);
let preferred=null;
if(from&&from!==id&&backAt>=0){
preferred=mfFrontFocusOrigins.get(from)||null;
for(let i=mfFrontFocusPath.length-1;i>backAt;i--)mfFrontFocusOrigins.delete(mfFrontFocusPath[i]);
mfFrontFocusPath.length=backAt+1;
}else if(from!==id){
const source=from&&$(from);
if(active&&active!==document.body&&active.isConnected!==false&&(!source||source.contains(active)))
mfFrontFocusOrigins.set(id,active);
if(backAt>=0)mfFrontFocusPath.length=backAt+1;else mfFrontFocusPath.push(id);
}else if(!mfFrontFocusPath.length)mfFrontFocusPath.push(id);
mfFrontFocusLater(el,preferred);
}
function mfFrontFocusRestore(id,fallback){
const target=mfFrontFocusOrigins.get(id)||fallback;
mfFrontFocusOrigins.delete(id);
if(mfFrontFocusPath[mfFrontFocusPath.length-1]===id)mfFrontFocusPath.pop();
const ticket=++mfFrontFocusTicket;
requestAnimationFrame(()=>{
if(ticket!==mfFrontFocusTicket||!mfFrontElementVisible(target)||typeof target.focus!=='function')return;
try{target.focus({preventScroll:true});}catch(e){target.focus();}
});
}
function mfFrontFocusReset(){
++mfFrontFocusTicket;mfFrontFocusPath.length=0;mfFrontFocusOrigins.clear();
}
function mfPauseSetModal(active){
const overlay=$('pauseOverlay');if(!overlay)return;
if(active){
if(mfPauseModalActive)return;
mfPauseModalActive=true;mfPauseInertRestore.length=0;
for(const node of Array.from(document.body.children||[])){
if(node===overlay||MF_PAUSE_MODAL_EXEMPT.has(node.id)||node.tagName==='SCRIPT')continue;
mfPauseInertRestore.push({node,property:!!node.inert,attribute:node.hasAttribute&&node.hasAttribute('inert')});
node.inert=true;if(node.setAttribute)node.setAttribute('inert','');
}
}else{
if(!mfPauseModalActive)return;
mfPauseModalActive=false;
for(const prior of mfPauseInertRestore){
if(!prior.node||prior.node.isConnected===false)continue;
prior.node.inert=prior.property;
if(prior.attribute){if(prior.node.setAttribute)prior.node.setAttribute('inert','');}
else if(prior.node.removeAttribute)prior.node.removeAttribute('inert');
}
mfPauseInertRestore.length=0;
}
}
function mfPauseHigherModalVisible(){
for(const id of ['accDlg','apConfirmOverlay','apOverlay','dispatch'])if(mfFrontElementVisible($(id)))return true;
return false;
}
function mfPauseFocusable(){
const overlay=$('pauseOverlay');if(!overlay||!overlay.querySelectorAll)return [];
return Array.from(overlay.querySelectorAll('button:not(:disabled),[href],input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex]:not([tabindex="-1"])'))
.filter(mfFrontElementVisible);
}
function mfPauseTrapKeydown(ev){
const overlay=$('pauseOverlay');
if(!mfFrontElementVisible(overlay)||mfPauseHigherModalVisible())return;
const controls=mfPauseFocusable();if(!controls.length)return;
if((ev.key==='Enter'||ev.key===' ')&&!overlay.contains(ev.target)){
ev.preventDefault();ev.stopPropagation();if(ev.stopImmediatePropagation)ev.stopImmediatePropagation();
controls[0].focus({preventScroll:true});return;
}
if(ev.key!=='Tab')return;
const first=controls[0],last=controls[controls.length-1],active=document.activeElement;
if(ev.shiftKey&&(active===first||!overlay.contains(active))){
ev.preventDefault();ev.stopPropagation();last.focus({preventScroll:true});
}else if(!ev.shiftKey&&(active===last||!overlay.contains(active))){
ev.preventDefault();ev.stopPropagation();first.focus({preventScroll:true});
}
}
function mfOpenPause(){
if(!running)return;
const active=document.activeElement;
if(active&&active!==document.body&&active.isConnected!==false)mfPauseFocusOrigin=active;
const net=typeof window!=='undefined'&&window.MFMatchRuntime&&typeof MFMatchRuntime.status==='function'?MFMatchRuntime.status():null;
/* A local overlay may not stop a server-authoritative room. Online play
keeps consuming 30 Hz ticks while the menu is open. */
const live=!!(net&&net.state==='running');
paused=!live;
$('pauseTitle').textContent=live?'MATCH LIVE':'PAUSED';
$('pauseStatus').hidden=!live;
$('resumeBtn').textContent=live?'βΆ RETURN TO MATCH':'βΆ RESUME';
$('pauseOverlay').style.display='flex';
mfPauseSetModal(true);
const target=$('resumeBtn');requestAnimationFrame(()=>{if(mfFrontElementVisible($('pauseOverlay'))&&target)target.focus({preventScroll:true});});
}
function mfClosePause(){
paused=false;mfPauseSetModal(false);$('pauseOverlay').style.display='none';
let target=mfPauseFocusOrigin;
if(!target||target.isConnected===false||!mfFrontElementVisible(target))target=$('menuBtn');
mfPauseFocusOrigin=null;
requestAnimationFrame(()=>{if(mfFrontElementVisible(target)&&target)target.focus({preventScroll:true});});
}
/* STAGE8_FRONT_FOCUS_END */
/* THE DIORAMA IS THE MENU'S BACKGROUND, AND NOTHING ELSE'S.
Every other front screen β War Room, Development, Operations, Armory, the
Dossier, the store, Settings β is an opaque full-screen panel. Behind them
the attract branch in frame() was still stepping the entire simulation and
drawing a complete 3D frame (terrain, every model, SSAO, bloom, at full
resolution) for nobody to see. On a phone that is the research tree quietly
heating the device, and then handing a thermally throttled GPU to the match
the player opens next. */
let attractVisible=true;
function frontRouteTarget(id){
const el=(typeof id==='string'&&id)?$(id):null;
if(el)return el;
/* Mixed OTA installs can briefly run newer JS against an older HTML shell.
Refuse the transition before touching the currently visible route; a
missing optional screen must leave a usable menu, never a blank app. */
try{console.warn('[front-route] target unavailable:',id);}catch(e){}
return null;
}
function hideFrontScreens(except){
for(const id of FRONT_SCREEN_IDS){
if(id===except) continue;
const el=$(id); if(el) el.style.display='none';
}
if(typeof apClose==='function') try{ apClose(); }catch(e){}
const ap=$('apOverlay'); if(ap) ap.style.display='none';
const apc=$('apConfirmOverlay'); if(apc) apc.style.display='none';
if(except===undefined){
mfFrontFocusReset();
mfPauseSetModal(false);
attractVisible=false; // bare call = dropping into a match
if(document.body&&document.body.dataset){
document.body.dataset.frontScreen='';
delete document.body.dataset.frontPopup;
}
if(typeof audMusicEnterMatch==='function') audMusicEnterMatch();
}
}
function showFrontScreen(id){
const el=frontRouteTarget(id);if(!el)return false;
const from=document.body.dataset.frontScreen||'';
hideFrontScreens(id);
el.style.display='flex';
/* The menu artwork should arrive like a live console, but the route itself
remains synchronous and focus-safe. Toggling one scoped class restarts the
short compositor-only reveal without moving controls beneath a held touch. */
el.classList.remove('mfFrontEntering');
void el.offsetWidth;
el.classList.add('mfFrontEntering');
document.body.dataset.frontScreen=id;
delete document.body.dataset.frontPopup;
attractVisible=(id==='startScreen');
/* Re-evaluated every time the menu is shown rather than once at boot: a
session can be dropped mid-play, and the offer has to be there when the
player lands back here β which is the moment they are looking for it. */
if(id==='startScreen'&&typeof sessRenderResume==='function') sessRenderResume();
if(typeof audMusicEnterScreen==='function') audMusicEnterScreen(id);
mfFrontFocusRoute(from,id,el);
return true;
}
/* The battlefield already owns a shared-context 3D preview renderer. Reuse it
in menu rooms instead of inventing screenshots of units: one context serves
every hidden/visible card and the pump pauses work for hidden destinations. */
function mfEnsureMenu3D(hostId,kind,id,tag){
const host=$(hostId);
if(!host||host.dataset.ready||typeof mfIntelPreviewWindow!=='function')return;
host.replaceChildren(mfIntelPreviewWindow(kind,id,tag,typeof playerKitKey==='function'?playerKitKey():'nova'));
host.dataset.ready='1';
}
/* Match overlays are not front screens: opening one must keep match music and
closing it must reveal the battlefield rather than route to the menu. They
still use a validated, explicit route so optional OTA UI cannot blank the
shell and Android Back can close the same state the HUD button opened. */
function showMatchPopup(id){
const el=frontRouteTarget(id);if(!el)return false;
hideFrontScreens();
el.style.display='flex';
document.body.dataset.frontPopup=id;
return true;
}
function closeMatchPopup(id){
const el=frontRouteTarget(id);if(!el)return false;
el.style.display='none';
if(document.body.dataset.frontPopup===id)delete document.body.dataset.frontPopup;
/* Closing a front-screen-shaped match popup must restore the HUD in the same
turn. Depending only on hudflow's observer left mfMenuOpen latched in short
landscape until an unrelated mutation happened, so Back looked inert even
though the Inbox itself had closed. */
if(typeof mfFlowLayout==='function')mfFlowLayout();
return true;
}
function openSettings(from){
settingsFrom=from;
renderSettings();
if(from==='pause'){mfPauseSetModal(false);$('pauseOverlay').style.display='none';}
showFrontScreen('settingsScr');
}
let nativeBackExitAt=0;
function nativeLayerVisible(id){
const el=$(id);return !!(el&&getComputedStyle(el).display!=='none');
}
function nativeBackTap(id){
const el=$(id);if(!el)return false;
if(typeof MF_POINTER_COMMIT!=='undefined') MF_POINTER_COMMIT=-1e9;
/* Blur FIRST. Android Back used to navigate straight out of a screen with a
text field still focused, so the field's commit handler never ran and
whatever had been typed was discarded β silently, which is the worst way to
lose a name someone chose. */
const a=document.activeElement;
if(a&&a!==document.body&&typeof a.blur==='function') a.blur();
el.click();
return true;
}
function handleNativeBack(AppPlugin){
if(nativeLayerVisible('mfNoticeHistory')){if(typeof mfNoticeHistoryClose==='function')mfNoticeHistoryClose();return;}
/* Close the topmost modal first. Android Back now follows the same visual
hierarchy as the on-screen controls instead of terminating the Activity. */
if(nativeLayerVisible('apConfirmOverlay')){nativeBackTap('apConfirmNo');return;}
if(nativeLayerVisible('apOverlay')){if(typeof apClose==='function')apClose();return;}
if(nativeLayerVisible('accDlg')){nativeBackTap('accDlgN');return;}
if(nativeLayerVisible('dispatch')){nativeBackTap('dispOk');return;}
const layers=[
['settingsScr','setBack'],['profileScr','profBack'],['armory','armoryBack'],
['setupScr','setupBack'],['warScr','warBack'],['devScr','devBack'],['opsScr','opsBack'],
['dailyScr','dailyBack'],['dossierScr','dossBack'],['socialScr','socialBack'],['inboxScr','inboxBack'],['updScr','updBack'],['gameOver','restartBtn']
];
for(const L of layers)if(nativeLayerVisible(L[0])){nativeBackTap(L[1]);return;}
if(nativeLayerVisible('pauseOverlay')){nativeBackTap('resumeBtn');return;}
if(typeof aiming!=='undefined'&&aiming>=0){
if(aiming===5&&typeof cancelArtilleryBarrageAim==='function')cancelArtilleryBarrageAim(true);
else aiming=-1;
toast('Targeting cancelled');sfx('ui');return;
}
if(typeof placing!=='undefined'&&placing){cancelPlace();sfx('ui');return;}
if(nativeLayerVisible('buildMenu')||nativeLayerVisible('bldMenu2')||nativeLayerVisible('prodMenu')){
closeMenus();sfx('ui');return;
}
if(nativeLayerVisible('baseFinder')){if(typeof closeBaseFinder==='function')closeBaseFinder(true);else $('baseFinder').style.display='none';sfx('ui');return;}
/* Drafted map commands outrank Pause. Leaving either mode armed while opening
the overlay makes the first tap after Resume execute an old instruction. */
if(typeof armQueue!=='undefined'&&armQueue){cancelQueueDraft(false);return;}
if(typeof armRally!=='undefined'&&armRally>=0){
if(typeof disarmRally==='function')disarmRally();else armRally=-1;
toast('Rally placement cancelled');sfx('ui');return;
}
if(typeof armPatrol!=='undefined'&&armPatrol){cancelPatrolDraft(false);return;}
if(typeof armFormation!=='undefined'&&armFormation){
armFormation=false;orderPreview=null;
const f=$('formBtn');if(f)f.classList.remove('on');toast('Formation placement cancelled');sfx('ui');return;
}
if(typeof boxMode!=='undefined'&&boxMode){boxMode=false;const b=$('boxBtn');if(b)b.classList.remove('on');sfx('ui');return;}
if(running){mfOpenPause();sfx('ui');return;}
const now=performance.now();
if(now-nativeBackExitAt<1800){if(AppPlugin&&AppPlugin.exitApp)AppPlugin.exitApp();return;}
nativeBackExitAt=now;toast('Press Back again to exit MASSFRONT');
}
function nativeBackEscape(e){
/* Desktop Escape follows the same hierarchy as Android Back. Capture-owned
modals (the intro and account portal) either preventDefault or stop the
event first, so their local focus traps remain authoritative. */
if(e.key!=='Escape'||e.defaultPrevented||e.repeat||e.isComposing)return;
e.preventDefault();e.stopPropagation();handleNativeBack();
}
function initNativeNavigation(){
if(typeof window!=='undefined'&&!window.__mfNativeEscapeReady){
window.__mfNativeEscapeReady=true;
window.addEventListener('keydown',nativeBackEscape);
}
const C=typeof window!=='undefined'&&window.Capacitor;
const A=C&&C.Plugins&&C.Plugins.App;
if(!A||typeof A.addListener!=='function')return;
A.addListener('backButton',()=>handleNativeBack(A));
}
/* One exit transaction for victory, defeat and Pause > Main Menu. Partial
visibility flips left pointer capture, tutorial chrome and modal layers from
the match alive behind the front end. Resetting them together makes the
return path deterministic and gives Android Back the same clean hierarchy as
a cold launch. */
function returnToMainMenu(){
mfResultPresentationEpoch++;
mfLastResultCanRestart=false;
const networkRuntime=typeof window!=='undefined'&&window.MFMatchRuntime,
networkConsumer=typeof window!=='undefined'&&window.MFMatchCommandConsumer;
/* Only an explicit menu exit releases the match's input/lockstep ownership.
A closed socket or terminal screen must never reopen offline mutation. */
if(networkRuntime&&typeof networkRuntime.close==='function')networkRuntime.close();
if(networkConsumer&&typeof networkConsumer.leaveSession==='function')networkConsumer.leaveSession();
if(window.MFSocialUI&&typeof MFSocialUI.clearFinishedMatch==='function')MFSocialUI.clearFinishedMatch();
/* Training's protected rules are scoped to its operation. This is the one
intentional early-exit path; incidental UI state changes must not call it. */
if(typeof cancelTrainingMission==='function') cancelTrainingMission();
/* Weekly borrows the player's threat/modifier plan for its authored brief.
endgameRecord hands it back at the end of a FINISHED run β abandoning one
never reached that code, so quitting a Weekly kept the loan forever. */
if(typeof weeklyMode!=='undefined'&&weeklyMode&&typeof restoreWeeklyConfig==='function'){
restoreWeeklyConfig(); weeklyMode=false;
}
/* Same contract for an authored campaign mission's modifier set. */
if(typeof storyCampaignRestoreMods==='function') storyCampaignRestoreMods();
paused=false;mfPauseSetModal(false);mfPauseFocusOrigin=null;running=false;matchLive=false;
if(typeof audMusicLeaveMatch==='function') audMusicLeaveMatch();
if(typeof resetInputState==='function') resetInputState();
/* Do not leave an old front-end screen in the DOM hit-test stack. All menu
overlays share a z-index, so one stale `display:flex` layer can sit above
the newly shown main menu and silently eat every tap. */
for(const id of FRONT_SCREEN_IDS.concat(['pauseOverlay','gameOver','levelUp','loadScr'])){
const el=$(id); if(el) el.style.display='none';
}
if(typeof adClearPostMatchAd==='function') adClearPostMatchAd();
if(typeof apClose==='function') apClose();
document.querySelectorAll('.apOverlay,.apConfirmOverlay').forEach(el=>{ el.style.display='none'; });
const dlg=$('accDlg'); if(dlg) dlg.style.display='none';
const dp=$('dispatch'); if(dp){ dp.style.display='none'; dp.classList.remove('in'); }
closeMenus(); cancelPlace();
showHudDock(false);
showFrontScreen('startScreen');
renderMetaHead(); setupAttract();
if(typeof storyCheck==='function') setTimeout(storyCheck,420);
}
/* Takeovers may wrap returnToMainMenu more than once across OTA/source load
orders. Protected onboarding must retain one stable path to the real base
cleanup so its faction gate is not unloaded by a Galactic return wrapper. */
window.__MF_RETURN_TO_BASE_FOR_COMMISSIONING__=returnToMainMenu;
function restartCurrentBattle(){
if(!gameEnded||!mfLastResultCanRestart)return false;
mfLastResultCanRestart=false;
mfResultPresentationEpoch++;
/* A completed loss may leave a pre-defeat recovery snapshot. Clear it before
building a genuinely fresh attempt on the same selected battlefield. */
if(typeof sessClear==='function')sessClear();
if(typeof adClearPostMatchAd==='function')adClearPostMatchAd();
if(typeof mfDepart!=='undefined')mfDepart.fromVictory=false;
paused=false;running=false;matchLive=false;
if(typeof resetInputState==='function')resetInputState();
const go=$('gameOver');if(go)go.style.display='none';
closeMenus();cancelPlace();hideFrontScreens();
mfLoadScreenFill();$('loadScr').style.display='flex';
requestAnimationFrame(()=>requestAnimationFrame(()=>{
applyTheme();newSkirmish();
$('loadScr').style.display='none';
stopAttract();
if(typeof mfFlowLayout==='function')mfFlowLayout();
}));
return true;
}
function continueToNextMap(){
const C=typeof window!=='undefined'&&window.MFMatchCommandConsumer;
if(C&&typeof C.sessionActive==='function'&&C.sessionActive())return returnToMainMenu();
/* Rewards already landed in endGame/metaGrant. This only launches the next
unlocked War Table site β do not call returnToMainMenu first or the
attract diorama eats the loadout. */
if(typeof mfDepart!=='undefined') mfDepart.fromVictory=false;
if(typeof mfConquestHasNextMap!=='function'||!mfConquestHasNextMap()){
if(typeof returnToMainMenu==='function') returnToMainMenu();
return;
}
const map=mfConquestNextMap();
const L=typeof mfConquestLocate==='function'?mfConquestLocate(map):null;
if(!L||typeof syncBattlefieldFromMap!=='function'||!syncBattlefieldFromMap(map)){
if(typeof toast==='function') toast('NO NEXT BATTLEFIELD');
if(typeof returnToMainMenu==='function') returnToMainMenu();
return;
}
curTheme=L.P.theme; curRegionId=L.R.id;
if(!(typeof storyCampaignPlanBorrowed==='function'&&storyCampaignPlanBorrowed())){
META.setup=META.setup||{};
META.setup.m=curMap; META.setup.t=curTheme;
if(typeof metaSave==='function') metaSave();
}
paused=false; running=false; matchLive=false;
if(typeof audMusicLeaveMatch==='function') audMusicLeaveMatch();
const go=$('gameOver'); if(go) go.style.display='none';
if(typeof adClearPostMatchAd==='function') adClearPostMatchAd();
closeMenus(); cancelPlace();
hideFrontScreens();
mfLoadScreenFill();
$('loadScr').style.display='flex';
requestAnimationFrame(()=>requestAnimationFrame(()=>{
applyTheme(); newSkirmish();
$('loadScr').style.display='none';
stopAttract();
if(typeof mfFlowLayout==='function') mfFlowLayout();
}));
}
/* Fill the loading screen with the intel the game already authored. PLANETS
(gl.js:1768) carries ds / biodome / sector / diameter / dayLen / temp /
climate / lore, and each region carries poi + hook β a genuinely large body
of worldbuilding that the player never saw, because the only place it could
appear was a screen that said "SURVEYING TERRAINβ¦" and nothing else.
Everything is optional-chained: an unknown map must still load. */
function mfLoadScreenFill(){
const $=id=>document.getElementById(id);
const setT=(id,v)=>{ const e=$(id); if(e) e.textContent=v||''; };
const MD=(typeof MAPDEFS!=='undefined'&&typeof curMap!=='undefined')?MAPDEFS[curMap]:null;
const mapKey=typeof curMap!=='undefined'?String(curMap):'';
let P=null,R=null,pk='';
try{
pk=(typeof planetForMap==='function')?planetForMap(curMap):'';
P=(pk&&typeof PLANETS!=='undefined')?PLANETS[pk]:null;
if(P&&P.regions) R=P.regions.find(r=>r.maps&&r.maps.indexOf(curMap)>=0)||null;
}catch(e){}
/* Title prefers the authored map name over the generic status line. */
setT('loadTitle',(MD&&MD.nm)||'GENERATING BATTLEFIELD');
setT('loadEyebrow',P?('DEPLOYING TO Β· '+P.nm):'DEPLOYING');
/* poi is the named location; hook is the one-line scene set. */
setT('loadPoi',(R&&R.poi)||(MD&&MD.poi)||'');
setT('loadHook',(R&&R.hook)||(MD&&MD.ds)||'');
const host=$('loadStats');
if(host){
const chips=[];
const add=(k,v)=>{ if(v) chips.push('