LLM-Assisted Reverse Engineering and Pathfinding Optimization for Legacy Game Engines
This article examines how general-purpose large language models can support the modification of a legacy real-time strategy game engine. It covers an evidence-driven workflow for reverse engineering, pathfinding congestion and stale grid reservations, wave-based AI attacks, and alternative implementations of missing combat mechanics. The central lesson is to use models for hypothesis generation, patch planning, and test design while relying on logs, replays, and repeatable experiments to validate every change.
1. Why Legacy Game Engines Need a Different Approach
Many older real-time strategy (RTS) engines share the same characteristics: mature core gameplay, relatively fixed data structures, incomplete mechanics in early releases, and fragmented public documentation. Later expansions often introduced substantial new behavior.
For an individual developer who wants to customize the base game, two problems tend to emerge:
- The desired behavior is clear, but the implementation path is not. A developer may want the computer opponent to launch sustained large-scale attacks, reduce congestion during infantry assembly, or allow passengers to fire from vehicles. Without source code or complete documentation, it may be unclear where the engine handles unit states, pathfinding, firing, or experience attribution.
- Missing mechanics can block further work. The base release may lack expansion-specific behavior, such as passenger firing, garrison combat and experience attribution, or ranged aircraft that maintain distance from their targets. Implementing substitutes can become a prolonged trial-and-error process.
The case discussed here involved private modifications to the base version of a classic RTS game. The goal was not to build a complete commercial mod, but to evaluate whether a general-purpose large language model (LLM) could improve efficiency across reverse engineering, solution design, patch implementation, and regression testing.
The resulting work included:
- Sustained, wave-based attacks by the computer opponent.
- Less local congestion and idle waiting during large infantry gatherings.
- Cleanup of stale occupancy caused by unit deaths, building demolition, and invalid path caches.
- Fixes for miscellaneous internal errors and abnormal states.
- Mode-specific AI configurations, with a higher active-unit scale in endurance mode.
- Testable alternative implementations for passenger firing, garrison experience attribution, and ranged aircraft that remain airborne.
A general-purpose LLM is neither a debugger nor a replacement for reverse engineering. Its strongest role is to interpret evidence, generate hypotheses, organize implementation options, draft tests, and assist diagnosis. Reliable conclusions still depend on logs, replays, breakpoints, differential comparisons, and repeatable experiments.
2. Integrating LLM Assistance into an Engineering Feedback Loop
2.1 Define Testable Behavior Before Asking How to Implement It
Legacy-engine modifications often begin with vague requests such as “make the AI stronger,” “fix traffic jams,” or “stop the crashes.” These requests do not provide a direct way to evaluate success.
A more useful starting point is a set of observable acceptance criteria:
- Does each AI attack wave have explicit gathering, departure, attack, retreat, or reinforcement states?
- When many units pass through a narrow choke point, does average waiting time decrease? Does the proportion of units oscillating in place fall?
- After a building is demolished, are its occupied cells released within a bounded time? Are affected path caches invalidated?
- When a passenger fires, do damage attribution, kill credit, and experience attribution match the intended rules?
- Do ranged aircraft maintain an attack-range band instead of repeatedly flying directly above the target?
These criteria distinguish an explanation that merely sounds plausible from one that can be tested.
2.2 Prioritize Evidence: Logs, Configuration, and Observed Behavior
Instead of asking a model how an undocumented engine implements a mechanic, provide evidence and ask it to organize possible explanations.
Useful inputs include:
- Configuration excerpts: unit attributes, weapon parameters, movement speed, and occupancy radius.
- Log excerpts: path requests, state transitions, and abnormal interruptions.
- Replay observations: which unit types become blocked, on which terrain, and in which formations.
- Version comparisons: differences between the base release and an expansion under the same conditions.
- Minimal reproduction steps: a small set of maps, units, and command sequences.
The workflow can be summarized as:
Observe abnormal behavior-> Collect minimal evidence-> Ask the model for possible causes-> Design experiments that distinguish those causes-> Validate with replays and logs-> Preserve the patch and regression tests
The critical step is designing discriminating experiments.
For example, congestion might result from an outdated path cache or an unreleased unit reservation. To distinguish them, test a unit retracing the same route immediately after another unit dies, and separately test pathfinding through an area after a building is demolished. Observations alone are not enough to identify the cause.
2.3 Prefer Data-Driven Changes and Minimal Interception
Broad modifications to an old engine introduce unnecessary risk. A safer patch strategy is:
- Start with configuration. If parameter tables, mode profiles, or unit properties can solve the problem, avoid changing engine logic.
- Use scripting next. Where available, use event callbacks, state-machine extensions, or behavior scripts to override local behavior.
- Minimize interception points. Intercept movement intent, attack intent, damage resolution, or grid occupancy only where necessary.
- Keep changes reversible. Give each patch an independent toggle to support comparisons and regression diagnosis.
- Make regression tests repeatable. Fix the map, random seed, and command sequence, and retain important replays and metrics.
An LLM can draft patches, pseudocode, and test cases. Whether a patch is accepted must depend on actual execution results.
3. Case Study: Pathfinding Congestion and Stale Grid Reservations
3.1 Congestion Rarely Has a Single Cause
When large infantry groups become blocked, the obvious explanation is poor pathfinding. In practice, several problems can produce similar symptoms:
- Occupancy radius does not match visual unit size, causing the engine to overestimate choke-point capacity.
- Formation destinations are too concentrated, so multiple units compete for the same cell.
- Mixed-speed groups repeatedly attempt to overtake one another, creating local deadlocks.
- Path caches are not invalidated promptly, so units continue following outdated routes.
- Reservations remain after a unit dies, teleports, or enters a transport.
- Building demolition or terrain changes leave stale entries in the occupancy grid.
- Too many path requests arrive in one frame, creating a temporary processing bottleneck.
Replacing the pathfinding function alone is therefore unlikely to address the full problem. A better breakdown separates five concerns: capacity estimation, local avoidance, reservation release, request scheduling, and cache invalidation.
3.2 Clean Up Reservations Before Tuning Movement
A “ghost cell” is a cell that is physically free but still marked as occupied or reserved. Common triggers include unit death, loading into a transport, building demolition, abnormal unit destruction, and interrupted path recalculation.
A reservation structure with expiration and owner validation can help:
struct Reservation:cell_id: CellIdowner_id: UnitIdexpire_tick: intreason: stringfunction maintain_reservations(now_tick):for r in reservations:if r.expire_tick < now_tick:release(r.cell_id, r.owner_id)continueif not is_alive(r.owner_id):release(r.cell_id, r.owner_id)continueif not still_needs_cell(r.owner_id, r.cell_id):release(r.cell_id, r.owner_id)
This pseudocode expresses a lifecycle rule: every reservation needs an owner, a lifetime, and explicit release conditions.
Clearing a cell only when a unit leaves it is insufficient because exceptional execution paths may skip that cleanup. Expiration ticks and owner-liveness checks reduce the likelihood that stale reservations persist indefinitely.
3.3 Combine Local Avoidance with Batched Path Requests
In congestion hotspots, local avoidance scoring can reduce the need for every unit to recalculate a complete path each frame:
function on_move_tick(unit):if unit.state != MOVING:returnscore = congestion_score(unit.current_cell, unit.next_cell)if score > LOCAL_AVOID_THRESHOLD:request_local_avoidance(unit)if should_repath(unit, score):enqueue_path_request(unit, priority=unit.stuck_ticks)
Important design considerations include:
- Prefer local avoidance to global recalculation. Small positional adjustments are less expensive and suit dense infantry groups.
- Batch path requests. Prioritize them by time spent stuck, task priority, and distance to the destination rather than processing a burst in one frame.
- Score the neighborhood. Consider occupancy trends two or three cells ahead, not just the current cell.
- Use tiered recalculation thresholds. Mild congestion should trigger local adjustments; severe blocking should trigger a full path recalculation.
- Spread formation destinations. Replace a single assembly point with multiple ring-shaped or grid-based destinations to reduce competition for individual cells.
3.4 Measure the Results
Congestion fixes should not be judged only by whether movement looks smoother. Useful metrics include:
- Average waiting ticks per unit.
- Proportion of units oscillating in place.
- Unit throughput through narrow choke points.
- Path requests and recalculations per frame.
- Number of units stuck beyond a defined threshold.
- Number of stale reservations cleared.
- Number of cache invalidations for the same route.
Logs can summarize these metrics for before-and-after comparisons. An LLM can help select metrics, outline analysis scripts, and interpret unusual fluctuations, but the measurements must come from actual runs.
4. Case Study: Sustained AI Attacks and Mode-Specific Configuration
4.1 Replace Sporadic Deployment with an Attack-Wave State Machine
Increasing resource income or shortening production intervals does not necessarily create sustained pressure. A wave-based state machine offers more predictable organization:
states: IDLE -> GATHER -> MARCH -> ASSAULT -> RECYCLEIDLE:if resources >= wave_threshold and active_groups < max_groups:select_mode_profile()enter GATHERGATHER:collect_units_until(composition_reached or timeout)enter MARCHMARCH:move_to_rally_point()if group_ready and enemy_detected:enter ASSAULTASSAULT:assign_targets()if group_loss_ratio > retreat_threshold:enter RECYCLERECYCLE:merge_survivors_into_next_wave()enter IDLE
The key benefit is separating force production from attack organization. Even with abundant resources, units still pass through gathering, marching, assault, and recovery rather than attacking individually and being lost piecemeal.
4.2 Express Mode Differences as Data
Different game modes require different AI behavior. Mode profiles can represent those differences:
mode_profile:name: standardwave_threshold: ...composition_tags: [...]max_active_groups: ...retreat_loss_ratio: ...same_screen_soft_cap: ...mode_profile:name: endurancewave_threshold: ...composition_tags: [infantry_heavy, support]max_active_groups: ...retreat_loss_ratio: ...same_screen_soft_cap: ...
Endurance mode can raise the soft cap on simultaneously active units, increase the infantry proportion, and shorten the interval between later waves. These changes must be paired with performance safeguards and path-request scheduling. Otherwise, pathfinding and combat processing become bottlenecks as unit counts grow.
4.3 Optimize for Sustainability, Not Just Strength
Sustained AI pressure depends on several coordinated decisions:
- Decouple resources from waves. Resources determine available forces; the state machine determines when to organize attacks.
- Use rally points and attack routes. Avoid sending units directly from production buildings toward the enemy.
- Retreat and recycle survivors. Remaining units can join the next wave instead of repeatedly entering unwinnable fights.
- Balance unit composition. Infantry-only forces are prone to congestion; support units, ranged units, or vehicles can distribute the load.
- Protect soft limits. As active-unit counts approach the cap, reduce new-wave frequency to preserve stable movement and combat processing.
The sustained mass attacks and substantially larger active forces achieved in endurance mode came from mode profiles, wave scheduling, and congestion control working together—not from increasing one parameter.
5. Case Study: Implementing Missing Combat Mechanics
5.1 Passenger Firing Through Proxy Attacks
A base engine may support transport vehicles without supporting passengers firing from them. Simply adding a weapon to the vehicle does not preserve passenger behavior. A more general approach is to represent passenger firing as proxy attacks:
- Maintain a seat table containing each passenger, facing direction, and weapon state.
- When a passenger boards, register its attack capability as a proxy attack source on the vehicle rather than discarding it.
- Update available firing arcs as the vehicle moves.
- Unregister the proxy attack source when the passenger dies or exits.
- Record the actual damage source for kill credit and experience attribution.
function on_damage_event(event):source = resolve_damage_source(event)record_damage(source.actual_owner, event.victim, event.amount)if event.victim.is_dead:credit = resolve_kill_credit(source)award_experience(credit)
The hardest issue is not whether the passenger can fire, but consistent attribution. Damage sources, kill credit, experience awards, and UI messages must agree. A shared damage-event pipeline is preferable to separate patches for each vehicle type.
5.2 Garrison Combat and Experience: Unify Damage Accounting
Garrison systems can fail when building attacks, infantry attacks, and experience awards follow different logic. A consistent approach is to:
- Generate a common damage event for every attack.
- Include the actual shooter, its carrier, and the controlling player in that event.
- Resolve experience according to a configurable policy: award it to the building, the garrisoned unit, proportionally, or to the last damage source.
- Use the same cleanup path for garrison destruction and experience settlement when a building is destroyed.
- Log abnormal events, such as a dead garrisoned unit continuing to cause damage.
function resolve_kill_credit(damage_source):if damage_source.kind == GARRISON:return policy.resolve(building_owner=damage_source.carrier_owner,infantry_owner=damage_source.shooter_owner,last_hit=damage_source.last_hit)if damage_source.kind == PROXY_WEAPON:return damage_source.actual_ownerreturn damage_source.owner
A mechanic that fires correctly but awards experience incorrectly is still broken. Tests should cover garrison kills, building destruction, passenger deaths during combat, mixed garrisons, and changes in the source of the final damage.
5.3 Ranged Aircraft: Maintain an Attack-Range Ring
Some older engines make aircraft approach a position directly above the target before attacking. To support ranged aircraft that remain airborne and keep their distance, intercept the attack-movement intent and use a hover-attack state machine:
state HoverAttack:if distance(unit, target) > max_range:move_to_best_ring(unit, target, preferred_range)else if can_fire(unit, target):face(unit, target)fire(unit, target)else if under_threat(unit):reposition_within_ring(unit, target)else:hold_position(unit)
Implementation considerations include:
- Select positions on the range ring. Prefer positions that permit firing, satisfy movement constraints, and avoid threats.
- Track moving targets. Update the chosen position as the target moves without recalculating a complete path every frame.
- Respect cooldowns and facing. Entering range does not necessarily mean the weapon can fire immediately.
- Define retreat behavior. When an enemy closes in, prioritize restoring distance rather than continuing to hover.
- Batch updates. Avoid recalculating ring positions for large numbers of aircraft simultaneously.
This state-machine approach is more reliable than changing weapon parameters alone because it explicitly separates approach, hover, fire, and reposition behavior.
6. Best Practices for Working with an LLM
6.1 Include Constraints and Acceptance Criteria
“Help me fix pathfinding” is an inefficient prompt. A useful request should contain:
- Observed behavior: the terrain and formations in which units become congested.
- Available evidence: logs, configuration values, and reproduction steps.
- Constraints: preserve save compatibility, avoid substantial per-frame overhead, and limit changes to local behavior.
- Requested output: hypotheses first, distinguishing experiments second, and pseudocode last.
- Acceptance criteria: waiting time, stuck-unit ratio, path-request volume, and abnormal-log counts.
6.2 Ask for Falsifiable Proposals
An LLM may produce a convincing explanation that does not match the engine. Require it to:
- Separate established facts from inferences and unverified hypotheses.
- Design a minimal experiment for each hypothesis.
- State what would invalidate the proposal.
- Identify potentially affected modules.
- Provide a rollback plan.
6.3 Let the Model Accelerate Work, Not Decide Correctness
A practical division of responsibility is:
- Developer: define goals, collect evidence, assess risk, and perform final validation.
- Model: organize clues, generate candidate causes, draft pseudocode, expand test coverage, and summarize log patterns.
- Toolchain: run replays, collect metrics, compare behavior, and capture failures.
Treating the LLM as an analytical assistant rather than an automatic repair system makes the workflow more dependable.
7. Regression Testing Checklist
Legacy-engine modifications need broad regression coverage. At minimum, test:
- Empty-map baseline: verify frame rate and logs with no units or buildings.
- Single-unit movement: straight routes, turns, narrow passages, and building corners.
- Large infantry gatherings: different formations, movement speeds, and destinations.
- Unit death and destruction: reservation release and path-cache invalidation.
- Building demolition: garrison cleanup, grid release, and experience settlement.
- Loading and unloading: registration and removal of passenger proxy attacks.
- Ranged aircraft: moving targets, range boundaries, close threats, and weapon cooldowns.
- Endurance mode: active-unit caps, wave intervals, and performance metrics.
- Recovery from interruptions: loading a save mid-session, pausing, restarting, and rapidly switching modes.
- Long replay runs: watch for drift in memory use, logs, and state tables over time.
Summarize results in a comparison table covering pre-patch behavior, post-patch behavior, extreme scenarios, and regression scenarios. Only changes validated through repeatable replays should become part of the maintained implementation.
8. Conclusion
General-purpose LLMs can help developers modify legacy game engines by accelerating reverse-engineering analysis, hypothesis generation, solution decomposition, pseudocode drafting, and test design. They do not provide a one-step engine rewrite.
The decisive factors remain engineering discipline:
- Define behavior that can be accepted or rejected through testing.
- Build an evidence chain from logs and replays.
- Separate pathfinding congestion into capacity, reservation, cache, and scheduling problems.
- Organize AI attacks with state machines rather than parameter increases alone.
- Keep damage accounting and state lifecycles consistent across passenger firing, garrison combat, and ranged-aircraft behavior.
- Pair every patch with a minimal reproduction and regression metrics.
For individual developers and small teams, this approach can reduce the exploration cost of modifying an old engine. It does not make every hypothesis correct. It makes incorrect hypotheses easier to expose and useful implementations easier to retain.
The model broadens the analysis; the engineering feedback loop turns that analysis into reliable changes.
