Software Development Game Development 1 vues

This 200KB Chess Engine Runs in Windows Recovery Mode

M
Mohamed IDBRAHIM
Auteur
This 200KB Chess Engine Runs in Windows Recovery Mode

This 200KB Chess Engine Runs in Windows Recovery Mode

What if your chess engine was so lean it could run while your operating system was dying?

Picture this: you're knee-deep in a critical system recovery, Windows is barely breathing, and yet—there it is. A fully functional chess engine. Not some stripped-down toy. A battle-tested engine with alpha-beta pruning, neural network infrastructure, and parallel search. All crammed into a binary smaller than most JPEGs.

Sound insane? That's because it is. And it's exactly what wesmar/Chess delivers.

Most developers assume "modern" means "bloated." We've normalized 200MB Electron apps for todo lists. We've accepted that "lightweight" is marketing speak for "only 50 dependencies." But what happens when someone rejects that entire philosophy? What happens when a developer applies Data-Oriented Design (DOD) principles with religious fervor, squeezing every byte, every cache line, every CPU cycle until the result barely resembles contemporary software?

You get something that shouldn't exist. Something that exposes how much waste we've accepted as standard. Something that makes you question every npm install you've ever run.

This is the story of wesmar/Chess—a C++20 chess engine that proves modern code can be smaller, faster, and more capable than anything we've been told is possible. Whether you're a systems programmer hunting optimization secrets, a chess enthusiast curious about engine internals, or simply someone who refuses to believe 200KB can contain multitudes... keep reading. The technical revelations ahead will rewire how you think about software efficiency.

What is wesmar/Chess?

wesmar/Chess is a lightweight, educational chess engine written in modern C++20, featuring a pure WinAPI graphical interface and absolutely zero external dependencies. Created by Marek Wesołowski (WESMAR) during Christmas 2025/2026, it represents a deliberate rebellion against the complexity epidemic infecting modern software development.

The project's stated mission cuts straight to the point: most chess engines are either too simple (missing professional techniques) or too complex (thousands of files, external dependencies galore). wesmar/Chess occupies the razor-thin middle ground—educational yet powerful—implementing genuine professional chess engine techniques in clean, readable code that won't overwhelm learners.

But here's where it gets genuinely interesting. This isn't merely about chess. It's a case study in Data-Oriented Design—a programming paradigm that prioritizes how data flows through hardware over abstract elegance. The engine maximizes computational throughput while drastically reducing binary size and eliminating all external library dependencies. The result? A piece of software that runs in environments where even basic utilities fail.

The Windows Recovery Environment (WinRE) isn't some trivial target. It's a minimal preboot environment with severely restricted resources, limited API availability, and no guarantee of standard runtime libraries. That wesmar/Chess executes here isn't a party trick—it's proof of architectural purity. When your code has zero dependencies, statically links everything, and fits in processor cache, you unlock deployment scenarios that dependency-heavy applications literally cannot approach.

The engine has garnered attention precisely because it contradicts prevailing assumptions. In an era where "modern C++" often implies heavy abstraction, template metaprogramming complexity, and substantial runtime overhead, wesmar/Chess demonstrates that C++20's advanced features can serve performance rather than hinder it. Concepts, constexpr evaluation, and modern type system features enable cleaner code that compiles to tighter binaries than many C equivalents.

Key Features: The Technical Arsenal

What capabilities hide inside this sub-500KB package? The feature list reads like a graduate-level computer science curriculum compressed into executable form.

Search Algorithm Sophistication

The engine implements a comprehensive suite of professional search techniques rarely found together in educational projects:

  • Minimax with Alpha-Beta Pruning forms the backbone—efficient move tree search that eliminates branches when better alternatives are proven
  • Principal Variation Search (PVS) optimizes alpha-beta by assuming the first move is best, re-searching only when this assumption fails
  • Iterative Deepening finds the best move within time constraints, progressively deepening search until cutoff
  • Aspiration Windows narrow search windows based on previous iteration scores, accelerating cutoffs
  • Quiescence Search eliminates the "horizon effect" by extending tactical sequences until positions stabilize

Aggressive Pruning Ecosystem

The pruning strategy is where wesmar/Chess demonstrates genuine engine-strength sophistication:

  • Null Move Pruning (NMP) skips branches where the opponent cannot improve even with two consecutive moves—intelligently disabled in endgames to avoid zugzwang catastrophes
  • ProbCut prunes when shallow tactical searches at higher beta already exceed expected bounds, using captures-only search with SEE filtering
  • Late Move Reduction (LMR) applies a logarithmic formula (log(depth) × log(moveIndex) / 2.25) to reduce search depth for quiet moves ordered late, with automatic re-search on alpha improvement
  • Late Move Pruning (LMP), Futility Pruning, Reverse Futility Pruning, Delta Pruning, and Mate Distance Pruning complete an aggressive but safe pruning portfolio

