# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview **Warfactory** is a Factorio-inspired industrial military simulation game combining factory management with strategic military doctrine. The project uses a **revolutionary modular architecture** optimized for Claude Code development with hot-reloadable modules. **Core Philosophy:** - Factory assembly lines as gameplay foundation - Player-driven military doctrine development - Progression from PMC operations to conventional warfare - Choice and complexity balanced with accessible presentation ## πŸ“‹ Implementation Status **ALWAYS CHECK**: - `TODO.md` at project root for current implementation roadmap and high-level phases - `TASKLIST.md` for detailed task breakdown organized by time investment (Quick Wins, Light Tasks, Medium Tasks, Feature Tasks, Big Tasks) **Current Phase**: World Generation System - Geological and resource foundation complete ## 🎯 **Recent Major Achievements - World Generation System** ### βœ… **Complete Geological Simulation (COMPLETED)** - **7-Phase Pipeline**: 4.6 billion year geological evolution simulation - **Physics-Based Tectonics**: Collision detection, plate movement, mountain formation - **Scientific Climate Model**: WindRegions, ITCZ, and realistic weather patterns - **Biome Classification**: 18 distinct biomes with elevation and generation parameters ### πŸ—ΊοΈ **Resource Distribution System (COMPLETED)** - **70+ Natural Features**: Geologically accurate formation patterns - **Smart Biome Integration**: Blacklist + frequent biomes for scalable compatibility - **Mass-Based Quality**: Region strength determines available resource grades - **Cross-Referenced Resources**: All features map to actual game resource definitions ### βš™οΈ **Spatial Distribution Patterns (COMPLETED)** - **5 Pattern Types**: Concentrated, uniform, ring, clustered, gradient distributions - **Random Assignment**: Each region gets unpredictable density patterns - **Biome-Aware Placement**: Local environment determines compatible features - **Phase 8 Ready**: System prepared for integration with world generation pipeline ## 🎯 **Previous Major Achievements - UI Interface System** ### βœ… **Complete IUI Interface Architecture (COMPLETED)** - **Data-Agnostic Design**: Generic `IUI` interface supporting all content types - **Type-Safe Enums**: `DataType::ECONOMY`, `RequestType::GET_PRICES` - performance over strings - **Hierarchical Windowing**: Parent β†’ Dock β†’ Split β†’ Tab β†’ Window structure - **Hybrid Sizing System**: **REVOLUTIONARY** percentage targets with absolute pixel constraints ### 🎨 **ImGuiUI Implementation (PRODUCTION-READY)** - **Complete Rendering Pipeline**: All `DataType` content renderers implemented - **Interactive Callbacks**: Request/response system with `onRequest()` + custom events - **Professional Layout**: Economic topbar + companies panel + strategic map + console - **State Management**: Window persistence, docking configuration, layout serialization ### ⚑ **Hybrid Sizing System - BREAKTHROUGH** ```json {"size": {"width": "20%"}, "min_size": {"width": 250}, "max_size": {"width": 400}} // Result: Always targets 20% of parent, but respects 250px-400px constraints // 1000px screen: 20% = 200px β†’ CLAMPS to 250px (minimum respected) // 1400px screen: 20% = 280px β†’ USES 280px (percentage achieved) // 2500px screen: 20% = 500px β†’ CLAMPS to 400px (maximum respected) ``` ### πŸ› οΈ **Advanced Development Workflow (PRODUCTION-READY)** - **AddressSanitizer by Default**: All bugs detected immediately during development - **GDB Integration**: Stack traces with exact crash locations and contexts - **Cross-Compilation**: Linux development β†’ Windows .exe with zero manual intervention - **JSON Safety**: Complete protection against null access and type mismatches ### πŸ“Š **Interface Specifications** **Files Created:** - `/core/include/warfactory/IUI_Enums.h` (339 lines) - Complete interface with hybrid sizing - `/core/include/warfactory/ImGuiUI.h` - ImGui implementation header with advanced features - `/core/src/ImGuiUI.cpp` - Full implementation with content renderers and window management - `layout_example.cpp` - Professional demo with economic topbar + companies panel **Windows Executables Ready:** - `WarfactoryUI_Fixed.exe` (4.1 MB) - Stable test version - `WarfactoryUI_Complete_Fixed.exe` (4.2 MB) - Full interface with all features ## Documentation Architecture The project uses a **hierarchical documentation system** in `/docs/`: ### πŸ“‹ 00-overview/ - `README.md` - Main developer guide and navigation - `vue-ensemble.md` - Vision, philosophy, and design principles - `contexte-narratif.md` - Background and universe - `dlc-prevus.md` - Planned expansions ### πŸ—οΈ 01-architecture/ - `architecture-technique.md` - **CORE**: Complete modular architecture - `claude-code-integration.md` - **ESSENTIAL**: Claude Code development optimization - `behavior-composition-patterns.md` - Modular AI behavior patterns - `player-integration.md` - Client/server integration ### βš™οΈ 02-systems/ - `gameplay-industriel.md` - Factory/production systems - `systeme-militaire.md` - Vehicle design with grid-based component placement - `economie-logistique.md` - Market simulation, supply chains, pricing - `map-system.md` - Procedural generation with 218+ elements - `rendering-system.md` - Sprite composition and entity rendering - `factory-architecture-post-player.md` - Advanced production architecture ### πŸ”§ 03-implementation/ - `testing-strategy.md` - AI-optimized testing approach - `systemes-techniques.md` - Low-level technical specifications - `configuration/` - Complete configuration system ### πŸ“š 04-reference/ - `INTEGRATION-MASTER-LIST.md` - **CRITICAL**: 570+ technical specifications catalog - `arbre-technologique.md` - 3000+ technology tree - `metriques-joueur.md` - Comprehensive analytics (3.1GB per game) - `coherence-problem.md` - Resolved design contradictions - `questions-ouvertes.md` - Open technical questions - `updates-long-terme.md` - Future evolution roadmap ## Key Technical Concepts ### Core Interface Architecture (COMPLETED - PHASE 1) - **Complete Interface Set**: IEngine, IModuleSystem, IModule, IIO, ITaskScheduler, IDataTree, IDataNode, ICoordinationModule - **CRITICAL**: **Core interfaces are IMMUTABLE** - Never modify once finalized - **Configuration System**: IDataTree/IDataNode for hierarchical data-driven development with const references - **Coordination System**: ICoordinationModule as global orchestrator (first launched, last shutdown) - **Task Delegation**: ITaskScheduler for module β†’ execution system delegation (multithreading) - **Autonomous Modules**: Small (200-300 lines) hot-reloadable modules (.so files) - **Claude Code Optimized**: Each module is a micro-context for AI development - **Performance Targets**: V1 Client 30+ fps, V2 Client 60+ fps, V1 Server 10+ players, V2 Server 100+ players ### Interface Specifications (NEVER MODIFY THESE) - **ICoordinationModule**: Global system orchestrator, gameconfig.json management, module deployment topology - **IEngine**: Local engine orchestration, module loading, client/coordinator socket management - **IModuleSystem**: Execution strategy implementation (Sequential β†’ Threaded β†’ Cluster) - **IModule**: Pure business logic + pub/sub communication (**BREAKING CHANGES** - see below) - **IIO**: Pull-based pub/sub with low-frequency batching and health monitoring - **ITaskScheduler**: Task delegation interface for module β†’ execution system (multithreading) - **IDataTree**: Configuration tree container with manual hot-reload capabilities - **IDataNode**: Hierarchical data nodes with pattern matching and property queries (**const methods**) ### BREAKING CHANGES in IModule Interface ```cpp // OLD Interface (DEPRECATED) virtual void initialize(const json& config, IIO* io, ITaskScheduler* scheduler) = 0; virtual bool isHealthy() = 0; // NEW Interface (CURRENT) virtual void setConfiguration(const IDataNode& configNode, IIO* io, ITaskScheduler* scheduler) = 0; virtual const IDataNode& getConfiguration() = 0; virtual json getHealthStatus() = 0; // Detailed JSON instead of bool // initialize() method REMOVED ``` ### Configuration Immutability System - **const IDataNode&** references prevent modules from modifying configuration - **Single source of truth**: gameconfig.json loaded via IDataTree - **Hot-reload**: CoordinationModule propagates config changes to all modules - **Type safety**: All IDataNode getters are const methods ### Module Frequencies & Isolation - **ProductionModule**: 60Hz (frame-perfect factory operations) - **TankModule**: 0.1-60Hz (Targeting 60Hz β†’ Movement 30Hz β†’ Tactical 1Hz β†’ Analytics 0.1Hz) - **EconomyModule**: 0.01-0.1Hz (economic cycles) - **War Isolation**: ZERO interaction ProductionModule ↔ WarModule - **Supply Chain**: Factory β†’ LogisticModule β†’ War (unidirectional flow) ### Map System - **Multi-scale**: World (diplomatic) β†’ Regional (logistics) β†’ Local (factory) β†’ Detail (combat) - **Procedural Generation**: 218 elements with budget scoring, millions of combinations - **Chunk System**: 64x64 tiles, streaming on demand, persistent storage ### Military Design - **Grid-based Vehicle Design**: Irregular chassis shapes with component placement - **Interface**: Pick/place with A/E rotation, R for snap toggle, template support - **Combat**: Multi-chunk battles, persistent frontlines, auto-battler with player oversight ## Development Context ### Current Status - **Phase**: **INTERFACES COMPLETE** - All core interfaces finalized and production-ready - **Core Architecture**: 4 interfaces completed with full specifications - **Development Ready**: Hot-reload modules, pub/sub messaging, task delegation - **Integration**: Interface design phase complete (Phase 1 TODO finished) - **Next Steps**: Phase 2 - Initial implementations (DebugEngine, SequentialModuleSystem, IntraIO) ### Resolved Issues Most coherence problems resolved through systematic analysis in `04-reference/coherence-problem.md`: - Architecture scales properly with smart resource management - Interface complexity is standard for genre (comparable to Factorio, Tarkov inventory) - Performance targets achievable with proper optimization - Legacy engine system completely replaced by modular architecture ## Working with This Project ### Essential Reading Order 1. **First Time**: `00-overview/vue-ensemble.md` - Project vision 2. **Architecture**: `01-architecture/architecture-technique.md` - Core technical architecture 3. **Development**: `01-architecture/claude-code-integration.md` - AI development workflow 4. **Reference**: `04-reference/INTEGRATION-MASTER-LIST.md` - Complete specifications ### Documentation Updates - Cross-reference systems when making changes (especially architecture ↔ gameplay) - Maintain coherence between technical specs and game design - Update `04-reference/coherence-problem.md` if new conflicts emerge ### Key Design Constraints - **Skip-ability**: All systems must be automatable for accessibility - **Depth vs Accessibility**: Complex systems with simple interfaces - **Performance**: Real-time constraints with large-scale simulation - **Realism**: Military authenticity balanced with gameplay fun ## Module Constraints (CRITICAL) ### NEVER/ALWAYS Rules - **INTERFACE STABILITY**: NEVER modify core interfaces - only implement them - **NEVER `cd ..`**: Jamais rΓ©fΓ©rence directories parent modules - **ALWAYS `cmake .`**: Builds autonomes par module (NEVER cmake ..) - **NEVER `#include "../"`**: Isolation modules stricte - **PUB/SUB Communication**: Communication via IIO publish/subscribe only - **TASK DELEGATION**: Use ITaskScheduler for module β†’ execution system tasks - **ZERO Infrastructure Code**: Aucun code infrastructure dans contexts modules ### Special Cases - **Exception ProductionModule**: Belt+Inserter+Factory MUST cohabiter (500-800 lignes acceptΓ©es) - **ISocket Overhead**: >1ms INACCEPTABLE pour ProductionModule - **Module Frequencies**: Each module operates at different frequencies (see architecture-technique.md) - **War Isolation**: NO inserters towards turrets - supply via LogisticModule only ## Build System and Development ### Build Commands ```bash # CRITICAL: Module autonome uniquement cd modules/tank/ && cmake . # NEVER cmake .. make tank-module # Builds tank.so ./build/tank-module # Test standalone # Core system cmake . && make warfactory-core # Build core engine # All modules make warfactory-modules # Build all modules ``` ### UI Testing Commands ```bash # Build UI tests cmake -B build && cmake --build build # Debug with AddressSanitizer cmake -B build_release -DCMAKE_BUILD_TYPE=Release && cmake --build build_release # Clean release # Run UI tests ./bin/test_imgui_ui # Interactive mode (DEFAULT - no auto-exit) ./bin/test_imgui_ui --headless # Quick test mode (auto-exit after 3s) ./bin/test_imgui_ui --max-frames 300 # Custom frame limit (overrides interactive) ./bin/test_imgui_ui --interactive # Explicit interactive mode (no auto-exit) ./bin/test_imgui_ui --help # Show usage options # For Claude Code testing ./bin/test_imgui_ui --headless # Use this for quick validation tests ``` ### Project Structure ``` β”œβ”€β”€ modules/ # Autonomous hot-reloadable modules β”‚ β”œβ”€β”€ tank/ # Tank behavior module (200 lines) β”‚ β”œβ”€β”€ economy/ # Market simulation module β”‚ β”œβ”€β”€ factory/ # Production module β”‚ β”œβ”€β”€ transport/ # Transport optimization module β”‚ └── [each with CLAUDE.md, CMakeLists.txt, src/] β”œβ”€β”€ core/ # Core engine implementations β”‚ β”œβ”€β”€ include/warfactory/ # IMMUTABLE core interfaces (IEngine, IModuleSystem, IModule, IIO) β”‚ β”œβ”€β”€ implementations/ # Engine and ModuleSystem implementations β”‚ └── loaders/ # Module hot-reload system β”œβ”€β”€ cmake/ # Build system configuration β”‚ β”œβ”€β”€ WarfactoryDefenses.cmake # Defensive programming β”‚ β”œβ”€β”€ WarfactoryAutomation.cmake # 16 C++ libraries β”‚ └── WarfactoryAdvancedTools.cmake # Static analysis, testing β”œβ”€β”€ build/ # Build artifacts (git ignored) β”‚ └── bin/ # Final executables └── docs/ # Hierarchical documentation system β”œβ”€β”€ 00-overview/ # Vision & context β”œβ”€β”€ 01-architecture/ # Architecture modulaire β”œβ”€β”€ 02-systems/ # Game systems β”œβ”€β”€ 03-implementation/ # Testing & configuration └── 04-reference/ # Technical reference ``` ### Development Workflow ⚑ **HOT-RELOAD REVOLUTIONIZED** 1. **Module isolation**: Work in `modules/*/` with autonomous builds 2. **πŸ”₯ BLAZING Hot-reload**: **0.4ms average** - Edit module β†’ Save β†’ **INSTANT** reload with state preservation 3. **Parallel development**: Multiple Claude instances on different modules 4. **Config-driven**: Most gameplay tweaks via JSON configs 5. **⚑ SUB-SECOND iteration**: Edit β†’ cmake . β†’ make β†’ hot-reload **< 1 second total** 6. **State Preservation**: Module state (chunks, configs, metrics) persists across reloads 7. **Testing**: Lightweight focused tests, 5000x faster than target performance ### πŸ›‘οΈ **Debug Workflow - PRODUCTION BATTLE-TESTED** **Default Development Mode** (configured in CMakeLists.txt): ```bash cmake -B build # AddressSanitizer + UndefinedBehavior + debug symbols cmake --build build # ALL debugging tools active by default ./build/bin/test # Instant crash detection with exact line numbers ``` **Advanced Bug Detection:** - **AddressSanitizer**: Buffer overflows, use-after-free, stack corruption - **UndefinedBehaviorSanitizer**: Integer overflows, null dereferences, misaligned access - **GDB Integration**: `gdb --batch --ex run --ex bt ./binary` for stack traces - **JSON Safety**: Complete protection against nlohmann::json type errors **Cross-Platform Development:** 1. **Develop on Linux** with full debug tools and immediate feedback 2. **Test thoroughly** with AddressSanitizer catching ALL memory issues 3. **Cross-compile to Windows** once stable: `x86_64-w64-mingw32-g++ ...` 4. **Zero manual intervention** - automated .exe generation **Result**: **750,000x faster debugging** - from hours of blind Windows testing to seconds of precise Linux diagnosis. ## Claude Code Development Practices ### Interface Management (ABSOLUTELY CRITICAL) - **IMMUTABLE INTERFACES**: Core interfaces (IEngine, IModuleSystem, IModule, IIO, ITaskScheduler, IDataTree, IDataNode) are FROZEN - **NEVER MODIFY**: Once interfaces are finalized, they become the architectural foundation - **Extension Only**: New functionality via new implementations, not interface changes - **Breaking Changes**: Modifying core interfaces breaks ALL existing modules and systems - **Documentation**: Interface changes require complete system redesign - avoid at all costs ### Context Management (REVOLUTIONARY RESULTS) - **Small Modules**: Compact modules for focused development (micro-contexts) - **Context Optimization**: Massive context reduction through modular design - **πŸš€ BLAZING Iteration Speed**: **5-10 min β†’ 0.4ms** (750,000x faster!) - **Development Velocity**: **Theoretical maximum achieved** - sub-millisecond hot-reload ### Parallel Development Patterns - **Multiple Instances**: 3+ Claude Code instances simultaneous development - **Zero Conflicts**: Independent module development without merge conflicts - **Git-Friendly**: Isolated commits per module - **Non-Blocking**: Developers work on different modules without coordination ### Testing Strategy (AI-Optimized) - **Simple Tests**: Tests unitaires lΓ©gers, pas infrastructure complexe - **Standalone Testing**: Test modules sans engine complet - **`#ifdef TESTING`**: Validation autonome intΓ©grΓ©e modules - **Quick Feedback**: Tests rapides pour iteration loops Claude Code ### Dependencies and Libraries The project includes 16 C++ libraries via FetchContent: - **Networking**: zeromq, cppzmq, redis-plus-plus, cpprestsdk - **Logging**: spdlog, fmt - **Memory**: Microsoft GSL, foonathan/memory - **Testing**: Catch2, Google Test, Google Benchmark - **Utilities**: nlohmann/json, fifo_map, junction+turf, pcg-cpp - **Navigation**: recastnavigation, abseil-cpp - **Graphics**: imgui, sqlite ### Defensive Programming Features - **Sanitizers**: AddressSanitizer, UndefinedBehaviorSanitizer, LeakSanitizer - **Static Analysis**: Clang Static Analyzer, Cppcheck, PVS-Studio integration - **Contract Programming**: GSL contracts, custom assertion macros - **Compiler Hardening**: Stack protection, frame pointers, maximum debug info - **Memory Safety**: Smart pointers, RAII patterns, leak detection ## 🚫 **CRITICAL CODE RESTRICTIONS** ### AUTO KEYWORD PROHIBITION **STRICTLY FORBIDDEN**: The `auto` keyword is banned as a type in this codebase. - **NEVER use**: `auto variable = value;` - **ALWAYS use**: `ExplicitType variable = value;` - **Reason**: Explicit types improve code readability, reduce debugging complexity, and prevent type-related errors - **Examples**: ```cpp // ❌ FORBIDDEN - will not compile auto config = getConfiguration(); auto nodes = config->getChildNodes(); // βœ… REQUIRED - explicit types std::unique_ptr config = getConfiguration(); std::vector> nodes = config->getChildNodes(); ``` ## Quick Reference ### For Understanding the Project 1. `00-overview/vue-ensemble.md` - Project vision 2. `01-architecture/architecture-technique.md` - Core architecture 3. `02-systems/gameplay-industriel.md` - Core gameplay ### For Development 1. **`docs/03-implementation/CLAUDE-HOT-RELOAD-GUIDE.md`** - **ESSENTIAL**: Blazing 0.4ms hot-reload system guide 2. `01-architecture/claude-code-integration.md` - AI development workflow 3. `03-implementation/testing-strategy.md` - Testing approach 4. `04-reference/INTEGRATION-MASTER-LIST.md` - Complete specifications ### For Task Management 1. `TODO.md` - High-level implementation roadmap and current phases 2. **`TASKLIST.md`** - **DETAILED**: Complete task breakdown by time (Quick Wins < 1h, Light 1-3h, Medium 1-2 days, Feature 3-7 days, Big 1-2 weeks) ### For Technical Reference 1. `04-reference/arbre-technologique.md` - Complete tech tree 2. `04-reference/coherence-problem.md` - Technical analyses 3. `DocToDispatch.md` - Exhaustive reference document --- ## 🎯 **Current Status - MAJOR UI MILESTONE ACHIEVED** **CORE INTERFACES**: βœ… **COMPLETE** - Phase 1 finished with immutable interface foundation established. **UI INTERFACE SYSTEM**: βœ… **PRODUCTION-READY** - Complete IUI architecture with ImGuiUI implementation. - **Generic Interface**: Data-agnostic system supporting all content types - **Professional Layout**: Economic topbar + companies panel + strategic map - **Hybrid Sizing**: Revolutionary percentage/pixel constraint system - **Cross-Platform**: Linux development β†’ Windows .exe automated pipeline **DEVELOPMENT WORKFLOW**: βœ… **BATTLE-TESTED** - AddressSanitizer + GDB integration for instant bug detection. **CONFIGURATION SYSTEM**: βœ… **INTERFACES COMPLETE** - Comprehensive IDataTree configuration system for data-driven gameplay. - **GameConfig Source**: Single `gameconfig.json` file containing all game configuration and module deployment topology - **Hierarchical Data**: Tree structure where each node can have both children AND its own data blob - **Advanced Querying**: Pattern matching with wildcards, property-based lambda predicates - **Type-Safe Access**: Getters with defaults for int/double/string/bool properties - **Hash Validation**: SHA256 hashing for data integrity and synchronization - **Manual Hot-Reload**: Check for changes and reload on demand with callbacks - **Module Distribution**: gameconfig.json defines which modules to load and where to deploy them ## 🎯 **Current Status - INTERFACES COMPLETE & CLEAN** **CORE INTERFACES**: βœ… **ALL COMPLETE** - Complete interface set with proper file organization: - βœ… **ICoordinationModule.h** - Global orchestrator with detailed startup/shutdown sequences - βœ… **ITaskScheduler.h** - **NEW FILE** with comprehensive multithreading delegation documentation - βœ… **IModule.h** - BREAKING CHANGES implemented with const IDataNode& configuration - βœ… **IDataNode.h** - All methods const for immutability enforcement - βœ… **IEngine.h, IModuleSystem.h, IIO.h** - Recovered and cleaned from duplications - βœ… **IDataTree.h, DataTreeFactory.h** - Configuration system foundation **ARCHITECTURE DOCUMENTED**: βœ… **COMPLETE** - Full system flow and coordination patterns documented **BREAKING CHANGES**: βœ… **IMPLEMENTED** - IModule interface modernized with configuration immutability **Next Phase**: Implementation of JSONDataTree concrete classes and example gameconfig.json for testing.