Add factory optimization and transport economic system documentation
- Add factory-architecture-post-player.md: Performance-optimized factory engine * ProductionModule monolithic design for belt+inserter+factory performance * SIMD optimization analysis: too complex for Claude Code, prefer simplicity * War module complete isolation with distributed sub-systems * Economic simulation: Victoria 3-level complexity with progressive sophistication * Performance-driven architecture: critical local, strategic distributed - Add transport-economic-system.md: Comprehensive transport and economic simulation * Transport mode hierarchy: ship/train/air/truck with pure cost optimization * Market mechanics: economic phases, order stacking, dynamic pricing * Trading companies: arbitrage, optimization, market making business models * Geographic economics: infrastructure ROI, regional specialization * Player-agnostic design: pure economic simulation without artificial advantages - Update README.md: Reflect current development focus * Updated current work to transport and economic systems * Next steps aligned with new module implementations * Documentation structure expanded with new technical reports Technical highlights: - Transport cost optimization: 0.10€/kg ship vs 5.00€/kg truck (50x difference) - Volume thresholds: 1000t minimum for ship transport economic viability - Infrastructure access binary: competitive moat through geographic advantages - Market clearing algorithm: efficient price discovery with transport constraints - Economic realism: natural geographic specialization and infrastructure ROI 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
df0e9d0629
commit
40e59964da
@ -12,6 +12,8 @@ Warfactory est un jeu de simulation industrielle militaire inspiré de Factorio,
|
||||
- **[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
|
||||
- **[Factory Architecture Post-Player](factory-architecture-post-player.md)** - 🔥 **NOUVEAU** : Factory engine optimisé
|
||||
- **[Transport Economic System](transport-economic-system.md)** - 🔥 **NOUVEAU** : Système transport & économique
|
||||
|
||||
### Systèmes de Jeu
|
||||
- **[Gameplay Industriel](gameplay-industriel.md)** - Production, ressources, optimisation
|
||||
@ -111,16 +113,16 @@ cmake . && make factory-module # → factory.so
|
||||
- **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
|
||||
- **Transport System** : Mode hierarchy (ship/train/air/truck) avec cost optimization
|
||||
- **Market Mechanics** : Economic phases, order stacking, dynamic pricing
|
||||
- **Trading Companies** : Arbitrage, transport optimization, market making
|
||||
- **Geographic Economics** : Infrastructure investment, regional specialization
|
||||
|
||||
### 📋 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
|
||||
- **TradingModule Implementation** : Business models (arbitrage, optimization, market making)
|
||||
- **MarketModule Implementation** : Economic phases, order matching, price discovery
|
||||
- **InfrastructureModule Implementation** : ROI calculation, regional development
|
||||
- **Integration Testing** : Transport system avec ProductionModule
|
||||
|
||||
---
|
||||
|
||||
|
||||
431
docs/factory-architecture-post-player.md
Normal file
431
docs/factory-architecture-post-player.md
Normal file
@ -0,0 +1,431 @@
|
||||
# Rapport : Architecture Factory Game Post-Intégration Joueur
|
||||
|
||||
## 🏗️ Factory Engine & Optimisation de Performance
|
||||
|
||||
### Leçons Factorio (Analyse des Devlogs)
|
||||
|
||||
L'analyse des devlogs de Factorio révèle des optimisations cruciales pour les factory games :
|
||||
|
||||
#### Transport Lines Revolution
|
||||
- **Merger segments adjacents** : Fusionner les tapis roulants contigus en lignes logiques uniques
|
||||
- **Gains de performance** : x50-100 amélioration via réduction complexité algorithmique
|
||||
- **Principe** : Traiter une ligne de 100 segments comme 1 entité plutôt que 100 entités séparées
|
||||
|
||||
#### Compression Caching Intelligent
|
||||
- **Items "collés"** : Une fois optimisés, ils restent dans cet état
|
||||
- **Cache des gaps** : Mémoriser les espaces vides pour optimisation O(1)
|
||||
- **Principe** : Éviter recalculation constante d'états stables
|
||||
|
||||
#### Bulk Inserters Strategy
|
||||
- **Attendre main pleine** : Différer mouvement jusqu'à stack optimal
|
||||
- **Garantir efficacité** : Maximiser items par transfert
|
||||
- **Principe** : Batch operations vs individual transfers
|
||||
|
||||
#### SIMD & Vectorization
|
||||
- **Processing parallèle** : 8+ items simultanément avec AVX2
|
||||
- **Gains massifs** : Performance x4-8 sur opérations critiques
|
||||
- **Complexité élevée** : Optimisation manuelle requise
|
||||
|
||||
### Décision Architecture Performance
|
||||
|
||||
**SIMD = Trop complexe pour Claude Code**
|
||||
|
||||
**Analyse coût/bénéfice** :
|
||||
- ✅ **Gains** : Performance x4-8 sur boucles critiques
|
||||
- ❌ **Coûts** : Code complexe, debugging difficile, contexte Claude Code explosé
|
||||
|
||||
**Solutions alternatives** :
|
||||
- **Compiler auto-vectorization** : GCC/Clang optimisations automatiques
|
||||
- **Abstraction layers** : Libraries tierces (Intel TBB, etc.)
|
||||
- **GPU compute** : Déléguer calculs lourds au GPU
|
||||
- **Privilégier simplicité** : Architecture maintenable vs optimisation prématurée
|
||||
|
||||
## 🎯 Architecture Modulaire Factory
|
||||
|
||||
### Règle d'Or de Distribution
|
||||
|
||||
**Performance-Based Module Distribution** :
|
||||
|
||||
```
|
||||
Performance CRITIQUE → Same Module (belt+inserter+factory)
|
||||
Performance IMPORTANTE → Same Process (logic, UI)
|
||||
Performance MOYENNE → Same Machine (audio, debug)
|
||||
Performance INDIFF → Network (analytics, telemetry)
|
||||
```
|
||||
|
||||
### ProductionModule = Monolithe Nécessaire
|
||||
|
||||
**Décision architecturale clé** : Belt + Inserter + Factory DOIVENT cohabiter
|
||||
|
||||
#### Justification Technique
|
||||
- **Interactions frame-perfect** : 60fps timing critique
|
||||
- **Interdépendances serrées** : Item transfer nécessite coordination exacte
|
||||
- **ISocket overhead** : Communication inter-module trop lente (>1ms inacceptable)
|
||||
- **Performance native** : Appels directs vs sérialisation JSON
|
||||
|
||||
#### Trade-off Accepté
|
||||
- **Modularité** : Sacrifiée pour ProductionModule
|
||||
- **Performance** : Priorité absolue sur factory core
|
||||
- **Claude Code** : Module plus gros (500-800 lignes) mais logique cohérente
|
||||
|
||||
### Autres Modules Restent Séparés
|
||||
|
||||
Les systèmes non-critiques maintiennent la modularité :
|
||||
|
||||
#### PowerModule (Distribution Énergie)
|
||||
- **Responsabilités** : Génération, distribution, stockage énergie
|
||||
- **Performance** : Updates périodiques (10Hz acceptable)
|
||||
- **Communication** : Via IIO avec ProductionModule
|
||||
|
||||
#### LogicModule (Automation)
|
||||
- **Responsabilités** : Circuits, combinators, automation intelligente
|
||||
- **Performance** : Réactif mais pas frame-critical
|
||||
- **Communication** : Signals vers ProductionModule
|
||||
|
||||
#### LogisticModule (Transport Longue Distance)
|
||||
- **Responsabilités** : Trains, robots, transport inter-bases
|
||||
- **Performance** : Planification long-terme (1Hz acceptable)
|
||||
- **Communication** : Coordination avec ProductionModule
|
||||
|
||||
#### WarModule (Combat & Stratégie)
|
||||
- **Responsabilités** : Combat, défense, stratégie militaire
|
||||
- **Performance** : Décisions stratégiques (0.1Hz acceptable)
|
||||
- **Communication** : Isolation complète avec ProductionModule
|
||||
|
||||
## ⚔️ War Module Architecture
|
||||
|
||||
### Isolation Gameplay Complète
|
||||
|
||||
**Principe fondamental** : Zero interaction directe ProductionModule ↔ WarModule
|
||||
|
||||
#### Séparation Stricte
|
||||
- **Pas d'inserters vers turrets** : Logistique autonome pour war assets
|
||||
- **Interface via LogisticModule** uniquement : Munitions, réparations transitent
|
||||
- **Combat isolated** : War logic complètement indépendant de factory logic
|
||||
|
||||
#### Avantages Architecture
|
||||
- **Debugging isolé** : Bug war ≠ crash factory
|
||||
- **Performance séparée** : War optimization n'impacte pas factory FPS
|
||||
- **Development parallèle** : Claude Code sur war logic sans comprendre factory
|
||||
|
||||
### War = Orchestrateur Tactique
|
||||
|
||||
**Décomposition en sous-systèmes spécialisés** :
|
||||
|
||||
#### TargetingModule
|
||||
- **Responsabilité** : Acquisition et tracking cibles
|
||||
- **Performance** : Real-time (60Hz) pour précision combat
|
||||
- **Algorithmes** : Line of sight, range calculation, target prioritization
|
||||
|
||||
#### MovementModule
|
||||
- **Responsabilité** : Coordination et déplacement unités
|
||||
- **Performance** : Smooth interpolation (30Hz)
|
||||
- **Algorithmes** : Formation keeping, collision avoidance, unit coordination
|
||||
|
||||
#### PathfindingModule
|
||||
- **Responsabilité** : Calcul routes optimales
|
||||
- **Performance** : Async computation (background threads)
|
||||
- **Algorithmes** : A*, hierarchical pathfinding, flow fields
|
||||
|
||||
#### TacticalModule
|
||||
- **Responsabilité** : Stratégie de bataille et décisions
|
||||
- **Performance** : Strategic thinking (1Hz)
|
||||
- **Algorithmes** : Decision trees, strategy evaluation, resource allocation
|
||||
|
||||
#### TacticalAnalyticsModule
|
||||
- **Responsabilité** : Intelligence et prédictions
|
||||
- **Performance** : Deep analysis (0.1Hz)
|
||||
- **Algorithmes** : Pattern recognition, threat assessment, predictive modeling
|
||||
|
||||
### Distribution Network Friendly
|
||||
|
||||
**War = Décisions stratégiques** (échelle temps : secondes/minutes)
|
||||
**Factory = Optimisation temps réel** (échelle temps : frames/millisecondes)
|
||||
|
||||
#### Latency Tolerance
|
||||
- **50-100ms acceptable** pour décisions tactiques
|
||||
- **Network distribution possible** pour tous sous-modules war
|
||||
- **Load balancing** : Spread war computation across servers
|
||||
|
||||
#### Scalability Natural
|
||||
- **Solo game** : War modules local
|
||||
- **Multiplayer** : War modules distribués par faction
|
||||
- **MMO** : War clusters par région géographique
|
||||
|
||||
## 🏭 Composition Factory Engine
|
||||
|
||||
### ProductionModule Complet
|
||||
|
||||
**Composants intégrés pour performance optimale** :
|
||||
|
||||
#### Production (Core Manufacturing)
|
||||
- **Assemblers** : Recipe processing, input/output management
|
||||
- **Mining** : Resource extraction, ore processing
|
||||
- **Integration** : Direct memory access, zero-copy transfers
|
||||
|
||||
#### Transport (Unified Movement System)
|
||||
- **Belts** : Item transport, compression, line optimization
|
||||
- **Underground** : Tunneling, space efficiency
|
||||
- **Splitters** : Flow control, item routing
|
||||
- **Pipes** : Fluid transport, pressure systems
|
||||
|
||||
#### Logistics (Item Transfer)
|
||||
- **Inserters** : Precise item movement, timing critical
|
||||
- **Filters** : Item selection, routing logic
|
||||
- **Stack optimization** : Bulk transfers, efficiency maximization
|
||||
|
||||
#### Storage (Inventory Management)
|
||||
- **Chests** : Static storage, capacity management
|
||||
- **Buffers** : Flow smoothing, production decoupling
|
||||
- **Inventaires** : Item tracking, slot management
|
||||
|
||||
### Évolution Progressive Belts
|
||||
|
||||
**Complexité croissante pour maintenir Claude Code compatibility** :
|
||||
|
||||
#### Phase 1 : Mono-item Belts (Claude Code Friendly)
|
||||
- **1 item type par belt** : Logique simple, 200 lignes code
|
||||
- **No lane splitting** : Éviter complexité algorithmique
|
||||
- **Direct transfer** : Item A → Item A uniquement
|
||||
|
||||
#### Phase 2 : Multi-item Belts
|
||||
- **Mixed items** : Multiple types sur même belt
|
||||
- **Simple queuing** : FIFO sans optimisation
|
||||
- **Claude Code** : 300 lignes, logique encore gérable
|
||||
|
||||
#### Phase 3 : Dual-lane Belts
|
||||
- **Left/right lanes** : Indépendance partielle
|
||||
- **Lane preference** : Routing intelligent
|
||||
- **Claude Code** : 400-500 lignes, limite complexity
|
||||
|
||||
#### Phase 4 : Full Factorio Complexity (SIMD Optimized)
|
||||
- **Advanced compression** : Gap elimination, chunk processing
|
||||
- **Vector operations** : AVX2 parallel processing
|
||||
- **Human Code** : Optimisation manuelle, SIMD intrinsics
|
||||
|
||||
### Data Layout Future-Proof
|
||||
|
||||
**Structure SOA (Structure of Arrays) dès le début** :
|
||||
|
||||
```cpp
|
||||
// SOA Layout pour SIMD readiness
|
||||
struct BeltSystem {
|
||||
std::vector<float> positions_x; // [x0, x1, x2, x3, ...]
|
||||
std::vector<float> positions_y; // [y0, y1, y2, y3, ...]
|
||||
std::vector<int> item_types; // [t0, t1, t2, t3, ...]
|
||||
std::vector<float> speeds; // [s0, s1, s2, s3, ...]
|
||||
};
|
||||
|
||||
// Future SIMD processing ready:
|
||||
// __m256 pos_x = _mm256_load_ps(&positions_x[i]);
|
||||
```
|
||||
|
||||
**Avantages** :
|
||||
- **SIMD ready** : Pas de refactoring data layout futur
|
||||
- **Cache efficient** : Memory access patterns optimaux
|
||||
- **Claude Code compatible** : Simple vectors, pas de complex structs
|
||||
|
||||
## 💰 Simulation Économique Complexe
|
||||
|
||||
### Full Economic Simulation Vision
|
||||
|
||||
**Objectif** : Victoria 3-level economic complexity dans factory game context
|
||||
|
||||
#### PopulationModule (Demographics)
|
||||
- **Classes démographiques** : Workers, Engineers, Managers avec besoins différentiés
|
||||
- **Population growth** : Birth/death rates, migration patterns
|
||||
- **Social mobility** : Education, promotion, class transitions
|
||||
|
||||
#### MarketModule (Price Discovery)
|
||||
- **Supply/demand dynamics** : Real-time price adjustment
|
||||
- **Market makers** : AI traders, liquidity provision
|
||||
- **Price volatility** : Speculation, market shocks, bubbles
|
||||
|
||||
#### MoneyModule (Monetary System)
|
||||
- **Currency flow** : Money creation, circulation, destruction
|
||||
- **Banking system** : Loans, interest rates, credit
|
||||
- **Inflation modeling** : Money supply effects, price indexes
|
||||
|
||||
#### TradeModule (International Commerce)
|
||||
- **Import/export** : International trade flows
|
||||
- **Exchange rates** : Currency valuation, forex markets
|
||||
- **Trade policies** : Tariffs, quotas, trade agreements
|
||||
|
||||
#### PolicyModule (Government Intervention)
|
||||
- **Fiscal policy** : Taxation, government spending
|
||||
- **Monetary policy** : Interest rates, money supply control
|
||||
- **Regulation** : Industry oversight, market intervention
|
||||
|
||||
### Complexité Progressive
|
||||
|
||||
**Start Simple → Scale Complex** :
|
||||
|
||||
#### Phase 1 : Basic Economics
|
||||
- **1 population class** : Generic workers
|
||||
- **5 core goods** : Iron, copper, coal, steel, circuits
|
||||
- **Simple supply/demand** : Linear price adjustment
|
||||
|
||||
#### Phase 2 : Intermediate Economics
|
||||
- **3 population classes** : Workers, engineers, managers
|
||||
- **20 goods categories** : Expanded resource tree
|
||||
- **Market dynamics** : Price volatility, speculation
|
||||
|
||||
#### Phase 3 : Complex Economics
|
||||
- **Full demographic model** : Age, education, skills
|
||||
- **100+ goods** : Complete production chains
|
||||
- **Advanced policies** : Government intervention, regulation
|
||||
|
||||
#### Configuration-Driven Complexity
|
||||
```json
|
||||
{
|
||||
"economic_complexity": "intermediate",
|
||||
"population_classes": 3,
|
||||
"market_volatility": 0.15,
|
||||
"government_intervention": true
|
||||
}
|
||||
```
|
||||
|
||||
### Emergent Behavior Objectif
|
||||
|
||||
**Economic Events Cascade Through System** :
|
||||
|
||||
#### Resource Discovery Chain
|
||||
1. **New ore deposit found** → Increased supply
|
||||
2. **Ore prices crash** → Mining companies struggle
|
||||
3. **Workers migrate** → Regional population shift
|
||||
4. **New markets emerge** → Economic boom in region
|
||||
|
||||
#### War Economic Impact
|
||||
1. **Military conflict** → Supply chain disruption
|
||||
2. **Resource scarcity** → Price inflation
|
||||
3. **War production** → Economic restructuring
|
||||
4. **Post-war recession** → Market readjustment
|
||||
|
||||
#### Technology Economic Impact
|
||||
1. **Automation breakthrough** → Productivity gains
|
||||
2. **Labor displacement** → Unemployment spike
|
||||
3. **Wage pressure** → Social unrest
|
||||
4. **Government intervention** → Economic policy changes
|
||||
|
||||
#### Player Decision Ripples
|
||||
- **Factory expansion** → Local job creation → Population growth
|
||||
- **Resource hoarding** → Artificial scarcity → Price manipulation
|
||||
- **Technology research** → Industry disruption → Economic transformation
|
||||
|
||||
## 🔧 Architecture Finale Optimisée
|
||||
|
||||
### Core Game (Local Performance)
|
||||
|
||||
**Performance-critical systems remain local** :
|
||||
|
||||
```cpp
|
||||
ProductionModule {
|
||||
// Monolithe nécessaire pour performance
|
||||
Belt + Inserter + Factory + Storage
|
||||
// 500-800 lignes, acceptable pour Claude Code
|
||||
// Frame-perfect coordination, zero ISocket overhead
|
||||
}
|
||||
|
||||
LogicModule {
|
||||
// Automation réactive
|
||||
Circuits + Combinators + Smart Automation
|
||||
// 200-300 lignes, pure logic, Claude Code friendly
|
||||
}
|
||||
```
|
||||
|
||||
### Distributed Services (Network Tolerant)
|
||||
|
||||
**Strategic systems leverage network distribution** :
|
||||
|
||||
```cpp
|
||||
PowerModule {
|
||||
// Updates périodiques (10Hz acceptable)
|
||||
Generation + Distribution + Storage
|
||||
// Network latency irrelevant for power planning
|
||||
}
|
||||
|
||||
LogisticModule {
|
||||
// Planification long-terme (1Hz acceptable)
|
||||
Trains + Robots + Inter-base Transport
|
||||
// Route planning can handle 50-100ms latency
|
||||
}
|
||||
|
||||
WarModule {
|
||||
// Stratégie militaire (0.1-1Hz acceptable)
|
||||
Targeting + Movement + Pathfinding + Tactical + Analytics
|
||||
// Strategic decisions tolerant to network delays
|
||||
}
|
||||
|
||||
EconomicModule {
|
||||
// Simulation complexe (0.01-0.1Hz acceptable)
|
||||
Population + Market + Money + Trade + Policy
|
||||
// Economic modeling happens on longer timescales
|
||||
}
|
||||
```
|
||||
|
||||
### Benefits Architecture Finale
|
||||
|
||||
#### Performance Optimization
|
||||
- **Critical systems local** : Zero network latency impact
|
||||
- **Strategic systems distributed** : Horizontal scaling possible
|
||||
- **Natural separation** : Performance requirements dictate architecture
|
||||
|
||||
#### Development Efficiency
|
||||
- **Claude Code** : Travaille sur modules simples (200-500 lignes)
|
||||
- **Human optimization** : Focus sur performance kernels critiques
|
||||
- **Parallel development** : Teams work on different performance tiers
|
||||
|
||||
#### Scaling Flexibility
|
||||
- **Solo laptop** : All modules local pour development
|
||||
- **Multiplayer server** : Critical local, strategic distributed
|
||||
- **MMO factory game** : Full distribution avec même architecture
|
||||
|
||||
#### Evolution Support
|
||||
- **Progressive complexity** : Start simple, add sophistication
|
||||
- **No architectural refactoring** : Module boundaries stable
|
||||
- **Performance tuning** : Individual module optimization
|
||||
|
||||
## 🎮 Gameplay Vision Unifiée
|
||||
|
||||
**Factory Game avec Simulation Économique Complète** :
|
||||
|
||||
### Gameplay Layers
|
||||
|
||||
#### Production Layer (Real-time, Local)
|
||||
- **Optimisation factory** : Belt throughput, inserter timing
|
||||
- **Resource flow** : Efficient material processing
|
||||
- **Performance critical** : 60fps responsive, frame-perfect
|
||||
|
||||
#### Automation Layer (Reactive, Local)
|
||||
- **Smart systems** : Circuits, combinators, adaptive logic
|
||||
- **Responsive control** : React to production changes
|
||||
- **Low latency** : Sub-second response times
|
||||
|
||||
#### Strategic Layer (Planned, Distributed)
|
||||
- **Military strategy** : Unit coordination, tactical planning
|
||||
- **Long-term decisions** : Base expansion, technology research
|
||||
- **Network tolerant** : Seconds to minutes decision cycles
|
||||
|
||||
#### Economic Layer (Emergent, Distributed)
|
||||
- **Market dynamics** : Supply/demand, price discovery
|
||||
- **Complex simulation** : Population, policies, international trade
|
||||
- **Deep computation** : Minutes to hours for complex economic modeling
|
||||
|
||||
### Unified Experience
|
||||
|
||||
**Chaque aspect du jeu optimisé selon ses contraintes naturelles** :
|
||||
|
||||
- **Factory optimization** → Immediate feedback, tactical decisions
|
||||
- **Economic strategy** → Long-term planning, strategic thinking
|
||||
- **Military coordination** → Medium-term tactics, resource allocation
|
||||
- **Automation intelligence** → Reactive adaptation, efficiency optimization
|
||||
|
||||
**Résultat** : Factory game qui évolue naturellement vers simulation économique complexe sans sacrifier performance core gameplay.
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
L'architecture post-intégration joueur révèle des trade-offs cruciaux entre modularité et performance. En acceptant un ProductionModule monolithique pour les systèmes critiques tout en maintenant la modularité pour les systèmes stratégiques, nous obtenons le meilleur des deux mondes :
|
||||
|
||||
**Performance native** où nécessaire + **Modularité Claude Code** où possible = **Factory game AAA avec développement IA-optimized**.
|
||||
545
docs/transport-economic-system.md
Normal file
545
docs/transport-economic-system.md
Normal file
@ -0,0 +1,545 @@
|
||||
# Rapport : Système Transport & Économique
|
||||
|
||||
## 🚛 Architecture Transport System
|
||||
|
||||
### Transport Mode Hierarchy
|
||||
|
||||
**Selection Cascade basée sur optimisation économique pure** :
|
||||
|
||||
```
|
||||
Decision Tree (Cost Optimization):
|
||||
1. Volume ≥ 1000t + Port Access → Bateau (0.10€/kg)
|
||||
2. Else + Rail Access → Train (0.50€/kg)
|
||||
3. Else + Airport Access → Air (2.00€/kg)
|
||||
4. Else → Camion (5.00€/kg)
|
||||
|
||||
Pas de facteur urgency - pure economic optimization
|
||||
```
|
||||
|
||||
#### Justification Économique
|
||||
- **Coût maritime** : 50x moins cher que camion (économies d'échelle massives)
|
||||
- **Seuil volume** : 1000 tonnes nécessaire pour rentabiliser navire
|
||||
- **Infrastructure binaire** : Access ou pas access, pas de gradients
|
||||
- **Simplification décisionnelle** : Arbre de décision clair pour IA
|
||||
|
||||
### Infrastructure Access Binary
|
||||
|
||||
**Propriétés géographiques des entreprises** :
|
||||
|
||||
```cpp
|
||||
struct CompanyLocation {
|
||||
bool hasPortAccess = false; // Access maritime
|
||||
bool hasRailAccess = false; // Access ferroviaire
|
||||
bool hasAirportAccess = false; // Access aérien
|
||||
bool alwaysTruckAccess = true; // Camion toujours disponible
|
||||
|
||||
float transportMultiplier() {
|
||||
// Geographic competitive advantage
|
||||
return hasPortAccess ? 0.10f :
|
||||
hasRailAccess ? 0.50f :
|
||||
hasAirportAccess ? 2.00f : 5.00f;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Avantage Concurrentiel Géographique
|
||||
- **Coastal locations** : Avantage économique structurel
|
||||
- **Inland accessible par rail** : Compromis coût/accessibilité
|
||||
- **Remote locations** : Coût transport élevé = premium prices
|
||||
- **Strategic positioning** : Infrastructure access = competitive moat
|
||||
|
||||
## 📊 Market Mechanics
|
||||
|
||||
### Order System (Passes Économiques)
|
||||
|
||||
**Phases économiques séquentielles** :
|
||||
|
||||
```
|
||||
Economic Cycle (24h):
|
||||
1. Offer Phase (6h): Producers submit sell orders
|
||||
2. Demand Phase (6h): Consumers submit buy orders
|
||||
3. Market Clearing (1h): Price discovery & matching
|
||||
4. Transport Assignment (1h): Mode selection per transaction
|
||||
5. Execution Phase (10h): Delivery + payment processing
|
||||
|
||||
Order Stacking Strategy:
|
||||
├─ Multiple sellers combine orders during Offer Phase
|
||||
├─ Volume aggregation unlock ship transport thresholds
|
||||
├─ Waiting mechanism incentivizes collaboration
|
||||
├─ Economic pressure creates natural cooperation
|
||||
```
|
||||
|
||||
#### Benefits Système Passes
|
||||
- **Price discovery efficient** : Concentration temporelle des échanges
|
||||
- **Volume optimization** : Incitation à collaboration pour seuils
|
||||
- **Market transparency** : Informations disponibles pour tous
|
||||
- **Strategic timing** : Players peuvent anticiper cycles
|
||||
|
||||
### Dynamic Pricing Mechanism
|
||||
|
||||
**Formation des prix multi-facteurs** :
|
||||
|
||||
```cpp
|
||||
class PriceFormation {
|
||||
float calculatePrice(Good good, Region region) {
|
||||
float basePrice = supplyDemandEquilibrium(good);
|
||||
float transportPremium = calculateTransportCosts(region);
|
||||
float scarcityMultiplier = getScarcityPressure(good, region);
|
||||
float regionGradient = getRegionalPriceGradient(good, region);
|
||||
|
||||
return basePrice * (1 + transportPremium + scarcityMultiplier + regionGradient);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Price Formation Components
|
||||
|
||||
##### Base Price (Supply/Demand Equilibrium)
|
||||
- **Market clearing price** : Intersection offre/demande
|
||||
- **Global reference** : Prix de base mondial
|
||||
- **Volatility buffer** : Mécanismes anti-manipulation
|
||||
|
||||
##### Transport Cost Limits (Buyer-Defined)
|
||||
- **Maximum transport %** : Buyers set acceptable transport cost ratio
|
||||
- **Example** : "Transport max 15% of goods value"
|
||||
- **Market filtering** : Orders rejected if transport too expensive
|
||||
- **Geographic arbitrage limits** : Natural price convergence mechanism
|
||||
|
||||
##### Scarcity Premium (Desperation Bidding)
|
||||
- **Stock depletion** : Companies with low inventory bid premium
|
||||
- **Regional shortages** : Isolated regions pay survival premiums
|
||||
- **Urgent orders** : Rush delivery commands price multipliers
|
||||
- **Market psychology** : Fear of shortage drives irrational bidding
|
||||
|
||||
##### Regional Price Gradients (Geographic Arbitrage)
|
||||
```
|
||||
Price Examples (Iron):
|
||||
├─ Coastal Region: 10€/kg (baseline + ship transport)
|
||||
├─ Rail Accessible: 11€/kg (baseline + rail premium)
|
||||
├─ Airport Only: 20€/kg (baseline + air premium)
|
||||
├─ Remote Truck: 50€/kg (baseline + truck premium + scarcity)
|
||||
```
|
||||
|
||||
## 🏗️ Storage & Inventory System
|
||||
|
||||
### Company Storage Strategy
|
||||
|
||||
**Adaptive Inventory Management basée sur niveaux de stock** :
|
||||
|
||||
```cpp
|
||||
enum InventoryStrategy {
|
||||
DESPERATE, // Stock < 20% → Premium bidding
|
||||
NORMAL, // Stock 20-50% → Market price buying
|
||||
CAUTIOUS, // Stock 50-80% → Opportunistic buying only
|
||||
OVERSUPPLIED // Stock > 80% → Stop purchasing
|
||||
};
|
||||
|
||||
class InventoryManager {
|
||||
PurchaseDecision evaluate(float stockLevel, float marketPrice) {
|
||||
if(stockLevel < 0.20f) return {true, marketPrice * 1.5f}; // Desperate
|
||||
if(stockLevel < 0.50f) return {true, marketPrice}; // Normal
|
||||
if(stockLevel < 0.80f) return {false, marketPrice * 0.8f}; // Opportunistic
|
||||
return {false, 0.0f}; // Stop buying
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Inventory Trade-offs
|
||||
- **Large inventory** : Security vs storage costs (€0.02/kg/day)
|
||||
- **Small inventory** : Lower costs vs supply chain risk
|
||||
- **Timing optimization** : Buy during market oversupply
|
||||
- **Geographic arbitrage** : Coastal storage → Inland distribution
|
||||
|
||||
### Bulk Purchase Cycles
|
||||
|
||||
**Natural market pulse patterns** :
|
||||
|
||||
```
|
||||
Market Cycle Pattern:
|
||||
1. Multiple companies hit 20% stock simultaneously
|
||||
2. Competing desperate bids create price spikes
|
||||
3. Large combined volumes enable ship transport unlock
|
||||
4. Price normalization as inventory restored
|
||||
5. Market oversupply as orders arrive simultaneously
|
||||
6. Price correction downward
|
||||
7. Cycle repeats with natural frequency
|
||||
```
|
||||
|
||||
#### Emergent Behavior
|
||||
- **Synchronized depletion** : Similar consumption patterns
|
||||
- **Bidding wars** : Scarcity-driven competition
|
||||
- **Transport optimization** : Volume consolidation benefits
|
||||
- **Natural cycles** : Self-organizing market rhythms
|
||||
|
||||
## 💼 Trading Companies
|
||||
|
||||
### Business Models Emergents
|
||||
|
||||
#### Pure Arbitrage Strategy
|
||||
```cpp
|
||||
class ArbitrageTrader {
|
||||
Strategy coastalToInland() {
|
||||
// 1. Buy coastal (cheap ship transport access)
|
||||
// 2. Store in strategic inland locations
|
||||
// 3. Sell to remote regions (premium prices)
|
||||
// Profit = Price differential - storage - transport
|
||||
return {buyCoastal, storeStrategic, sellRemote};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Transport Optimization Strategy
|
||||
```cpp
|
||||
class TransportOptimizer {
|
||||
Strategy aggregateSmallProducers() {
|
||||
// 1. Aggregate small producer outputs
|
||||
// 2. Combine orders to unlock ship thresholds
|
||||
// 3. Share transport savings with producers
|
||||
// Profit = Transport efficiency gains
|
||||
return {aggregateOrders, unlockShipping, shareGains};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Market Making Strategy
|
||||
```cpp
|
||||
class MarketMaker {
|
||||
Strategy stabilizeSupply() {
|
||||
// 1. Buffer supply volatility with inventory
|
||||
// 2. Provide reliable supply to consumers
|
||||
// 3. Smooth price fluctuations
|
||||
// Profit = Stability service premium
|
||||
return {bufferVolatility, guaranteeSupply, chargePremium};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Specialization Types
|
||||
|
||||
#### Geographic Specialists
|
||||
- **Regional expertise** : Deep knowledge specific areas
|
||||
- **Infrastructure relationships** : Port/rail access deals
|
||||
- **Local market intelligence** : Cultural/regulatory knowledge
|
||||
- **Logistics optimization** : Region-specific transport solutions
|
||||
|
||||
#### Commodity Specialists
|
||||
- **Deep vertical knowledge** : Single commodity expertise
|
||||
- **Quality assessment** : Grading, certification, standards
|
||||
- **Technical logistics** : Specialized handling, storage
|
||||
- **Market prediction** : Supply/demand pattern expertise
|
||||
|
||||
#### Logistics Specialists
|
||||
- **Transport optimization** : Multi-modal route planning
|
||||
- **Volume consolidation** : Order aggregation expertise
|
||||
- **Infrastructure leverage** : Maximum transport efficiency
|
||||
- **Timing coordination** : Economic cycle optimization
|
||||
|
||||
#### Financial Specialists
|
||||
- **Risk management** : Hedging, insurance, derivatives
|
||||
- **Futures markets** : Long-term contract management
|
||||
- **Credit facilities** : Financing for trade operations
|
||||
- **Currency hedging** : International trade protection
|
||||
|
||||
## 🌍 Geographic Economics
|
||||
|
||||
### Natural Economic Geography Evolution
|
||||
|
||||
#### Coastal Concentration Dynamics
|
||||
```
|
||||
Market Forces Sequence:
|
||||
1. Initial coastal rush (transport cost advantages)
|
||||
2. Land price premiums develop (scarcity)
|
||||
3. Congestion costs emerge (infrastructure limits)
|
||||
4. Port capacity bottlenecks (throughput limits)
|
||||
5. Labor shortage premiums (competition)
|
||||
6. Economic equilibrium reached (cost parity)
|
||||
```
|
||||
|
||||
#### Regional Specialization Patterns
|
||||
```cpp
|
||||
enum RegionType {
|
||||
RESOURCE_EXTRACTION, // Fixed by geological deposits
|
||||
MANUFACTURING_HUB, // Transport cost optimization
|
||||
TRADING_CENTER, // Infrastructure convergence
|
||||
CONSUMER_MARKET // Population concentration
|
||||
};
|
||||
|
||||
class RegionalSpecialization {
|
||||
RegionType determineOptimalFocus(Region region) {
|
||||
if(hasNaturalResources(region)) return RESOURCE_EXTRACTION;
|
||||
if(hasTransportHub(region)) return TRADING_CENTER;
|
||||
if(hasManufacturingCosts(region)) return MANUFACTURING_HUB;
|
||||
return CONSUMER_MARKET;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Infrastructure Investment Economics
|
||||
|
||||
#### Economic Justification Model
|
||||
```cpp
|
||||
class InfrastructureROI {
|
||||
bool justifyRailInvestment(Region region) {
|
||||
float currentTransportCosts = calculateTruckCosts(region);
|
||||
float projectedVolume = estimateTradeVolume(region);
|
||||
float railConstructionCost = calculateRailCost(region);
|
||||
float railOperatingCost = calculateRailOperations(region);
|
||||
|
||||
float savings = (currentTransportCosts - railOperatingCost) * projectedVolume;
|
||||
float paybackPeriod = railConstructionCost / savings;
|
||||
|
||||
return paybackPeriod < MAX_PAYBACK_YEARS;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Investment Triggers
|
||||
- **Sustained high transport costs** : Market signals infrastructure need
|
||||
- **Volume thresholds reached** : Economies of scale justify investment
|
||||
- **Regional economic pressure** : Political/social demand for development
|
||||
- **Competitive necessity** : Rival regions gaining advantages
|
||||
|
||||
### Infrastructure Impact Simulation
|
||||
```
|
||||
Pre-Rail Region:
|
||||
├─ Truck transport only (5.00€/kg)
|
||||
├─ High consumer prices
|
||||
├─ Limited economic activity
|
||||
├─ Population outmigration
|
||||
|
||||
Post-Rail Region:
|
||||
├─ Rail transport available (0.50€/kg)
|
||||
├─ 90% transport cost reduction
|
||||
├─ Economic boom, new businesses
|
||||
├─ Population influx, urbanization
|
||||
```
|
||||
|
||||
## ⚙️ Implementation Details
|
||||
|
||||
### Economic Agents (Player-Agnostic Design)
|
||||
|
||||
**Tous les entités = agents économiques** :
|
||||
|
||||
```cpp
|
||||
class EconomicAgent {
|
||||
public:
|
||||
virtual void submitOrders() = 0;
|
||||
virtual void processTransactions() = 0;
|
||||
virtual void updateStrategy() = 0;
|
||||
|
||||
// No special player privileges
|
||||
// Pure economic simulation
|
||||
};
|
||||
|
||||
class ProductionCompany : public EconomicAgent { ... };
|
||||
class ConsumptionCompany : public EconomicAgent { ... };
|
||||
class TransportCompany : public EconomicAgent { ... };
|
||||
class TradingCompany : public EconomicAgent { ... };
|
||||
class InfrastructureInvestor : public EconomicAgent { ... };
|
||||
```
|
||||
|
||||
#### Agent Equality Principle
|
||||
- **No player privileges** : Tous agents soumis aux mêmes règles
|
||||
- **Pure simulation** : Économie émergente sans intervention arbitraire
|
||||
- **Fair competition** : Success basé sur strategy, pas status
|
||||
- **Realistic behavior** : AI agents comportement économique rationnel
|
||||
|
||||
### Market Clearing Algorithm
|
||||
|
||||
**Order Matching Process** :
|
||||
|
||||
```cpp
|
||||
class MarketClearingEngine {
|
||||
void processMarketCycle() {
|
||||
// 1. Collect all orders from economic phases
|
||||
auto sellOrders = collectSellOrders();
|
||||
auto buyOrders = collectBuyOrders();
|
||||
|
||||
// 2. Sort for optimal matching
|
||||
std::sort(sellOrders.begin(), sellOrders.end(), priceAscending);
|
||||
std::sort(buyOrders.begin(), buyOrders.end(), priceDescending);
|
||||
|
||||
// 3. Match orders within transport cost limits
|
||||
auto matches = matchOrdersWithTransportLimits(sellOrders, buyOrders);
|
||||
|
||||
// 4. Apply volume consolidation for shipping
|
||||
auto consolidatedMatches = applyVolumeConsolidation(matches);
|
||||
|
||||
// 5. Calculate optimal transport modes
|
||||
for(auto& match : consolidatedMatches) {
|
||||
match.transportMode = selectOptimalTransport(match);
|
||||
}
|
||||
|
||||
// 6. Execute deliveries with realistic time delays
|
||||
scheduleDeliveries(consolidatedMatches);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Algorithm Benefits
|
||||
- **Economic efficiency** : Optimal price discovery
|
||||
- **Transport optimization** : Automatic mode selection
|
||||
- **Volume benefits** : Consolidation incentives
|
||||
- **Realistic timing** : Delivery delays based on transport mode
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
**Système de configuration économique** :
|
||||
|
||||
```json
|
||||
{
|
||||
"transport": {
|
||||
"ship_threshold_tonnes": 1000,
|
||||
"ship_cost_per_kg": 0.10,
|
||||
"train_cost_per_kg": 0.50,
|
||||
"air_cost_per_kg": 2.00,
|
||||
"truck_cost_per_kg": 5.00,
|
||||
"delivery_time_ship_days": 14,
|
||||
"delivery_time_train_days": 3,
|
||||
"delivery_time_air_days": 1,
|
||||
"delivery_time_truck_days": 2
|
||||
},
|
||||
"storage": {
|
||||
"cost_per_kg_per_day": 0.02,
|
||||
"urgent_stock_threshold": 0.20,
|
||||
"normal_stock_threshold": 0.50,
|
||||
"oversupplied_threshold": 0.80,
|
||||
"max_storage_capacity_multiplier": 10.0
|
||||
},
|
||||
"market": {
|
||||
"transport_cost_limit_percentage": 0.15,
|
||||
"order_stacking_wait_days": 7,
|
||||
"economic_phase_duration_hours": 6,
|
||||
"price_volatility_damping": 0.1,
|
||||
"scarcity_premium_multiplier": 2.0
|
||||
},
|
||||
"infrastructure": {
|
||||
"rail_construction_cost_per_km": 1000000,
|
||||
"port_construction_cost": 50000000,
|
||||
"airport_construction_cost": 100000000,
|
||||
"max_infrastructure_payback_years": 15
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Configuration Benefits
|
||||
- **Tunable economics** : Adjust economic parameters for gameplay
|
||||
- **Progressive complexity** : Start simple, add sophistication
|
||||
- **A/B testing** : Compare different economic models
|
||||
- **Regional variation** : Different parameters per geographic region
|
||||
|
||||
## 🎯 System Benefits & Integration
|
||||
|
||||
### Economic Realism Achievements
|
||||
|
||||
#### Natural Geographic Specialization
|
||||
- **Resource-based clustering** : Mining near deposits
|
||||
- **Manufacturing optimization** : Transport cost minimization
|
||||
- **Trading hub emergence** : Infrastructure convergence points
|
||||
- **Realistic urban development** : Economic forces drive settlement patterns
|
||||
|
||||
#### Infrastructure ROI Modeling
|
||||
- **Investment justification** : Economic case for infrastructure
|
||||
- **Regional transformation** : Infrastructure changes economic landscape
|
||||
- **Competitive dynamics** : Regions compete for transport access
|
||||
- **Long-term planning** : Infrastructure decisions have lasting impact
|
||||
|
||||
#### Market Cycle Emergence
|
||||
- **Natural rhythms** : Supply/demand cycles self-organize
|
||||
- **Price discovery** : Efficient market mechanisms
|
||||
- **Arbitrage opportunities** : Geographic and temporal price differences
|
||||
- **Risk/reward balance** : Higher profits require higher risks
|
||||
|
||||
### Emergent Complexity Demonstration
|
||||
|
||||
#### Trading Company Evolution
|
||||
- **Business model innovation** : New strategies emerge from economic pressure
|
||||
- **Specialization development** : Companies find profitable niches
|
||||
- **Market efficiency improvement** : Traders reduce transaction costs
|
||||
- **Economic ecosystem richness** : Multiple business models coexist
|
||||
|
||||
#### Regional Economic Development
|
||||
- **Coastal advantage phase** : Early transport cost benefits
|
||||
- **Infrastructure investment phase** : Economic pressure drives development
|
||||
- **Economic equilibrium phase** : Costs equalize across regions
|
||||
- **Competitive specialization phase** : Regions find comparative advantages
|
||||
|
||||
#### Supply Chain Sophistication
|
||||
- **Simple direct trade** → **Multi-hop arbitrage** → **Complex logistics networks**
|
||||
- **Individual transactions** → **Volume consolidation** → **Integrated supply chains**
|
||||
- **Local markets** → **Regional trade** → **Global economic integration**
|
||||
|
||||
### Simple Implementation Strategy
|
||||
|
||||
#### Clear Decision Trees
|
||||
```cpp
|
||||
TransportMode selectTransport(Order order, Route route) {
|
||||
if(order.volume >= 1000 && route.hasPortAccess()) return SHIP;
|
||||
if(route.hasRailAccess()) return TRAIN;
|
||||
if(route.hasAirportAccess()) return AIR;
|
||||
return TRUCK;
|
||||
}
|
||||
```
|
||||
|
||||
#### Binary Infrastructure Access
|
||||
- **No gradients** : Access or no access, simple boolean
|
||||
- **Clear competitive advantage** : Infrastructure = economic moat
|
||||
- **Easy AI reasoning** : Simple rules for AI decision-making
|
||||
- **Scalable complexity** : Add infrastructure types without algorithm changes
|
||||
|
||||
#### Modular Economic Components
|
||||
```cpp
|
||||
// Easy integration with existing architecture
|
||||
class TransportModule : public IModule { ... };
|
||||
class TradingModule : public IModule { ... };
|
||||
class InfrastructureModule : public IModule { ... };
|
||||
class MarketModule : public IModule { ... };
|
||||
```
|
||||
|
||||
### Scalability Architecture
|
||||
|
||||
#### Progressive Sophistication
|
||||
- **Phase 1** : Basic transport cost differences
|
||||
- **Phase 2** : Order stacking and volume optimization
|
||||
- **Phase 3** : Trading companies and arbitrage
|
||||
- **Phase 4** : Infrastructure investment and regional development
|
||||
- **Phase 5** : Complex economic simulation (Victoria 3-level)
|
||||
|
||||
#### Performance Scaling
|
||||
- **Local decisions** : Transport mode selection (real-time)
|
||||
- **Regional coordination** : Market clearing (hourly)
|
||||
- **Economic simulation** : Complex modeling (daily)
|
||||
- **Infrastructure planning** : Long-term investment (monthly)
|
||||
|
||||
### Player-Agnostic Benefits
|
||||
|
||||
#### Pure Economic Simulation
|
||||
- **No artificial advantages** : Players compete on equal terms
|
||||
- **Emergent strategies** : Success comes from economic insight
|
||||
- **Educational value** : Players learn real economic principles
|
||||
- **Sandbox flexibility** : Multiple valid approaches to success
|
||||
|
||||
#### AI Agent Integration
|
||||
- **Consistent behavior** : All agents follow same economic rules
|
||||
- **Realistic competition** : AI competitors use rational strategies
|
||||
- **Market depth** : Many agents create liquid markets
|
||||
- **Economic ecosystem** : Rich environment for player interaction
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
Le système transport & économique crée une **simulation économique réaliste** où :
|
||||
|
||||
- **Geographic advantages** émergent naturellement des coûts de transport
|
||||
- **Business models sophistiqués** évoluent des pressions économiques
|
||||
- **Infrastructure investment** suit la logique économique ROI
|
||||
- **Market dynamics** créent cycles et opportunités réalistes
|
||||
|
||||
**Ready for integration** dans l'architecture modulaire :
|
||||
- **ProductionModule** : Interface avec transport costs
|
||||
- **TradingModule** : Business logic des trading companies
|
||||
- **InfrastructureModule** : Investment et construction logic
|
||||
- **MarketModule** : Economic phases et price discovery
|
||||
|
||||
**Résultat** : **Economic simulation depth** comparable aux meilleurs strategy games, avec **implementation simplicity** compatible Claude Code development ! 🚛💰🏗️
|
||||
Loading…
Reference in New Issue
Block a user