Memory Architecture Innovations

The stack-allocated MoveList structure deserves special attention—a fixed 256-move array eliminating millions of heap allocations per search. The entire hot path uses zero malloc() calls. Combined with incremental Zobrist key updates, incremental MG/EG score maintenance, and O(1) piece list updates via swap-with-last removal, the engine achieves memory performance that garbage-collected languages cannot theoretically match.

The 64-byte cache-aligned mailbox representation is a masterclass in hardware-conscious design. While pure bitboards dominate chess engine folklore, wesmar/Chess proves that cache locality often trumps algorithmic complexity—the entire board state loads in a single L1 cache line fetch.

Use Cases: Where This Engine Dominates

1. Educational Deep-Dive for Aspiring Engine Developers

Most chess engines force a brutal choice: study simplified tutorials that omit critical techniques, or drown in 100,000+ line monstrosities like Stockfish. wesmar/Chess provides production-quality implementations of advanced concepts—Singular Extensions, ProbCut, tapered evaluation—in a digestible codebase. The suggested reading order (Board.cpp → Evaluation.cpp → MoveGenerator.cpp → ChessGame.cpp) creates a genuine learning progression.

2. Embedded and Recovery Environment Deployment

The WinRE compatibility isn't theoretical. System administrators can deploy this for diagnostic downtime entertainment, but more practically, it demonstrates techniques applicable to any resource-constrained environment. Medical devices, industrial controllers, automotive systems—anywhere binary size and dependency elimination matter, this architecture provides a template.

3. UCI Engine Analysis Integration

The included ChessEngineUCI.exe integrates with standard chess GUIs like Arena. Analysts seeking a lightweight, understandable engine for position study benefit from transparent evaluation logic and adjustable difficulty levels. Unlike opaque neural network engines, the hand-crafted evaluation reveals why positions are assessed particular ways.

4. Data-Oriented Design Research and Benchmarking

For systems programmers, wesmar/Chess serves as a measurable DOD case study. The ~800KB savings versus Magic Bitboards, the L1 cache alignment strategy, the stack-vs-heap allocation decisions—all provide concrete benchmarks for architectural debates. Teams arguing about performance can point to real numbers: 200KB binaries, <100ms startup, 16-64MB transposition tables.

Step-by-Step Installation & Setup Guide

Prebuilt Binaries (Fastest Path)

The project provides ready-to-run executables requiring zero installation:

# Download from GitHub Releases
# URL: https://github.com/wesmar/Chess/releases/download/latest/Chess.7z
# Password: github.com

# Extract and run directly—no installer, no registry changes, no dependencies
Chess_x64.exe           # 64-bit full version (~500 KB)
Chess_x64_minSize.exe   # 64-bit minimal (~200 KB) — the WinRE champion
Chess_x86.exe           # 32-bit version (~450 KB)
Chess_x86_minSize.exe   # 32-bit minimal (~160 KB)

The minSize variants use no CRT linking—pure operating system calls with minimal runtime overhead. These are your WinRE-compatible builds.

Building from Source

System Requirements:

  • Windows 10 or later
  • Visual Studio 2022+ with C++20 support (v143 toolset minimum)
  • Tested with Visual Studio 2026 (v145 toolset)

Automated Build:

# Clone repository
git clone https://github.com/wesmar/Chess.git
cd Chess

# Build all configurations with reproducible builds (/BREPRO flag)
build_all.bat

# Outputs appear in 'bin' directory with deterministic checksums

Manual MSBuild:

# Open "Developer Command Prompt for VS 2022+"

# Standard 64-bit release
msbuild Chess.vcxproj /p:Configuration=Release /p:Platform=x64

# Minimal size 64-bit (no CRT, maximum optimization)
msbuild Chess.vcxproj /p:Configuration=Release_MinSize /p:Platform=x64

# UCI console engine only
msbuild ChessEngineUCI.vcxproj /p:Configuration=Release /p:Platform=x64

Configuration Files:

On first run, the GUI creates settings.ini automatically:

[Display]
FlipBoard=0
ShowCoordinates=1
ShowLegalMoves=1
AnimateMoves=1
AnimationSpeed=300

