AI Coding Agents for Reverse Engineering and Rebuilding a Legacy Game Engine

    This retrospective examines an AI-agent-driven effort to rebuild a legacy real-time strategy game engine from binaries and resource files. It covers staged acceptance criteria, proprietary format decoding, license-aware dependency decisions, UI reconstruction, deterministic simulation, and lockstep multiplayer, along with the automated checks and human oversight needed to manage high-volume development.

    1. Defining the Problem: Why Rewrite Instead of Wrap?

    Many classic single-player games survive only as executables and resource archives; their original source projects have been lost. Three common approaches are to hook the original program through a compatibility layer, run it in a virtual machine, or rewrite the engine entirely.

    The first two require less investment but have clear limits: platform dependencies, restricted resolutions, limited multiplayer options, and poor maintainability. A rewrite costs more, but produces a maintainable, portable, and extensible codebase.

    The experiment therefore had a clear objective: use AI coding tools as the primary development workforce to reverse-engineer a legacy real-time strategy game from its binaries, reimplement it in a modern systems programming language, and deliver it in stages through multiplayer support.

    One boundary applied throughout: no third-party implementation code could be copied. Publicly documented algorithmic ideas could inform an independent implementation, and every dependency had to pass a license review. This constraint became one of the project’s largest hidden costs.

    2. Experiment Design: Break the Rewrite into Verifiable Stages

    Asking a model to “rewrite this game” in one step is a recipe for failure. A more effective approach is to establish a roadmap and validate each stage separately.

    Stage Goal Acceptance criteria
    Pre-Alpha Project skeleton, build toolchain, logging, resource loading The application starts and loads main-menu resources
    Alpha-1 Complete UI Menus, sidebar, and unit panels are interactive
    Alpha-2 Combat and gameplay logic The mining–construction–production loop works end to end
    Beta Multiplayer Two clients can complete a lockstep match and reconnect

    Development ran continuously with minimal supervision, producing hundreds of commits per day. At that pace, the human role had to change: validate behavior, review samples, and enforce automated gates rather than review every line. This shift explains the engineering infrastructure described later.

    3. Day 1: Reverse-Engineering Formats and Making License-Aware Decisions

    Legacy game resources often use custom proprietary formats: magic headers, offset tables, palettes, block compression, and interleaved indices. Ready-made parsing libraries were rarely available. At this stage, the model spent more effort on reverse engineering and testing suspected constants than on writing code.

    3.1 Replace Scattered Magic Constants with Format Tables

    A common weakness in an initial parser is hardcoding offsets and constants inside conditional branches. A more robust design consolidates format knowledge into explicit tables.

    1. struct FormatSpec {
    2. magic: bytes, // Magic signature
    3. header_len: usize,
    4. palette: PaletteKind,
    5. codec: CodecKind, // Raw | Rle | BlockCyclic
    6. frame_stride: usize,
    7. }
    8. fn parse(spec: &FormatSpec, buf: &[u8]) -> Result<Frame> {
    9. assert_magic(spec.magic, buf)?;
    10. let pal = load_palette(spec.palette, buf)?;
    11. let mut off = spec.header_len;
    12. for _ in 0..spec.frame_count(buf)? {
    13. let raw = decode(spec.codec, &buf[off..], spec.frame_stride)?;
    14. off += raw.consumed;
    15. emit(raw.pixels, pal);
    16. }
    17. Ok(last_frame)
    18. }

    Turning magic constants into explicit format data has two benefits. Model-generated changes are less likely to disrupt unrelated branches, and humans can quickly check the reverse-engineering findings.

    3.2 License Conflicts Can Become Real Blockers

    One representative issue involved a video container format with only two available reference implementations. One used a strong copyleft license that conflicted with the project’s permissive-license requirements. The other used weak copyleft licensing with dynamic-linking requirements, while the project used static linking.

    The model initially proposed writing its own implementation. When asked to consult the references, it repeatedly raised licensing objections, leading to a prolonged back-and-forth.

    The lesson was not simply that the model was difficult to work with. It was that license constraints should become machine-checkable gates at project initialization, rather than remain rules repeatedly negotiated in conversation.

    • Maintain a dependency allowlist that permits only permissive licenses.
    • Add license scanning to the build pipeline and fail the build when a prohibited license is detected.
    • Document the rule that algorithmic ideas may be studied, but implementations must be written independently.
    1. license_gate:
    2. allowed: [permissive-style]
    3. denied: [strong-copyleft, weak-copyleft-static]
    4. on_violation: fail_build

    Once these rules were formalized, similar disputes largely disappeared. A model’s sensitivity to licensing can exceed that of a typical developer. In compliance-sensitive projects, that can be useful—provided the criteria are explicit and actionable.

    4. Alpha-1: Reconstructing the UI

    The UI is easy to underestimate because it combines resource decoding, layout, fonts, and input handling.

    • Resolution-independent layout: The original engine used hardcoded coordinates for a fixed resolution. The rewrite needed anchors and relative layout to support modern displays.
    • Bitmap fonts and text measurement: Fixed-width bitmap fonts required reconstructed character spacing, line height, wrapping, and truncation rules while preserving the original appearance.
    • Event loop and state machines: Explicitly model input, state transitions, and redraws to prevent circular dependencies between UI and combat logic.
    • Layered resource loading: Load metadata first and decode resources on demand instead of decompressing everything at startup.

    For acceptance testing, use screenshot comparisons. Render the same scene in the original and rewritten versions, then compare differences pixel by pixel. This is more reliable than visual inspection alone and easier to automate.

    5. Alpha-2: Determinism Is the Core of Combat Simulation

    The hardest part of an RTS simulation is not necessarily algorithmic complexity. It is repeatability: the same sequence of commands must produce the same result. Without that property, saves, replays, and multiplayer cannot be trusted.

    The project imposed four engineering constraints:

    1. No floating-point arithmetic in simulation: Represent positions, damage, and speed with fixed-point values, such as 16.16 or 24.8, to avoid cross-platform floating-point differences.
    2. Stable iteration order: Update units and resolve collisions in stable ID order. Do not let unordered hash-container iteration directly drive simulation logic.
    3. Seedable randomness: Route randomness through seeded pseudorandom streams, separated by purpose so that combat randomness and visual effects do not interfere.
    4. Separate simulation from presentation: Rendering may run at a variable frame rate, while simulation advances at a fixed timestep, such as one tick every 1/30 second.
    1. // Pseudocode: fixed timestep, fixed-point arithmetic, stable ordering
    2. loop {
    3. accumulate(real_dt);
    4. while accumulator >= TICK {
    5. for id in sorted_unit_ids() { // Stable order
    6. step_unit(id, fixed_point_state);
    7. }
    8. rng_combat.step();
    9. accumulator -= TICK;
    10. }
    11. render(alpha = accumulator / TICK);
    12. }

    Add replay consistency tests alongside these constraints. Record an input sequence, replay it, and compare state hashes at every tick. This provides a regression safety net and is a prerequisite for multiplayer.

    6. Beta: Deterministic Lockstep Multiplayer

    With a deterministic simulation, clients can synchronize commands rather than continuously synchronize world state. This is the lockstep model.

    • Collect local commands each tick, exchange them with the remote client, and execute them together at the agreed tick.
    • Use an input buffer to absorb network jitter, adjusting its depth according to measured latency.
    • Periodically compare state hashes; mismatches trigger alerts and resynchronization.
    • Reconnection relies on replaying missing input-log entries rather than transferring a full state snapshot.

    Lockstep requires very little bandwidth and is relatively straightforward to implement. Its trade-offs are latency sensitivity and the risk that any nondeterministic behavior will cause clients’ simulations to diverge.

    The determinism requirements in the previous section are therefore prerequisites, not optional optimizations.

    7. Engineering Infrastructure for a Long-Running Agent Workflow

    With hundreds of commits per day, human attention must go where it has the greatest leverage.

    • Automated gates: Put builds, unit tests, license scans, and replay consistency tests into the pipeline. Failures block progress.
    • Observability: Centralize structured logs in a logging service. Monitor frame time, tick duration, memory use, and parsing failure rates, with automatic notifications for anomalies.
    • Versioned artifacts: Store build artifacts and resource packages in object storage, retaining versions for rollback and comparison.
    • Reproducible builds: Use a container platform to standardize toolchain versions and reduce environment-specific build failures.
    • Context and cost management: Narrow the model’s context to files relevant to the current stage. Split long tasks into segments to avoid quality degradation from excessive context.
    • Sampled human review: Rotate reviews across modules, focusing on licensing, unsafe boundaries, and determinism-sensitive code.

    8. Conclusions and a Reusable Checklist

    The main lesson was not simply that AI can write a game engine. Three broader findings emerged.

    1. Compliance belongs in automated gates from the start. Encoding dependency and license rules in the pipeline is more effective than repeatedly debating them in prompts.
    2. Determinism is a hidden organizing principle in legacy engine rewrites. Fixed-point arithmetic, fixed timesteps, stable iteration, and seeded randomness determine whether saves, replays, and multiplayer work reliably.
    3. Humans become acceptance owners and rule designers. When code generation outpaces reading capacity, the highest-value work is defining acceptance criteria, reviewing representative samples, and building automated safeguards.

    The method extends beyond games. Legacy systems with missing source code, incomplete documentation, or unavailable dependencies can benefit from the same combination: a staged roadmap, table-driven format reverse engineering, a deterministic core, automated gates, and supporting observability.

    In long-running engineering projects of this kind, Baidu AI Cloud can serve as supporting infrastructure through object storage, container platforms, logging services, and monitoring and alerts. These general-purpose capabilities support artifact management, builds, and observability, leaving human attention for the decisions that require judgment.