Where Thrawn's Revenge's galactic lag comes from, and a data-only fix that more than doubled the frame rate in my tests
I spent a few weeks measuring TR's galactic map frame by frame. This post explains what makes it slow, what I changed (XML and Lua only, as a submod for TR), and how I tested it. I saw no large change in which factions own which planets, though that check is coarse.
The short version. TR's galaxy is slow for two separate reasons.
1. A freeze every 40 seconds of galaxy time. Every AI faction moves its idle units on the same frame, and each move starts a slow target search. Spreading those passes out across the 40 seconds, and letting units that ask the same question share an answer, removed the multi-second freeze in my early-campaign tests. I haven't measured the final version late in a long campaign, where frames over a second are still likely, and the answer sharing occasionally sends a unit after a different target than TR would (about 1 time in 270 in my checks), explained below.
2. A slow frame even when nothing is happening. In my early tests TR's typical frame cost about 28 ms against vanilla's 4. About half of that is the AI scoring its goals and the engine rebuilding galaxy-wide paths. Rewriting TR's AI equations so they do the same math with fewer lookups, and giving the AI a short breather between goal sweeps, cuts it substantially. The Workshop version leaves the breather out so the AI scores its goals as often as in TR (see "What I changed").
If you only want the changes, skip to "What I changed". The sections before it show where the time goes.
What it looks like when you play
Averages hide the hitches you feel, so I counted how often frames ran long per minute of real time.
Plain TR averages about one frame over a full second per minute of play. Neither fixed version had a single one in 20 games, and every frame of every game was logged.
The Core fixes alone don't cut the number of 100 ms hitches per minute. They make each frame cheaper, so more frames fit in a minute, but the 100 ms ones stay. The two extra changes in the Full fix halve them.
With plain TR, the galaxy clock advanced 0.69 seconds per real second at speed 1 because the game couldn't keep up; with the Full fix it advanced 0.82. While the galaxy is running (not paused on a battle prompt), the same real time gets you about 20% more campaign.
Problem 1: the 40-second freeze
If you've played TR's galactic conquest for a while you know this one: the galaxy stops dead for a second or more, roughly every 40 seconds, and it's worse in a campaign that has been running a while.
What causes it
The freeze is GalacticFreeStore.lua. Every AI faction has a "free store": the units that aren't assigned to an attack or a defense. TR sets the free store's unit service rate to 40 seconds, so every 40 seconds the engine calls On_Unit_Service for every idle unit of that faction. Many of those calls end in MoveUnit, which runs a target search (FindTarget) to decide where the unit should go.
Two things make this hurt:
- All twelve AI factions run their pass on the same frame. The engine starts them on one shared timer, and nothing spreads them out. Twelve passes back to back is one very long frame.
- The searches are expensive, and they get more expensive. In the profiles, 94 to 98% of the free-store script's time is spent inside target searches. A search tends to take about 1 ms more for every planet the searching faction owns, and the number of idle units grows as armies pile up.
TR's 10% move allowance doesn't limit the searches. The allowance only counts searches that end in a move, and 67 to 89% of searches end without one (no target found, or TR's own checks reject it). So the number of searches tracks the number of idle units, not the allowance.
The freeze also survives saving and reloading. The free-store state comes back from the save, timer included.
Problem 2: the slow frame when nothing is happening
Even between freezes, TR's galaxy runs about 28 to 31 ms a frame. I ran the same measurement on vanilla FoC's largest galaxy for comparison.
To find where that logic time goes, I sampled what the game was doing about 170 times a second and grouped the samples by engine system.
Cost 1: the AI scoring its goals
The galactic AI works through a list of possible moves: each is a goal from TR's AI XML (say, conquer a planet) paired with a target (which planet). Every frame, each AI faction scores one such pair, and scoring it means evaluating the perception equations behind it: the XML formulas that rate a planet or a fleet for that goal. One complete trip through that list is a sweep. TR's AI has no pause between sweeps on Normal and Hard (Galactic_AI_Goal_Cycle_Sleep_Duration is 0), so this runs every frame for every AI faction, all game.
The engine evaluates every term of an equation every time. Nothing short-circuits: multiplying by a zero doesn't skip the other factor. So the only ways to make this cheaper are fewer lookups per equation, or fewer evaluations. Some of TR's equations repeat the same lookup many times over; for example Is_Owned_By_Enemy makes 360 lookups.
By goal type, Conquer_To_Reconnect alone accounts for about 15% of a typical frame's game work.
Cost 2: rebuilding galaxy-wide paths
This one is in the engine, not TR. When a fleet arrives at a planet, leaves, merges or jumps, the engine clears that planet's displayed owner (its icon). When the planet is next updated, the engine sees the icon doesn't match the owner and rebuilds every faction's travel costs and shortest paths across the whole galaxy, even though nobody's ownership changed. In TR I counted 153 rebuilds in 20 seconds, against 8 in vanilla. Each one costs an estimated 20 ms at TR's galaxy size.
To check that this really costs what the profile says, I switched the icon clearing off in memory in a running game, as a one-off test. No files were changed, and this is not something anyone should ship. The chart includes two measures of the slower frames: the 95th percentile frame time is the time that 95% of frames are faster than, and the 99th percentile uses 99%.
This was an exploratory test, not a pre-planned one. I ran six windows (on, off, off, on, on, off) and compare the first four. The last "off" window looked like the galaxy was held on a screen for part of it (unusually many very fast frames, and only 39 galaxy seconds advanced in 60 real seconds), though I couldn't confirm that, and the third "on" window then has no matching "off" beside it. A data-only mod can't switch this off. It can only make fewer fleet moves.
The rebuilds probably explain the second one-second frame after each freeze, too. During its pass, the free store issues hundreds of move orders. In the game where I logged who made each icon clear, the biggest freeze held 347 clears made by the script, and the very next frame ran 37 rebuilds back to back. A second logged game showed the same shape (237 clears in its biggest script freeze, then 38 rebuilds), though there I didn't record who made each clear. (The logging itself pauses the game at each clear, so those freezes ran longer than normal.) Across ordinary profiled games, though, only 13 of 30 long script frames were followed by a rebuild frame, so it's a strong pattern rather than a rule.
What I changed
Everything is plain XML and Lua in a submod that loads on top of TR. TR's own files are never edited. It's on the Steam Workshop as a submod of TR (TR Galactic Lag Fix); the tests loaded the same files from a folder with Modpath. The submod's files are built by a small script from TR's own files, after it checks each one against the exact TR version the changes were written for. For the Lua, it appends wrappers to a byte-for-byte copy of TR's script. For the XML, it rewrites only the specific equation bodies and values it targets and leaves every other byte alone.
That means the submod carries its own copies of the TR files it changes. If a TR update changes one of those files, the submod's older copy would still load over it until I rebuild the submod for the new version.
I tested two bundles. Core fixes are the first four changes. Full fix is those four plus the last two. (In the build script, change 4 is two components, factoring and common-factors, so the Core bundle lists five.)
The Workshop version is the Full fix without changes 3 and 6, the two that make the AI act less often. I took them out after testing so the AI behaves closer to plain TR: it starts each goal sweep straight after the last, as TR does, and moves safe heroes every pass. The numbers in this write-up are for the tested bundles, which include the pause. I didn't time the Workshop build. By my rough estimate (explained under change 3), it's something like 2 to 4 ms a frame slower without the pause, and I haven't estimated the hero change. In the build script both are off unless you ask for them (sleep and hero-cadence).
The Lua changes only take effect in a new campaign. EaW saves store the scripts' functions, so loading an old save made without the layer brings back TR's own Lua. The XML changes should still apply, since the game reads them at start-up (I haven't confirmed that for every file), but the stagger, search sharing and hero change do nothing until a new campaign. The reverse (a save made with the layer, loaded without it) would bring the layer's functions back and may depend on it. I haven't tested that.
1. Stagger the free-store passes Core
Each AI faction's first free-store pass is shifted to its own slot in the 40-second cycle, then TR's normal 40-second rhythm carries on from there. The slot comes from the player ID (times the golden ratio, so no two factions land together). Same work per faction, just not all on one frame.
2. Share search results within a pass Core
Within one free-store pass, units of the same type at the same planet looking for the same kind of target reuse the first unit's search result instead of running it again. All of TR's own per-unit checks still run on that result. If a search result depends on something about the individual unit beyond its type and location, sharing could pick a different target than TR would. The build script has a check mode that runs the real search alongside every shared result and counts any disagreements. I've now run it in game, with one addition: for some units it also runs TR's own search twice, to see whether that search ever disagrees with itself. Over five games of the same campaign, 9 of 2,422 shared results (about 0.4%, or 1 in 270) pointed at a different target than TR's own search, while TR's search never disagreed with itself (0 of 2,812 repeats). So the difference is real but small: now and then a unit is sent after a different target than it would be in TR. I haven't measured whether that changes how a campaign plays out.
3. Give the AI a 10-second breather between goal sweeps Core not in the Workshop version
Sets Galactic_AI_Goal_Cycle_Sleep_Duration from 0 to 10 seconds for Normal and Hard (the Default and Skynet profiles). Easy Default already pauses for 40; the other difficulty profiles are left as TR ships them. The busiest factions have several hundred (goal, target) pairs and score one per frame, so by my estimate a full sweep takes something like 15 to 20 seconds at TR's normal frame rate; the breather adds 10 seconds after each sweep. Sweep length depends on frame rate, and the fixes change frame rate, so I haven't measured the actual change in how quickly the AI reacts. This is a real behaviour change: the pause can delay how soon the AI notices new opportunities, although the faster frame rate shortens each sweep, so the net effect is unmeasured. I picked 10 to keep the pause small.
I didn't measure what the pause saves on its own. Scoring goals costs about 10 ms of a typical plain-TR frame (see "Where a typical frame goes"), and the pause idles it for roughly a third of each cycle, so by my rough estimate it's worth something like 2 to 4 ms a frame once the equations are tidied. The Workshop version leaves it out, so the AI goes straight into its next sweep, as in TR. With faster frames, each sweep also finishes sooner than in plain TR.
4. Tidy up the AI equations Core
Rewrites equations in TRBasicGalacticEquations.xml, TROffensiveGalacticEquations.xml and DefensiveGalacticEquations.xml so repeated lookups are factored out and evaluated once. Think a·X + a·Y + a·Z becoming a·(X + Y + Z), applied hundreds of times. Before writing anything, the script checks algebraically that each rewritten equation is exactly the original polynomial. That's exact on paper; the game's floating-point arithmetic can round the last digits differently when terms are regrouped, so results can differ by tiny amounts. A few examples:
| equation | lookups before | after |
|---|---|---|
Is_Connected_To_Enemy_Human | 380 | 112 |
Is_Owned_By_Enemy | 360 | 74 |
Is_Connected_To_Enemy | 197 | 53 |
Is_Owned_By_Active_Enemy | 144 | 47 |
It also factors the two scores every free-store target search evaluates for every friendly planet, which makes each search cheaper.
5. Group type checks into one lookup Full fix
Runs like c·IsType(A) + c·IsType(B) become a single IsType lookup with several Parameter_Type bindings, the same form TR already uses in Is_Important_Planet. Applied to BasicGalacticEquations_Generated.xml and BasicGalacticEquations.xml. The check assumes that a lookup listing several types returns the sum of the separate lookups. Under that assumption, it proves the equations equal before writing them. TR's own use of this form suggests the assumption holds.
6. Move idle heroes every other pass Full fix not in the Workshop version
Combat heroes sitting in a safe spot get re-positioned on alternate free-store passes instead of every pass. Any hero in danger, and every non-hero unit, still goes through TR's normal service. This is also a behaviour trade: a safe hero can take an extra 40 seconds to be sent somewhere new. The Workshop version leaves this out, so safe heroes are moved every pass, as in TR.
I only tested the bundles, not each change on its own, so I can't tell you exactly how much each one is worth. In this study, the Core fixes take 11.1 ms off the average frame, and the two Full-fix changes take off another 5.9 ms on top of that.
Does it change how the AI plays?
The point was to make the AI cheaper to run, not to change its decisions. So for every game I recorded who owned which planets at the end, and how many battles the AI started against me.
Battles the AI started against me during each test's measurement window. Note the window covers a bit more galaxy time than the 120 measured seconds, because stretches around battle screens were cut from the frame data but not from this count: 121 to 149 galaxy seconds, averaging 134 (plain), 132 (Core) and 132 (Full). The counts: 3.6 per game in plain TR (0 to 8), 3.0 with the Core fixes (1 to 5), and 2.7 with the Full fix (0 to 6). The difference between plain and Full fix is −0.9 battles, with a 95% range of −2.8 to +1.0. That's no clear change either way. Ten games is too few to say more.
This is a coarse check, early in one campaign. It found no large shift in who owns what, but individual games vary a lot (Zsinj ended anywhere from 13 to 21 planets), so smaller differences could hide in that noise. It can't prove the AI plays identically, and two of the changes (the breather and the hero cadence) deliberately trade a bit of reaction time for speed. The Workshop version leaves both out.
How I tested it
I set the test rules before collecting any results.
- I wrote the plan first. The versions, the number of games, what I'd measure, how I'd compare them and what would get a game thrown out were all written down and committed before the first test game. I ran the study with the game windowed at 1920×1080.
- 30 fresh games, 10 per version, in a balanced order. The games ran in blocks of three, one of each version, with the order fixed in advance and rotated so no version always went first or last. That spreads slow drift over the day (heat, background programs) across all three versions, though it can't guarantee perfectly even exposure.
- The same scenario every time. The large Era 1 campaign as the Empire on Normal. Each game was fast-forwarded to 400 seconds of galaxy time, then measured for 120 seconds at speed 1. Battles were auto-resolved, and time held by battle prompts and result screens was cut out of the measurement automatically.
- Nobody touched the machine. The game scrolls the map when the mouse is near the screen edge, even in the background, which changes what's drawn. So the script parked the cursor, reset the camera to a fixed view before measuring, and recorded where the cursor was at the end. It was still parked at the end of every game.
- One main number, chosen in advance: average frame time per game. Each game counts as one data point, not each frame.
- A stricter bar because I compared three versions. Comparing three pairs gives three chances of a fluke, so I tightened the threshold to cover all three at once (the Holm method). All three differences clear it by a huge margin: if the versions were really the same speed, gaps this big would turn up by chance less than once in a million tries. The stricter bar applies to that yes-or-no test; the 95% ranges shown below are the ordinary ones.
- Every game is reported. No game failed and none were excluded, in either run. The full list is in the data.
| comparison | change in average frame time (ms) | 95% range for the change (ms) |
|---|---|---|
| Full fix vs plain TR | −17.0 ms | −19.1 to −15.0 ms |
| Core fixes vs plain TR | −11.1 ms | −13.3 to −9.0 ms |
| Full fix vs Core fixes | −5.9 ms | −7.0 to −4.8 ms |
| also measured | plain TR | Core | Full | Full minus plain: 95% range for the change |
|---|---|---|---|---|
| 95th percentile frame | 73.4 ms | 55.4 ms | 42.3 ms | −35.0 to −27.3 ms |
| 99th percentile frame | 121.5 ms | 107.2 ms | 71.9 ms | −57.7 to −41.4 ms |
| frames over 100 ms | 1.85% | 1.17% | 0.39% | −1.8 to −1.1 percentage points |
| galaxy seconds per real second | 0.69 | 0.76 | 0.82 | +0.11 to +0.16 |
When it ran: overnight on an idle machine, as planned, over about 6 hours 16 minutes, with nothing changed from the plan. Other programs used 15 to 24% of the CPU during the games, varying run to run. That's recorded per game, and it came out even across versions: 16.2% on average in the plain TR games, 16.6% in Core, 16.1% in Full.
The test script waited for each game to save its whole frame log before closing it, so no frames were lost.
How frames were timed: with a small DLL that sits between the game and Direct3D and logs every frame, the same build and settings in every game. Claude Opus 5.5 wrote the DLL, with GPT-6 Astra reviewing it adversarially until it signed off. It's only a measuring tool: the fix doesn't use it, and you don't need it to play with the fix.
What the timer itself costs. Every version ran the same DLL with the same settings, and its own work is inside every frame time and frame rate in this post. I haven't measured whether that work costs more or less in one version than another. I couldn't time a game with no DLL at all, because the outside timer that would do it needs admin rights I didn't have on this machine. So I measured the cost in two parts, in a separate test with its own written plan: 26 Full-fix games at 1920×1080, half of them with the DLL's optional measurements (GPU timing, per-draw timing and a memory sampler) switched off.
- Its own per-frame code took 0.18 ms a frame, about 1% of a frame. The DLL timed this itself.
- The optional measurements made no detectable difference: with them on, frames averaged 0.7 ms faster, with a 95% range of 2.6 ms faster to 1.2 ms slower. That's noise, not a speed-up.
- Upper bound for the parts I measured: adding the top ends of both ranges gives 1.4 ms a frame, in that test's Full-fix games. It leaves out one part I couldn't measure: a counter and one extra function call on each of about 2,650 Direct3D calls a frame. That part has no number, so 1.4 ms isn't a bound on the whole DLL.
That test ran on a busier machine than the main study (other programs used 24 to 38% of the CPU, against 15 to 24%), and its frames were slower overall, about 16 to 24 ms instead of about 12, so its range came out about three times wider than planned. Four of its 30 games failed during the fast-forward and were excluded as the plan said: three after their campaign start timed out, and one after a normal start, for a reason I didn't investigate. After the first three I added one check, written down before it took effect: after a late start, if the game didn't answer my test scripts, end the game at once instead of after 30 minutes. No later start timed out, so the check never triggered, and it didn't change what was measured.
The "why" parts of this post (the freeze cause, where frame time goes, the path rebuilds) come from a sampling profiler and a debugger, in separate exploratory runs at a different window size, some before the first run of the main test and some after it. Those exploratory runs helped me find the causes; they were separate from the planned comparison of the bundles.
What didn't work
Not everything I tried helped, and some of it made things worse:
- First version of the stagger. It handed out slots through a shared
GlobalValuecounter. In game, no free store ever got a slot, and 11 of 12 stopped making routine moves at all. As far as I can tell,GlobalValueisn't available in free-store scripts. Replaced by the player-ID version. - Replacing TR's per-planet shipyard tables with lookups. In fresh campaigns the AI factions never started, most likely because some of TR's setup Lua evaluates those equations directly and errors out. Shelved.
- Grouping faction checks (like change 5, but for
IsFaction). No measurable difference in 16 games. Left out. - Silencing GameScoring's periodic debug dumps and trimming the per-planet plugin update loop. No measurable difference in 8 games. Left out.
- Capping free-store orders per frame. This one looked promising on paper: limit each faction to 16 routine move attempts per frame (each attempt runs a few target searches; units in danger are exempt), since the biggest freezes came from hundreds of orders at once. I couldn't show that it helped: the measured gain was small and uncertain. My best guess is that the stagger had already broken those bursts up, but I didn't test that directly. And it clearly changed the AI.
The capped windows also ran longer in galaxy time (147 seconds on average against 129), so per galaxy second that's about 3.5 times as many attacks. And I ended with about 2.5 fewer planets. Holding back routine moves seems to leave units near the front, where they get swept into attacks, but that's a guess.
A small exploratory test with no pre-set plan: 4 games without the cap and 3 with it, because one capped game stalled before its measurement started, for a reason I didn't record.
That last result is why I treat changes that move fewer units as possible behaviour trade-offs.
Limits
- One desktop PC on Windows, game windowed at 1920×1080 with vsync off (a different window size for the exploratory charts). Your numbers will differ, and I haven't tested whether the gaps between versions are the same on other hardware.
- One campaign, one faction, one difficulty, measured early (about 400 to 560 seconds of galaxy time). The freeze is bigger in a campaign that has run a while. Even with the stagger, at cycle 50 one faction's pass alone took 1.1 to 1.3 seconds in my earlier test, so the Full fix will probably still produce some frames over a second late in a long game. I haven't measured the final fix there.
- Battles auto-resolved, camera fixed at the minimap's centre view, game window in the background.
- Space and land battles weren't touched or measured. This is galactic map only.
- Saves. Every test game was a fresh start. The Lua changes need a new campaign, and loading saves across versions is untested (details under "What I changed").
- TR updates. The submod carries copies of the TR files it changes, so it matches one TR version. After a TR update it needs rebuilding and re-checking.
- The timer is in every number. Its own per-frame code takes about 0.2 ms, and the parts I could measure come to at most about 1.4 ms a frame, in Full-fix games on a busier machine. Its per-call work is unmeasured, and so is its cost in plain TR's and the Core fixes' frames (details under "How I tested it").
- The Workshop version wasn't timed. It leaves out the pause and the hero change, so expect it to be slower than the Full fix numbers. The 2 to 4 ms for the pause is an estimate, and the hero change has none.
- The path rebuilds are untouched. They're engine behaviour. They're now the main source of the hitches that remain, and the only data-side lever is fewer fleet moves.
Files and test results
The fix is on the Steam Workshop as a submod of TR: TR Galactic Lag Fix. It's the Full fix without the pause and the hero change (changes 3 and 6), so the AI plans goals and moves heroes as often as in TR. That exact build wasn't timed.
The script that builds the submod, the test plans, every game's frame log (the timer-cost test's included), and the analysis scripts are here: github.com/molosat/EaWX-Optimizer. You don't need the script to use the submod. It's there so anyone can see exactly what changed and check the build against TR's own files.
The frame timer is released separately, here: github.com/molosat/alamo-profiler. It's a timer-only build, not the exact DLL the tests ran: the same timing code, with the command channel my test scripts used to drive the game taken out. You build it from source and put its d3d9.dll in the folder of the executable the game actually runs (for Steam FoC, the corruption folder; it needs the current 64-bit build). It writes a log of every frame, and a Python script summarises the log. The test scripts belong to a private tool I'm not releasing, so you can check the frame logs and the analysis, but you can't replay my runs click for click. Use the timer in single player only, never in multiplayer.
Each change is small, readable and independent, so they can be used separately. I'd be interested in results from other machines, especially late in a long campaign.