[Game]
GameMode=1          ; 0=Human vs Human, 1=Human vs Computer, 2=Computer vs Computer
AIDifficulty=3      ; Range: 1 (random moves) to 10 (expert depth)
Threads=4           ; Auto-detected; override up to 64
AutoPromoteQueen=1  ; Auto-promote to queen; disable for underpromotion practice

[Colors]
LightSquare=240,240,245
DarkSquare=70,80,100

REAL Code Examples from the Repository

Let's examine actual implementation patterns that make this engine extraordinary.

Example 1: The 1-Byte Piece Structure

The Piece.h file reveals the Data-Oriented Design philosophy in microcosm:

// Piece.h — Complete piece representation in a single byte
// No v-table, no polymorphism, no heap allocation

#pragma once
#include <cstdint>

class Piece {
public:
    // Bit layout: [color:1][type:3][moved:1][reserved:3]
    // 0 = empty, 1-6 = pawn, knight, bishop, rook, queen, king
    static constexpr uint8_t COLOR_MASK = 0x80;  // Bit 7: 0=white, 1=black
    static constexpr uint8_t TYPE_MASK  = 0x0E;  // Bits 1-3: piece type
    static constexpr uint8_t MOVED_MASK = 0x01;  // Bit 0: has moved flag

    constexpr Piece() noexcept : m_data(0) {}
    constexpr explicit Piece(uint8_t data) noexcept : m_data(data) {}
    
    // Factory methods avoid raw constructor calls
    static constexpr Piece Make(uint8_t type, bool white, bool moved = false) noexcept {
        return Piece(static_cast<uint8_t>(
            (type << 1) | 
            (white ? 0 : COLOR_MASK) | 
            (moved ? MOVED_MASK : 0)
        ));
    }

    [[nodiscard]] constexpr bool IsEmpty() const noexcept { return m_data == 0; }
    [[nodiscard]] constexpr bool IsWhite() const noexcept { return (m_data & COLOR_MASK) == 0; }
    [[nodiscard]] constexpr uint8_t Type() const noexcept { return (m_data & TYPE_MASK) >> 1; }
    [[nodiscard]] constexpr bool HasMoved() const noexcept { return (m_data & MOVED_MASK) != 0; }
    
    // Inline mutation for make/unmake efficiency
    constexpr void SetMoved() noexcept { m_data |= MOVED_MASK; }
    constexpr void ClearMoved() noexcept { m_data &= ~MOVED_MASK; }

private:
    uint8_t m_data;  // The entire piece state — one byte, period
};

Why this matters: A 64-square board requires only 64 bytes. The entire position fits in a single cache line. Compare to object-oriented designs with virtual inheritance, where each piece might consume 16-32 bytes with v-table pointers and alignment padding. This isn't micro-optimization—it's orders-of-magnitude memory bandwidth reduction during tree traversal.

Example 2: Stack-Allocated MoveList

The MoveGenerator.cpp demonstrates zero-allocation move generation:

// MoveGenerator.h — Fixed-size stack array eliminates heap pressure

#pragma once
#include <array>
#include <cstdint>
#include "Move.h"

class MoveList {
public:
    // Maximum legal moves in any chess position is 218 (per research)
    // 256 provides comfortable margin with power-of-two alignment
    static constexpr size_t CAPACITY = 256;
    
    // Default construction — no dynamic allocation, ever
    MoveList() noexcept : m_count(0) {}
    
    // Push with bounds checking in debug, unchecked in release for speed
    void Add(Move move) noexcept {
        assert(m_count < CAPACITY);  // Debug-only validation
        m_moves[m_count++] = move;
    }
    
    [[nodiscard]] size_t Count() const noexcept { return m_count; }
    [[nodiscard]] bool Empty() const noexcept { return m_count == 0; }
    
    // Iterator interface for range-based for loops
    [[nodiscard]] Move* begin() noexcept { return m_moves.data(); }
    [[nodiscard]] Move* end() noexcept { return m_moves.data() + m_count; }
    
    // Index access with optional bounds checking
    [[nodiscard]] Move operator[](size_t index) const noexcept {
        assert(index < m_count);
        return m_moves[index];
    }

    // Sorting interface for move ordering heuristics
    void SortByScore() noexcept;  // SEE, MVV-LVA, killers, history
    void Swap(size_t a, size_t b) noexcept {
        std::swap(m_moves[a], m_moves[b]);
    }

private:
    std::array<Move, CAPACITY> m_moves;  // Stack-allocated, cache-friendly
    size_t m_count;
    
    // Explicitly deleted to prevent accidental heap copies
    // MoveList is intended for automatic storage duration only
};

