Skip to main content

Server and Client Refactoring Plan

Goal​

Split the monolithic ServerMain.cs into a modular, maintainable architecture targeting 300 concurrent players, and restructure the Godot client to follow Godot conventions.

Where it stands​

The plan is partly done, not finished. The folders and some classes exist, but most game logic is still on the ServerMain class.

ServerMain.cs itself had grown to 15,760 lines. On 2026-11-11 it was split, member by member and unchanged, into files under Moondog.GameServer/ServerMain/ (Login.cs, Combat.cs, Pets.cs, Carts.cs, Broadcast.cs and so on), all partial class ServerMain. ServerMain.cs keeps the fields, _Ready, _Process and _PhysicsProcess. Put new code in the file for its feature, or a new one, and not back in ServerMain.cs. A new file with RPCs must be added to server_sources in rpc_contract.json.

What has been extracted and is used:

  • Network/SessionManager.cs, Network/PlayerSession.cs, Network/ActiveJobState.cs
  • DbWorker.cs, the background database queue
  • Data/Cache/: ItemCache, NodeTypeCache, CreatureCache, SkillNameCache
  • Gameplay/Crafting/CraftingManager.cs (station kinds, failure, tool wear, quality) and Gameplay/Gathering/GatheringLedger.cs (the staged gathering transaction)
  • Feature files beside ServerMain.cs: BirdFlight.cs, Karma.cs, CarryLoad.cs, AdminCharacterCommands.cs, ReplayLog.cs and the Npc*.cs dialogue, quest and relationship rules

What exists only as a stub: most of Gameplay/ — AI, Combat, Economy, Guild, Housing, Party, Quest, Spawning and WorldEvents — is 12–80 lines each, mostly constants. Modules/ModuleLoader.cs and IServerModule.cs exist but nothing loads modules through them. The RPC methods themselves are all still on ServerMain, because Godot routes RPCs by node path.

On the client, the autoloads in the target structure exist and are registered in project.godot, one per system. scripts/Network.gd (about 3,300 lines) is still the root node and still holds the RPC stubs and most of the networking. Sign-in and the character list are one screen, scenes/Login.tscn with scripts/Login.gd, a node of Main.tscn; the half-built scenes/auth/Login.tscn and CharacterSelect.tscn and the unused scenes/main/Main.gd from the first pass were removed 2026-11-12.

Everything below is the plan as it was written. Use it as the direction, not as a description of the code.

Server Refactoring Target Structure​

Moondog.GameServer/
├── Core/
│ ├── Server.cs # Entry point, main loop
│ ├── ServerConfig.cs # Configuration
│ └── IServerModule.cs # Module interface
├── Network/
│ ├── RpcHandler.cs # RPC registration/dispatch
│ ├── SessionManager.cs # PlayerSession lifecycle
│ └── PacketSerializer.cs # Custom serialization
├── Gameplay/
│ ├── Combat/
│ │ ├── CombatSystem.cs
│ │ ├── ActiveDefenseSystem.cs
│ │ └── ProjectileSystem.cs
│ ├── AI/
│ │ ├── CreatureAI.cs
│ │ ├── NavMeshManager.cs
│ │ └── ThreatSystem.cs
│ ├── Party/
│ │ ├── PartyManager.cs
│ │ └── LootDistributor.cs
│ ├── Guild/
│ │ ├── GuildManager.cs
│ │ └── GuildBank.cs
│ ├── Housing/
│ │ ├── HousingManager.cs
│ │ └── PlotSystem.cs
│ ├── Economy/
│ │ ├── TradeManager.cs
│ │ ├── AuctionHouse.cs
│ │ └── MarketData.cs
│ ├── Quest/
│ │ ├── QuestManager.cs
│ │ ├── ObjectiveTracker.cs
│ │ └── DialogueSystem.cs
│ ├── WorldEvents/
│ │ ├── EventManager.cs
│ │ └── ParticipationTracker.cs
│ ├── Crafting/
│ │ ├── CraftingManager.cs
│ │ ├── JobProcessor.cs
│ │ └── StationManager.cs
│ └── Spawning/
│ ├── SpawnerManager.cs
│ ├── CreaturePool.cs
│ └── LootSystem.cs
├── Data/
│ ├── DbWorker.cs # Background DB queue
│ ├── Repository/
│ │ ├── ICharacterRepository.cs
│ │ ├── CharacterRepository.cs
│ │ ├── IItemRepository.cs
│ │ ├── ItemRepository.cs
│ │ ├── IWorldRepository.cs
│ │ └── WorldRepository.cs
│ └── Cache/
│ ├── IItemCache.cs
│ ├── ItemCache.cs
│ ├── INodeTypeCache.cs
│ └── NodeTypeCache.cs
└── Modules/
├── ModuleLoader.cs # Loads all IServerModule
└── ModuleRegistration.cs # Dependency injection

