Replace engine architecture with modular triple interface system

- Remove old 10-engine system (engines/ directory deleted)
- Implement C++ triple interface architecture:
  * IEngine: Execution coordination (Debug → Production)
  * IModuleSystem: Strategy pattern (Sequential → Threaded → Cluster)
  * IModule: Pure game logic interface (200-300 lines per module)
  * IIO: Communication transport (Intra → Local → Network)

- Add autonomous module structure:
  * modules/factory/: Production logic with autonomous build
  * modules/economy/: Market simulation with autonomous build
  * modules/logistic/: Supply chain with autonomous build
  * Each module: CLAUDE.md + CMakeLists.txt + shared/ + build/

- Benefits for Claude Code development:
  * Ultra-focused contexts (200 lines vs 50K+ lines)
  * Autonomous builds (cmake . from module directory)
  * Hot-swappable infrastructure without logic changes
  * Parallel development across multiple Claude instances

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
StillHammer 2025-09-20 09:15:03 +08:00
parent bb92e9dc93
commit 61ef2293ad
66 changed files with 3074 additions and 2178 deletions

View File

@ -46,32 +46,16 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
# Add subdirectories for all engines
add_subdirectory(engines/Designer-Engine)
add_subdirectory(engines/Economy-Engine)
add_subdirectory(engines/Event-Engine)
add_subdirectory(engines/Factory-Engine)
add_subdirectory(engines/Intelligence-Engine)
add_subdirectory(engines/Logistic-Engine)
add_subdirectory(engines/MacroEntity-Engine)
add_subdirectory(engines/Map-Engine)
add_subdirectory(engines/Operation-Engine)
add_subdirectory(engines/War-Engine)
# Add subdirectories for modular architecture
add_subdirectory(core)
add_subdirectory(modules)
# Build all engines target
add_custom_target(all-engines
# Build core system target
add_custom_target(warfactory-core
DEPENDS
designer-engine
economy-engine
event-engine
factory-engine
intelligence-engine
logistic-engine
macroentity-engine
map-engine
operation-engine
war-engine
COMMENT "Building all Warfactory engines"
warfactory-engine
warfactory-modules
COMMENT "Building Warfactory modular core"
)
# =============================================================================
@ -79,40 +63,40 @@ add_custom_target(all-engines
# =============================================================================
if(ENABLE_ADVANCED_TOOLS)
# Fuzzing targets for all engines
add_custom_target(fuzz-all-engines
COMMENT "Running fuzzing on all engines"
# Fuzzing targets for modular system
add_custom_target(fuzz-all-modules
COMMENT "Running fuzzing on all modules"
)
# Static analysis for all engines
add_custom_target(analyze-all-engines
COMMENT "Running static analysis on all engines"
# Static analysis for modular system
add_custom_target(analyze-all-modules
COMMENT "Running static analysis on all modules"
)
# Coverage for all engines
add_custom_target(coverage-all-engines
COMMENT "Generating coverage reports for all engines"
# Coverage for modular system
add_custom_target(coverage-all-modules
COMMENT "Generating coverage reports for all modules"
)
# Concurrency analysis for all engines
add_custom_target(concurrency-all-engines
COMMENT "Running concurrency analysis on all engines"
# Concurrency analysis for modular system
add_custom_target(concurrency-all-modules
COMMENT "Running concurrency analysis on all modules"
)
# ABI validation for all engines
add_custom_target(abi-all-engines
COMMENT "Validating ABI for all engines"
# ABI validation for modular system
add_custom_target(abi-all-modules
COMMENT "Validating ABI for all modules"
)
# Master testing target
add_custom_target(test-everything
DEPENDS fuzz-all-engines analyze-all-engines coverage-all-engines
COMMENT "Run all advanced testing on all engines"
DEPENDS fuzz-all-modules analyze-all-modules coverage-all-modules
COMMENT "Run all advanced testing on modular system"
)
message(STATUS "🎯 Advanced testing targets configured")
message(STATUS " - Use 'make fuzz-all-engines' for fuzzing")
message(STATUS " - Use 'make analyze-all-engines' for static analysis")
message(STATUS " - Use 'make fuzz-all-modules' for fuzzing")
message(STATUS " - Use 'make analyze-all-modules' for static analysis")
message(STATUS " - Use 'make test-everything' for complete testing")
endif()
@ -131,8 +115,8 @@ if(TARGET cppcheck)
add_custom_target(cppcheck-all
COMMAND cppcheck --enable=all --inconclusive --std=c++20
--suppressions-list=${CMAKE_SOURCE_DIR}/cppcheck-suppressions.txt
${CMAKE_SOURCE_DIR}/engines/*/src ${CMAKE_SOURCE_DIR}/engines/*/include
COMMENT "Running Cppcheck on all engines"
${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/modules
COMMENT "Running Cppcheck on modular system"
)
add_dependencies(validate-all cppcheck-all)
endif()
@ -141,97 +125,47 @@ endif()
find_program(CLANG_TIDY_EXECUTABLE clang-tidy)
if(CLANG_TIDY_EXECUTABLE)
add_custom_target(clang-tidy-all
COMMAND find ${CMAKE_SOURCE_DIR}/engines -name "*.cpp" -exec ${CLANG_TIDY_EXECUTABLE} {} +
COMMENT "Running clang-tidy on all engines"
COMMAND find ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/modules -name "*.cpp" -exec ${CLANG_TIDY_EXECUTABLE} {} +
COMMENT "Running clang-tidy on modular system"
)
add_dependencies(validate-all clang-tidy-all)
endif()
# Build rapide tous les engines
# Build rapide tous les modules
add_custom_target(build-all-fast
DEPENDS all-engines
COMMENT "Fast build of all engines"
DEPENDS warfactory-core
COMMENT "Fast build of modular system"
)
# Clean + rebuild complet
add_custom_target(rebuild-all
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target clean
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target all-engines
COMMENT "Clean rebuild of all engines"
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target warfactory-core
COMMENT "Clean rebuild of modular system"
)
# Documentation de tous les engines
# Documentation de tous les modules
add_custom_target(docs-all
COMMENT "Generating documentation for all engines"
COMMENT "Generating documentation for modular system"
)
# Tests de tous les engines
add_custom_target(test-all-engines
# Tests de tous les modules
add_custom_target(test-all-modules
COMMAND ${CMAKE_CTEST_COMMAND} --parallel 4 --output-on-failure
COMMENT "Running tests for all engines"
COMMENT "Running tests for all modules"
)
# Performance benchmarks
add_custom_target(bench-all-engines
COMMENT "Running benchmarks for all engines"
add_custom_target(bench-all-modules
COMMENT "Running benchmarks for all modules"
)
# Claude Code workflow target - build + test + validate
add_custom_target(claude-workflow
DEPENDS build-all-fast validate-all test-all-engines
DEPENDS build-all-fast validate-all test-all-modules
COMMENT "Complete Claude Code development workflow"
)
# Builds rotatifs pour tous les engines en mode Debug
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_custom_target(rotary-builds-all
DEPENDS
economy-engine_test_rotary
war-engine_test_rotary
designer-engine_test_rotary
factory-engine_test_rotary
intelligence-engine_test_rotary
logistic-engine_test_rotary
macroentity-engine_test_rotary
map-engine_test_rotary
operation-engine_test_rotary
event-engine_test_rotary
COMMENT "Build all sanitizer variants for all engines"
)
add_custom_target(rotary-tests-all
DEPENDS
economy-engine_run_rotary
war-engine_run_rotary
designer-engine_run_rotary
factory-engine_run_rotary
intelligence-engine_run_rotary
logistic-engine_run_rotary
macroentity-engine_run_rotary
map-engine_run_rotary
operation-engine_run_rotary
event-engine_run_rotary
COMMENT "Run rotary sanitizer testing for all engines"
)
# Claude workflow étendu avec sanitizers rotatifs
add_custom_target(claude-workflow-rotary
DEPENDS claude-workflow rotary-builds-all
COMMENT "Complete Claude workflow with rotary sanitizer builds"
)
message(STATUS "🔄 Rotary sanitizer targets configured:")
message(STATUS " - make rotary-builds-all : Build all sanitizer variants")
message(STATUS " - make rotary-tests-all : Run all sanitizer tests")
message(STATUS " - make claude-workflow-rotary : Full workflow + rotary")
endif()
# CI/CD simulation
add_custom_target(ci-simulation
DEPENDS rebuild-all validate-all test-all-engines docs-all
COMMENT "Simulate CI/CD pipeline"
)
# Build workflow adaptatif selon FAST_BUILD
if(FAST_BUILD)
add_custom_target(claude-workflow-fast
@ -239,31 +173,28 @@ if(FAST_BUILD)
COMMENT "Fast Claude Code development workflow (daily iteration)"
)
message(STATUS "🤖 Fast build targets configured:")
message(STATUS " - make build-all-fast : Quick build all engines")
message(STATUS " - make build-all-fast : Quick build modular system")
message(STATUS " - make claude-workflow-fast : Fast Claude development cycle")
else()
message(STATUS "🤖 Full automation targets configured:")
message(STATUS " - make validate-all : Comprehensive validation")
message(STATUS " - make build-all-fast : Quick build all engines")
message(STATUS " - make build-all-fast : Quick build modular system")
message(STATUS " - make claude-workflow : Full Claude development cycle")
message(STATUS " - make ci-simulation : Simulate CI/CD pipeline")
endif()
# Installation rules
install(TARGETS
designer-engine
economy-engine
event-engine
factory-engine
intelligence-engine
logistic-engine
macroentity-engine
map-engine
operation-engine
war-engine
DESTINATION bin
# CI/CD simulation
add_custom_target(ci-simulation
DEPENDS rebuild-all validate-all test-all-modules docs-all
COMMENT "Simulate CI/CD pipeline"
)
# Installation rules (to be updated when targets exist)
# install(TARGETS
# warfactory-core
# DESTINATION bin
# )
# =============================================================================
# PACKAGING AUTOMATIQUE AVEC CPACK
# =============================================================================
@ -273,7 +204,7 @@ include(CPack)
# Configuration générale du package
set(CPACK_PACKAGE_NAME "Warfactory")
set(CPACK_PACKAGE_VENDOR "Warfactory Project")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Factorio-inspired industrial military simulation - Multi-engine architecture")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Factorio-inspired industrial military simulation - Modular architecture")
set(CPACK_PACKAGE_VERSION_MAJOR 1)
set(CPACK_PACKAGE_VERSION_MINOR 0)
set(CPACK_PACKAGE_VERSION_PATCH 0)
@ -323,19 +254,23 @@ if(APPLE)
endif()
# Composants pour installation sélective
set(CPACK_COMPONENTS_ALL engines libraries headers documentation)
set(CPACK_COMPONENTS_ALL core modules libraries headers documentation)
# Description des composants
set(CPACK_COMPONENT_ENGINES_DISPLAY_NAME "Game Engines")
set(CPACK_COMPONENT_ENGINES_DESCRIPTION "Core game engines (Economy, War, Factory, etc.)")
set(CPACK_COMPONENT_ENGINES_GROUP "Runtime")
set(CPACK_COMPONENT_CORE_DISPLAY_NAME "Core System")
set(CPACK_COMPONENT_CORE_DESCRIPTION "Core modular system and runtime")
set(CPACK_COMPONENT_CORE_GROUP "Runtime")
set(CPACK_COMPONENT_MODULES_DISPLAY_NAME "Game Modules")
set(CPACK_COMPONENT_MODULES_DESCRIPTION "Pluggable game modules (Economy, Combat, etc.)")
set(CPACK_COMPONENT_MODULES_GROUP "Runtime")
set(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "Development Libraries")
set(CPACK_COMPONENT_LIBRARIES_DESCRIPTION "Static and shared libraries for engine development")
set(CPACK_COMPONENT_LIBRARIES_DESCRIPTION "Static and shared libraries for module development")
set(CPACK_COMPONENT_LIBRARIES_GROUP "Development")
set(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "Header Files")
set(CPACK_COMPONENT_HEADERS_DESCRIPTION "C++ header files for engine APIs")
set(CPACK_COMPONENT_HEADERS_DESCRIPTION "C++ header files for module APIs")
set(CPACK_COMPONENT_HEADERS_GROUP "Development")
set(CPACK_COMPONENT_DOCUMENTATION_DISPLAY_NAME "Documentation")
@ -360,26 +295,6 @@ set(CPACK_SOURCE_IGNORE_FILES
"\\.gitmodules"
)
# Installation des composants
install(TARGETS
designer-engine economy-engine event-engine factory-engine
intelligence-engine logistic-engine macroentity-engine
map-engine operation-engine war-engine
COMPONENT engines
DESTINATION bin
)
# Si les libraries sont créées par l'automation
if(TARGET designer-engine-lib)
install(TARGETS
designer-engine-lib economy-engine-lib event-engine-lib factory-engine-lib
intelligence-engine-lib logistic-engine-lib macroentity-engine-lib
map-engine-lib operation-engine-lib war-engine-lib
COMPONENT libraries
DESTINATION lib
)
endif()
# Headers
install(DIRECTORY include/
COMPONENT headers

48
core/CMakeLists.txt Normal file
View File

@ -0,0 +1,48 @@
cmake_minimum_required(VERSION 3.20)
project(WarfactoryCore LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Load Warfactory defenses
include(../cmake/WarfactoryDefenses.cmake)
include(../cmake/WarfactoryAutomation.cmake)
# Output directories
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
# Core includes
include_directories(include)
# Core library with interfaces
add_library(warfactory-core SHARED
src/Engine.cpp
src/ModuleSystem.cpp
src/Socket.cpp
src/ModuleLoader.cpp
)
target_include_directories(warfactory-core PUBLIC
include
)
# Main executable
add_executable(warfactory-engine
src/main.cpp
)
target_link_libraries(warfactory-engine
PRIVATE warfactory-core
)
# Install rules
install(TARGETS warfactory-core warfactory-engine
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
)
install(DIRECTORY include/
DESTINATION include
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
)

View File

@ -0,0 +1,84 @@
#pragma once
#include <string>
#include <memory>
#include <nlohmann/json.hpp>
#include "IModuleSystem.h"
#include "IIO.h"
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Main engine interface - coordinates everything
*
* DebugEngine -> Sequential execution, full logging
* ProductionEngine -> Optimized execution, minimal overhead
* TestEngine -> Isolated execution for unit tests
*/
class IEngine {
public:
virtual ~IEngine() = default;
/**
* @brief Initialize engine with configuration
* @param configPath Path to engine configuration file
*/
virtual void initialize(const std::string& configPath) = 0;
/**
* @brief Set module execution system
* @param moduleSystem Strategy for running modules
*/
virtual void setModuleSystem(std::shared_ptr<IModuleSystem> moduleSystem) = 0;
/**
* @brief Set communication system
* @param io Communication transport
*/
virtual void setIO(std::shared_ptr<IIO> io) = 0;
/**
* @brief Load modules from configuration
* Will scan module directories and load .so files
*/
virtual void loadModules() = 0;
/**
* @brief Start main game loop
* Blocks until shutdown() called
*/
virtual void run() = 0;
/**
* @brief Process single frame/tick
* For step debugging and testing
*/
virtual void step() = 0;
/**
* @brief Stop engine and cleanup all resources
*/
virtual void shutdown() = 0;
/**
* @brief Get engine status and metrics
* @return JSON with performance data, loaded modules, etc.
*/
virtual json getStatus() const = 0;
/**
* @brief Get engine type identifier
*/
virtual std::string getEngineType() const = 0;
/**
* @brief Handle runtime commands (reload module, change config, etc.)
* @param command JSON command to execute
* @return JSON response
*/
virtual json handleCommand(const json& command) = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,69 @@
#pragma once
#include <string>
#include <functional>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Input/Output interface - swappable transport
*
* IntraIO -> Same process (direct call)
* LocalIO -> Same machine (named pipes/sockets)
* NetworkIO -> Network/Internet (TCP/WebSocket)
*/
class IIO {
public:
virtual ~IIO() = default;
/**
* @brief Initialize IO with configuration
* @param config Transport-specific configuration
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Send JSON message
* @param message JSON data to send
* @param target Target identifier (module name, endpoint, etc.)
*/
virtual void send(const json& message, const std::string& target) = 0;
/**
* @brief Receive JSON message (blocking)
* @return Received JSON message
*/
virtual json receive() = 0;
/**
* @brief Check if message available (non-blocking)
* @return true if message ready to receive
*/
virtual bool hasMessage() const = 0;
/**
* @brief Set message handler for async operation
* @param handler Function to call when message received
*/
virtual void setMessageHandler(std::function<void(const json&)> handler) = 0;
/**
* @brief Start async message processing
*/
virtual void startAsync() = 0;
/**
* @brief Stop async processing and cleanup
*/
virtual void shutdown() = 0;
/**
* @brief Get IO type identifier
*/
virtual std::string getType() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,51 @@
#pragma once
#include <string>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Pure game logic interface - Claude Code works ONLY on this
*
* Each module = 200-500 lines of pure game logic
* No infrastructure code, no threading, no networking
* Just: receive JSON input -> process logic -> return JSON output
*/
class IModule {
public:
virtual ~IModule() = default;
/**
* @brief Initialize module with configuration
* @param config JSON configuration for this module
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Process game logic - PURE FUNCTION
* @param input JSON input from other modules or engine
* @return JSON output to send to other modules
*/
virtual json process(const json& input) = 0;
/**
* @brief Get module metadata
* @return Module name, version, dependencies
*/
virtual json getMetadata() const = 0;
/**
* @brief Cleanup resources
*/
virtual void shutdown() = 0;
/**
* @brief Module name for identification
*/
virtual std::string getName() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,91 @@
#pragma once
#include <string>
#include <memory>
#include <nlohmann/json.hpp>
#include "IModule.h"
#include "IIO.h"
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Execution strategy interface - swappable performance
*
* SequentialModuleSystem -> One module at a time (debug)
* ThreadedModuleSystem -> Each module in own thread
* PoolModuleSystem -> Module tasks across thread pool
* ClusterModuleSystem -> Modules across multiple machines
*/
class IModuleSystem {
public:
virtual ~IModuleSystem() = default;
/**
* @brief Initialize module system
* @param config System configuration (thread count, etc.)
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Load module from shared library
* @param modulePath Path to .so/.dll file
* @param moduleConfig Configuration for the module
*/
virtual void loadModule(const std::string& modulePath, const json& moduleConfig) = 0;
/**
* @brief Unload module
* @param moduleName Name of module to unload
*/
virtual void unloadModule(const std::string& moduleName) = 0;
/**
* @brief Send message to specific module
* @param targetModule Module name to send to
* @param message JSON message to send
*/
virtual void sendToModule(const std::string& targetModule, const json& message) = 0;
/**
* @brief Broadcast message to all modules
* @param message JSON message to broadcast
*/
virtual void broadcast(const json& message) = 0;
/**
* @brief Start execution loop
* Will run until shutdown() called
*/
virtual void startLoop() = 0;
/**
* @brief Process one iteration (for step debugging)
*/
virtual void tick() = 0;
/**
* @brief Stop execution and cleanup
*/
virtual void shutdown() = 0;
/**
* @brief Set communication IO
* @param io IO implementation to use
*/
virtual void setIO(std::shared_ptr<IIO> io) = 0;
/**
* @brief Get list of loaded modules
* @return JSON array of module metadata
*/
virtual json getLoadedModules() const = 0;
/**
* @brief Get execution strategy name
*/
virtual std::string getStrategyName() const = 0;
};
} // namespace warfactory

31
core/src/main.cpp Normal file
View File

@ -0,0 +1,31 @@
#include <iostream>
#include <memory>
#include <warfactory/IEngine.h>
#include <warfactory/IModuleSystem.h>
#include <warfactory/IIO.h>
using namespace warfactory;
int main(int argc, char* argv[]) {
std::cout << "🏭 Warfactory Modular Engine Starting..." << std::endl;
try {
// TODO: Create concrete implementations
// auto engine = std::make_shared<DebugEngine>();
// auto moduleSystem = std::make_shared<SequentialModuleSystem>();
// auto io = std::make_shared<IntraIO>();
std::cout << "⚠️ Interfaces defined - need concrete implementations" << std::endl;
std::cout << "📋 Next steps:" << std::endl;
std::cout << " 1. Implement DebugEngine" << std::endl;
std::cout << " 2. Implement SequentialModuleSystem" << std::endl;
std::cout << " 3. Implement IntraIO" << std::endl;
std::cout << " 4. Create FactoryModule.so" << std::endl;
return 0;
}
catch (const std::exception& e) {
std::cerr << "❌ Engine failed: " << e.what() << std::endl;
return 1;
}
}

1067
docs/DocToDispatch.md Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,130 +0,0 @@
# Client Documentation
## Overview
The **Smart Client** provides the user interface and interacts with the server coordinator using a request/response pattern.
**Key Responsibilities:**
- User interface for all game systems
- Request/response communication with server
- Local state caching and optimization
- Fog of War rendering and management
## Architecture
### Smart Client Pattern
From `architecture-technique.md`:
- **No Streaming**: Pure request/response communication
- **Stateless Requests**: Each request is independent
- **Local Caching**: Client-side optimization for responsiveness
- **FOW Integration**: Chunk-level fog of war rendering
### User Interface Systems
#### Multi-Scale Interface
From `map-system.md`:
- **World View**: Diplomatic and strategic overview
- **Regional View**: Logistics and major operations coordination
- **Local View**: Factory management and base operations
- **Detail View**: Combat oversight and precise control
#### Factory Management Interface
From `gameplay-industriel.md`:
- **Production Line Design**: Factorio-like belt and assembler placement
- **Resource Flow Visualization**: Real-time production monitoring
- **Optimization Tools**: Bottleneck identification and efficiency metrics
- **Automation Controls**: Production scheduling and priority management
#### Vehicle Design Interface
From `systeme-militaire.md`:
- **Grid-Based Placement**: Component positioning on vehicle chassis
- **Interface Controls**: Pick/place with A/E rotation, R for snap toggle
- **Template System**: Save/load vehicle blueprints
- **Validation Feedback**: Real-time design constraint checking
#### Military Command Interface
- **Frontline Visualization**: Persistent battle line display
- **Auto-Battler Controls**: Strategic oversight without micro-management
- **Intelligence Dashboard**: Reconnaissance and enemy analysis
- **Strategic Planning**: Operation coordination and resource allocation
## Core Client Systems
### Communication Manager
```cpp
class ClientCommunication {
// Server communication
ServerResponse sendRequest(const ClientRequest& request);
void cacheResponse(const ServerResponse& response);
bool hasValidCache(const RequestKey& key) const;
// FOW management
void updateFOW(const FOWData& data);
bool isVisible(int chunkX, int chunkY) const;
void requestChunkData(int chunkX, int chunkY);
// State synchronization
void synchronizeState();
void handleGlobalEvent(const GlobalEvent& event);
};
```
### Interface Controllers
#### Factory Interface
- **Belt Placement**: Drag-and-drop belt network design
- **Assembler Configuration**: Production recipe and priority settings
- **Resource Monitoring**: Real-time throughput and efficiency display
- **Expansion Planning**: Factory layout optimization tools
#### Design Interface
- **Component Library**: Available vehicle components and specifications
- **Chassis Editor**: Irregular shape design and component placement
- **Performance Calculator**: Real-time design statistics and validation
- **Blueprint Manager**: Template save/load and sharing system
#### Strategic Interface
- **Company Dashboard**: Economic, military, and industrial overviews
- **Diplomatic Panel**: Inter-company relations and negotiations
- **Research Tree**: Technology progression and breakthrough system
- **Analytics Dashboard**: Comprehensive metrics and trend analysis
### Performance Optimization
#### Local Caching
- **Response Caching**: Store frequently accessed data locally
- **Predictive Loading**: Pre-fetch likely needed data
- **Cache Invalidation**: Smart cache updates on state changes
- **Compression**: Minimize bandwidth usage
#### Rendering Optimization
- **LOD System**: Level-of-detail based on zoom and relevance
- **Culling**: Only render visible and relevant elements
- **Chunk Streaming**: Dynamic loading of map data
- **UI Responsiveness**: Maintain 60fps interface performance
## Client Request Patterns
### Common Request Types
1. **State Queries**: Get current system state (factory status, battles, etc.)
2. **Action Commands**: Execute player actions (place building, issue orders)
3. **Data Updates**: Refresh cached information (market prices, research progress)
4. **Event Subscriptions**: Register for relevant global events
### FOW-Aware Requests
- **Visibility Checks**: Ensure requested data is visible to player
- **Partial Information**: Handle incomplete data due to FOW
- **Intelligence Requests**: Request reconnaissance on hidden areas
- **Update Notifications**: Receive visibility changes and new intel
## Key Design Documents
- `architecture-technique.md` - Smart Client specification
- `gameplay-industriel.md` - Factory interface requirements
- `systeme-militaire.md` - Vehicle design and combat interfaces
- `map-system.md` - Multi-scale interface coordination
- `mecaniques-jeu.md` - UI integration with game mechanics
## Implementation Notes
- Request/response pattern eliminates complex state synchronization
- Local caching provides responsive user experience
- FOW integration requires careful visibility checking
- Multi-scale interface demands efficient view switching

View File

@ -1,69 +0,0 @@
# Designer-Engine Documentation
## Engine Overview
**Designer-Engine** handles autonomous vehicle conception for AI companies and provides design assistance for players.
**Key Responsibilities:**
- Vehicle design generation (1-2 designs globally per tick)
- Component grid placement and validation
- Blueprint management and evolution
- AI-driven design optimization
## Core Systems
### Vehicle Design System
From `systeme-militaire.md`:
- **Grid-based Component Placement**: Irregular chassis shapes with precise component positioning
- **Interface Mechanics**: Pick/place with A/E rotation, R for snap toggle
- **Template Support**: Save/load vehicle blueprints
- **Validation**: Ensure design constraints (weight, power, armor coverage)
### Design Evolution
From `arbre-technologique.md`:
- **Progressive Evolution**: T-72 → T-80 → T-90 design lineage
- **Technology Integration**: New components unlock through research
- **Doctrine Adaptation**: Designs adapt to military doctrine preferences
### Performance Requirements
From `architecture-technique.md`:
- **Design Rate**: 1-2 vehicle designs globally per tick maximum
- **Autonomous Operation**: AI companies generate designs independently
- **Player Assistance**: Provide design suggestions and optimization
## Engine Architecture
### Core Classes
```cpp
class DesignerEngine {
// Design management (1-2 designs globally per tick)
std::unique_ptr<VehicleDesign> createDesign(const std::string& type);
void validateDesign(const VehicleDesign& design);
void saveBlueprint(const VehicleDesign& design, const std::string& name);
// Blueprint evolution
void evolveBlueprintsFromExisting(); // T-72 → T-80 → T-90
// Performance monitoring
double getDesignRate() const;
size_t getPendingDesigns() const;
};
```
### Communication with Other Engines
- **War-Engine**: Receives combat effectiveness feedback for design optimization
- **Economy-Engine**: Gets cost constraints and production capabilities
- **Intelligence-Engine**: Receives reconnaissance data on enemy designs
- **MacroEntity-Engine**: Gets company design preferences and doctrine
- **Event-Engine**: Processes breakthrough events for new technologies
## Key Design Documents
- `systeme-militaire.md` - Vehicle design system details
- `arbre-technologique.md` - Technology progression and design evolution
- `architecture-technique.md` - Performance specifications
- `mecaniques-jeu.md` - Research integration
## Implementation Notes
- Focus on autonomous AI design generation
- Player assistance tools for design optimization
- Blueprint persistence and sharing system
- Technology integration from research breakthroughs

View File

@ -1,70 +0,0 @@
# Economy-Engine Documentation
## Engine Overview
**Economy-Engine** handles market simulation, pricing dynamics, and economic interactions between companies.
**Key Responsibilities:**
- Real-time market pricing simulation
- Supply and demand calculations
- Company economic interactions
- Resource flow optimization
## Core Systems
### Market Simulation
From `economie-logistique.md`:
- **Dynamic Pricing**: Supply/demand based price fluctuations
- **Market Depth**: Multiple buyers/sellers with varying priorities
- **Price Discovery**: Realistic market mechanisms
- **Resource Categories**: Raw materials, components, finished products
### Economic Mechanics
- **Company Budgets**: Financial constraints and cash flow
- **Trade Networks**: Inter-company commerce
- **Market Manipulation**: Large players affecting prices
- **Economic Warfare**: Sanctions, embargos, trade restrictions
### Performance Requirements
From `architecture-technique.md`:
- **Real-time Processing**: Market updates at 60fps
- **Scalability**: Support 1000+ AI companies
- **Autonomous Operation**: Self-regulating market dynamics
## Engine Architecture
### Core Classes
```cpp
class EconomyEngine {
// Market management
void updateMarketPrices();
double getPrice(const std::string& resource) const;
void processTradeOrder(const TradeOrder& order);
// Company economics
void updateCompanyBudgets();
bool validateTransaction(int buyerCompany, int sellerCompany, const TradeOrder& order);
// Market analysis
MarketData getMarketData(const std::string& resource) const;
std::vector<PriceHistory> getPriceHistory(const std::string& resource) const;
};
```
### Communication with Other Engines
- **Factory-Engine**: Production costs and output volumes
- **Logistic-Engine**: Transportation costs and supply chain efficiency
- **MacroEntity-Engine**: Company budgets, diplomatic trade relations
- **War-Engine**: Wartime economic impacts, resource scarcity
- **Intelligence-Engine**: Market intelligence and economic espionage
## Key Design Documents
- `economie-logistique.md` - Complete economic system design
- `architecture-technique.md` - Performance specifications
- `coherence-problem.md` - Economic balance considerations
- `mecaniques-jeu.md` - Economic progression mechanics
## Implementation Notes
- Negative prices are allowed for certain scenarios (waste disposal, etc.)
- Market depth simulation for realistic price discovery
- Company-specific pricing preferences and strategies
- Economic warfare and sanction mechanics

View File

@ -1,70 +0,0 @@
# Event-Engine Documentation
## Engine Overview
**Event-Engine** handles the breakthrough system, global events, and event-driven mechanics throughout the game.
**Key Responsibilities:**
- Breakthrough system processing (scrap analysis → technology)
- Global event generation (geopolitical, natural disasters)
- Event scheduling and timing
- Research progression triggers
## Core Systems
### Breakthrough System
From `mecaniques-jeu.md`:
- **Scrap Analysis**: Combat wreckage provides technology insights
- **Technology Discovery**: Reverse engineering captured equipment
- **Progressive Unlocks**: Gradual technology revelation
- **Failure/Success Mechanics**: Not all analysis succeeds
### Global Events
From `arbre-technologique.md`:
- **Geopolitical Events**: International conflicts, alliances
- **Natural Disasters**: Impact on production and logistics
- **Market Events**: Economic shocks, resource discoveries
- **Technology Events**: Scientific breakthroughs, espionage
### Event Scheduling
- **Delayed Events**: Timed consequences of player actions
- **Cascading Events**: Events triggering other events
- **Random Events**: Procedural event generation
- **Player-Triggered Events**: Research completions, diplomatic actions
## Engine Architecture
### Core Classes
```cpp
class EventEngine {
// Event management
void scheduleEvent(std::unique_ptr<GameEvent> event, double delaySeconds);
void triggerImmediateEvent(std::unique_ptr<GameEvent> event);
// Breakthrough system (event-driven with scrap analysis)
void analyzeScrapForBreakthrough(const std::string& scrapData);
void triggerBreakthrough(const std::string& technologyDomain);
// Global events
void generateRandomEvent();
void processScheduledEvents();
};
```
### Communication with Other Engines
- **War-Engine**: Receives battle data for scrap analysis
- **Intelligence-Engine**: Coordinates breakthrough discoveries
- **MacroEntity-Engine**: Triggers diplomatic events
- **Economy-Engine**: Generates market disruption events
- **All Engines**: Broadcasts global events affecting all systems
## Key Design Documents
- `mecaniques-jeu.md` - Breakthrough system and research mechanics
- `arbre-technologique.md` - Technology progression events
- `architecture-technique.md` - Event processing performance
- `coherence-problem.md` - Event balance and timing
## Implementation Notes
- Event-driven architecture for breakthrough system
- Scrap analysis probability mechanics
- Global event impact on all game systems
- Cascading event chains for complex scenarios

View File

@ -1,70 +0,0 @@
# Factory-Engine Documentation
## Engine Overview
**Factory-Engine** handles Factorio-like production simulation with assembly lines, belts, and automated manufacturing.
**Key Responsibilities:**
- Production line simulation
- Resource flow management
- Factory optimization
- Industrial automation
## Core Systems
### Production System
From `gameplay-industriel.md`:
- **Assembly Lines**: Multi-stage production processes
- **Belt Networks**: Resource transportation within factories
- **Assemblers**: Automated production units
- **Quality Control**: Production efficiency and defect rates
### Resource Flow
- **Input/Output Management**: Raw materials → finished products
- **Throughput Optimization**: Bottleneck identification and resolution
- **Inventory Management**: Buffer stocks and storage
- **Production Scheduling**: Order prioritization and batching
### Factory Design
- **Layout Optimization**: Efficient factory floor planning
- **Upgrade Paths**: Production line improvements
- **Automation Levels**: Manual → semi-auto → fully automated
- **Modular Design**: Expandable production modules
## Engine Architecture
### Core Classes
```cpp
class FactoryEngine {
// Factory management
void addProductionLine(std::unique_ptr<ProductionLine> line);
void removeProductionLine(int lineId);
// Production control
void startProduction();
void stopProduction();
void pauseProduction();
// Performance monitoring
double getTickRate() const;
size_t getActiveLines() const;
};
```
### Communication with Other Engines
- **Economy-Engine**: Production costs, resource pricing, order fulfillment
- **Logistic-Engine**: Raw material delivery, finished goods shipping
- **Designer-Engine**: Vehicle production requirements and specifications
- **Intelligence-Engine**: Production metrics and efficiency reporting
- **MacroEntity-Engine**: Company production goals and priorities
## Key Design Documents
- `gameplay-industriel.md` - Complete factory system design
- `economie-logistique.md` - Production economics and supply chains
- `architecture-technique.md` - Performance requirements
- `mecaniques-jeu.md` - Research and upgrade mechanics
## Implementation Notes
- Factorio-inspired belt and assembler mechanics
- Real-time production simulation at 60fps
- Modular production line design
- Automatic optimization suggestions for players

View File

@ -1,70 +0,0 @@
# Intelligence-Engine Documentation
## Engine Overview
**Intelligence-Engine** handles comprehensive metrics collection (3.1GB adaptive scaling), reconnaissance systems, and fog of war management.
**Key Responsibilities:**
- Metrics collection with adaptive scaling (2 pts/min → 0.4 pts/min multiplayer)
- Satellite reconnaissance and intelligence gathering
- Fog of War (FOW) management at chunk granularity
- Analytics and intelligence reporting
## Core Systems
### Metrics Collection
From `metriques-joueur.md`:
- **Adaptive Scaling**: 3.1GB per game with intelligent compression
- **Data Points**: 2 points/minute solo → 0.4 points/minute in multiplayer
- **Categories**: Economic, military, industrial, diplomatic metrics
- **Real-time Analytics**: Live dashboard and trend analysis
### Reconnaissance System
From `architecture-technique.md`:
- **Satellite Intel**: Graduated levels (buildings → factories → company-specific)
- **Intelligence Gathering**: Economic espionage, military reconnaissance
- **Counter-Intelligence**: Protecting own information, detecting spying
- **Information Warfare**: Disinformation and intelligence manipulation
### Fog of War Management
- **Chunk Granularity**: 64x64 tile visibility units
- **Company-Specific FOW**: Each company has independent visibility
- **Information Sharing**: Allied intelligence cooperation
- **Visibility Mechanics**: Line of sight, reconnaissance units
## Engine Architecture
### Core Classes
```cpp
class IntelligenceEngine {
// Metrics (adaptive scaling: 2 pts/min → 0.4 pts/min multiplayer)
void collectMetrics(int companyId, const std::string& data);
void pushMetricsToDatabase();
void adjustScalingForMultiplayer(int numCompanies);
// Reconnaissance (satellite: buildings → factories → company specific)
void updateSatelliteIntel(int x, int y, const std::string& intelLevel);
std::string getIntelligence(int companyId, int x, int y) const;
// FOW management (chunk granularity)
void setChunkVisibility(int companyId, int chunkX, int chunkY, bool visible);
};
```
### Communication with Other Engines
- **All Engines**: Collects metrics from every system
- **Map-Engine**: Coordinates FOW and chunk visibility
- **MacroEntity-Engine**: Company intelligence operations
- **War-Engine**: Military reconnaissance and battle intelligence
- **Economy-Engine**: Economic intelligence and market analysis
## Key Design Documents
- `metriques-joueur.md` - Complete metrics system specification
- `architecture-technique.md` - FOW and reconnaissance mechanics
- `map-system.md` - Chunk-based visibility system
- `coherence-problem.md` - Performance optimization strategies
## Implementation Notes
- 3.1GB data scaling requires sophisticated compression
- Real-time metrics processing with minimal performance impact
- Chunk-level FOW for optimal performance
- Intelligence sharing mechanics between allied companies

View File

@ -1,70 +0,0 @@
# Logistic-Engine Documentation
## Engine Overview
**Logistic-Engine** handles transport networks, supply chains, and convoy management across all map scales.
**Key Responsibilities:**
- Supply chain coordination between production sites
- Convoy routing and management
- Infrastructure vulnerability and security
- Transport optimization across multiple map scales
## Core Systems
### Supply Chain Management
From `economie-logistique.md`:
- **Multi-Site Coordination**: Raw materials → production → distribution
- **Route Optimization**: Cost-effective transportation paths
- **Capacity Planning**: Transport vehicle allocation
- **Supply Reliability**: Backup routes and contingency planning
### Transport Networks
From `map-system.md`:
- **Multi-Scale Routes**: World → Regional → Local scale coordination
- **Infrastructure**: Roads, railways, shipping lanes, air corridors
- **Convoy Management**: Vehicle groups with escorts and timing
- **Vulnerability**: Routes are visible on map and attackable
### Route Security
- **Infrastructure Protection**: Defending supply lines
- **Convoy Escorts**: Military protection for valuable shipments
- **Route Intelligence**: Monitoring for threats and optimal paths
- **Alternative Routing**: Adapting to blocked or dangerous routes
## Engine Architecture
### Core Classes
```cpp
class LogisticEngine {
// Supply chain management
void createSupplyChain(const std::string& chainId, const std::vector<int>& sites);
void updateRoute(const std::string& routeId, const std::vector<std::pair<int,int>>& waypoints);
// Convoy management
void dispatchConvoy(const std::string& convoyId, const std::string& routeId);
void trackConvoyProgress(const std::string& convoyId);
// Infrastructure (routes visible on map, attackable)
void markInfrastructureVulnerable(const std::string& routeId, bool vulnerable);
bool isRouteSecure(const std::string& routeId) const;
};
```
### Communication with Other Engines
- **Economy-Engine**: Transportation costs, supply/demand coordination
- **Factory-Engine**: Production schedules and inventory requirements
- **War-Engine**: Route security, convoy protection, infrastructure attacks
- **Map-Engine**: Route planning across multiple map scales
- **Intelligence-Engine**: Route intelligence and threat assessment
## Key Design Documents
- `economie-logistique.md` - Complete supply chain system
- `map-system.md` - Multi-scale transport coordination
- `systeme-militaire.md` - Infrastructure vulnerability and protection
- `architecture-technique.md` - Performance requirements
## Implementation Notes
- Routes are visible on map and can be targeted by enemies
- Multi-scale coordination requires efficient route planning
- Real-time convoy tracking and threat response
- Supply chain resilience through redundant routing

View File

@ -1,72 +0,0 @@
# MacroEntity-Engine Documentation
## Engine Overview
**MacroEntity-Engine** handles companies, diplomacy, and administration points with macro-level strategic rhythm.
**Key Responsibilities:**
- Company management (2-4 features per company)
- Diplomatic relations and sanctions
- Administration points system (1000 points/day, 1 day = 10 min real)
- Macro-level strategic decisions (~1 action every 3-5 days per company)
## Core Systems
### Company Management
From `mecaniques-jeu.md`:
- **Company Features**: 2-4 distinct capabilities per company
- **Strategic Focus**: Specialization in military, economic, or industrial domains
- **Company Evolution**: Gradual expansion and capability development
- **AI Behavior**: Distinct personalities and strategic preferences
### Administration System
- **Point Allocation**: 1000 administration points per day (10 minutes real-time)
- **Action Costs**: Major decisions consume administration points
- **Daily Reset**: Fresh allocation each game day
- **Strategic Pacing**: Prevents rapid micro-management, encourages planning
### Diplomacy System
From `coherence-problem.md`:
- **Relations Management**: Company-to-company diplomatic status
- **Economic Sanctions**: Trade restrictions and embargos
- **Military Alliances**: Coordinated defense and intelligence sharing
- **Diplomatic Actions**: Treaties, trade agreements, conflict declarations
## Engine Architecture
### Core Classes
```cpp
class MacroEntityEngine {
// Company management (2-4 features per company)
void createCompany(int companyId, const std::string& name);
void updateCompanyFeatures(int companyId);
// Administration (1000 points/day, 1 day = 10 min real)
bool consumeAdminPoints(int companyId, int points);
void resetDailyAdminPoints(int companyId);
// Diplomacy (sanctions, embargos, relations)
void setDiplomaticRelation(int company1, int company2, const std::string& relation);
void applySanctions(int targetCompany, const std::vector<std::string>& sanctions);
// Performance: ~1 action every 3-5 days per company (macro rhythm)
double getActionFrequency() const { return actionFrequency_; }
};
```
### Communication with Other Engines
- **Economy-Engine**: Diplomatic trade relations, sanctions impact
- **War-Engine**: Military alliances, conflict coordination
- **Intelligence-Engine**: Diplomatic intelligence, espionage operations
- **All Engines**: Company-level decision coordination and policy implementation
## Key Design Documents
- `mecaniques-jeu.md` - Administration and company systems
- `coherence-problem.md` - Diplomatic balance and sanctions
- `architecture-technique.md` - Macro-level performance requirements
- `economie-logistique.md` - Company economic interactions
## Implementation Notes
- Macro rhythm: 1 action every 3-5 days prevents micro-management
- Administration points create meaningful strategic choices
- Company features provide distinct strategic identities
- Diplomatic actions have long-term consequences across all systems

View File

@ -1,70 +0,0 @@
# Map-Engine Documentation
## Engine Overview
**Map-Engine** handles procedural generation, chunk streaming, and multi-scale map coordination with 218+ terrain elements.
**Key Responsibilities:**
- Procedural terrain generation with budget system (-10 to +10)
- Chunk management (64x64 tiles, streaming on demand)
- Multi-scale map coordination (World → Regional → Local → Detail)
- Fog of War coordination with Intelligence-Engine
## Core Systems
### Procedural Generation
From `map-system.md`:
- **218 Terrain Elements**: Comprehensive terrain feature set
- **Budget System**: -10 to +10 scoring for balanced generation
- **Millions of Combinations**: Procedural variety through element mixing
- **Scale-Appropriate Detail**: Different detail levels for each map scale
### Chunk System
From `systemes-techniques.md`:
- **64x64 Tiles**: Standard chunk size (1m×1m tiles)
- **Streaming**: On-demand loading/unloading for memory optimization
- **Persistent Storage**: Chunk data persistence across sessions
- **Memory Management**: Automatic cleanup of unused chunks
### Multi-Scale Architecture
- **World Scale**: Diplomatic and strategic overview
- **Regional Scale**: Logistics and major operations
- **Local Scale**: Factory and base management
- **Detail Scale**: Combat and precise operations
## Engine Architecture
### Core Classes
```cpp
class MapEngine {
// Chunk management (64x64 tiles, 1m×1m)
std::shared_ptr<Chunk> getChunk(int x, int y);
void generateChunk(int x, int y);
void unloadChunk(int x, int y);
// FOW (granularity: chunk level)
void updateFOW(int companyId, const std::vector<std::pair<int,int>>& visibleChunks);
bool isChunkVisible(int companyId, int x, int y) const;
// 218 procedural elements, budget -10 to +10
void generateTerrain(int chunkX, int chunkY);
};
```
### Communication with Other Engines
- **Intelligence-Engine**: FOW coordination and chunk visibility
- **War-Engine**: Combat terrain effects, battle locations
- **Logistic-Engine**: Route planning across multiple scales
- **Factory-Engine**: Terrain suitability for industrial development
- **All Engines**: Coordinate actions across appropriate map scales
## Key Design Documents
- `map-system.md` - Complete multi-scale map system
- `systemes-techniques.md` - Chunk system and memory management
- `architecture-technique.md` - Performance requirements and streaming
- `coherence-problem.md` - Multi-scale coordination challenges
## Implementation Notes
- 218 terrain elements provide rich procedural variety
- Budget system ensures balanced and interesting terrain
- Chunk streaming maintains performance with large worlds
- Multi-scale coordination requires careful data synchronization

View File

@ -1,67 +0,0 @@
# Operation-Engine Documentation
## Engine Overview
**Operation-Engine** handles military strategy, adaptive AI generals with machine learning, and strategic decision-making.
**Key Responsibilities:**
- Strategic planning and AI generals with ML adaptation
- Military doctrine evolution through learning
- Battle analysis and strategy optimization
- Operational coordination across multiple engagements
## Core Systems
### AI General System
From `architecture-technique.md`:
- **Machine Learning Adaptation**: AI generals learn from battle results
- **Behavioral Evolution**: Strategies adapt based on success/failure patterns
- **Personality Systems**: Distinct AI general characteristics and preferences
- **Performance Tracking**: Success metrics and learning algorithms
### Strategic Planning
From `systeme-militaire.md`:
- **Operation Coordination**: Multi-battle strategic campaigns
- **Resource Allocation**: Strategic asset distribution
- **Timing Coordination**: Synchronized multi-front operations
- **Contingency Planning**: Alternative strategies and fallback plans
### Doctrine Evolution
- **Learning from Results**: Battle outcomes inform strategic adjustments
- **Company Doctrines**: Faction-specific strategic preferences
- **Adaptive Strategies**: Dynamic response to enemy tactics
- **Knowledge Transfer**: Successful strategies spread between AI generals
## Engine Architecture
### Core Classes
```cpp
class OperationEngine {
// Strategic planning and AI generals with ML
void createOperation(const std::string& operationId, const std::string& type);
void assignGeneral(const std::string& operationId, std::unique_ptr<AIGeneral> general);
void adaptBehaviorFromResults(const std::string& generalId, bool success);
// Doctrine evolution (learning from successes/failures)
void updateDoctrine(const std::string& companyId, const std::string& lessons);
void analyzeBattleReports(const std::vector<std::string>& reports);
};
```
### Communication with Other Engines
- **War-Engine**: Receives battle results for learning and strategy adaptation
- **Intelligence-Engine**: Strategic intelligence and reconnaissance coordination
- **MacroEntity-Engine**: Company-level strategic goals and doctrine preferences
- **Designer-Engine**: Vehicle design requirements based on strategic needs
- **Logistic-Engine**: Strategic supply chain and operational logistics
## Key Design Documents
- `systeme-militaire.md` - Military strategic systems
- `architecture-technique.md` - AI general ML specifications
- `mecaniques-jeu.md` - Doctrine evolution mechanics
- `coherence-problem.md` - Strategic AI balance considerations
## Implementation Notes
- AI generals use machine learning to adapt strategies
- Battle reports provide data for strategic learning
- Doctrine evolution creates dynamic strategic environments
- Multi-operation coordination requires sophisticated planning algorithms

View File

@ -1,71 +0,0 @@
# War-Engine Documentation
## Engine Overview
**War-Engine** handles combat simulation, multi-chunk battles, persistent frontlines, and auto-battler mechanics with player oversight.
**Key Responsibilities:**
- Combat simulation across multiple chunks
- Persistent frontline management
- Auto-battler mechanics with strategic player control
- Battle result analysis and reporting
## Core Systems
### Combat System
From `systeme-militaire.md`:
- **Multi-Chunk Battles**: Combat spanning multiple 64x64 tile chunks
- **Auto-Battler Mechanics**: Automated tactical combat with strategic oversight
- **Unit Coordination**: Multi-vehicle formations and tactical maneuvers
- **Terrain Effects**: Map-based combat modifiers and tactical considerations
### Frontline Management
- **Persistent Frontlines**: Battle lines that persist across sessions
- **Dynamic Front Movement**: Frontlines shift based on combat results
- **Strategic Control Points**: Key locations affecting frontline stability
- **Frontline Intelligence**: Reconnaissance and frontline monitoring
### Battle Resolution
- **Real-time Combat**: Fast-paced tactical resolution
- **Player Oversight**: Strategic control without micro-management
- **Battle Reporting**: Detailed analysis for Operation-Engine learning
- **Casualty Tracking**: Unit losses and damage assessment
## Engine Architecture
### Core Classes
```cpp
class WarEngine {
// Combat management
void initiateBattle(const BattleSetup& setup);
void updateActiveBattles();
BattleResult resolveBattle(int battleId);
// Frontline system
void updateFrontlines();
std::vector<FrontlineSegment> getFrontlines(int companyId) const;
void setFrontlinePosition(int segmentId, const Position& newPosition);
// Auto-battler with player oversight
void setPlayerOversight(int battleId, const StrategicOrders& orders);
AutoBattlerResult processAutoBattle(int battleId);
};
```
### Communication with Other Engines
- **Operation-Engine**: Provides battle results for strategic learning
- **Designer-Engine**: Vehicle combat effectiveness feedback
- **Intelligence-Engine**: Battle intelligence and reconnaissance data
- **Map-Engine**: Multi-chunk combat terrain coordination
- **Event-Engine**: Provides scrap data for breakthrough system
## Key Design Documents
- `systeme-militaire.md` - Complete combat system specification
- `architecture-technique.md` - Multi-chunk battle performance
- `map-system.md` - Combat terrain integration
- `mecaniques-jeu.md` - Auto-battler mechanics and player control
## Implementation Notes
- Multi-chunk battles require efficient spatial coordination
- Auto-battler provides engaging combat without micro-management
- Persistent frontlines create strategic territorial control
- Battle analysis feeds into strategic AI learning systems

View File

@ -1,107 +0,0 @@
# Server Coordinator Documentation
## Overview
The **Server Coordinator** orchestrates communication between the 10 autonomous engines and manages the Smart Client architecture.
**Key Responsibilities:**
- Engine coordination and communication routing
- Smart Client request/response management
- Performance monitoring and load balancing
- System-wide state synchronization
## Architecture
### Smart Client Pattern
From `architecture-technique.md`:
- **Request/Response Only**: No streaming, stateless communication
- **Engine Autonomy**: Engines operate independently between requests
- **Performance Target**: 60fps with 1000+ AI companies
- **FOW Granularity**: Chunk-level fog of war coordination
### Engine Coordination
- **Inter-Engine Communication**: Message routing between engines
- **State Synchronization**: Coordinated updates across engine boundaries
- **Event Broadcasting**: Global events distributed to all engines
- **Performance Monitoring**: Engine load balancing and optimization
## Core Systems
### Communication Hub
```cpp
class ServerCoordinator {
// Engine management
void registerEngine(EngineType type, std::shared_ptr<Engine> engine);
void routeMessage(const Message& message);
void broadcastEvent(const GlobalEvent& event);
// Client management
void handleClientRequest(const ClientRequest& request);
ClientResponse processRequest(const ClientRequest& request);
void updateClientFOW(int clientId, const FOWUpdate& update);
// Performance monitoring
void monitorEnginePerformance();
void balanceEngineLoads();
PerformanceMetrics getSystemMetrics() const;
};
```
### Engine Communication Patterns
#### Economy ↔ Factory
- Production cost calculations
- Resource availability updates
- Manufacturing order processing
#### War ↔ Operation
- Battle result analysis
- Strategic learning data
- Tactical coordination
#### Intelligence ↔ All Engines
- Metrics collection from every system
- FOW updates and coordination
- Performance analytics
#### Event → All Engines
- Global event broadcasting
- Breakthrough notifications
- System-wide state changes
### Client Request Processing
From `architecture-technique.md`:
1. **Request Validation**: Ensure client permissions and data integrity
2. **Engine Routing**: Direct requests to appropriate engines
3. **State Coordination**: Manage cross-engine dependencies
4. **Response Assembly**: Compile responses from multiple engines
5. **FOW Filtering**: Apply visibility restrictions per client
### Performance Requirements
- **60fps Target**: Maintain real-time performance
- **1000+ Companies**: Scale to massive multiplayer scenarios
- **Engine Autonomy**: Minimize blocking between engines
- **Memory Efficiency**: Optimize inter-engine communication
## Key Integration Points
### Fog of War Coordination
- **Intelligence-Engine**: FOW state management
- **Map-Engine**: Chunk visibility coordination
- **Client Filtering**: Per-client visibility enforcement
### Event System Integration
- **Event-Engine**: Global event generation and scheduling
- **All Engines**: Event consumption and response
- **Client Notification**: Event broadcasting to relevant clients
### Metrics and Analytics
- **Intelligence-Engine**: System-wide metrics collection
- **Performance Monitoring**: Real-time system health
- **Load Balancing**: Dynamic resource allocation
## Implementation Notes
- Smart Client pattern eliminates streaming complexity
- Engine autonomy maximizes parallel processing
- FOW at chunk granularity optimizes performance
- Message routing minimizes engine coupling

@ -1 +0,0 @@
Subproject commit 00bcd93158fdbdb85d09107a508809454819442a

@ -1 +0,0 @@
Subproject commit 5e5a997675398847c371d5ba723018fa013ca6d8

View File

@ -1,27 +0,0 @@
cmake_minimum_required(VERSION 3.20)
project(EventEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(event-engine ${SOURCES})
# Set output directory
set_target_properties(event-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(event-engine)

View File

@ -1,21 +0,0 @@
# Event Engine
Engine autonome gérant événements et systèmes événementiels.
## Responsabilités
- Génération événements aléatoires et scripted
- Système breakthrough technologique event-driven
- Coordination événements cross-engine
- Gestion temporal events et timing global
## Architecture
- **Autonome** : Génération événements indépendante
- **Communication** : Events vers tous engines selon contexte
- **Performance** : Event queue optimisée, dispatching async
- **Scope** : Événements globaux, breakthrough, coordination temporelle
## Features
- Breakthrough system avec scrap analysis
- Événements géopolitiques majeurs
- Integration météo/catastrophes naturelles
- Event scripting pour scénarios narratifs

View File

@ -1,54 +0,0 @@
#pragma once
#include <memory>
#include <queue>
#include <thread>
namespace Warfactory {
namespace Event {
class GameEvent;
class BreakthroughSystem;
class EventQueue;
/**
* Autonomous Event Engine
* Handles breakthrough system and global events
*/
class EventEngine {
public:
EventEngine();
~EventEngine();
bool initialize();
void run();
void shutdown();
// Event management
void scheduleEvent(std::unique_ptr<GameEvent> event, double delaySeconds);
void triggerImmediateEvent(std::unique_ptr<GameEvent> event);
// Breakthrough system (event-driven with scrap analysis)
void analyzeScrapForBreakthrough(const std::string& scrapData);
void triggerBreakthrough(const std::string& technologyDomain);
// Global events (geopolitical, natural disasters, etc.)
void generateRandomEvent();
void processScheduledEvents();
private:
void engineLoop();
void updateEventQueue();
void dispatchEvents();
std::unique_ptr<EventQueue> eventQueue_;
std::unique_ptr<BreakthroughSystem> breakthroughSystem_;
std::thread engineThread_;
bool running_;
void sendEvents();
void receiveEventTriggers();
};
} // namespace Event
} // namespace Warfactory

View File

@ -1,25 +0,0 @@
#include <iostream>
#include "event-engine/EventEngine.h"
using namespace Warfactory::Event;
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Event-Engine..." << std::endl;
auto engine = std::make_unique<EventEngine>();
if (!engine->initialize()) {
std::cerr << "Failed to initialize Event-Engine" << std::endl;
return 1;
}
std::cout << "Event-Engine initialized successfully" << std::endl;
// Run the autonomous engine
engine->run();
engine->shutdown();
std::cout << "Event-Engine shutdown complete" << std::endl;
return 0;
}

View File

@ -1,144 +0,0 @@
#include "event-engine/EventEngine.h"
#include <iostream>
#include <chrono>
namespace Warfactory {
namespace Event {
class GameEvent {
public:
GameEvent() = default;
virtual ~GameEvent() = default;
virtual void execute() {}
};
class BreakthroughSystem {
public:
BreakthroughSystem() = default;
void analyzeScrap(const std::string& scrapData) {
std::cout << "Analyzing scrap: " << scrapData << std::endl;
}
void triggerBreakthrough(const std::string& domain) {
std::cout << "Breakthrough triggered in: " << domain << std::endl;
}
};
class EventQueue {
public:
EventQueue() = default;
void scheduleEvent(std::unique_ptr<GameEvent> event, double delay) {
events_.push(std::move(event));
}
void addImmediate(std::unique_ptr<GameEvent> event) {
events_.push(std::move(event));
}
bool hasEvents() const { return !events_.empty(); }
std::unique_ptr<GameEvent> popEvent() {
if (events_.empty()) return nullptr;
auto event = std::move(const_cast<std::unique_ptr<GameEvent>&>(events_.front()));
events_.pop();
return event;
}
private:
std::queue<std::unique_ptr<GameEvent>> events_;
};
EventEngine::EventEngine() : running_(false) {
std::cout << "EventEngine constructor" << std::endl;
eventQueue_ = std::make_unique<EventQueue>();
breakthroughSystem_ = std::make_unique<BreakthroughSystem>();
}
EventEngine::~EventEngine() {
if (running_) {
shutdown();
}
}
bool EventEngine::initialize() {
std::cout << "EventEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void EventEngine::run() {
std::cout << "EventEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&EventEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void EventEngine::shutdown() {
std::cout << "EventEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void EventEngine::scheduleEvent(std::unique_ptr<GameEvent> event, double /*delaySeconds*/) {
eventQueue_->scheduleEvent(std::move(event), 0.0);
}
void EventEngine::triggerImmediateEvent(std::unique_ptr<GameEvent> event) {
eventQueue_->addImmediate(std::move(event));
}
void EventEngine::analyzeScrapForBreakthrough(const std::string& scrapData) {
breakthroughSystem_->analyzeScrap(scrapData);
}
void EventEngine::triggerBreakthrough(const std::string& technologyDomain) {
breakthroughSystem_->triggerBreakthrough(technologyDomain);
}
void EventEngine::generateRandomEvent() {
std::cout << "Generating random global event" << std::endl;
}
void EventEngine::processScheduledEvents() {
while (eventQueue_->hasEvents()) {
auto event = eventQueue_->popEvent();
if (event) {
event->execute();
}
}
}
void EventEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
updateEventQueue();
dispatchEvents();
processScheduledEvents();
sendEvents();
receiveEventTriggers();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void EventEngine::updateEventQueue() {
}
void EventEngine::dispatchEvents() {
}
void EventEngine::sendEvents() {
}
void EventEngine::receiveEventTriggers() {
}
} // namespace Event
} // namespace Warfactory

View File

@ -1,27 +0,0 @@
cmake_minimum_required(VERSION 3.20)
project(FactoryEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(factory-engine ${SOURCES})
# Set output directory
set_target_properties(factory-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(factory-engine)

View File

@ -1,21 +0,0 @@
# Factory Engine
Engine autonome gérant les usines et production industrielle.
## Responsabilités
- Simulation usines Factorio-like (belts, assemblers, inserters)
- Calculs production, input/output, energy, qualité
- Optimisation automatique vs manuel joueur (skip-ability)
- Gestion multi-usines et coordination production
## Architecture
- **Autonome** : Simulations production indépendantes
- **Communication** : Demandes materials vers Logistic, output vers Economy
- **Performance** : 60fps simulation factory, algorithmes optimisés
- **Scope** : Production locale, chaînes assemblage
## Features
- Système qualité (placement optimal vs lookup tables)
- Energy management facile (pas bottleneck)
- Extraction simplifiée (focus sur assemblage)
- Automation complète ou contrôle manuel joueur

View File

@ -1,57 +0,0 @@
#pragma once
#include <memory>
#include <vector>
#include <thread>
namespace Warfactory {
namespace Factory {
class ProductionLine;
class Belt;
class Assembler;
/**
* Autonomous Factory Engine
* Handles Factorio-like production simulation
*/
class FactoryEngine {
public:
FactoryEngine();
~FactoryEngine();
// Engine lifecycle
bool initialize();
void run();
void shutdown();
// Factory management
void addProductionLine(std::unique_ptr<ProductionLine> line);
void removeProductionLine(int lineId);
// Production control
void startProduction();
void stopProduction();
void pauseProduction();
// Performance monitoring
double getTickRate() const { return tickRate_; }
size_t getActiveLines() const { return productionLines_.size(); }
private:
void engineLoop();
void updateProduction();
void processInputOutput();
std::vector<std::unique_ptr<ProductionLine>> productionLines_;
std::thread engineThread_;
bool running_;
double tickRate_;
// Communication with other engines
void sendProductionData();
void receiveOrders();
};
} // namespace Factory
} // namespace Warfactory

View File

@ -1,25 +0,0 @@
#include <iostream>
#include "factory/FactoryEngine.h"
using namespace Warfactory::Factory;
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Factory Engine..." << std::endl;
auto engine = std::make_unique<FactoryEngine>();
if (!engine->initialize()) {
std::cerr << "Failed to initialize Factory Engine" << std::endl;
return 1;
}
std::cout << "Factory Engine initialized successfully" << std::endl;
// Run the autonomous engine
engine->run();
engine->shutdown();
std::cout << "Factory Engine shutdown complete" << std::endl;
return 0;
}

View File

@ -1,122 +0,0 @@
#include "factory/FactoryEngine.h"
#include <iostream>
#include <chrono>
namespace Warfactory {
namespace Factory {
class ProductionLine {
public:
ProductionLine(int id) : id_(id) {}
int getId() const { return id_; }
void update() {}
private:
int id_;
};
class Belt {
public:
Belt() = default;
};
class Assembler {
public:
Assembler() = default;
};
FactoryEngine::FactoryEngine()
: running_(false), tickRate_(60.0) {
std::cout << "FactoryEngine constructor" << std::endl;
}
FactoryEngine::~FactoryEngine() {
if (running_) {
shutdown();
}
}
bool FactoryEngine::initialize() {
std::cout << "FactoryEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void FactoryEngine::run() {
std::cout << "FactoryEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&FactoryEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void FactoryEngine::shutdown() {
std::cout << "FactoryEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void FactoryEngine::addProductionLine(std::unique_ptr<ProductionLine> line) {
std::cout << "Adding production line: " << line->getId() << std::endl;
productionLines_.push_back(std::move(line));
}
void FactoryEngine::removeProductionLine(int lineId) {
auto it = std::remove_if(productionLines_.begin(), productionLines_.end(),
[lineId](const std::unique_ptr<ProductionLine>& line) {
return line->getId() == lineId;
});
productionLines_.erase(it, productionLines_.end());
}
void FactoryEngine::startProduction() {
std::cout << "Starting production" << std::endl;
}
void FactoryEngine::stopProduction() {
std::cout << "Stopping production" << std::endl;
}
void FactoryEngine::pauseProduction() {
std::cout << "Pausing production" << std::endl;
}
void FactoryEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
updateProduction();
processInputOutput();
sendProductionData();
receiveOrders();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void FactoryEngine::updateProduction() {
for (auto& line : productionLines_) {
line->update();
}
}
void FactoryEngine::processInputOutput() {
}
void FactoryEngine::sendProductionData() {
}
void FactoryEngine::receiveOrders() {
}
} // namespace Factory
} // namespace Warfactory

@ -1 +0,0 @@
Subproject commit 3563fb7289c4efbaa1646e794f8372ad54400021

View File

@ -1,27 +0,0 @@
cmake_minimum_required(VERSION 3.20)
project(LogisticEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(logistic-engine ${SOURCES})
# Set output directory
set_target_properties(logistic-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(logistic-engine)

View File

@ -1,21 +0,0 @@
# Logistic Engine
Engine autonome gérant transport et supply chains.
## Responsabilités
- Transport materials entre usines/sites
- Gestion convois, routes, infrastructure logistique
- Coordination supply chains multi-sites
- Vulnérabilités transport et sécurisation routes
## Architecture
- **Autonome** : Calculs logistiques indépendants
- **Communication** : Coordination avec Factory et Economy Engines
- **Performance** : Optimisation routes, gestion async convois
- **Scope** : Transport macro, supply lines
## Features
- Routes visualisées (infrastructure visible sur map)
- Convois suivent réseau routier/rail
- Infrastructure attaquable (vulnérabilités strategiques)
- Optimisation automatique vs contrôle manuel

View File

@ -1,56 +0,0 @@
#pragma once
#include <memory>
#include <vector>
#include <thread>
#include <unordered_map>
namespace Warfactory {
namespace Logistic {
class Convoy;
class Route;
class SupplyChain;
/**
* Autonomous Logistic Engine
* Handles transport and supply chains
*/
class LogisticEngine {
public:
LogisticEngine();
~LogisticEngine();
bool initialize();
void run();
void shutdown();
// Supply chain management
void createSupplyChain(const std::string& chainId, const std::vector<int>& sites);
void updateRoute(const std::string& routeId, const std::vector<std::pair<int,int>>& waypoints);
// Convoy management
void dispatchConvoy(const std::string& convoyId, const std::string& routeId);
void trackConvoyProgress(const std::string& convoyId);
// Infrastructure (routes visible on map, attackable)
void markInfrastructureVulnerable(const std::string& routeId, bool vulnerable);
bool isRouteSecure(const std::string& routeId) const;
private:
void engineLoop();
void updateConvoys();
void optimizeRoutes();
std::unordered_map<std::string, std::unique_ptr<SupplyChain>> supplyChains_;
std::unordered_map<std::string, std::unique_ptr<Route>> routes_;
std::unordered_map<std::string, std::unique_ptr<Convoy>> convoys_;
std::thread engineThread_;
bool running_;
void sendLogisticData();
void receiveTransportRequests();
};
} // namespace Logistic
} // namespace Warfactory

View File

@ -1,25 +0,0 @@
#include <iostream>
#include "logistic-engine/LogisticEngine.h"
using namespace Warfactory::Logistic;
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Logistic-Engine..." << std::endl;
auto engine = std::make_unique<LogisticEngine>();
if (!engine->initialize()) {
std::cerr << "Failed to initialize Logistic-Engine" << std::endl;
return 1;
}
std::cout << "Logistic-Engine initialized successfully" << std::endl;
// Run the autonomous engine
engine->run();
engine->shutdown();
std::cout << "Logistic-Engine shutdown complete" << std::endl;
return 0;
}

View File

@ -1,156 +0,0 @@
#include "logistic-engine/LogisticEngine.h"
#include <iostream>
#include <chrono>
namespace Warfactory {
namespace Logistic {
class Convoy {
public:
Convoy(const std::string& id) : id_(id) {}
std::string getId() const { return id_; }
void update() {}
private:
std::string id_;
};
class Route {
public:
Route(const std::string& id) : id_(id), secure_(true) {}
std::string getId() const { return id_; }
void setWaypoints(const std::vector<std::pair<int,int>>& waypoints) {
waypoints_ = waypoints;
}
void setVulnerable(bool vulnerable) { secure_ = !vulnerable; }
bool isSecure() const { return secure_; }
private:
std::string id_;
std::vector<std::pair<int,int>> waypoints_;
bool secure_;
};
class SupplyChain {
public:
SupplyChain(const std::string& id) : id_(id) {}
std::string getId() const { return id_; }
void setSites(const std::vector<int>& sites) { sites_ = sites; }
private:
std::string id_;
std::vector<int> sites_;
};
LogisticEngine::LogisticEngine() : running_(false) {
std::cout << "LogisticEngine constructor" << std::endl;
}
LogisticEngine::~LogisticEngine() {
if (running_) {
shutdown();
}
}
bool LogisticEngine::initialize() {
std::cout << "LogisticEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void LogisticEngine::run() {
std::cout << "LogisticEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&LogisticEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void LogisticEngine::shutdown() {
std::cout << "LogisticEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void LogisticEngine::createSupplyChain(const std::string& chainId, const std::vector<int>& sites) {
auto chain = std::make_unique<SupplyChain>(chainId);
chain->setSites(sites);
supplyChains_[chainId] = std::move(chain);
std::cout << "Created supply chain: " << chainId << std::endl;
}
void LogisticEngine::updateRoute(const std::string& routeId, const std::vector<std::pair<int,int>>& waypoints) {
auto it = routes_.find(routeId);
if (it != routes_.end()) {
it->second->setWaypoints(waypoints);
} else {
auto route = std::make_unique<Route>(routeId);
route->setWaypoints(waypoints);
routes_[routeId] = std::move(route);
}
std::cout << "Updated route: " << routeId << std::endl;
}
void LogisticEngine::dispatchConvoy(const std::string& convoyId, const std::string& routeId) {
auto convoy = std::make_unique<Convoy>(convoyId);
convoys_[convoyId] = std::move(convoy);
std::cout << "Dispatched convoy " << convoyId << " on route " << routeId << std::endl;
}
void LogisticEngine::trackConvoyProgress(const std::string& convoyId) {
auto it = convoys_.find(convoyId);
if (it != convoys_.end()) {
std::cout << "Tracking convoy: " << convoyId << std::endl;
}
}
void LogisticEngine::markInfrastructureVulnerable(const std::string& routeId, bool vulnerable) {
auto it = routes_.find(routeId);
if (it != routes_.end()) {
it->second->setVulnerable(vulnerable);
std::cout << "Route " << routeId << " marked as " << (vulnerable ? "vulnerable" : "secure") << std::endl;
}
}
bool LogisticEngine::isRouteSecure(const std::string& routeId) const {
auto it = routes_.find(routeId);
return (it != routes_.end()) ? it->second->isSecure() : false;
}
void LogisticEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
updateConvoys();
optimizeRoutes();
sendLogisticData();
receiveTransportRequests();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void LogisticEngine::updateConvoys() {
for (auto& [id, convoy] : convoys_) {
convoy->update();
}
}
void LogisticEngine::optimizeRoutes() {
}
void LogisticEngine::sendLogisticData() {
}
void LogisticEngine::receiveTransportRequests() {
}
} // namespace Logistic
} // namespace Warfactory

@ -1 +0,0 @@
Subproject commit 063263d904b3148b3c2a7f6a4abb62b35010bdb8

@ -1 +0,0 @@
Subproject commit 426b2f4012d6955eb3ac88092ade4d578aceeee5

View File

@ -1,27 +0,0 @@
cmake_minimum_required(VERSION 3.20)
project(OperationEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(operation-engine ${SOURCES})
# Set output directory
set_target_properties(operation-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(operation-engine)

View File

@ -1,21 +0,0 @@
# Operation Engine
Engine autonome gérant opérations militaires et stratégie macro.
## Responsabilités
- Généraux IA avec ML et doctrines évolutives
- Planning opérations militaires macro
- Adaptation comportements selon succès/échecs terrain
- Analyse rapports War Engine pour décisions strategiques
## Architecture
- **Autonome** : Prise de décision stratégique autonome
- **Communication** : Ordres vers Combat Engine, demandes vers Logistic
- **Performance** : ML adaptatif, expérience terrain persistante
- **Scope** : Stratégie macro, AI decision making, planning
## Features
- IA générale adaptative (apprentissage des échecs)
- Doctrines militaires évolutives par region/company
- Analysis automatique situation complexe (question ouverte #1)
- Integration intelligence pour décisions informées

View File

@ -1,53 +0,0 @@
#pragma once
#include <memory>
#include <vector>
#include <thread>
#include <string>
namespace Warfactory {
namespace Operation {
class AIGeneral;
class StrategicPlanner;
class DoctrineSystem;
/**
* Autonomous Operation Engine
* Handles military strategy and adaptive AI generals
*/
class OperationEngine {
public:
OperationEngine();
~OperationEngine();
bool initialize();
void run();
void shutdown();
// Strategic planning and AI generals with ML
void createOperation(const std::string& operationId, const std::string& type);
void assignGeneral(const std::string& operationId, std::unique_ptr<AIGeneral> general);
void adaptBehaviorFromResults(const std::string& generalId, bool success);
// Doctrine evolution (learning from successes/failures)
void updateDoctrine(const std::string& companyId, const std::string& lessons);
void analyzeBattleReports(const std::vector<std::string>& reports);
private:
void engineLoop();
void processStrategicDecisions();
void adaptAIBehavior(); // ML-based adaptation
std::vector<std::unique_ptr<AIGeneral>> generals_;
std::unique_ptr<StrategicPlanner> planner_;
std::unique_ptr<DoctrineSystem> doctrines_;
std::thread engineThread_;
bool running_;
void sendOrders();
void receiveBattleReports();
};
} // namespace Operation
} // namespace Warfactory

View File

@ -1,25 +0,0 @@
#include <iostream>
#include "operation-engine/OperationEngine.h"
using namespace Warfactory::Operation;
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Operation-Engine..." << std::endl;
auto engine = std::make_unique<OperationEngine>();
if (!engine->initialize()) {
std::cerr << "Failed to initialize Operation-Engine" << std::endl;
return 1;
}
std::cout << "Operation-Engine initialized successfully" << std::endl;
// Run the autonomous engine
engine->run();
engine->shutdown();
std::cout << "Operation-Engine shutdown complete" << std::endl;
return 0;
}

View File

@ -1,150 +0,0 @@
#include "operation-engine/OperationEngine.h"
#include <iostream>
#include <chrono>
#include <unordered_map>
namespace Warfactory {
namespace Operation {
class AIGeneral {
public:
AIGeneral(const std::string& id) : id_(id), skillLevel_(1.0) {}
std::string getId() const { return id_; }
void adaptFromResult(bool success) {
if (success) {
skillLevel_ += 0.1;
} else {
skillLevel_ = std::max(0.1, skillLevel_ - 0.05);
}
std::cout << "AI General " << id_ << " skill updated to: " << skillLevel_ << std::endl;
}
double getSkillLevel() const { return skillLevel_; }
private:
std::string id_;
double skillLevel_;
};
class StrategicPlanner {
public:
StrategicPlanner() = default;
void createOperation(const std::string& operationId, const std::string& type) {
operations_[operationId] = type;
std::cout << "Created operation " << operationId << " of type: " << type << std::endl;
}
void processDecisions() {}
private:
std::unordered_map<std::string, std::string> operations_;
};
class DoctrineSystem {
public:
DoctrineSystem() = default;
void updateDoctrine(const std::string& companyId, const std::string& lessons) {
doctrines_[companyId] = lessons;
std::cout << "Updated doctrine for company " << companyId << ": " << lessons << std::endl;
}
void analyzeBattleReports(const std::vector<std::string>& reports) {
std::cout << "Analyzing " << reports.size() << " battle reports for doctrine improvements" << std::endl;
}
private:
std::unordered_map<std::string, std::string> doctrines_;
};
OperationEngine::OperationEngine() : running_(false) {
std::cout << "OperationEngine constructor" << std::endl;
planner_ = std::make_unique<StrategicPlanner>();
doctrines_ = std::make_unique<DoctrineSystem>();
}
OperationEngine::~OperationEngine() {
if (running_) {
shutdown();
}
}
bool OperationEngine::initialize() {
std::cout << "OperationEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void OperationEngine::run() {
std::cout << "OperationEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&OperationEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void OperationEngine::shutdown() {
std::cout << "OperationEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void OperationEngine::createOperation(const std::string& operationId, const std::string& type) {
planner_->createOperation(operationId, type);
}
void OperationEngine::assignGeneral(const std::string& /*operationId*/, std::unique_ptr<AIGeneral> general) {
std::cout << "Assigned general " << general->getId() << " to operation" << std::endl;
generals_.push_back(std::move(general));
}
void OperationEngine::adaptBehaviorFromResults(const std::string& generalId, bool success) {
for (auto& general : generals_) {
if (general->getId() == generalId) {
general->adaptFromResult(success);
break;
}
}
}
void OperationEngine::updateDoctrine(const std::string& companyId, const std::string& lessons) {
doctrines_->updateDoctrine(companyId, lessons);
}
void OperationEngine::analyzeBattleReports(const std::vector<std::string>& reports) {
doctrines_->analyzeBattleReports(reports);
}
void OperationEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
processStrategicDecisions();
adaptAIBehavior();
sendOrders();
receiveBattleReports();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void OperationEngine::processStrategicDecisions() {
planner_->processDecisions();
}
void OperationEngine::adaptAIBehavior() {
for (auto& general : generals_) {
}
}
void OperationEngine::sendOrders() {
}
void OperationEngine::receiveBattleReports() {
}
} // namespace Operation
} // namespace Warfactory

@ -1 +0,0 @@
Subproject commit 0f8fed5fefb45f011dd2f679e19cfb7a7b29ba26

37
modules/CMakeLists.txt Normal file
View File

@ -0,0 +1,37 @@
cmake_minimum_required(VERSION 3.20)
project(WarfactoryModules LANGUAGES CXX)
# Modules coordinator - builds all modules
add_subdirectory(factory)
add_subdirectory(economy)
add_subdirectory(logistic)
# Meta targets for all modules
add_custom_target(warfactory-modules
DEPENDS
factory-module
economy-module
logistic-module
COMMENT "Building all Warfactory modules"
)
add_custom_target(test-all-modules
DEPENDS
test-factory
test-economy
test-logistic
COMMENT "Testing all Warfactory modules"
)
add_custom_target(clean-all-modules
DEPENDS
clean-factory
clean-economy
clean-logistic
COMMENT "Cleaning all Warfactory modules"
)
message(STATUS "📦 All Warfactory modules configured:")
message(STATUS " make warfactory-modules : Build all .so files")
message(STATUS " make test-all-modules : Test all modules")
message(STATUS " make clean-all-modules : Clean all builds")

66
modules/economy/CLAUDE.md Normal file
View File

@ -0,0 +1,66 @@
# Economy Module - Pure Market Logic
## Context
You are working EXCLUSIVELY on economic simulation logic. No infrastructure, no networking, no threading.
## Responsibilities
- **Market simulation**: Supply/demand, pricing dynamics
- **Trading**: Buy/sell orders, market makers, price discovery
- **Economic indicators**: Inflation, growth, market health
- **Resource valuation**: Dynamic pricing based on scarcity/abundance
## Interface Contract
```cpp
// Input JSON examples:
{
"type": "market_update",
"item": "steel_plate",
"supply": 1000,
"demand": 800
}
{
"type": "trade",
"action": "buy",
"item": "copper_ore",
"quantity": 50,
"max_price": 2.5
}
// Output JSON examples:
{
"status": "trade_executed",
"item": "copper_ore",
"quantity": 50,
"price": 2.3,
"total_cost": 115.0
}
{
"market_data": {
"steel_plate": {"price": 5.2, "trend": "rising"},
"copper_ore": {"price": 2.3, "trend": "stable"}
}
}
```
## Build Commands
```bash
cd modules/economy/
cmake . # Build from THIS directory
make economy-module # Generates economy.so
make test-economy # Run isolated tests
./build/economy-module # Test the module
```
## File Limits
- **EconomyModule.cpp**: Max 300 lines
- **Pure logic only**: No sockets, threads, or engine dependencies
- **JSON in/out**: All communication via JSON messages
## Focus Areas
1. Market algorithms (supply/demand curves, price elasticity)
2. Trading mechanics (order books, market makers)
3. Economic modeling (inflation, economic cycles)
Claude Code should NEVER leave this directory or reference parent paths!

View File

@ -0,0 +1,63 @@
cmake_minimum_required(VERSION 3.20)
project(EconomyModule LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0 -DDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
include_directories(shared)
# Economy module as shared library (.so)
add_library(economy-module SHARED
src/EconomyModule.cpp
)
set_target_properties(economy-module PROPERTIES
PREFIX ""
SUFFIX ".so"
OUTPUT_NAME "economy"
)
# Test executable
add_executable(economy-test
src/EconomyModule.cpp
tests/EconomyTest.cpp
)
# Standalone executable
add_executable(economy-standalone
src/EconomyModule.cpp
src/main.cpp
)
add_custom_target(build-economy
DEPENDS economy-module
COMMENT "Building economy.so module"
)
add_custom_target(test-economy
DEPENDS economy-test
COMMAND ./build/economy-test
COMMENT "Running economy module tests"
)
add_custom_target(clean-economy
COMMAND ${CMAKE_COMMAND} -E remove_directory build
COMMAND ${CMAKE_COMMAND} -E make_directory build
COMMENT "Cleaning economy module build"
)
message(STATUS "💰 Economy Module configured:")
message(STATUS " cmake . : Configure")
message(STATUS " make economy-module : Build economy.so")
message(STATUS " make test-economy : Run tests")
message(STATUS " make clean-economy : Clean build")

View File

@ -0,0 +1,69 @@
#pragma once
#include <string>
#include <functional>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Input/Output interface - swappable transport
*
* IntraIO -> Same process (direct call)
* LocalIO -> Same machine (named pipes/sockets)
* NetworkIO -> Network/Internet (TCP/WebSocket)
*/
class IIO {
public:
virtual ~IIO() = default;
/**
* @brief Initialize IO with configuration
* @param config Transport-specific configuration
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Send JSON message
* @param message JSON data to send
* @param target Target identifier (module name, endpoint, etc.)
*/
virtual void send(const json& message, const std::string& target) = 0;
/**
* @brief Receive JSON message (blocking)
* @return Received JSON message
*/
virtual json receive() = 0;
/**
* @brief Check if message available (non-blocking)
* @return true if message ready to receive
*/
virtual bool hasMessage() const = 0;
/**
* @brief Set message handler for async operation
* @param handler Function to call when message received
*/
virtual void setMessageHandler(std::function<void(const json&)> handler) = 0;
/**
* @brief Start async message processing
*/
virtual void startAsync() = 0;
/**
* @brief Stop async processing and cleanup
*/
virtual void shutdown() = 0;
/**
* @brief Get IO type identifier
*/
virtual std::string getType() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,51 @@
#pragma once
#include <string>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Pure game logic interface - Claude Code works ONLY on this
*
* Each module = 200-500 lines of pure game logic
* No infrastructure code, no threading, no networking
* Just: receive JSON input -> process logic -> return JSON output
*/
class IModule {
public:
virtual ~IModule() = default;
/**
* @brief Initialize module with configuration
* @param config JSON configuration for this module
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Process game logic - PURE FUNCTION
* @param input JSON input from other modules or engine
* @return JSON output to send to other modules
*/
virtual json process(const json& input) = 0;
/**
* @brief Get module metadata
* @return Module name, version, dependencies
*/
virtual json getMetadata() const = 0;
/**
* @brief Cleanup resources
*/
virtual void shutdown() = 0;
/**
* @brief Module name for identification
*/
virtual std::string getName() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,76 @@
#pragma once
#include "IModule.h"
#include <nlohmann/json.hpp>
#include <string>
#include <stdexcept>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Base helper class for modules
*
* Provides common functionality and JSON helpers
* LOCAL COPY - Completely autonomous
*/
class ModuleBase : public IModule {
protected:
std::string module_name;
json module_config;
bool initialized = false;
public:
explicit ModuleBase(const std::string& name) : module_name(name) {}
std::string getName() const override {
return module_name;
}
void initialize(const json& config) override {
module_config = config;
initialized = true;
onInitialize(config);
}
void shutdown() override {
onShutdown();
initialized = false;
}
json getMetadata() const override {
return {
{"name", module_name},
{"version", "1.0.0"},
{"initialized", initialized},
{"type", "game_module"}
};
}
protected:
// Override these in concrete modules
virtual void onInitialize(const json& config) {}
virtual void onShutdown() {}
// JSON helpers
bool hasField(const json& obj, const std::string& field) const {
return obj.contains(field) && !obj[field].is_null();
}
template<typename T>
T getField(const json& obj, const std::string& field, const T& defaultValue = T{}) const {
if (hasField(obj, field)) {
return obj[field].get<T>();
}
return defaultValue;
}
void ensureInitialized() const {
if (!initialized) {
throw std::runtime_error("Module " + module_name + " not initialized");
}
}
};
} // namespace warfactory

View File

@ -0,0 +1,287 @@
#include "../shared/ModuleBase.h"
#include <iostream>
#include <map>
#include <cmath>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Economy Module - Pure market simulation logic
*
* Handles supply/demand, pricing, trading
* Claude Code works ONLY on this file (~200-300 lines max)
*/
class EconomyModule : public ModuleBase {
private:
struct MarketData {
double price = 1.0;
double supply = 0.0;
double demand = 0.0;
double base_price = 1.0;
std::string trend = "stable";
};
std::map<std::string, MarketData> markets;
double inflation_rate = 0.02;
int simulation_tick = 0;
public:
EconomyModule() : ModuleBase("Economy") {}
json process(const json& input) override {
ensureInitialized();
std::string type = getField<std::string>(input, "type");
if (type == "market_update") {
return handleMarketUpdate(input);
}
else if (type == "trade") {
return handleTrade(input);
}
else if (type == "get_prices") {
return getPrices();
}
else if (type == "simulate_tick") {
return simulateTick();
}
else if (type == "status") {
return getStatus();
}
return {{"error", "Unknown command type: " + type}};
}
protected:
void onInitialize(const json& config) override {
// Initialize base markets
if (config.contains("markets")) {
auto market_config = config["markets"];
for (auto& [item, data] : market_config.items()) {
MarketData market;
market.base_price = getField<double>(data, "base_price", 1.0);
market.price = market.base_price;
market.supply = getField<double>(data, "initial_supply", 100.0);
market.demand = getField<double>(data, "initial_demand", 100.0);
markets[item] = market;
}
}
// Initialize default markets if none provided
if (markets.empty()) {
loadDefaultMarkets();
}
inflation_rate = getField<double>(module_config, "inflation_rate", 0.02);
std::cout << "💰 Economy Module initialized with "
<< markets.size() << " markets" << std::endl;
}
private:
json handleMarketUpdate(const json& input) {
std::string item = getField<std::string>(input, "item");
if (markets.find(item) == markets.end()) {
// Create new market
markets[item] = MarketData{};
}
auto& market = markets[item];
if (input.contains("supply")) {
market.supply = getField<double>(input, "supply");
}
if (input.contains("demand")) {
market.demand = getField<double>(input, "demand");
}
// Recalculate price based on supply/demand
updatePrice(item);
return {
{"status", "updated"},
{"item", item},
{"new_price", market.price},
{"supply", market.supply},
{"demand", market.demand},
{"trend", market.trend}
};
}
json handleTrade(const json& input) {
std::string action = getField<std::string>(input, "action");
std::string item = getField<std::string>(input, "item");
double quantity = getField<double>(input, "quantity");
if (markets.find(item) == markets.end()) {
return {{"error", "Market not found for item: " + item}};
}
auto& market = markets[item];
double current_price = market.price;
if (action == "buy") {
double max_price = getField<double>(input, "max_price", 999999.0);
if (current_price > max_price) {
return {
{"status", "trade_rejected"},
{"reason", "price_too_high"},
{"current_price", current_price},
{"max_price", max_price}
};
}
// Execute buy order
market.demand += quantity;
market.supply = std::max(0.0, market.supply - quantity);
updatePrice(item);
return {
{"status", "trade_executed"},
{"action", "buy"},
{"item", item},
{"quantity", quantity},
{"price", current_price},
{"total_cost", quantity * current_price}
};
}
else if (action == "sell") {
double min_price = getField<double>(input, "min_price", 0.0);
if (current_price < min_price) {
return {
{"status", "trade_rejected"},
{"reason", "price_too_low"},
{"current_price", current_price},
{"min_price", min_price}
};
}
// Execute sell order
market.supply += quantity;
market.demand = std::max(0.0, market.demand - quantity);
updatePrice(item);
return {
{"status", "trade_executed"},
{"action", "sell"},
{"item", item},
{"quantity", quantity},
{"price", current_price},
{"total_revenue", quantity * current_price}
};
}
return {{"error", "Invalid trade action: " + action}};
}
json getPrices() {
json prices = json::object();
for (const auto& [item, market] : markets) {
prices[item] = {
{"price", market.price},
{"trend", market.trend},
{"supply", market.supply},
{"demand", market.demand}
};
}
return {
{"market_data", prices},
{"inflation_rate", inflation_rate},
{"simulation_tick", simulation_tick}
};
}
json simulateTick() {
simulation_tick++;
// Simulate market fluctuations
for (auto& [item, market] : markets) {
// Add some random market movement
double volatility = 0.05; // 5% volatility
double random_factor = 1.0 + (rand() / (double)RAND_MAX - 0.5) * volatility;
// Natural decay towards equilibrium
double equilibrium_ratio = market.demand / std::max(market.supply, 1.0);
market.price = market.base_price * equilibrium_ratio * random_factor;
// Apply inflation
market.base_price *= (1.0 + inflation_rate / 100.0);
updateTrend(item);
}
return {
{"status", "tick_processed"},
{"simulation_tick", simulation_tick},
{"markets_updated", markets.size()}
};
}
json getStatus() {
return {
{"module", "Economy"},
{"markets_count", markets.size()},
{"simulation_tick", simulation_tick},
{"inflation_rate", inflation_rate}
};
}
void updatePrice(const std::string& item) {
auto& market = markets[item];
if (market.supply <= 0) {
market.price = market.base_price * 2.0; // Scarcity premium
} else {
double ratio = market.demand / market.supply;
market.price = market.base_price * std::max(0.1, ratio);
}
updateTrend(item);
}
void updateTrend(const std::string& item) {
auto& market = markets[item];
double ratio = market.demand / std::max(market.supply, 1.0);
if (ratio > 1.2) {
market.trend = "rising";
} else if (ratio < 0.8) {
market.trend = "falling";
} else {
market.trend = "stable";
}
}
void loadDefaultMarkets() {
markets["iron_ore"] = {1.0, 100.0, 100.0, 1.0, "stable"};
markets["copper_ore"] = {1.2, 80.0, 90.0, 1.2, "stable"};
markets["coal"] = {0.8, 120.0, 100.0, 0.8, "stable"};
markets["steel_plate"] = {5.0, 50.0, 60.0, 5.0, "stable"};
markets["copper_wire"] = {2.0, 70.0, 75.0, 2.0, "stable"};
markets["circuit"] = {15.0, 20.0, 25.0, 15.0, "stable"};
}
};
} // namespace warfactory
// C-style export functions for dynamic loading
extern "C" {
warfactory::IModule* createModule() {
return new warfactory::EconomyModule();
}
void destroyModule(warfactory::IModule* module) {
delete module;
}
const char* getModuleName() {
return "Economy";
}
}

56
modules/factory/CLAUDE.md Normal file
View File

@ -0,0 +1,56 @@
# Factory Module - Pure Production Logic
## Context
You are working EXCLUSIVELY on factory production logic. No infrastructure, no networking, no threading.
## Responsibilities
- **Assembly lines**: Manage production queues and recipes
- **Resource flow**: Input materials → processing → output products
- **Efficiency**: Calculate throughput, bottlenecks, optimization
- **Automation**: Belt systems, inserters, production planning
## Interface Contract
```cpp
// Input JSON examples:
{
"type": "produce",
"recipe": "steel_plate",
"quantity": 100,
"inputs": {"iron_ore": 200, "coal": 50}
}
{
"type": "optimize",
"target_production": {"steel_plate": 50, "copper_wire": 100},
"available_machines": 10
}
// Output JSON examples:
{
"status": "producing",
"progress": 0.75,
"outputs": {"steel_plate": 75},
"efficiency": 0.85
}
```
## Build Commands
```bash
cd modules/factory/
cmake . # Build from THIS directory
make factory-module # Generates factory.so
make test-factory # Run isolated tests
./build/factory-module # Test the module
```
## File Limits
- **FactoryModule.cpp**: Max 300 lines
- **Pure logic only**: No sockets, threads, or engine dependencies
- **JSON in/out**: All communication via JSON messages
## Focus Areas
1. Production algorithms (recipe chains, efficiency)
2. Resource management (inventory, flow optimization)
3. Automation logic (belt routing, machine placement)
Claude Code should NEVER leave this directory or reference parent paths!

View File

@ -0,0 +1,69 @@
cmake_minimum_required(VERSION 3.20)
project(FactoryModule LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Build configuration
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0 -DDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
endif()
# Output to local build directory
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
# Include local shared headers
include_directories(shared)
# Factory module as shared library (.so)
add_library(factory-module SHARED
src/FactoryModule.cpp
)
# Set library properties for .so generation
set_target_properties(factory-module PROPERTIES
PREFIX "" # No "lib" prefix
SUFFIX ".so" # Force .so extension
OUTPUT_NAME "factory"
)
# Test executable (optional)
add_executable(factory-test
src/FactoryModule.cpp
tests/FactoryTest.cpp
)
# Standalone executable for testing
add_executable(factory-standalone
src/FactoryModule.cpp
src/main.cpp
)
# Build targets
add_custom_target(build-factory
DEPENDS factory-module
COMMENT "Building factory.so module"
)
add_custom_target(test-factory
DEPENDS factory-test
COMMAND ./build/factory-test
COMMENT "Running factory module tests"
)
# Clean local build
add_custom_target(clean-factory
COMMAND ${CMAKE_COMMAND} -E remove_directory build
COMMAND ${CMAKE_COMMAND} -E make_directory build
COMMENT "Cleaning factory module build"
)
message(STATUS "🏭 Factory Module configured:")
message(STATUS " cmake . : Configure")
message(STATUS " make factory-module : Build factory.so")
message(STATUS " make test-factory : Run tests")
message(STATUS " make clean-factory : Clean build")

View File

@ -0,0 +1,69 @@
#pragma once
#include <string>
#include <functional>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Input/Output interface - swappable transport
*
* IntraIO -> Same process (direct call)
* LocalIO -> Same machine (named pipes/sockets)
* NetworkIO -> Network/Internet (TCP/WebSocket)
*/
class IIO {
public:
virtual ~IIO() = default;
/**
* @brief Initialize IO with configuration
* @param config Transport-specific configuration
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Send JSON message
* @param message JSON data to send
* @param target Target identifier (module name, endpoint, etc.)
*/
virtual void send(const json& message, const std::string& target) = 0;
/**
* @brief Receive JSON message (blocking)
* @return Received JSON message
*/
virtual json receive() = 0;
/**
* @brief Check if message available (non-blocking)
* @return true if message ready to receive
*/
virtual bool hasMessage() const = 0;
/**
* @brief Set message handler for async operation
* @param handler Function to call when message received
*/
virtual void setMessageHandler(std::function<void(const json&)> handler) = 0;
/**
* @brief Start async message processing
*/
virtual void startAsync() = 0;
/**
* @brief Stop async processing and cleanup
*/
virtual void shutdown() = 0;
/**
* @brief Get IO type identifier
*/
virtual std::string getType() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,51 @@
#pragma once
#include <string>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Pure game logic interface - Claude Code works ONLY on this
*
* Each module = 200-500 lines of pure game logic
* No infrastructure code, no threading, no networking
* Just: receive JSON input -> process logic -> return JSON output
*/
class IModule {
public:
virtual ~IModule() = default;
/**
* @brief Initialize module with configuration
* @param config JSON configuration for this module
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Process game logic - PURE FUNCTION
* @param input JSON input from other modules or engine
* @return JSON output to send to other modules
*/
virtual json process(const json& input) = 0;
/**
* @brief Get module metadata
* @return Module name, version, dependencies
*/
virtual json getMetadata() const = 0;
/**
* @brief Cleanup resources
*/
virtual void shutdown() = 0;
/**
* @brief Module name for identification
*/
virtual std::string getName() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,76 @@
#pragma once
#include "IModule.h"
#include <nlohmann/json.hpp>
#include <string>
#include <stdexcept>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Base helper class for modules
*
* Provides common functionality and JSON helpers
* LOCAL COPY - Completely autonomous
*/
class ModuleBase : public IModule {
protected:
std::string module_name;
json module_config;
bool initialized = false;
public:
explicit ModuleBase(const std::string& name) : module_name(name) {}
std::string getName() const override {
return module_name;
}
void initialize(const json& config) override {
module_config = config;
initialized = true;
onInitialize(config);
}
void shutdown() override {
onShutdown();
initialized = false;
}
json getMetadata() const override {
return {
{"name", module_name},
{"version", "1.0.0"},
{"initialized", initialized},
{"type", "game_module"}
};
}
protected:
// Override these in concrete modules
virtual void onInitialize(const json& config) {}
virtual void onShutdown() {}
// JSON helpers
bool hasField(const json& obj, const std::string& field) const {
return obj.contains(field) && !obj[field].is_null();
}
template<typename T>
T getField(const json& obj, const std::string& field, const T& defaultValue = T{}) const {
if (hasField(obj, field)) {
return obj[field].get<T>();
}
return defaultValue;
}
void ensureInitialized() const {
if (!initialized) {
throw std::runtime_error("Module " + module_name + " not initialized");
}
}
};
} // namespace warfactory

View File

@ -0,0 +1,175 @@
#include "../shared/ModuleBase.h"
#include <iostream>
#include <map>
#include <vector>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Factory Module - Pure production logic
*
* Handles assembly lines, recipes, resource flow
* Claude Code works ONLY on this file (~200-300 lines max)
*/
class FactoryModule : public ModuleBase {
private:
// Production state
std::map<std::string, int> inventory;
std::map<std::string, json> recipes;
std::vector<json> production_queue;
public:
FactoryModule() : ModuleBase("Factory") {}
json process(const json& input) override {
ensureInitialized();
std::string type = getField<std::string>(input, "type");
if (type == "produce") {
return handleProduce(input);
}
else if (type == "optimize") {
return handleOptimize(input);
}
else if (type == "status") {
return getStatus();
}
return {{"error", "Unknown command type: " + type}};
}
protected:
void onInitialize(const json& config) override {
// Load recipes from config
if (config.contains("recipes")) {
recipes = config["recipes"];
}
// Initialize default recipes if none provided
if (recipes.empty()) {
loadDefaultRecipes();
}
std::cout << "🏭 Factory Module initialized with "
<< recipes.size() << " recipes" << std::endl;
}
private:
json handleProduce(const json& input) {
std::string recipe = getField<std::string>(input, "recipe");
int quantity = getField<int>(input, "quantity", 1);
if (recipes.find(recipe) == recipes.end()) {
return {{"error", "Recipe not found: " + recipe}};
}
// Check if we have enough inputs
json recipe_data = recipes[recipe];
json inputs = getField<json>(recipe_data, "inputs", json::object());
for (auto& [material, needed] : inputs.items()) {
int available = getField<int>(json(inventory), material, 0);
int required = needed.get<int>() * quantity;
if (available < required) {
return {
{"error", "Insufficient materials"},
{"material", material},
{"required", required},
{"available", available}
};
}
}
// Consume inputs and produce outputs
for (auto& [material, needed] : inputs.items()) {
inventory[material] -= needed.get<int>() * quantity;
}
json outputs = getField<json>(recipe_data, "outputs", json::object());
for (auto& [product, produced] : outputs.items()) {
inventory[product] += produced.get<int>() * quantity;
}
return {
{"status", "success"},
{"recipe", recipe},
{"quantity", quantity},
{"inventory", inventory}
};
}
json handleOptimize(const json& input) {
// Simple optimization algorithm
json target = getField<json>(input, "target_production", json::object());
int machines = getField<int>(input, "available_machines", 1);
json plan = json::array();
for (auto& [product, quantity] : target.items()) {
if (recipes.find(product) != recipes.end()) {
int batches = (quantity.get<int>() + machines - 1) / machines;
plan.push_back({
{"product", product},
{"batches", batches},
{"machines_needed", std::min(machines, quantity.get<int>())}
});
}
}
return {
{"optimization", plan},
{"efficiency", 0.85}, // Placeholder calculation
{"bottlenecks", json::array()}
};
}
json getStatus() {
return {
{"module", "Factory"},
{"inventory", inventory},
{"recipes_loaded", recipes.size()},
{"production_queue_size", production_queue.size()}
};
}
void loadDefaultRecipes() {
recipes["steel_plate"] = {
{"inputs", {{"iron_ore", 2}, {"coal", 1}}},
{"outputs", {{"steel_plate", 1}}},
{"time", 5.0}
};
recipes["copper_wire"] = {
{"inputs", {{"copper_ore", 1}}},
{"outputs", {{"copper_wire", 2}}},
{"time", 2.0}
};
recipes["circuit"] = {
{"inputs", {{"steel_plate", 1}, {"copper_wire", 3}}},
{"outputs", {{"circuit", 1}}},
{"time", 10.0}
};
}
};
} // namespace warfactory
// C-style export functions for dynamic loading
extern "C" {
warfactory::IModule* createModule() {
return new warfactory::FactoryModule();
}
void destroyModule(warfactory::IModule* module) {
delete module;
}
const char* getModuleName() {
return "Factory";
}
}

View File

@ -0,0 +1,58 @@
#include "../shared/ModuleBase.h"
#include "FactoryModule.cpp"
#include <iostream>
using json = nlohmann::json;
/**
* @brief Standalone test for FactoryModule
*
* Claude Code can run this to test the module locally
*/
int main() {
std::cout << "🏭 Testing Factory Module Standalone..." << std::endl;
try {
auto factory = std::make_unique<warfactory::FactoryModule>();
// Initialize with basic config
json config = {
{"module_name", "Factory"},
{"debug", true}
};
factory->initialize(config);
// Test production
json produce_cmd = {
{"type", "produce"},
{"recipe", "steel_plate"},
{"quantity", 5}
};
std::cout << "\n📤 Input: " << produce_cmd.dump(2) << std::endl;
// First attempt should fail (no materials)
json result = factory->process(produce_cmd);
std::cout << "📥 Result: " << result.dump(2) << std::endl;
// Add some materials and try again
json add_materials = {
{"type", "add_inventory"},
{"materials", {{"iron_ore", 20}, {"coal", 10}}}
};
// Test status
json status_cmd = {{"type", "status"}};
json status = factory->process(status_cmd);
std::cout << "\n📊 Status: " << status.dump(2) << std::endl;
factory->shutdown();
std::cout << "\n✅ Factory Module test completed successfully!" << std::endl;
return 0;
}
catch (const std::exception& e) {
std::cerr << "❌ Factory Module test failed: " << e.what() << std::endl;
return 1;
}
}

View File

@ -0,0 +1,67 @@
# Logistic Module - Pure Supply Chain Logic
## Context
You are working EXCLUSIVELY on logistics and transportation logic. No infrastructure, no networking, no threading.
## Responsibilities
- **Supply chains**: Resource routing, delivery optimization
- **Transportation**: Vehicle routing, capacity planning
- **Warehousing**: Inventory management, distribution centers
- **Route optimization**: Shortest path, load balancing
## Interface Contract
```cpp
// Input JSON examples:
{
"type": "plan_route",
"from": "factory_A",
"to": "warehouse_B",
"cargo": {"steel_plate": 100, "copper_wire": 50},
"constraints": {"max_weight": 1000, "max_distance": 500}
}
{
"type": "optimize_supply_chain",
"demand": {"location_1": {"steel_plate": 50}, "location_2": {"copper_wire": 30}},
"supply": {"factory_A": {"steel_plate": 200}, "factory_B": {"copper_wire": 100}}
}
// Output JSON examples:
{
"route": ["factory_A", "hub_1", "warehouse_B"],
"distance": 350,
"time": 45,
"cost": 120.5,
"vehicles_needed": 2
}
{
"supply_plan": [
{"from": "factory_A", "to": "location_1", "items": {"steel_plate": 50}},
{"from": "factory_B", "to": "location_2", "items": {"copper_wire": 30}}
],
"total_cost": 95.0,
"efficiency": 0.92
}
```
## Build Commands
```bash
cd modules/logistic/
cmake . # Build from THIS directory
make logistic-module # Generates logistic.so
make test-logistic # Run isolated tests
./build/logistic-module # Test the module
```
## File Limits
- **LogisticModule.cpp**: Max 300 lines
- **Pure logic only**: No sockets, threads, or engine dependencies
- **JSON in/out**: All communication via JSON messages
## Focus Areas
1. Routing algorithms (A*, Dijkstra, optimization)
2. Supply chain optimization (linear programming concepts)
3. Inventory management (stock levels, reorder points)
Claude Code should NEVER leave this directory or reference parent paths!

View File

@ -0,0 +1,63 @@
cmake_minimum_required(VERSION 3.20)
project(LogisticModule LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0 -DDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
include_directories(shared)
# Logistic module as shared library (.so)
add_library(logistic-module SHARED
src/LogisticModule.cpp
)
set_target_properties(logistic-module PROPERTIES
PREFIX ""
SUFFIX ".so"
OUTPUT_NAME "logistic"
)
# Test executable
add_executable(logistic-test
src/LogisticModule.cpp
tests/LogisticTest.cpp
)
# Standalone executable
add_executable(logistic-standalone
src/LogisticModule.cpp
src/main.cpp
)
add_custom_target(build-logistic
DEPENDS logistic-module
COMMENT "Building logistic.so module"
)
add_custom_target(test-logistic
DEPENDS logistic-test
COMMAND ./build/logistic-test
COMMENT "Running logistic module tests"
)
add_custom_target(clean-logistic
COMMAND ${CMAKE_COMMAND} -E remove_directory build
COMMAND ${CMAKE_COMMAND} -E make_directory build
COMMENT "Cleaning logistic module build"
)
message(STATUS "🚛 Logistic Module configured:")
message(STATUS " cmake . : Configure")
message(STATUS " make logistic-module : Build logistic.so")
message(STATUS " make test-logistic : Run tests")
message(STATUS " make clean-logistic : Clean build")

View File

@ -0,0 +1,69 @@
#pragma once
#include <string>
#include <functional>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Input/Output interface - swappable transport
*
* IntraIO -> Same process (direct call)
* LocalIO -> Same machine (named pipes/sockets)
* NetworkIO -> Network/Internet (TCP/WebSocket)
*/
class IIO {
public:
virtual ~IIO() = default;
/**
* @brief Initialize IO with configuration
* @param config Transport-specific configuration
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Send JSON message
* @param message JSON data to send
* @param target Target identifier (module name, endpoint, etc.)
*/
virtual void send(const json& message, const std::string& target) = 0;
/**
* @brief Receive JSON message (blocking)
* @return Received JSON message
*/
virtual json receive() = 0;
/**
* @brief Check if message available (non-blocking)
* @return true if message ready to receive
*/
virtual bool hasMessage() const = 0;
/**
* @brief Set message handler for async operation
* @param handler Function to call when message received
*/
virtual void setMessageHandler(std::function<void(const json&)> handler) = 0;
/**
* @brief Start async message processing
*/
virtual void startAsync() = 0;
/**
* @brief Stop async processing and cleanup
*/
virtual void shutdown() = 0;
/**
* @brief Get IO type identifier
*/
virtual std::string getType() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,51 @@
#pragma once
#include <string>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Pure game logic interface - Claude Code works ONLY on this
*
* Each module = 200-500 lines of pure game logic
* No infrastructure code, no threading, no networking
* Just: receive JSON input -> process logic -> return JSON output
*/
class IModule {
public:
virtual ~IModule() = default;
/**
* @brief Initialize module with configuration
* @param config JSON configuration for this module
*/
virtual void initialize(const json& config) = 0;
/**
* @brief Process game logic - PURE FUNCTION
* @param input JSON input from other modules or engine
* @return JSON output to send to other modules
*/
virtual json process(const json& input) = 0;
/**
* @brief Get module metadata
* @return Module name, version, dependencies
*/
virtual json getMetadata() const = 0;
/**
* @brief Cleanup resources
*/
virtual void shutdown() = 0;
/**
* @brief Module name for identification
*/
virtual std::string getName() const = 0;
};
} // namespace warfactory

View File

@ -0,0 +1,76 @@
#pragma once
#include "IModule.h"
#include <nlohmann/json.hpp>
#include <string>
#include <stdexcept>
using json = nlohmann::json;
namespace warfactory {
/**
* @brief Base helper class for modules
*
* Provides common functionality and JSON helpers
* LOCAL COPY - Completely autonomous
*/
class ModuleBase : public IModule {
protected:
std::string module_name;
json module_config;
bool initialized = false;
public:
explicit ModuleBase(const std::string& name) : module_name(name) {}
std::string getName() const override {
return module_name;
}
void initialize(const json& config) override {
module_config = config;
initialized = true;
onInitialize(config);
}
void shutdown() override {
onShutdown();
initialized = false;
}
json getMetadata() const override {
return {
{"name", module_name},
{"version", "1.0.0"},
{"initialized", initialized},
{"type", "game_module"}
};
}
protected:
// Override these in concrete modules
virtual void onInitialize(const json& config) {}
virtual void onShutdown() {}
// JSON helpers
bool hasField(const json& obj, const std::string& field) const {
return obj.contains(field) && !obj[field].is_null();
}
template<typename T>
T getField(const json& obj, const std::string& field, const T& defaultValue = T{}) const {
if (hasField(obj, field)) {
return obj[field].get<T>();
}
return defaultValue;
}
void ensureInitialized() const {
if (!initialized) {
throw std::runtime_error("Module " + module_name + " not initialized");
}
}
};
} // namespace warfactory

37
scripts/sync_helpers.sh Normal file
View File

@ -0,0 +1,37 @@
#!/bin/bash
# Sync helper files to all modules
# Run this when core interfaces change
CORE_HELPERS="core/include/warfactory"
MODULE_DIRS="modules/*/shared"
echo "🔄 Syncing helper files to all modules..."
if [ ! -d "$CORE_HELPERS" ]; then
echo "❌ Core helpers directory not found: $CORE_HELPERS"
exit 1
fi
for module_dir in $MODULE_DIRS; do
if [ -d "$module_dir" ]; then
module_name=$(dirname "$module_dir" | basename)
echo " → Syncing to $module_name"
# Copy core interfaces
cp "$CORE_HELPERS/IModule.h" "$module_dir/"
cp "$CORE_HELPERS/ISocket.h" "$module_dir/"
# Copy base helper (if exists)
if [ -f "modules/factory/shared/ModuleBase.h" ]; then
cp "modules/factory/shared/ModuleBase.h" "$module_dir/"
fi
fi
done
echo "✅ Helper sync completed!"
echo ""
echo "📋 Next steps:"
echo " cd modules/factory && cmake . && make factory-module"
echo " cd modules/economy && cmake . && make economy-module"
echo " cd modules/logistic && cmake . && make logistic-module"