Critical insight: During search, millions of positions are evaluated. Each position generates moves. Heap allocation at this frequency would dominate runtime with malloc/free overhead and cache pollution. The fixed array lives on the stack, gets reused automatically, and never fragments memory. The assert() pattern provides safety during development with zero release-build cost.

Example 3: Incremental Tapered Evaluation

The Evaluation.cpp reveals sophisticated score maintenance:

// Board.h — Incremental score members (excerpt)

class Board {
    // ... other members ...
    
    // Two scores maintained incrementally across make/unmake
    int m_incrementalScore;  // Middlegame score: material + MG PST
    int m_egScore;           // Endgame score: material + EG PST
    
    // Phase calculation for tapered interpolation
    // Q=4, R=2, B/N=1, max=24 → maps to 0-256 range
    uint16_t m_phase;
    
    // Zobrist hash for transposition table lookups
    uint64_t m_zobristKey;
    
    // Pawn bitboards for O(1) structure queries
    uint64_t m_pawnMasks[2];  // [0]=white pawns, [1]=black pawns
    
    // Piece lists for O(1) iteration without scanning 64 squares
    struct PieceEntry { uint8_t square; uint8_t pieceData; };
    std::array<PieceEntry, 16> m_whitePieces;  // Max 16 pieces per side
    std::array<PieceEntry, 16> m_blackPieces;
    uint8_t m_whiteCount, m_blackCount;
};

// Evaluation call — O(1) with precomputed values!
int Evaluate(const Board& board) {
    // Tapered interpolation: smooth transition from opening to endgame
    const int mg = board.m_incrementalScore;
    const int eg = board.m_egScore;
    const int phase = board.m_phase;  // 0=opening, 256=pure endgame
    
    // Integer arithmetic avoids floating-point conversion
    return (mg * phase + eg * (256 - phase)) / 256;
}

The genius: Traditional engines recompute evaluation from scratch—scanning all pieces, summing material, applying PST lookups. That's O(pieces) per node, multiplied by millions of nodes. wesmar/Chess updates both scores incrementally during MakeMove() and restores them via MoveRecord during UnmakeMove(). The evaluation function becomes constant time—a single integer multiply-add-divide sequence.

Example 4: Late Move Reduction Formula

From the search implementation, the LMR logarithmic formula:

// Search.cpp — Late Move Reduction with re-search logic

int Search(Board& board, int depth, int alpha, int beta, 
           int ply, bool isPV, MoveList& moves) {
    // ... alpha-beta framework ...
    
    for (size_t i = 0; i < moves.Count(); ++i) {
        Move move = moves[i];
        int score;
        
        // Late Move Reduction: reduce depth for moves ordered late
        // that are unlikely to cause alpha-beta cutoff
        int reduction = 0;
        if (depth >= 3 && i >= 2 && !IsCapture(move) && !IsCheck(move)) {
            // Logarithmic formula: deeper searches reduce more aggressively
            // moveIndex later in list → more reduction
            reduction = static_cast<int>(
                std::log(depth) * std::log(static_cast<double>(i + 1)) / 2.25
            );
            
            // Ensure we don't reduce into quiescence or negative depth
            reduction = std::clamp(reduction, 0, depth - 2);
        }
        
        board.MakeMove(move);
        
        if (reduction > 0) {
            // Reduced-depth search to test if move is interesting
            score = -Search(board, depth - 1 - reduction, -alpha - 1, -alpha, 
                           ply + 1, false, childMoves);
            
            // Re-search at full depth if reduced search suggests improvement
            if (score > alpha) {
                score = -Search(board, depth - 1, -beta, -alpha, 
                               ply + 1, isPV, childMoves);
            }
        } else {
            // Full-depth search for early moves, captures, checks
            score = -Search(board, depth - 1, -beta, -alpha, 
                           ply + 1, isPV, childMoves);
        }
        
        board.UnmakeMove(move);
        // ... alpha-beta updates ...
    }
}

Why logarithmic? The formula encodes empirical chess knowledge: at higher depths, the probability of late-ordered quiet moves being best drops superlinearly. The 2.25 denominator was tuned to balance search speed versus accuracy. The re-search mechanism ensures no tactical oversights—if a reduced search finds something good, we invest full effort.

Advanced Usage & Best Practices

Difficulty Calibration for Training

The 10-level system isn't linear. Level 1 plays random legal moves—useful for pattern recognition drills. Level 3 implements basic search with pruning disabled; beating this consistently indicates ~1400 Elo understanding. Levels 7+ activate full heuristics; level 10 with multiple threads challenges club players. For deliberate practice, play level 3 until bored, then jump to level 5.