Client Refactoring Target Structure (Godot 4 Conventions)​

godot_client/
├── autoloads/
│ ├── NetworkManager.gd # RPC handling, connection
│ ├── GameState.gd # Global state (player, party, guild)
│ ├── UIManager.gd # UI scene management
│ └── SettingsManager.gd # User preferences
├── scenes/
│ ├── main/
│ │ └── Main.tscn # Root scene
│ ├── world/
│ │ ├── World.tscn # World container
│ │ ├── Player.tscn # Player character
│ │ ├── Creature.tscn # AI creatures
│ │ ├── Projectile.tscn # Visual projectiles
│ │ └── Housing/
│ │ ├── Plot.tscn
│ │ └── HousingObject.tscn
│ ├── ui/
│ │ ├── HUD.tscn
│ │ ├── Inventory.tscn
│ │ ├── Crafting.tscn
│ │ ├── Party.tscn
│ │ ├── Guild.tscn
│ │ ├── QuestLog.tscn
│ │ ├── TradeWindow.tscn
│ │ ├── AuctionHouse.tscn
│ │ └── HousingUI.tscn
│ └── Login.tscn # Sign-in and character list
├── scripts/
│ ├── network/
│ │ ├── RpcRegistry.gd # RPC definitions (matches contract)
│ │ └── PacketSerializer.gd
│ ├── gameplay/
│ │ ├── Combat.gd
│ │ ├── Movement.gd
│ │ ├── AI/
│ │ │ └── CreatureAI.gd
│ │ └── Projectile.gd
│ ├── systems/
│ │ ├── InventorySystem.gd
│ │ ├── SkillSystem.gd
│ │ ├── QuestSystem.gd
│ │ └── HousingSystem.gd
│ └── utils/
│ ├── MathUtils.gd
│ └── SignalBus.gd
└── resources/
├── items.tres
├── creatures.tres
└── quests.tres

Key Refactoring Principles​

PrincipleApplication
Single ResponsibilityEach class/module handles one domain
Dependency InjectionModules receive dependencies via constructor
Event-DrivenModules communicate via events/signals, not direct calls
Config over CodeBehavior data in JSON/Resources, not hardcoded
Interface SegregationSmall interfaces (ICombatSystem, IAISystem)
Godot ConventionsScenes for composition, Autoloads for singletons, Signals for decoupling

Migration Strategy​

  1. Phase 1: Extract DbWorker + Repository classes (lowest risk)
  2. Phase 2: Extract SessionManager + RpcHandler (network layer)
  3. Phase 3: Extract gameplay systems one by one (Combat → AI → Party → Guild → Housing → Economy → Quest → Events)
  4. Phase 4: Wire up ModuleLoader in Server.cs
  5. Phase 5: Client restructure (parallel, matches server modules)
  6. Phase 6: Integration testing, verify all check scripts pass

300-Player Scaling Considerations​

AreaApproach
DB Connection PoolNpgsql pool (20-50 connections), DbWorker batching
Physics Tick60 Hz fixed, spatial grid for broad-phase
AI Tick15Hz, async pathfinding via NavigationServer3D
State Syncan unreliable state packet at 30 Hz, within a view radius, reliable messages for actions (see Game Server)
MemoryObject pooling for projectiles/creatures
Zone ShardingFuture: separate Server instances per zone

Critical Patterns to Preserve​

  1. Thread Safety: All DB access via DbWorker queue (never on main thread)
  2. Locking: _lock protects _sessions, _entities, _creatureInstances
  3. Caching: Load-once at startup, invalidate on admin reload
  4. Error Handling: Silent failures with GD.PrintErr, never throw

Integration Points​

  • ServerMain will inject repositories via constructor
  • All existing DbWorker.Submit calls continue working unchanged
  • Module registration happens in Program.cs / Server.cs

Test After Each Extraction​

dotnet build Moondog.GameServer
python3 scripts/check_rpc.py
python3 scripts/check_combat.py
python3 scripts/check_ranged_combat.py
# ... and the other scripts/check_*.py

Files to Modify​

  • ServerMain.cs — Remove extracted code, add constructor injection
  • Moondog.GameServer.csproj — Add new files
  • Program.cs / entry point — Wire up DI