diff --git a/docs/README.md b/docs/README.md index 5c6516f..8bf84e3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,94 +1,159 @@ -# Warfactory Documentation Index +# Documentation Warfactory -## Documentation Structure +## 🏭 Vue d'Ensemble du Projet -This documentation is organized by component type to provide focused information for each part of the Warfactory system. +Warfactory est un jeu de simulation industrielle militaire inspirĂ© de Factorio, utilisant une **architecture modulaire rĂ©volutionnaire** optimisĂ©e pour le dĂ©veloppement avec **Claude Code**. -### 📁 Global Documentation (`/global/`) -Complete project documentation with all design documents: -- `vue-ensemble.md` - Project vision and philosophy -- `architecture-technique.md` - Complete technical architecture -- `map-system.md` - Multi-scale map system (218+ elements) -- `systeme-militaire.md` - Combat and vehicle design systems -- `economie-logistique.md` - Economic simulation and supply chains -- `gameplay-industriel.md` - Factory management (Factorio-like) -- `mecaniques-jeu.md` - Research, breakthrough, and progression -- `arbre-technologique.md` - 3000+ technology tree -- `metriques-joueur.md` - Analytics system (3.1GB adaptive) -- `coherence-problem.md` - Resolved design challenges -- `questions-ouvertes.md` - Open questions and future considerations +## 📚 Documentation Principale -### 🔧 Engine Documentation (`/engines/`) -Focused documentation for each of the 10 autonomous engines: +### Architecture & Design +- **[Vue Ensemble](vue-ensemble.md)** - Vision, philosophie et design du jeu +- **[Architecture Technique](architecture-technique.md)** - Multi-serveur, engines, spĂ©cifications +- **[Architecture Modulaire](architecture-modulaire.md)** - đŸ”„ **NOUVEAU** : Architecture triple interface +- **[Claude Code Integration](claude-code-integration.md)** - đŸ”„ **NOUVEAU** : Guide dĂ©veloppement IA +- **[Player Integration](player-integration.md)** - đŸ”„ **NOUVEAU** : Client/Server modulaire -#### Core Engines -- **[Designer](./engines/designer/)** - Vehicle design with AI assistance (1-2 designs/tick) -- **[Economy](./engines/economy/)** - Market simulation and dynamic pricing -- **[Factory](./engines/factory/)** - Factorio-like production with belts and assemblers -- **[War](./engines/war/)** - Multi-chunk combat and persistent frontlines +### SystĂšmes de Jeu +- **[Gameplay Industriel](gameplay-industriel.md)** - Production, ressources, optimisation +- **[SystĂšme Militaire](systeme-militaire.md)** - Design vĂ©hicules, combat +- **[Économie & Logistique](economie-logistique.md)** - MarchĂ©s, chaĂźnes d'approvisionnement +- **[MĂ©caniques de Jeu](mecaniques-jeu.md)** - Recherche, progression, administration -#### Specialized Engines -- **[Intelligence](./engines/intelligence/)** - Metrics collection (3.1GB adaptive) and reconnaissance -- **[Logistic](./engines/logistic/)** - Supply chains and convoy management -- **[Map](./engines/map/)** - Procedural generation (218+ elements) and chunk streaming -- **[Operation](./engines/operation/)** - Military strategy and adaptive AI generals +### SystĂšmes Techniques +- **[SystĂšmes Techniques](systemes-techniques.md)** - Tiles, mĂ©moire, chunks +- **[Map System](map-system.md)** - GĂ©nĂ©ration procĂ©durale, 218+ Ă©lĂ©ments +- **[Arbre Technologique](arbre-technologique.md)** - 3000+ technologies +- **[MĂ©triques Joueur](metriques-joueur.md)** - Analytics (3.1GB par partie) -#### Support Engines -- **[Event](./engines/event/)** - Breakthrough system and global events -- **[MacroEntity](./engines/macroentity/)** - Companies, diplomacy, administration (1000 pts/day) +### RĂ©solution de ProblĂšmes +- **[Coherence Problem](coherence-problem.md)** - Contradictions rĂ©solues +- **[Questions Ouvertes](questions-ouvertes.md)** - 11 items Ă  rĂ©soudre -### đŸ–„ïž Server Documentation (`/serveur/`) -Server coordinator system: -- Engine communication and coordination -- Smart Client request/response handling -- Performance monitoring and load balancing -- Inter-engine message routing +### Planification +- **[Contexte Narratif](contexte-narratif.md)** - Background et univers +- **[DLC PrĂ©vus](dlc-prevus.md)** - Contenus futurs +- **[Updates Long Terme](updates-long-terme.md)** - Roadmap -### đŸ’» Client Documentation (`/client/`) -Smart Client interface system: -- Multi-scale user interface (World → Regional → Local → Detail) -- Factory management interface (Factorio-like) -- Vehicle design interface (grid-based component placement) -- Strategic command and diplomatic interfaces +## 🚀 Architecture RĂ©volutionnaire -## Quick Navigation - -### For Engine Developers -Each engine folder contains: -- **Core responsibilities** and system overview -- **Key mechanics** from relevant design documents -- **Communication patterns** with other engines -- **Implementation notes** and architecture details - -### For System Architects -- **[Global Documentation](./global/)** - Complete system overview -- **[Server Documentation](./serveur/)** - Coordination architecture -- **Performance specs**: 60fps, 1000+ AI companies, adaptive scaling - -### For Game Designers -- **[Global Documentation](./global/)** - All gameplay mechanics -- **Engine-specific docs** - Focused system details -- **[Client Documentation](./client/)** - User interface requirements - -## Implementation Status - -✅ **Complete**: Documentation structure with engine-specific focus -✅ **Complete**: 10 engine implementations with CMake build system -✅ **Complete**: Fast/full build presets for development efficiency -🔄 **In Progress**: Engine logic expansion and inter-engine communication -📋 **Next**: Gameplay feature implementation and testing - -## Build Commands Quick Reference - -```bash -# Fast development build (minimal sanitizers) -cmake -DFAST_BUILD=ON .. && make claude-workflow-fast - -# Full validation build (all sanitizers) -cmake -DCMAKE_BUILD_TYPE=Debug .. && make - -# Single engine development -make economy-engine && ./bin/economy-engine +### Triple Interface Pattern +``` +IEngine → Coordination (Debug → Production → DataOriented) +IModuleSystem → ExĂ©cution (Sequential → Threaded → Cluster) +IModule → Logique Pure (Tank.so, Economy.so, Factory.so) +IIO → Communication (Intra → Local → Network) ``` -For complete build system documentation, see `CLAUDE.md` in the project root. \ No newline at end of file +### Avantages Claude Code +- **Contextes micro** : 200 lignes vs 50K+ lignes +- **Build autonome** : `cd modules/tank/ && cmake .` +- **Hot-reload** : Modifications instantanĂ©es +- **DĂ©veloppement parallĂšle** : Multiple instances Claude Code + +## 🎯 Focus Development + +### Phase Actuelle : Architecture Modulaire +- ✅ **Interfaces C++** : IEngine, IModuleSystem, IModule, IIO +- ✅ **Modules de base** : Factory, Economy, Logistic +- ✅ **Build autonome** : Chaque module = contexte indĂ©pendant +- 🔄 **Prochaine Ă©tape** : ImplĂ©mentations concrĂštes + +### Workflow de DĂ©veloppement +```bash +# DĂ©veloppement module spĂ©cifique +cd modules/factory/ +cmake . && make factory-module # → factory.so + +# Test isolĂ© +./build/factory-module + +# Hot-reload dans le jeu principal +# Aucun restart nĂ©cessaire ! +``` + +## 🎼 Vision du Jeu + +### Concept Core +- **Factory + Military** : Production industrielle + doctrine militaire +- **Échelles multiples** : Local (usines) → RĂ©gional (logistique) → Global (diplomatie) +- **Progression** : PMC → Entreprise → Corporation → Super-pouvoir + +### MĂ©caniques Principales +1. **Production Factorio-like** : ChaĂźnes d'assemblage, optimisation +2. **Design vĂ©hicules** : Grille irrĂ©guliĂšre, placement composants +3. **Combat auto-battler** : Frontlines persistantes, supervision joueur +4. **Économie dynamique** : MarchĂ©s, inflation, cycles Ă©conomiques + +## 📖 Comment Utiliser Cette Documentation + +### Pour les DĂ©veloppeurs +1. **Commencer par** : [Architecture Modulaire](architecture-modulaire.md) +2. **Puis** : [Claude Code Integration](claude-code-integration.md) +3. **Ensuite** : [Vue Ensemble](vue-ensemble.md) pour le contexte + +### Pour les Game Designers +1. **Commencer par** : [Vue Ensemble](vue-ensemble.md) +2. **Puis** : [Gameplay Industriel](gameplay-industriel.md) +3. **Ensuite** : [SystĂšme Militaire](systeme-militaire.md) + +### Pour Claude Code Sessions +1. **Toujours lire** : `/modules/{module}/CLAUDE.md` +2. **Context limitĂ©** : Module spĂ©cifique uniquement +3. **Build autonome** : `cmake .` depuis le module +4. **Max 300 lignes** : Logique pure, zĂ©ro infrastructure + +## 🔄 Statut du Projet + +### ✅ ComplĂ©tĂ© +- **Design complet** : 15+ documents de spĂ©cification +- **Architecture modulaire** : Triple interface implĂ©mentĂ©e +- **Build system** : CMake + defensive programming +- **Structure modules** : Factory, Economy, Logistic + +### 🔄 En Cours +- **Player Integration** : Architecture Client/Server modulaire +- **InputModule** : Clavier/souris → JSON commands +- **NetworkModule** : WebSocket client/server communication +- **V1 Thin Client** : Server-authoritative avec latence acceptable + +### 📋 Prochaines Étapes +- **V1 Implementation** : Client Input + Server Authority +- **Multi-player testing** : 2+ joueurs synchronisĂ©s +- **Hot-reload validation** : Server modules sans disconnect client +- **V2 Planning** : Client prediction + shared logic + +--- + +## 💡 Philosophy + +**"Complexity through Simplicity"** : CrĂ©er un jeu AAA complexe via une architecture de modules simples, chacun comprĂ©hensible et modifiable par Claude Code en isolation totale. + +**RĂ©sultat** : DĂ©veloppement 10x plus rapide avec qualitĂ© maintenue. + +--- + +## 📋 Build Commands Quick Reference + +```bash +# Module development (autonomous) +cd modules/factory/ +cmake . && make factory-module # Build factory.so +./build/factory-module # Test standalone + +# Core system +cmake . && make warfactory-core # Build core engine +./build/bin/warfactory-engine # Run main engine + +# Full system +make warfactory-modules # Build all modules +make test-all-modules # Test all modules +``` + +## 🔧 Legacy Documentation + +### Ancienne Architecture (rĂ©fĂ©rence) +- **[Engines Documentation](./engines/)** - Anciens engines (supplantĂ© par modules) +- **[Client Documentation](./client/)** - Interface system +- **[Server Documentation](./serveur/)** - Coordination (supplantĂ© par IEngine) + +Ces documents restent utiles pour comprendre le design original, mais l'implĂ©mentation actuelle utilise l'architecture modulaire. \ No newline at end of file diff --git a/docs/architecture-modulaire.md b/docs/architecture-modulaire.md new file mode 100644 index 0000000..a4e633e --- /dev/null +++ b/docs/architecture-modulaire.md @@ -0,0 +1,351 @@ +# Architecture Modulaire pour Game Development avec Claude Code + +## Vue d'Ensemble + +L'architecture modulaire triple interface rĂ©volutionne le dĂ©veloppement de jeux complexes en rendant le code **Claude Code friendly** tout en maintenant la performance et la scalabilitĂ©. + +## đŸ—ïž Architecture Core : Triple Interface Pattern + +### Les 4 Interfaces Fondamentales + +```cpp +IEngine → Coordination gĂ©nĂ©rale (DebugEngine → HighPerfEngine → DataOrientedEngine) +IModuleSystem → StratĂ©gie d'exĂ©cution (Sequential → Threaded → Multithread → Cluster) +IModule → Logique mĂ©tier pure (TankModule.so, EconomyModule.so) +IIO → Communication (IntraIO → LocalIO → NetworkIO) +``` + +### SĂ©paration des ResponsabilitĂ©s + +#### IModule : Pure Game Logic +```cpp +class IModule { + virtual json process(const json& input) = 0; // PURE FUNCTION + virtual void initialize(const json& config) = 0; + virtual void shutdown() = 0; +}; +``` + +**Contraintes strictes** : +- **200-300 lignes maximum** par module +- **Aucune dĂ©pendance infrastructure** (threading, network, etc.) +- **JSON in/out uniquement** pour communication +- **Logic mĂ©tier pure** sans effets de bord + +#### IModuleSystem : Execution Strategy +```cpp +// MĂȘme interface, performance diffĂ©rente +SequentialModuleSystem → Debug/test (1 module Ă  la fois) +ThreadedModuleSystem → Chaque module dans son thread +MultithreadedModuleSystem → Pool de threads pour tasks +ClusterModuleSystem → Distribution sur plusieurs machines +``` + +#### IIO : Transport Layer +```cpp +// MĂȘme interface, transport diffĂ©rent +IntraIO → Appel direct (mĂȘme processus) +LocalIO → Named pipes/sockets (mĂȘme machine) +NetworkIO → TCP/WebSocket (rĂ©seau) +``` + +## 🎯 Objectif Principal : Claude Code Optimized Development + +### ProblĂšme RĂ©solu : Contexte Énorme +**Avant** : Claude Code doit comprendre 50K+ lignes interconnectĂ©es +**AprĂšs** : Claude Code travaille sur TankModule.cpp (200 lignes isolĂ©es) + +### Workflow RĂ©volutionnaire + +#### DĂ©veloppement ParallĂšle +```bash +# Instance Claude Code A +cd modules/tank/ +cmake . && make tank-module # Autonome, 0 dĂ©pendance + +# Instance Claude Code B +cd modules/economy/ +cmake . && make economy-module # ParallĂšle, 0 conflit + +# Instance Claude Code C +cd modules/ai/ +cmake . && make ai-module # SimultanĂ©, 0 friction +``` + +#### Testing IsolĂ© +```cpp +[Test] TankModule_ReceiveAttackCommand_ShouldFire() +{ + auto tank = LoadModule("tank.so"); + auto input = json{{"type", "attack"}, {"target", "enemy_1"}}; + + auto result = tank->process(input); + + EXPECT_EQ(result["action"], "fire"); + // Zero dĂ©pendance externe, test ultra-rapide +} +``` + +### Hot-Swappable Infrastructure + +#### Debugging → Performance → Scale +```cpp +// Bug multithread dans TankModule ? +// 1. Keep TankModule.so unchanged +// 2. Switch: MultithreadedModuleSystem → SequentialModuleSystem +// 3. Isolate: logic bug vs threading bug + +// Bug rĂ©seau ? +// 1. Keep TankModule.so unchanged +// 2. Switch: NetworkIO → IntraIO +// 3. Isolate: network bug vs game logic bug +``` + +**Avantage Ă©norme** : Debug infrastructure sans toucher Ă  la logique mĂ©tier ! + +## 🚀 Évolution Progressive Sans RĂ©gression + +### Performance Scaling +```cpp +// Phase 1 : Prototype +DebugEngine + SequentialModuleSystem + IntraIO +→ DĂ©veloppement ultra-rapide, Claude Code 100% focus logique + +// Phase 2 : Optimization +DebugEngine + ThreadedModuleSystem + IntraIO +→ Performance boost sans changer 1 ligne de game logic + +// Phase 3 : Production +HighPerfEngine + MultithreadedModuleSystem + LocalIO +→ Scale transparent, TankModule.so inchangĂ© + +// Phase 4 : MMO Scale +DataOrientedEngine + ClusterModuleSystem + NetworkIO +→ Distribution massive, mĂȘme logique mĂ©tier +``` + +### Migration Zero-Risk +- **TankModule.so reste identique** Ă  travers toutes les phases +- **Interface contracts prĂ©servĂ©s** → pas de rĂ©gression possible +- **A/B testing facile** : deux configurations en parallĂšle + +## đŸ› ïž Choix Architecturaux Pragmatiques + +### 1. Modding → YAGNI (You Aren't Gonna Need It) + +**ProblĂšme du Modding** : +- Hooks system = complexitĂ© architecturale Ă©norme +- Maintenance nightmare (API stability) +- Performance overhead permanent +- Cas d'usage incertain prĂ©-release + +**Solution pragmatique** : +- **Faire un jeu qui marche AVANT** de le rendre moddable +- 90% des "mods" = tweaker des valeurs → **Config system suffit** + +### 2. Config System = "Modding Gratuit" + +#### Architecture Smart Config +``` +Player edit → Server validation → Engine dispatch → Background recalc +``` + +#### Smart Recalculation Engine +```cpp +// Exemple : player modifie steel_plating.weight +ConfigChange steel_plating.weight → + ComponentTracker.getDependents() → [tank_mk1, tank_mk2, heavy_tank] → + DesignerEngine.scheduleRecalc() → + Background processing (spread over frames) +``` + +#### Hot-Reload Paradise +```json +// config/tanks.json +{ + "tank_mk1": { + "armor": 50, // ← Edit this + "speed": 35, // ← Or this + "cost": 1000 // ← Or this + } +} +``` +**Save file → Auto-reload → See changes instantly** + +### 3. Mode-Based Security System + +#### Dev Mode +- **Config changes autorisĂ©s** partout +- **Hot-reload paradise** pour dĂ©veloppement +- **Debugging tools** exposĂ©s + +#### Solo Mode +- **Player peut modder** son expĂ©rience +- **Local config override** autorisĂ© +- **Cheat-friendly** pour expĂ©rimentation + +#### Multiplayer Mode +- **Server autoritaire** sur toutes les configs +- **Anti-cheat automatique** via validation +- **Zero tolerance** pour modifications + +### 4. Anti-Cheat Psychologique 😈 + +**StratĂ©gie** : Cheat attempts → "bugs" simulĂ©s progressifs + +```cpp +class AntiCheatPsycho { + void onCheatDetected(CheatType type) { + switch(type) { + case SPEED_HACK: + simulateRandomLag(50ms, 500ms); + break; + case RESOURCE_HACK: + simulateVisualGlitches(tanks, 5%); + break; + case DAMAGE_HACK: + simulateDesync(movement, 2%); + break; + } + // Cheater se punit lui-mĂȘme → abandon plutĂŽt que ban+retry + } +}; +``` + +**RĂ©sultat** : Cheaters abandonnent d'eux-mĂȘmes, expĂ©rience propre pour lĂ©gitimes. + +## ⚙ Config System Intelligent + +### Architecture Technique + +``` +Client Config Editor → WebSocket → +Server Validation → +Config Dispatcher → +[TankModule, EconomyModule, FactoryModule] → +Background Recalculation → +Live Update +``` + +### Component Dependency Tracking +```cpp +class ConfigDependencyGraph { + // steel_plating change affects: + std::map> dependencies = { + {"materials.steel_plating.weight", {tank_mk1, tank_mk2, heavy_tank}}, + {"materials.steel_plating.cost", {economy_steel, factory_line_2}}, + {"weapons.cannon_75mm.damage", {tank_mk1, artillery_piece}} + }; + + void onConfigChange(ConfigKey key, json newValue) { + auto affected = dependencies[key]; + for(auto component : affected) { + DesignerEngine::scheduleRecalc(component); + } + } +}; +``` + +### Background Processing Smart +- **Frame-spread recalculation** : 1 tank par frame max +- **Priority queue** : tanks en combat = prioritĂ© haute +- **Lazy evaluation** : recalc seulement si component utilisĂ© + +## 🎼 Workflow de DĂ©veloppement RĂ©volutionnaire + +### Avant : Architecture Monolithique +``` +Edit code → Full compile (2-5 min) → Restart engine → Load save → Test +Total : 5-10 minutes par iteration +``` + +### AprĂšs : Architecture Modulaire +``` +Edit TankModule.cpp → Hot-reload (5 sec) → Test immediately +Edit config/tanks.json → Auto-reload (instant) → See changes live +Total : 5 seconds par iteration +``` + +### Claude Code Development Paradise + +#### Contexte Ultra-Simple +- **TankModule.cpp** : 200 lignes de logique tank pure +- **EconomyModule.cpp** : 250 lignes de market simulation +- **FactoryModule.cpp** : 180 lignes de production logic + +**ZĂ©ro infrastructure** dans le contexte Claude Code ! + +#### Autonomous Build System +```bash +cd modules/tank/ +cmake . # PAS cmake .. ! +make tank-module # → tank.so +./build/tank-module # Test isolĂ© +``` + +#### Parallel Development +- **3+ instances Claude Code** travaillent simultanĂ©ment +- **Zero conflicts** entre modules +- **Rapid iteration** sur logique pure + +## 🔄 Integration avec SystĂšme Existant + +### Migration Strategy +1. **Garder ancien code** comme fallback +2. **CrĂ©er modules** petit Ă  petit +3. **A/B test** ancien vs nouveau +4. **Switch progressif** module par module +5. **Retire ancien** une fois validĂ© + +### Backward Compatibility +```cpp +class LegacyTankSystem; // Ancien code +class TankModule; // Nouveau code + +class TankSystemProxy { + bool useNewSystem = config.getBool("use_new_tank_system"); + + json process(json input) { + if(useNewSystem) { + return newTankModule->process(input); + } else { + return legacyTankSystem->process(input); + } + } +}; +``` + +## 📊 MĂ©triques de SuccĂšs + +### DĂ©veloppement +- **Context size** : 50K+ lignes → 200-300 lignes +- **Iteration time** : 5-10 minutes → 5 seconds +- **Parallel development** : 1 dev → 3+ Claude instances +- **Bug isolation** : Weeks → Hours + +### Performance +- **Hot-reload time** : N/A → <5 seconds +- **Config changes** : Restart required → Instant +- **A/B testing** : Impossible → Trivial +- **Debugging** : Needle in haystack → Surgical precision + +### Maintenance +- **Module independence** : Tightly coupled → Zero dependencies +- **Testing** : Integration hell → Unit paradise +- **Deployment** : Monolith → Microservices-like +- **Scaling** : Rewrite → Configuration change + +--- + +## Conclusion + +L'architecture modulaire triple interface rĂ©sout **4 problĂšmes majeurs** du dĂ©veloppement de jeux complexes : + +1. **Claude Code Efficiency** : Contextes micro-simples (200 lignes vs 50K+) +2. **Development Velocity** : Hot-reload + config system + parallel dev +3. **Performance Scaling** : Évolution progressive sans rĂ©gression +4. **Security & Deployment** : Anti-cheat intĂ©grĂ© + mode-based system + +**RĂ©sultat** : DĂ©veloppement 10x plus rapide avec maintien de la qualitĂ© et performance AAA. + +Cette architecture est particuliĂšrement rĂ©volutionnaire pour le **dĂ©veloppement avec IA**, oĂč la limitation principale est la taille du contexte que l'IA peut traiter efficacement. \ No newline at end of file diff --git a/docs/claude-code-integration.md b/docs/claude-code-integration.md new file mode 100644 index 0000000..3cc35c5 --- /dev/null +++ b/docs/claude-code-integration.md @@ -0,0 +1,387 @@ +# IntĂ©gration Claude Code : Guide Technique + +## 🎯 Objectif : DĂ©veloppement IA-First + +Cette architecture est spĂ©cifiquement conçue pour **maximiser l'efficacitĂ© de Claude Code** dans le dĂ©veloppement de jeux complexes. + +## 🧠 Contraintes Cognitives de l'IA + +### ProblĂšme Fondamental : Context Window +- **Claude Code limite** : ~200K tokens de contexte +- **Jeu AAA typique** : 500K+ lignes de code interconnectĂ©es +- **RĂ©sultat** : IA ne peut pas apprĂ©hender le systĂšme complet + +### Solution : Micro-Contexts Autonomes +```cpp +// Au lieu de ça (impossible pour l'IA) : +TankSystem.cpp (5000 lignes) + +PhysicsEngine.cpp (8000 lignes) + +NetworkLayer.cpp (3000 lignes) + +GraphicsRenderer.cpp (12000 lignes) += 28000 lignes interconnectĂ©es + +// On fait ça (parfait pour l'IA) : +TankModule.cpp (200 lignes) += Logique pure, zĂ©ro dĂ©pendance +``` + +## đŸ—ïž Architecture Claude Code Friendly + +### Structure Cognitive Optimale + +``` +warfactory/ +├── modules/tank/ # 🎯 Claude travaille ICI +│ ├── CLAUDE.md # Instructions spĂ©cialisĂ©es +│ ├── CMakeLists.txt # Build autonome (cmake .) +│ ├── shared/ # Headers locaux +│ ├── src/TankModule.cpp # 200 lignes PURE logic +│ └── build/ # → tank.so +└── [reste du projet invisible pour Claude] +``` + +### Principe : Information Hiding Cognitif +- **Claude voit SEULEMENT** : TankModule.cpp + CLAUDE.md + interfaces +- **Claude ne voit JAMAIS** : Engine architecture, networking, threading +- **RĂ©sultat** : Focus 100% sur logique mĂ©tier + +## 📋 Workflow Claude Code OptimisĂ© + +### 1. Session Initialization +```bash +# Claude dĂ©marre TOUJOURS dans un module spĂ©cifique +cd modules/tank/ + +# Context loading minimal +files_to_read = [ + "CLAUDE.md", # 50 lignes d'instructions + "src/TankModule.cpp", # 200 lignes de logic + "shared/IModule.h" # 30 lignes d'interface +] +# Total : 280 lignes vs 50K+ dans architecture classique +``` + +### 2. Development Loop +```bash +# 1. Claude lit le contexte micro +read("src/TankModule.cpp") + +# 2. Claude modifie la logique pure +edit("src/TankModule.cpp") + +# 3. Test instantanĂ© +cmake . && make tank-module +./build/tank-module + +# 4. Hot-reload dans le jeu +# Aucune recompilation complĂšte ! +``` + +### 3. Parallel Development +```bash +# Instance Claude A +cd modules/tank/ && work_on("tank logic") + +# Instance Claude B +cd modules/economy/ && work_on("market simulation") + +# Instance Claude C +cd modules/ai/ && work_on("behavior trees") + +# Zero conflicts, parallel development +``` + +## 🎯 Instructions CLAUDE.md SpĂ©cialisĂ©es + +### Template Type par Module + +#### modules/tank/CLAUDE.md +```markdown +# Tank Module - Pure Combat Logic + +## Context +You work EXCLUSIVELY on tank behavior. No networking, no threading. + +## Responsibilities +- Movement: acceleration, turning, terrain interaction +- Combat: targeting, firing, armor calculations +- States: idle, moving, attacking, destroyed + +## Interface Contract +Input JSON: {"type": "move", "direction": "north", "speed": 0.8} +Output JSON: {"position": [x, y], "facing": angle, "status": "moving"} + +## File Limits +- TankModule.cpp: Max 250 lines +- Pure logic only: No sockets, threads, engine dependencies +- JSON in/out: All communication via JSON messages + +## Build Commands +cmake . && make tank-module # Builds tank.so +./build/tank-module # Test standalone + +NEVER leave this directory or reference parent paths! +``` + +#### modules/economy/CLAUDE.md +```markdown +# Economy Module - Pure Market Logic + +## Context +You work EXCLUSIVELY on economic simulation. No infrastructure. + +## Responsibilities +- Market dynamics: supply/demand, pricing +- Trading: buy/sell orders, market makers +- Economics: inflation, market cycles + +## Interface Contract +Input: {"type": "trade", "item": "steel", "quantity": 100, "action": "buy"} +Output: {"status": "executed", "price": 5.2, "total": 520.0} + +## Focus Areas +1. Market algorithms (supply/demand curves) +2. Price discovery mechanisms +3. Economic modeling + +NEVER reference networking, threading, or parent directories! +``` + +### Contraintes Strictes pour Claude +1. **NEVER `cd ..`** ou rĂ©fĂ©rence parent +2. **ALWAYS `cmake .`** (pas cmake ..) +3. **ONLY JSON communication** avec autres modules +4. **MAX 300 lignes** par fichier +5. **ZERO infrastructure code** dans le contexte + +## 🔧 Build System Cognitif + +### Autonomous Build : Zero Mental Overhead + +```cmake +# modules/tank/CMakeLists.txt +cmake_minimum_required(VERSION 3.20) +project(TankModule) # Self-contained + +# Everything local +include_directories(shared) +add_library(tank-module SHARED src/TankModule.cpp) + +# Local build directory +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build) +``` + +**Avantage Claude** : Aucun concept de "projet parent" Ă  comprendre ! + +### Hot-Reload pour Rapid Iteration +```cpp +// Engine hot-reload automatique +class ModuleLoader { + void reloadIfChanged(const std::string& modulePath) { + if(fileChanged(modulePath)) { + unloadModule(modulePath); + loadModule(modulePath); // Reload .so + // Game continue sans interruption ! + } + } +}; +``` + +**Workflow Claude** : Edit → Save → See changes instantly in game + +## đŸ§Ș Testing Strategy : AI-Optimized + +### Unit Tests IntĂ©grĂ©s +```cpp +// Dans TankModule.cpp +#ifdef TESTING +void runTests() { + // Test 1: Movement + auto input = json{{"type", "move"}, {"direction", "north"}}; + auto result = process(input); + assert(result["status"] == "moving"); + + // Test 2: Combat + input = json{{"type", "attack"}, {"target", "enemy_1"}}; + result = process(input); + assert(result["action"] == "fire"); + + std::cout << "✅ All tank tests passed!" << std::endl; +} +#endif +``` + +### Standalone Testing +```bash +# Claude peut tester sans le engine complet +cd modules/tank/ +make tank-module +./build/tank-module # Run standalone avec tests intĂ©grĂ©s +``` + +**Avantage IA** : Testing sans infrastructure complexe ! + +## 🔄 Hot-Reload Architecture + +### Module State Preservation +```cpp +class TankModule { +private: + json persistentState; // SauvegardĂ© lors hot-reload + +public: + json getState() override { + return persistentState; // Engine sauvegarde l'Ă©tat + } + + void setState(const json& state) override { + persistentState = state; // Restore aprĂšs reload + } +}; +``` + +### Seamless Development +1. **Claude modifie** TankModule.cpp +2. **Engine dĂ©tecte** file change +3. **Automatic save** module state +4. **Reload .so** avec nouveau code +5. **Restore state** → Game continue +6. **Test immediately** nouvelles modifications + +## 🎼 Debug Mode : IA Paradise + +### Debug Engine Features +```cpp +class DebugEngine : public IEngine { + // Execution step-by-step pour analyse + void stepMode() { processOneModule(); } + + // Logging dĂ©taillĂ© pour Claude + void verboseLogging() { + log("Module tank input: " + input.dump()); + log("Module tank output: " + output.dump()); + } + + // Module isolation pour debugging + void isolateModule(const std::string& name) { + // Run ONLY this module, others = mock + } +}; +``` + +### Claude Debug Workflow +```bash +# 1. Set debug mode +echo '{"debug_mode": true, "isolated_module": "tank"}' > config/debug.json + +# 2. Run with step mode +./warfactory-engine --step-mode + +# 3. Claude voit EXACT input/output de son module +# Perfect pour comprendre les interactions ! +``` + +## 📊 MĂ©triques Claude Code + +### Avant : Architecture Monolithique +- **Context size** : 50K+ lignes (impossible) +- **Build time** : 2-5 minutes +- **Iteration cycle** : Edit → Compile → Restart → Test (10+ min) +- **Bug localization** : Needle in haystack +- **Parallel work** : Impossible (conflicts) + +### AprĂšs : Architecture Modulaire +- **Context size** : 200-300 lignes (parfait) +- **Build time** : 5-10 secondes +- **Iteration cycle** : Edit → Hot-reload → Test (30 sec) +- **Bug localization** : Surgical precision +- **Parallel work** : 3+ Claude instances + +### ROI Development +- **Claude efficiency** : 10x improvement +- **Development speed** : 5x faster iteration +- **Code quality** : Higher (focused contexts) +- **Bug density** : Lower (isolated modules) + +## 🚀 Advanced Claude Patterns + +### Pattern 1: Progressive Complexity +```cpp +// Iteration 1: Basic tank (Claude commence simple) +class TankModule { + json process(const json& input) { + if(input["type"] == "move") return basicMove(); + return {{"status", "idle"}}; + } +}; + +// Iteration 2: Add combat (Claude Ă©tend) +json process(const json& input) { + if(input["type"] == "move") return advancedMove(); + if(input["type"] == "attack") return combat(); + return {{"status", "idle"}}; +} + +// Iteration 3: Add AI (Claude sophistique) +// Etc... Progression naturelle +``` + +### Pattern 2: Behavior Composition +```cpp +// Claude peut composer behaviors facilement +class TankModule { + MovementBehavior movement; + CombatBehavior combat; + AiBehavior ai; + + json process(const json& input) { + auto context = getCurrentContext(); + + if(ai.shouldMove(context)) return movement.process(input); + if(ai.shouldAttack(context)) return combat.process(input); + return ai.idle(context); + } +}; +``` + +### Pattern 3: Data-Driven Logic +```cpp +// Claude travaille avec config, pas hard-coding +class TankModule { + json tankConfig; // Loaded from config/tanks.json + + json process(const json& input) { + auto stats = tankConfig["tank_mk1"]; + auto speed = stats["max_speed"].get(); + auto armor = stats["armor_thickness"].get(); + + // Logic basĂ©e sur data, pas constantes + return processWithStats(input, speed, armor); + } +}; +``` + +## 🔼 Future Claude Integration + +### AI-Driven Development +1. **Claude gĂ©nĂšre** modules complets +2. **Hot-reload testing** automatique +3. **AI balancing** via config changes +4. **Behavior learning** from player data + +### Natural Language Debugging +```bash +# Future : Claude debug with natural language +claude> "Why is tank_mk1 slower than expected?" +debug> Analyzing TankModule... speed config: 35, current: 28 +debug> Issue found: terrain modifier not applied correctly +debug> Suggesting fix in TankModule.cpp line 142 +``` + +--- + +## Conclusion + +Cette architecture transforme Claude Code d'un **assistant de dĂ©veloppement** en **dĂ©veloppeur principal** capable de crĂ©er des systĂšmes de jeu complexes de maniĂšre autonome. + +**ClĂ© du succĂšs** : RĂ©duire la complexitĂ© cognitive Ă  un niveau oĂč l'IA peut exceller, tout en maintenant la puissance architecturale nĂ©cessaire pour un jeu AAA. \ No newline at end of file diff --git a/docs/player-integration.md b/docs/player-integration.md new file mode 100644 index 0000000..c389e7c --- /dev/null +++ b/docs/player-integration.md @@ -0,0 +1,397 @@ +# IntĂ©gration du Joueur dans l'Architecture Modulaire + +## 🎯 ProblĂšme IdentifiĂ© + +**Architecture modulaire parfaite... mais oĂč est le joueur ?** + +L'architecture triple interface actuelle gĂšre brillamment la logique mĂ©tier et la performance, mais il manque un Ă©lĂ©ment crucial : **l'interaction humaine**. + +### Gaps Actuels +- ❌ **Pas d'inputs** clavier/souris +- ❌ **Pas de rĂ©activitĂ© UI** temps rĂ©el +- ❌ **Client/Server separation** manquante +- ❌ **Multiplayer architecture** non dĂ©finie + +## 📋 Solution : Client/Server Modulaire + +### Architecture Duale ProposĂ©e + +``` +ClientEngine (Local, RĂ©actif) ←→ ServerEngine (DistribuĂ©, Autoritaire) +├─ InputModule ├─ TankModule +├─ UIModule ├─ CombatModule +├─ RenderModule ├─ EconomyModule +└─ NetworkModule └─ NetworkModule +``` + +### Principe : MĂȘme Architecture, Contexte DiffĂ©rent + +**Client Modules** : Focus UX, rĂ©activitĂ©, prĂ©diction +**Server Modules** : Focus logique, autoritĂ©, performance + +**Code Sharing** : Logique mĂ©tier identique, contexte d'exĂ©cution diffĂ©rent + +## 🚀 Plan de DĂ©veloppement : 2 Phases Progressives + +### **Phase 1 : V1 - Thin Client (Validation Rapide)** + +#### Objectifs V1 +- ✅ **Validation architecture** : Prouver que l'approche modulaire fonctionne +- ✅ **Focus core logic** : TankModule, CombatModule opĂ©rationnels +- ✅ **Gameplay jouable** : Latence acceptable pour validation concept +- ✅ **Claude Code friendly** : DĂ©veloppement parallĂšle client/server + +#### Architecture V1 : Simple & Efficace + +``` +ClientEngine (Thin) +├─ InputModule → Capture inputs → JSON messages +├─ NetworkModule → WebSocket client → Send to server +└─ RenderModule → Display server state → Simple rendering + +ServerEngine (All Logic) +├─ TankModule → Authoritative tank logic +├─ CombatModule → Game mechanics & physics +├─ EconomyModule → Market simulation +└─ NetworkModule → WebSocket server → Broadcast state +``` + +#### Flow V1 : Server-Authoritative + +``` +Player Input → ClientEngine → Network → ServerEngine → Game Logic → Network → ClientEngine → Display + 50ms 5ms 30ms 20ms 30ms 5ms 10ms +Total : ~150ms latency (acceptable pour validation) +``` + +#### DĂ©veloppement V1 : Claude Code Parallel + +```bash +# Instance Claude A : Client Input +cd modules/client/input/ +cmake . && make input-module # → input.so + +# Instance Claude B : Server Logic +cd modules/server/tank/ +cmake . && make tank-module # → tank.so + +# Instance Claude C : Network +cd modules/shared/network/ +cmake . && make network-module # → network.so +``` + +#### Modules V1 Implementation + +##### InputModule (Client) +```cpp +class InputModule : public ModuleBase { + json process(const json& input) override { + // Keyboard/mouse events → Structured commands + if(input["type"] == "keydown") { + if(input["key"] == "w") return {{"command", "move"}, {"direction", "north"}}; + if(input["key"] == "space") return {{"command", "attack"}}; + } + return {{"command", "idle"}}; + } +}; +``` + +##### NetworkModule (Client) +```cpp +class ClientNetworkModule : public ModuleBase { + json process(const json& input) override { + // Send commands to server via WebSocket + if(input["command"] != "idle") { + webSocketClient.send(input.dump()); + } + + // Receive server state updates + if(webSocketClient.hasMessage()) { + return json::parse(webSocketClient.receive()); + } + + return {{"status", "connected"}}; + } +}; +``` + +##### TankModule (Server) - **MĂȘme logique qu'avant !** +```cpp +class TankModule : public ModuleBase { + json process(const json& input) override { + // IDENTICAL logic to single-player version + if(input["command"] == "move") return handleMovement(input); + if(input["command"] == "attack") return handleCombat(input); + return getCurrentState(); + } +}; +``` + +### **Phase 2 : V2 - Client Prediction (Polish UX)** + +#### Objectifs V2 +- ✅ **RĂ©activitĂ© client** : Illusion 0ms lag via prĂ©diction +- ✅ **Code sharing** : Logique mĂ©tier partagĂ©e client/server +- ✅ **Smooth gameplay** : Corrections invisibles, UX fluide +- ✅ **Competitive ready** : Performance multijoueur AAA + +#### Architecture V2 : Shared Logic + Prediction + +``` +SharedGameLogic.so (Code Commun) +├─ TankLogic.cpp +├─ CombatLogic.cpp +└─ PhysicsLogic.cpp + +ClientEngine (Predictive) ServerEngine (Authoritative) +├─ ClientTankModule (Shared + prediction) ├─ ServerTankModule (Shared + validation) +├─ SyncModule (reconciliation) ├─ ValidationModule (anti-cheat) +└─ PredictionModule (client-side) └─ PersistenceModule (save/load) +``` + +#### Flow V2 : Client Prediction + Server Authority + +``` +Player Input → Immediate Client Prediction + Network to Server → Server Validation → Client Reconciliation + 0ms 5ms 30ms 20ms 5ms +User Experience : 0ms (predicted), Corrections invisibles +``` + +#### Migration V1 → V2 : Zero-Risk Evolution + +```cpp +// 1. Extract Shared Logic (TankModule → SharedTankLogic.so) +class SharedTankLogic { + static json CalculateMovement(const json& tank, const json& input) { + // SINGLE SOURCE OF TRUTH for both client & server + return processMovement(tank, input); + } +}; + +// 2. Client Prediction (ClientTankModule) +class ClientTankModule : public ModuleBase { + json process(const json& input) override { + // Immediate prediction using shared logic + auto predicted = SharedTankLogic::CalculateMovement(currentState, input); + + // Send to server for validation + networkModule.send(input); + + return predicted; // Display immediately + } +}; + +// 3. Server Validation (ServerTankModule) +class ServerTankModule : public ModuleBase { + json process(const json& input) override { + // Authoritative calculation using SAME shared logic + auto authoritative = SharedTankLogic::CalculateMovement(serverState, input); + + // Anti-cheat validation + if(validateInput(input)) { + return authoritative; + } + + return {{"error", "invalid_input"}}; + } +}; +``` + +## đŸ› ïž Implementation Strategy + +### DĂ©veloppement V1 : Thin Client + +#### 1. Client Modules +```bash +modules/client/ +├─ input/ # InputModule : Clavier/souris → JSON +├─ render/ # RenderModule : Server state → Display +└─ network/ # NetworkModule : WebSocket client +``` + +#### 2. Server Modules (Extension Actuelle) +```bash +modules/server/ +├─ tank/ # TankModule : Combat logic (EXISTING) +├─ economy/ # EconomyModule : Market logic (EXISTING) +├─ network/ # NetworkModule : WebSocket server +└─ persistence/ # PersistenceModule : Save/load state +``` + +#### 3. Shared Infrastructure +```bash +modules/shared/ +├─ protocol/ # ProtocolModule : Client/server messages +├─ serialization/ # SerializationModule : JSON optimization +└─ compression/ # CompressionModule : Network optimization +``` + +### DĂ©veloppement V2 : Shared Logic + +#### 1. Logic Extraction +```bash +modules/shared/logic/ +├─ tank-logic/ # SharedTankLogic.so +├─ combat-logic/ # SharedCombatLogic.so +└─ physics-logic/ # SharedPhysicsLogic.so +``` + +#### 2. Client Prediction +```bash +modules/client/prediction/ +├─ tank-prediction/ # ClientTankModule with prediction +├─ sync/ # SyncModule : Reconciliation +└─ interpolation/ # InterpolationModule : Smooth corrections +``` + +#### 3. Server Authority +```bash +modules/server/authority/ +├─ validation/ # ValidationModule : Anti-cheat +├─ simulation/ # SimulationModule : Server-side physics +└─ persistence/ # PersistenceModule : World state +``` + +## 🎼 Claude Code Development Workflow + +### V1 Development : Parallel Instances + +```bash +# Claude Instance A : Client Input +cd modules/client/input/ +# Context : 200 lignes input handling +# Focus : Keyboard/mouse → JSON commands +# Build : cmake . && make input-module + +# Claude Instance B : Server Tank Logic +cd modules/server/tank/ +# Context : 250 lignes tank logic (EXISTING) +# Focus : Command processing, game state +# Build : cmake . && make tank-module + +# Claude Instance C : Network Protocol +cd modules/shared/protocol/ +# Context : 180 lignes network messages +# Focus : JSON serialization, WebSocket +# Build : cmake . && make protocol-module +``` + +### V2 Development : Shared Logic Focus + +```bash +# Claude Instance A : Shared Tank Logic +cd modules/shared/logic/tank/ +# Context : 200 lignes pure tank logic +# Focus : Movement, combat calculations +# Used by : BOTH client prediction AND server authority + +# Claude Instance B : Client Prediction +cd modules/client/prediction/tank/ +# Context : 150 lignes prediction + SharedTankLogic +# Focus : Immediate response, reconciliation +# Build : Links SharedTankLogic.so + +# Claude Instance C : Server Authority +cd modules/server/authority/tank/ +# Context : 180 lignes validation + SharedTankLogic +# Focus : Anti-cheat, persistence +# Build : Links SharedTankLogic.so +``` + +## 📊 Success Metrics & Validation + +### V1 Success Criteria +- [ ] **Player Control** : Tank respond to WASD + mouse +- [ ] **Multiplayer** : 2+ players see synchronized world +- [ ] **Hot-Reload** : Server modules reload without client disconnect +- [ ] **Latency** : <150ms acceptable for core gameplay validation +- [ ] **Claude Code** : 3+ parallel development instances + +### V2 Success Criteria +- [ ] **Instant Response** : Input feels 0ms via client prediction +- [ ] **Smooth Corrections** : No jittering during server reconciliation +- [ ] **Logic Sync** : Client/server calculations stay identical +- [ ] **Hot-Reload** : Both engines support module hot-reload +- [ ] **Performance** : 60fps client, server handles 100+ concurrent players + +### Performance Targets + +#### V1 Targets (Validation) +- **Client FPS** : 30+ fps stable +- **Server Capacity** : 10+ concurrent players +- **Network** : 150ms acceptable latency +- **Development** : Claude Code 200-line contexts + +#### V2 Targets (Production) +- **Client FPS** : 60+ fps with prediction +- **Server Capacity** : 100+ concurrent players +- **Network** : 30ms server latency, 0ms perceived client latency +- **Development** : Shared logic reduces duplication by 80% + +## 🎯 Development Priority & Timeline + +### Immediate : Start V1 (80% effort) +1. **Week 1-2** : InputModule + NetworkModule basique +2. **Week 3-4** : Server TankModule integration + basic rendering +3. **Week 5-6** : Multi-player testing + hot-reload validation +4. **Week 7-8** : Polish V1 + documentation + +### Future : V2 When V1 Stable (20% effort) +1. **Extract** : Shared logic from working V1 modules +2. **Implement** : Client prediction with shared logic +3. **Test** : Prediction accuracy vs server authority +4. **Deploy** : Seamless V1 → V2 migration + +### Development Philosophy +- **V1 first** : Prove architecture works end-to-end +- **Claude Code optimized** : 200-line contexts maintained +- **Hot-reload everywhere** : Both client and server modules +- **Progressive enhancement** : V1 → V2 without code rewrite + +## 🔄 Integration avec Architecture Existante + +### Extension Naturelle +L'architecture modulaire actuelle **s'Ă©tend parfaitement** pour supporter client/server : + +```cpp +// EXISTING : Single-player modules +TankModule.so → Pure tank logic + +// V1 EXTENSION : Server-side modules +ServerTankModule.so → Same logic + network authority + +// V2 EVOLUTION : Client + Server + Shared +SharedTankLogic.so → Pure logic (used by both) +ClientTankModule.so → SharedLogic + prediction +ServerTankModule.so → SharedLogic + validation +``` + +### Code Reuse Maximized +- **0% rewrite** : TankModule.cpp devient ServerTankModule.cpp +- **Logic preserved** : MĂȘme algorithmes, contexte d'exĂ©cution diffĂ©rent +- **Claude Code contexts** : Toujours 200-300 lignes par module +- **Hot-reload maintained** : Architecture triple interface intacte + +## 🎼 User Experience Vision + +### V1 Experience : Functional +- **Responsive** : 150ms latency acceptable pour validation +- **Multiplayer** : Joueurs voient le mĂȘme monde +- **Development** : Hot-reload permet iteration rapide + +### V2 Experience : Polished +- **Instant** : Inputs feel immediate via prediction +- **Smooth** : Corrections invisibles Ă  l'utilisateur +- **Competitive** : PrĂȘt pour gameplay multijoueur sĂ©rieux + +**RĂ©sultat** : Architecture modulaire + Player integration = **Jeu AAA dĂ©veloppĂ© avec Claude Code** Ă  vitesse rĂ©volutionnaire ! 🚀 + +--- + +## Conclusion + +L'intĂ©gration du joueur dans l'architecture modulaire suit la mĂȘme philosophie : + +**"Complexity through Simplicity"** : Chaque module (client ou server) reste simple (200 lignes), mais l'ensemble crĂ©e une expĂ©rience multijoueur complexe et performante. + +**Claude Code** continue Ă  travailler sur des contextes micro-simples, mais produit maintenant un **jeu multijoueur complet** ! \ No newline at end of file