Transposition Table Sizing

The 16-64MB default adapts to available RAM. For long analysis sessions, manually increase via settings or UCI parameters. Larger tables improve endgame precision where positions repeat. For blitz games, smaller tables reduce cache pressure and improve nps (nodes per second).

NNUE Activation (Future-Proofing)

The infrastructure exists; weights don't. When training completes, place nn-small.nnue in the executable directory and switch HybridEvaluator mode. The NeuralEvaluator with incremental accumulator updates will activate, potentially gaining 100+ Elo with minimal speed cost.

Reproducible Build Verification

The /BREPRO flag enables deterministic compilation. Security-conscious users can rebuild and verify binary identity against releases, confirming no injected modifications.

Comparison with Alternatives

Feature wesmar/Chess Stockfish Crafty GNU Chess
Binary Size 160-500 KB ~2-5 MB ~1 MB ~2 MB
Dependencies Zero None (but large) None Gnuchess library
WinRE Compatible ✅ Yes ❌ No ❌ No ❌ No
Source Lines ~10,000 ~150,000 ~50,000 ~30,000
C++ Standard C++20 C++17 C C
NNUE Support Infrastructure ready Full No No
Learning Curve Gentle Steep Moderate Moderate
Parallel Search Root-parallel YBWC/Splitpoint Yes Yes
UCI Protocol ✅ Yes ✅ Yes ✅ Yes ✅ Yes
Hand-Crafted Eval ✅ Yes Hybrid ✅ Yes ✅ Yes
Educational Value ⭐⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐ ⭐⭐⭐

The verdict: Stockfish dominates raw strength but drowns learners in complexity. wesmar/Chess sacrifices ~500 Elo for comprehensibility and deployability. Choose it when you need to understand the engine, deploy it anywhere, or modify it confidently.

FAQ

Q: Can this engine actually beat serious players? A: At maximum settings with multiple threads, it plays at strong club level (~1800-2000 Elo estimated). Not Stockfish-crushing, but genuinely challenging for most humans.

Q: Why WinAPI instead of cross-platform frameworks? A: Deliberate simplicity choice. Every abstraction layer adds size and complexity. WinAPI provides sufficient functionality without SDL/Qt bloat. A Linux port would require ~500 lines of X11 or Wayland code.

Q: How does the 64-byte board compare to bitboards performance-wise? A: For move generation, bitboards win. For iterative search traversal (the actual bottleneck), cache-aligned mailbox dominates. The ~800KB Magic Bitboard lookup tables would evict critical data from L1 cache.

Q: Is the NNUE infrastructure actually functional? A: All code compiles and runs inference tests. It requires trained weights (nn-small.nnue) to activate. The architecture supports HalfKP features with SIMD-optimized dense layers.

Q: Can I use this commercially? A: MIT License permits virtually unlimited use. Attribution to Marek Wesołowski appreciated but not legally required.

Q: What's the actual Elo rating? A: No formal CCRL/CEGT testing yet. Estimated 1800-2000 at level 10 based on search depth and feature comparison to rated engines.

Q: Why no Syzygy tablebase support yet? A: Tablebase files are 1GB+; contradicts the minimal-size philosophy. Planned as optional external file loading, not embedded.

Conclusion

wesmar/Chess isn't merely a chess engine. It's a manifesto against software bloat, a masterclass in Data-Oriented Design, and a proof that modern C++ can achieve C-level efficiency without sacrificing expressiveness.

The 200KB binary running in Windows Recovery Environment isn't a gimmick—it's the logical consequence of architectural decisions made at every level. Stack allocation over heap. Cache lines over convenience. Incremental updates over recomputation. Each choice compounds until the result seems impossible by contemporary standards.

For developers, this repository offers actionable optimization patterns applicable far beyond chess. The 1-byte piece encoding, the fixed-array move lists, the incremental evaluation maintenance—these translate to any performance-critical domain. For chess programmers, it provides a rare bridge between tutorial simplicity and engine-grade sophistication.

The project invites contribution: NNUE weight training, Syzygy integration, MultiPV analysis. But even in current form, it challenges assumptions that have calcified into industry norms.

Your move. Clone the repository, build the minimal version, and witness what happens when someone refuses to accept that "modern" must mean "massive." The source code awaits at github.com/wesmar/Chess—and unlike most GitHub stars you'll collect, this one might actually change how you write software.

Checkmate, bloat.

Commentaires 0

Aucun commentaire pour l'instant. Soyez le premier à réagir !

Laisser un commentaire