Working on the world
This commit is contained in:
@@ -105,6 +105,7 @@ public sealed partial class WorldHandler : IClientMessageHandler
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var mobs = await db.Set<DungeonMobDefinition>()
|
||||
.AsNoTracking()
|
||||
.Where(m => m.IsEnabled)
|
||||
.Include(m => m.AbilityAssignments)
|
||||
.ThenInclude(a => a.AbilityDefinition)
|
||||
@@ -112,9 +113,20 @@ public sealed partial class WorldHandler : IClientMessageHandler
|
||||
_mobDefinitions = mobs.ToDictionary(m => m.Id);
|
||||
|
||||
var npcs = await db.Set<DungeonNpcDefinition>()
|
||||
.AsNoTracking()
|
||||
.Where(n => n.IsEnabled)
|
||||
.ToListAsync();
|
||||
_npcDefinitions = npcs.ToDictionary(n => n.Id);
|
||||
|
||||
// Log mob stats for debugging
|
||||
foreach (var mob in mobs.Take(5))
|
||||
{
|
||||
var stats = mob.GetStatsForBracket(1);
|
||||
_log.LogInformation(
|
||||
"MobDef {Id} '{Name}': MoveSpeed={MoveSpeed}, AggroRange={AggroRange}, LeashRange={LeashRange}, Behavior={Behavior}, Abilities={AbilityCount}",
|
||||
mob.Id, mob.Name, stats.MoveSpeed, stats.AggroRange, stats.LeashRange, mob.Behavior,
|
||||
mob.AbilityAssignments?.Count(a => a.IsEnabled) ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
@@ -593,8 +605,17 @@ public sealed partial class WorldHandler : IClientMessageHandler
|
||||
if (_activeZones.TryAdd(zoneKey, zoneSim))
|
||||
{
|
||||
_log.LogInformation(
|
||||
"Activated zone simulation {ZoneKey}: {MobCount} mobs, {NpcCount} NPCs",
|
||||
zoneKey, zoneSim.Mobs.Count, zoneSim.Npcs.Count);
|
||||
"Activated zone simulation {ZoneKey}: {MobCount} mobs, {NpcCount} NPCs, {SpawnPoints} spawn points",
|
||||
zoneKey, zoneSim.Mobs.Count, zoneSim.Npcs.Count,
|
||||
zoneSim.MobSpawnTracker?.SpawnPointCount ?? 0);
|
||||
|
||||
// Log mob details for debugging
|
||||
foreach (var mob in zoneSim.Mobs.Values.Take(3))
|
||||
{
|
||||
_log.LogInformation(
|
||||
" Mob {Id} '{Name}' at ({X:F0},{Y:F0}): MoveSpeed={MoveSpeed}, Behavior={Behavior}, State={State}, Abilities={AbilityCount}",
|
||||
mob.Id, mob.Name, mob.X, mob.Y, mob.Stats.MoveSpeed, mob.Behavior, mob.State, mob.Abilities.Count);
|
||||
}
|
||||
return zoneSim;
|
||||
}
|
||||
|
||||
@@ -680,6 +701,19 @@ public sealed partial class WorldHandler : IClientMessageHandler
|
||||
try
|
||||
{
|
||||
zoneSim.Tick(tick, TickDeltaSeconds);
|
||||
|
||||
// Periodic debug log every ~10 seconds (100 ticks)
|
||||
if (tick % 100 == 0 && zoneSim.Mobs.Count > 0)
|
||||
{
|
||||
var sample = zoneSim.Mobs.Values.FirstOrDefault();
|
||||
if (sample != null)
|
||||
{
|
||||
_log.LogDebug(
|
||||
"Zone {ZoneKey} tick {Tick}: {MobCount} mobs, {PlayerCount} players. Sample mob {Id} '{Name}' state={State} pos=({X:F0},{Y:F0}) speed={Speed}",
|
||||
zoneKey, tick, zoneSim.Mobs.Count, zoneSim.Players.Count,
|
||||
sample.Id, sample.Name, sample.State, sample.X, sample.Y, sample.Stats.MoveSpeed);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -751,10 +785,18 @@ public sealed partial class WorldHandler : IClientMessageHandler
|
||||
{
|
||||
try
|
||||
{
|
||||
_log.LogInformation(
|
||||
"Persisting location for character {CharacterId}: Region={RegionId} Zone=({ZoneX},{ZoneY},{ZoneZ}) Chunk=({ChunkX},{ChunkY}) Pos=({X:F1},{Y:F1})",
|
||||
s.CharacterId, s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ, s.ChunkX, s.ChunkY, s.X, s.Y);
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId);
|
||||
if (character == null) return;
|
||||
if (character == null)
|
||||
{
|
||||
_log.LogWarning("Character {CharacterId} not found for position persist", s.CharacterId);
|
||||
return;
|
||||
}
|
||||
|
||||
character.WorldRegionId = s.RegionId;
|
||||
character.WorldZoneX = s.ZoneX;
|
||||
@@ -766,10 +808,12 @@ public sealed partial class WorldHandler : IClientMessageHandler
|
||||
character.WorldY = s.Y;
|
||||
character.LastPlayedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
_log.LogInformation("Successfully persisted location for character {CharacterId}", s.CharacterId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogWarning(ex, "Failed to persist world location for character {CharacterId}", s.CharacterId);
|
||||
_log.LogError(ex, "Failed to persist world location for character {CharacterId}", s.CharacterId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+536
-220
@@ -1,266 +1,582 @@
|
||||
# Client Changes Required After WorldHandler Refactor
|
||||
# Client Fixes for World Systems Update
|
||||
|
||||
## Existing Protocol: UNCHANGED
|
||||
All existing OpCodes (700-711) and payload shapes are identical. No changes needed for spawn, input, or state.
|
||||
This document covers all client-side changes needed for the world overhaul:
|
||||
Z-levels, world mobs/NPCs, combat, object interaction, and portal updates.
|
||||
|
||||
## NEW: OpCode 712 - WORLD_CHUNK_DELTA (Server -> Client)
|
||||
---
|
||||
|
||||
The server now pushes live chunk deltas to clients whenever the world is edited (admin panel, etc).
|
||||
Any player who has the affected chunk in their visible set receives the delta immediately,
|
||||
without waiting for a full chunk reload.
|
||||
## 1. Breaking Changes
|
||||
|
||||
### When it fires
|
||||
- Admin places/removes a tile via the world editor
|
||||
- Admin places/removes an object, NPC, or mob spawn
|
||||
- Admin clears or deletes a chunk
|
||||
### 1.1 Chunk Key Format (6-part, was 5-part)
|
||||
|
||||
All chunk keys now include `zoneZ`:
|
||||
|
||||
```
|
||||
OLD: "{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}"
|
||||
NEW: "{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}"
|
||||
```
|
||||
|
||||
Update any client-side chunk key parsing/caching to expect the 6-segment format.
|
||||
|
||||
### 1.2 WORLD_STATE (711) - New Fields
|
||||
|
||||
The per-tick `WORLD_STATE` payload now includes `mobs` and `npcs` arrays.
|
||||
These are **null** when no zone simulation is active, so guard against null.
|
||||
|
||||
### Payload shape
|
||||
```json
|
||||
{
|
||||
"kind": "chunk_delta",
|
||||
"regionId": 1,
|
||||
"zoneX": 0,
|
||||
"zoneY": 0,
|
||||
"chunkX": 3,
|
||||
"chunkY": 2,
|
||||
"fromVersion": 5,
|
||||
"toVersion": 6,
|
||||
"op": { ... }
|
||||
"tick": 1234,
|
||||
"ackSeq": 42,
|
||||
"self": {
|
||||
"x": 1024.5, "y": 512.3,
|
||||
"velocityX": 120.0, "velocityY": 0.0,
|
||||
"regionId": 1,
|
||||
"zoneX": 0, "zoneY": 0,
|
||||
"chunkX": 5, "chunkY": 3
|
||||
},
|
||||
"players": [ ... ],
|
||||
"mobs": [ // NEW - nullable
|
||||
{
|
||||
"id": 1,
|
||||
"definitionId": 101,
|
||||
"name": "Goblin",
|
||||
"x": 800.0, "y": 400.0,
|
||||
"health": 45, "maxHealth": 100,
|
||||
"isAlive": true,
|
||||
"state": "Idle", // "Idle","Chasing","Attacking","Dead"
|
||||
"animation": "idle_down",
|
||||
"facing": "down",
|
||||
"spriteConfig": "{...}",
|
||||
"tintColor": "#ffffff",
|
||||
"scale": 1.0
|
||||
}
|
||||
],
|
||||
"npcs": [ // NEW - nullable
|
||||
{
|
||||
"id": 1,
|
||||
"definitionId": 5,
|
||||
"name": "Village Elder",
|
||||
"x": 1200.0, "y": 600.0,
|
||||
"health": 100, "maxHealth": 100,
|
||||
"isAlive": true,
|
||||
"canShop": true,
|
||||
"hasDialog": true,
|
||||
"animation": "idle",
|
||||
"spriteConfig": "{...}",
|
||||
"tintColor": "#ffffff",
|
||||
"scale": 1.0
|
||||
}
|
||||
],
|
||||
"chunkUpdates": [ ... ],
|
||||
"portalEvent": { ... },
|
||||
"errors": [ ... ]
|
||||
}
|
||||
```
|
||||
|
||||
### `op` types the client must handle
|
||||
Mob/NPC arrays contain all entities within **1536px** (48 tiles) of the player, same Z-level only. Render mobs and NPCs from these arrays every tick. Dead mobs (`isAlive: false`) should show death animation and remain for looting.
|
||||
|
||||
### 1.3 Chunk Payload - `zoneZ` Added
|
||||
|
||||
Every chunk payload now includes `zoneZ` in its `chunk` object:
|
||||
|
||||
#### `tile_upsert` - A tile was added or changed
|
||||
```json
|
||||
{
|
||||
"type": "tile_upsert",
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"sheetId": 3,
|
||||
"frameIndex": 42,
|
||||
"isWalkable": true,
|
||||
"isInvisiblePaywall": false
|
||||
"type": "chunk_full",
|
||||
"chunk": {
|
||||
"regionId": 1,
|
||||
"zoneX": 0, "zoneY": 0,
|
||||
"zoneZ": 0, // NEW
|
||||
"chunkX": 5, "chunkY": 3,
|
||||
"version": 12345,
|
||||
"width": 20, "height": 20
|
||||
},
|
||||
"tiles": [ ... ],
|
||||
"objects": [ ... ],
|
||||
"npcs": [ ... ],
|
||||
"mobs": [ ... ]
|
||||
}
|
||||
```
|
||||
**Client action**: Find the chunk in `chunk_cache` by regionId/zoneX/zoneY/chunkX/chunkY.
|
||||
Update or insert the tile in the chunk's `tiles` array. Then call `_rebuild_world_visuals()`.
|
||||
Also update local walkability data if you cache it.
|
||||
|
||||
#### `tile_remove` - A tile was removed
|
||||
### 1.4 Visible Players Filtered by Z-Level
|
||||
|
||||
Players on different Z-levels are no longer visible to each other. The server
|
||||
already handles this -- the client just needs to be aware that entering a
|
||||
building (Z-level change) will make other ground-level players disappear.
|
||||
|
||||
---
|
||||
|
||||
## 2. New OpCodes
|
||||
|
||||
| OpCode | Constant | Direction | Purpose |
|
||||
|--------|-------------------------------|-----------|----------------------------------|
|
||||
| 720 | WORLD_COMBAT_STATE | S -> C | Combat events broadcast |
|
||||
| 721 | WORLD_ATTACK | C -> S | Player attacks mob or player |
|
||||
| 722 | WORLD_MOB_LOOT_REQUEST | C -> S | Loot a dead mob |
|
||||
| 723 | WORLD_MOB_LOOT_RESULT | S -> C | Loot contents |
|
||||
| 740 | WORLD_NPC_INTERACT | C -> S | Start NPC interaction |
|
||||
| 741 | WORLD_NPC_INTERACT_STATE | S -> C | NPC metadata + dialog/shop state |
|
||||
| 742 | WORLD_NPC_DIALOG_SELECT | C -> S | Choose a dialog option |
|
||||
| 743 | WORLD_NPC_DIALOG_RESULT | S -> C | Dialog option outcome |
|
||||
| 744 | WORLD_NPC_SHOP_ACTION | C -> S | Buy from NPC shop |
|
||||
| 745 | WORLD_NPC_SHOP_RESULT | S -> C | Shop transaction result |
|
||||
| 750 | WORLD_OBJECT_INTERACT | C -> S | Interact with world object |
|
||||
| 751 | WORLD_OBJECT_INTERACT_RESULT | S -> C | Object interaction result |
|
||||
| 752 | WORLD_OBJECT_STATE | S -> C | Object state broadcast (broken) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Combat System
|
||||
|
||||
### 3.1 Sending an Attack (721 WORLD_ATTACK) C -> S
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "tile_remove",
|
||||
"x": 12,
|
||||
"y": 8
|
||||
"targetType": "mob", // "mob" or "player"
|
||||
"targetMobId": 1, // required when targetType = "mob"
|
||||
"targetPlayerId": 67890 // required when targetType = "player"
|
||||
}
|
||||
```
|
||||
**Client action**: Remove the tile at (x, y) from the chunk's `tiles` array.
|
||||
Call `_rebuild_world_visuals()`. Mark that tile as walkable in local collision data.
|
||||
|
||||
#### `object_upsert` - An object was added or changed
|
||||
- Server validates: alive, not stunned, within 80px melee range.
|
||||
- PvP attacks are rejected unless the zone has `IsPvpEnabled = true`.
|
||||
|
||||
### 3.2 Combat Events (720 WORLD_COMBAT_STATE) S -> C
|
||||
|
||||
Sent to **all players in the zone** when combat occurs. Contains an `events`
|
||||
array. Each event has a `type` string field.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object_upsert",
|
||||
"id": 456,
|
||||
"events": [
|
||||
{
|
||||
"type": "PlayerAttack",
|
||||
"sourcePlayerId": 12345,
|
||||
"targetMobId": 1,
|
||||
"damage": 45,
|
||||
"damageTypeKey": "physical",
|
||||
"x": 800.0, "y": 400.0,
|
||||
"wasResisted": false,
|
||||
"wasWeakness": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Event types from player-initiated combat (WorldHandler.Combat.cs):**
|
||||
|
||||
| type | Fields | When |
|
||||
|-----------------|---------------------------------------------------------------------------|---------------------------|
|
||||
| `PlayerAttack` | sourcePlayerId, targetMobId, damage, damageTypeKey, x, y, wasResisted, wasWeakness | Player hits mob |
|
||||
| `MobDeath` | targetMobId, sourcePlayerId, x, y, xpReward, lootAvailable | Mob killed |
|
||||
| `PvpDamage` | sourcePlayerId, targetPlayerId, damage, damageTypeKey, x, y | Player hits player (PvP) |
|
||||
| `PlayerDeath` | targetPlayerId, sourcePlayerId, x, y, isPvpKill | Player killed (PvP) |
|
||||
| `AttackFailed` | error | Attack rejected |
|
||||
|
||||
`AttackFailed` error values: `"stunned"`, `"dead"`, `"target_not_found"`, `"out_of_range"`, `"pvp_disabled_in_zone"`, `"target_invulnerable"`
|
||||
|
||||
**Event types from zone simulation ticks (WorldZoneSimulation.cs via BroadcastCombatEventsAsync):**
|
||||
|
||||
| type | Fields | When |
|
||||
|--------------------|--------------------------------------------------------------------------|---------------------------|
|
||||
| `Damage` | sourceMobId, targetPlayerId, damage, damageTypeKey, x, y | Mob hits player |
|
||||
| `MobDeath` | targetMobId, sourcePlayerId, x, y | Mob dies from AI tick |
|
||||
| `PlayerDeath` | targetPlayerId, x, y | Player killed by mob |
|
||||
| `MobSpawn` | targetMobId, x, y, mobData (full mob serialize object) | Mob respawned |
|
||||
| `ProjectileSpawn` | sourceMobId, x, y | Mob fires projectile |
|
||||
| `AbilityUsed` | sourceMobId, targetPlayerId, damage, damageTypeKey, x, y | Mob uses ability |
|
||||
|
||||
Note: Zone-tick events use the generic serialization format:
|
||||
```json
|
||||
{
|
||||
"type": "Damage",
|
||||
"sourceMobId": 2,
|
||||
"sourcePlayerId": 0,
|
||||
"targetMobId": 0,
|
||||
"targetPlayerId": 12345,
|
||||
"damage": 25,
|
||||
"damageTypeKey": "fire",
|
||||
"x": 1024.0, "y": 512.0,
|
||||
"mobData": null
|
||||
}
|
||||
```
|
||||
|
||||
The client should handle **both** formats -- direct combat events from `WorldHandler.Combat.cs` (only the relevant fields) and zone-broadcast events (all fields present, irrelevant ones zeroed/null).
|
||||
|
||||
### 3.3 Mob Looting (722/723) C -> S / S -> C
|
||||
|
||||
**Request (722 WORLD_MOB_LOOT_REQUEST):**
|
||||
```json
|
||||
{ "mobId": 1 }
|
||||
```
|
||||
|
||||
Server validates: mob is dead, within 128px, exists.
|
||||
|
||||
**Response (723 WORLD_MOB_LOOT_RESULT):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"mobId": 1,
|
||||
"gold": 75,
|
||||
"items": []
|
||||
}
|
||||
```
|
||||
|
||||
Error cases: `"mob_not_found"`, `"mob_still_alive"`, `"too_far"`
|
||||
|
||||
Items array is currently empty (loot tables not yet integrated). Gold is `XpReward / 2`.
|
||||
|
||||
---
|
||||
|
||||
## 4. NPC Interaction System
|
||||
|
||||
### 4.1 Starting NPC Interaction (740/741)
|
||||
|
||||
**Request (740 WORLD_NPC_INTERACT):**
|
||||
```json
|
||||
{ "npcId": 1 }
|
||||
```
|
||||
|
||||
Server validates: NPC exists in zone sim, within 128px.
|
||||
|
||||
**Response (741 WORLD_NPC_INTERACT_STATE):**
|
||||
|
||||
The server sends NPC metadata, and then auto-sends dialog and/or shop state
|
||||
if the NPC supports them. All arrive on opcode 741.
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"npc": {
|
||||
"id": 1,
|
||||
"definitionId": 5,
|
||||
"name": "Village Elder",
|
||||
"canShop": true,
|
||||
"hasDialog": true,
|
||||
"isKillable": false,
|
||||
"behavior": "passive",
|
||||
"onAttackBehavior": "flee",
|
||||
"shopId": 10,
|
||||
"dialogTreeId": 25
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If `hasDialog && dialogTreeId != null`, a follow-up 741 arrives with dialog:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"npcId": 1,
|
||||
"dialogNode": {
|
||||
"id": 100,
|
||||
"text": "Hello traveler! What brings you here?",
|
||||
"isTerminal": false,
|
||||
"rewardGold": 0,
|
||||
"rewardXp": 0,
|
||||
"rewardItemDefinitionId": null,
|
||||
"rewardItemQuantity": 0
|
||||
},
|
||||
"options": [
|
||||
{ "id": 200, "text": "Tell me about yourself", "nextNodeId": 101 },
|
||||
{ "id": 201, "text": "I'm looking for work", "nextNodeId": 102 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If `canShop && shopId != null`, a follow-up 741 arrives with shop:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"shop": {
|
||||
"id": 10,
|
||||
"name": "General Store",
|
||||
"items": [
|
||||
{
|
||||
"slotIndex": 0,
|
||||
"itemDefinitionId": 42,
|
||||
"itemName": "Healing Potion",
|
||||
"quantity": 10,
|
||||
"priceGold": 50,
|
||||
"restocks": true,
|
||||
"restockIntervalSeconds": 3600
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Error cases on 741: `"npc_not_found"`, `"too_far"`
|
||||
|
||||
### 4.2 Selecting a Dialog Option (742/743)
|
||||
|
||||
**Request (742 WORLD_NPC_DIALOG_SELECT):**
|
||||
```json
|
||||
{ "npcId": 1, "optionId": 200 }
|
||||
```
|
||||
|
||||
**Response (743 WORLD_NPC_DIALOG_RESULT):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"npcId": 1,
|
||||
"nextNodeId": 101,
|
||||
"isTerminal": false
|
||||
}
|
||||
```
|
||||
|
||||
On success, the server also sends the next dialog node on opcode **741**
|
||||
(same as initial dialog state), so the client should update the dialog UI
|
||||
when it gets a new 741 with `dialogNode`.
|
||||
|
||||
If the selected option has **rewards** (gold, XP, items), they are applied
|
||||
server-side automatically when the next node loads. The client should display
|
||||
the `rewardGold`/`rewardXp`/`rewardItemDefinitionId` fields from the
|
||||
`dialogNode` in the follow-up 741 to show the player what they received.
|
||||
|
||||
If the option required consuming items (e.g. quest turn-in), those are
|
||||
deducted server-side as well. On `"condition_failed"` error, the option's
|
||||
prerequisite is not met.
|
||||
|
||||
Error cases on 743: `"npc_dialog_unavailable"`, `"invalid_option"`, `"condition_failed"`, `"requires_item"`, `"level_too_low"`, `"level_too_high"`, `"not_enough_gold"`
|
||||
|
||||
### 4.3 Buying from a Shop (744/745)
|
||||
|
||||
**Request (744 WORLD_NPC_SHOP_ACTION):**
|
||||
```json
|
||||
{
|
||||
"npcId": 1,
|
||||
"action": "buy",
|
||||
"slotIndex": 0,
|
||||
"quantity": 1
|
||||
}
|
||||
```
|
||||
|
||||
Only `"buy"` is currently supported.
|
||||
|
||||
**Response (745 WORLD_NPC_SHOP_RESULT):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"npcId": 1,
|
||||
"action": "buy",
|
||||
"itemDefinitionId": 42,
|
||||
"quantity": 1,
|
||||
"totalPrice": 50,
|
||||
"remainingGold": 450,
|
||||
"remainingStock": 9
|
||||
}
|
||||
```
|
||||
|
||||
On success, the server also re-sends the full shop state on opcode **741**
|
||||
(`shop` object) with updated quantities.
|
||||
|
||||
Error cases on 745: `"npc_shop_unavailable"`, `"unsupported_shop_action"`, `"shop_item_not_found"`, `"out_of_stock"`, `"character_not_found"`, `"not_enough_gold"` (includes `requiredGold` + `currentGold`), `"inventory_full"`
|
||||
|
||||
---
|
||||
|
||||
## 5. World Object Interaction
|
||||
|
||||
### 5.1 Interacting with an Object (750/751)
|
||||
|
||||
**Request (750 WORLD_OBJECT_INTERACT):**
|
||||
```json
|
||||
{
|
||||
"objectId": 999,
|
||||
"action": "interact"
|
||||
}
|
||||
```
|
||||
|
||||
`action` values: `"interact"` (default), `"break"` (for destructibles), `"loot"` (for containers).
|
||||
|
||||
Server validates: object exists in DB, within 128px.
|
||||
|
||||
**Response (751 WORLD_OBJECT_INTERACT_RESULT):**
|
||||
|
||||
Response shape varies by object type:
|
||||
|
||||
**Destructible object** (when `action = "break"` and `IsDestructible = true`):
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"objectId": 999,
|
||||
"type": "break",
|
||||
"gold": 25,
|
||||
"items": []
|
||||
}
|
||||
```
|
||||
|
||||
**Container / OpenContainer** (lootable):
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"objectId": 999,
|
||||
"type": "loot",
|
||||
"gold": 50,
|
||||
"items": []
|
||||
}
|
||||
```
|
||||
|
||||
**Trigger** (readable signs, plaques, etc.):
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"objectId": 999,
|
||||
"type": "readable",
|
||||
"name": "Weathered Sign",
|
||||
"text": "Danger ahead!"
|
||||
}
|
||||
```
|
||||
|
||||
**Teleport** (handled by movement system, not this handler):
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"objectId": 999,
|
||||
"type": "teleport",
|
||||
"message": "Portal triggered by movement."
|
||||
}
|
||||
```
|
||||
|
||||
**Generic / unhandled types:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"objectId": 999,
|
||||
"type": "heal",
|
||||
"name": "Healing Shrine",
|
||||
"metadataJson": "{...}"
|
||||
}
|
||||
```
|
||||
|
||||
Error cases on 751: `"object_not_found"`, `"object_chunk_not_found"`, `"too_far"`
|
||||
|
||||
### 5.2 Object State Broadcast (752 WORLD_OBJECT_STATE) S -> C
|
||||
|
||||
Broadcast to **all players in the zone** when an object's state changes
|
||||
(e.g. a destructible is broken):
|
||||
|
||||
```json
|
||||
{
|
||||
"objectId": 999,
|
||||
"state": "broken",
|
||||
"x": 5,
|
||||
"y": 3,
|
||||
"objectDefinitionId": 12,
|
||||
"objectName": "Portal Stone",
|
||||
"interactionType": "Teleport",
|
||||
"rotation": 0,
|
||||
"metadataJson": "{\"portalType\":\"world\",...}"
|
||||
"y": 10
|
||||
}
|
||||
```
|
||||
**Client action**: Upsert by `id` in the chunk's `objects` array. Call `_rebuild_world_entities()`.
|
||||
|
||||
#### `object_remove` - An object was removed
|
||||
The client should visually remove or swap the object sprite when receiving
|
||||
this. Coordinates are **tile** positions (not world pixels).
|
||||
|
||||
---
|
||||
|
||||
## 6. Portal / Z-Level System
|
||||
|
||||
### 6.1 Portal Metadata
|
||||
|
||||
Portal objects on tiles now include `targetZoneZ` and a `portalType` field
|
||||
in their `MetadataJson`:
|
||||
|
||||
| portalType | Behavior |
|
||||
|------------------|----------------------------------------------------------|
|
||||
| `"world"` | Teleport to different region/zone. Includes full target. |
|
||||
| `"building"` | Enter a building: stays same zoneX/zoneY, changes zoneZ. |
|
||||
| `"building_exit"`| Exit building: returns to zoneZ=0 (ground level). |
|
||||
|
||||
### 6.2 Portal Events in WORLD_STATE
|
||||
|
||||
When a player walks over a portal tile, the server triggers a teleport and
|
||||
includes a `portalEvent` in the next `WORLD_STATE`:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object_remove",
|
||||
"id": 456
|
||||
"portalEvent": {
|
||||
"type": "world_teleport",
|
||||
"sourceObjectId": 123,
|
||||
"regionId": 2,
|
||||
"zoneX": 1, "zoneY": 1, "zoneZ": 0,
|
||||
"chunkX": 2, "chunkY": 2,
|
||||
"x": 512.0, "y": 512.0
|
||||
}
|
||||
}
|
||||
```
|
||||
**Client action**: Remove the object with matching `id` from `objects`. Call `_rebuild_world_entities()`.
|
||||
|
||||
#### `npc_upsert` - An NPC spawn was added or changed
|
||||
```json
|
||||
{
|
||||
"type": "npc_upsert",
|
||||
"id": 789,
|
||||
"x": 10,
|
||||
"y": 15,
|
||||
"npcDefinitionId": 5,
|
||||
"npcName": "Merchant",
|
||||
"rotation": 0,
|
||||
"metadataJson": null
|
||||
}
|
||||
```
|
||||
**Client action**: Upsert by `id` in the chunk's `npcs` array. Call `_rebuild_world_entities()`.
|
||||
For building portals, the portal event may only change `zoneZ` while keeping
|
||||
the same region/zone XY. The client should:
|
||||
|
||||
#### `npc_remove`
|
||||
```json
|
||||
{ "type": "npc_remove", "id": 789 }
|
||||
```
|
||||
**Client action**: Remove NPC with matching `id`. Call `_rebuild_world_entities()`.
|
||||
1. Detect the `portalEvent` in `WORLD_STATE`.
|
||||
2. Clear loaded chunks (new Z-level = new tile data).
|
||||
3. Start loading chunks from the new position.
|
||||
4. The server sends new chunks via `chunkUpdates` automatically.
|
||||
|
||||
#### `mob_upsert` - A mob spawn was added or changed
|
||||
```json
|
||||
{
|
||||
"type": "mob_upsert",
|
||||
"id": 101,
|
||||
"x": 20,
|
||||
"y": 25,
|
||||
"mobDefinitionId": 3,
|
||||
"mobName": "Slime",
|
||||
"rotation": 0,
|
||||
"spawnCount": 2,
|
||||
"respawnSeconds": 30.0,
|
||||
"metadataJson": null
|
||||
}
|
||||
```
|
||||
**Client action**: Upsert by `id` in the chunk's `mobs` array. Call `_rebuild_world_entities()`.
|
||||
Portal cooldown is **0.8 seconds** (8 server ticks), enforced server-side.
|
||||
|
||||
#### `mob_remove`
|
||||
```json
|
||||
{ "type": "mob_remove", "id": 101 }
|
||||
```
|
||||
**Client action**: Remove mob with matching `id`. Call `_rebuild_world_entities()`.
|
||||
---
|
||||
|
||||
#### `chunk_clear` - All tiles/objects/npcs/mobs removed from chunk
|
||||
```json
|
||||
{ "type": "chunk_clear" }
|
||||
```
|
||||
**Client action**: Empty the chunk's `tiles`, `objects`, `npcs`, `mobs` arrays.
|
||||
Call `_rebuild_world_visuals()` and `_rebuild_world_entities()`.
|
||||
## 7. Client Implementation Checklist
|
||||
|
||||
#### `chunk_deleted` - Entire chunk deleted from DB
|
||||
```json
|
||||
{ "type": "chunk_deleted" }
|
||||
```
|
||||
**Client action**: Remove the chunk from `chunk_cache` entirely.
|
||||
Call `_rebuild_world_visuals()` and `_rebuild_world_entities()`.
|
||||
### Mob Rendering
|
||||
- [ ] Parse `mobs` array from WORLD_STATE (nullable -- skip if null)
|
||||
- [ ] Render mob sprites using `spriteConfig`, `tintColor`, `scale`
|
||||
- [ ] Animate using `animation` string (e.g. `"idle_down"`, `"walk_right"`)
|
||||
- [ ] Show mob health bars (health/maxHealth)
|
||||
- [ ] Handle mob states: Idle, Chasing, Attacking, Dead
|
||||
- [ ] Dead mobs: play death animation, show loot indicator if `lootAvailable`
|
||||
- [ ] Mob click/tap target -> send WORLD_ATTACK with `targetType: "mob"`
|
||||
- [ ] Show damage numbers from WORLD_COMBAT_STATE events
|
||||
|
||||
### Implementation guide for the client
|
||||
### NPC Rendering
|
||||
- [ ] Parse `npcs` array from WORLD_STATE (nullable -- skip if null)
|
||||
- [ ] Render NPC sprites using `spriteConfig`, `tintColor`, `scale`
|
||||
- [ ] Show interaction indicator (speech bubble? shop icon?) based on `canShop`/`hasDialog`
|
||||
- [ ] NPC click/tap -> send WORLD_NPC_INTERACT
|
||||
- [ ] Build dialog UI: show `dialogNode.text` + selectable `options`
|
||||
- [ ] On option click -> send WORLD_NPC_DIALOG_SELECT
|
||||
- [ ] Build shop UI: list items with prices, buy button
|
||||
- [ ] On buy -> send WORLD_NPC_SHOP_ACTION
|
||||
|
||||
In your GameState (or wherever you route opcodes), add a handler for opcode 712:
|
||||
### Combat UI
|
||||
- [ ] Register handler for opcode 720 (WORLD_COMBAT_STATE)
|
||||
- [ ] Floating damage numbers (position from event x/y)
|
||||
- [ ] Color coding: red for damage, yellow for resisted, green for weakness
|
||||
- [ ] Death handling: PvP death shows killer name, mob death shows respawn
|
||||
- [ ] XP popup on MobDeath events (`xpReward` field)
|
||||
- [ ] Mob target frame / health bar while attacking
|
||||
|
||||
```gdscript
|
||||
# In GameState or network handler:
|
||||
712: # WORLD_CHUNK_DELTA
|
||||
emit_signal("world_chunk_delta_received", data)
|
||||
```
|
||||
### Mob Looting
|
||||
- [ ] On dead mob click -> send WORLD_MOB_LOOT_REQUEST
|
||||
- [ ] Register handler for opcode 723 (WORLD_MOB_LOOT_RESULT)
|
||||
- [ ] Show loot window with gold + items
|
||||
- [ ] Update local gold counter from loot result
|
||||
|
||||
In the world scene script, connect to the signal and apply:
|
||||
### Object Interaction
|
||||
- [ ] Register handler for opcode 751 (WORLD_OBJECT_INTERACT_RESULT)
|
||||
- [ ] Register handler for opcode 752 (WORLD_OBJECT_STATE)
|
||||
- [ ] Object click/tap -> send WORLD_OBJECT_INTERACT (action based on object type)
|
||||
- [ ] Breakable objects: show break animation then remove sprite on WORLD_OBJECT_STATE
|
||||
- [ ] Lootable objects: show loot popup with gold + items
|
||||
- [ ] Readable objects: show text popup with `text` field
|
||||
- [ ] Handle WORLD_OBJECT_STATE broadcast to update/remove objects broken by other players
|
||||
|
||||
```gdscript
|
||||
func _setup_runtime():
|
||||
# ... existing connections ...
|
||||
if GameState:
|
||||
GameState.world_chunk_delta_received.connect(_on_world_chunk_delta_received)
|
||||
### Z-Level / Portals
|
||||
- [ ] Handle `portalEvent` in WORLD_STATE response
|
||||
- [ ] On portalEvent: clear chunk cache, transition to new position
|
||||
- [ ] Building entrance visual indicator on portal tiles
|
||||
- [ ] Building interior: same zone XY but different Z = different tile set
|
||||
- [ ] Track current `zoneZ` client-side (from `self` in WORLD_STATE)
|
||||
|
||||
func _on_world_chunk_delta_received(data: Dictionary):
|
||||
if runtime == null:
|
||||
return
|
||||
runtime.apply_chunk_delta(data)
|
||||
_rebuild_world_visuals()
|
||||
_rebuild_world_entities()
|
||||
```
|
||||
### PvP
|
||||
- [ ] Visual indicator when entering a PvP-enabled zone (server does not send zone flags yet -- use hardcoded zone list or future opcode)
|
||||
- [ ] Player click/tap in PvP zone -> send WORLD_ATTACK with `targetType: "player"`
|
||||
- [ ] Handle `PvpDamage` and `PlayerDeath` with `isPvpKill: true` events
|
||||
- [ ] Invulnerability visual (shield icon) when defender `isInvulnerable`
|
||||
|
||||
In the world runtime client, add the delta application logic:
|
||||
---
|
||||
|
||||
```gdscript
|
||||
func apply_chunk_delta(data: Dictionary):
|
||||
var key = _chunk_key(
|
||||
int(data.get("regionId", 0)),
|
||||
int(data.get("zoneX", 0)),
|
||||
int(data.get("zoneY", 0)),
|
||||
int(data.get("chunkX", 0)),
|
||||
int(data.get("chunkY", 0))
|
||||
)
|
||||
var op = data.get("op", {})
|
||||
var op_type = str(op.get("type", ""))
|
||||
## 8. Known Limitations / TODOs
|
||||
|
||||
if not chunk_cache.has(key):
|
||||
return # We don't have this chunk loaded, ignore
|
||||
|
||||
var chunk = chunk_cache[key]
|
||||
|
||||
match op_type:
|
||||
"tile_upsert":
|
||||
_delta_upsert_tile(chunk, op)
|
||||
"tile_remove":
|
||||
_delta_remove_tile(chunk, op)
|
||||
"object_upsert":
|
||||
_delta_upsert_by_id(chunk, "objects", op)
|
||||
"object_remove":
|
||||
_delta_remove_by_id(chunk, "objects", int(op.get("id", -1)))
|
||||
"npc_upsert":
|
||||
_delta_upsert_by_id(chunk, "npcs", op)
|
||||
"npc_remove":
|
||||
_delta_remove_by_id(chunk, "npcs", int(op.get("id", -1)))
|
||||
"mob_upsert":
|
||||
_delta_upsert_by_id(chunk, "mobs", op)
|
||||
"mob_remove":
|
||||
_delta_remove_by_id(chunk, "mobs", int(op.get("id", -1)))
|
||||
"chunk_clear":
|
||||
chunk["tiles"] = []
|
||||
chunk["objects"] = []
|
||||
chunk["npcs"] = []
|
||||
chunk["mobs"] = []
|
||||
"chunk_deleted":
|
||||
chunk_cache.erase(key)
|
||||
|
||||
# Update version tracking
|
||||
var new_version = int(data.get("toVersion", 0))
|
||||
if chunk_cache.has(key):
|
||||
chunk_cache[key]["version"] = new_version
|
||||
|
||||
func _delta_upsert_tile(chunk: Dictionary, op: Dictionary):
|
||||
var tx = int(op.get("x", -1))
|
||||
var ty = int(op.get("y", -1))
|
||||
var tiles = chunk.get("tiles", [])
|
||||
for i in range(tiles.size()):
|
||||
var t = tiles[i]
|
||||
if int(t.get("x", t.get("tileX", -1))) == tx and int(t.get("y", t.get("tileY", -1))) == ty:
|
||||
tiles[i] = op
|
||||
return
|
||||
tiles.append(op)
|
||||
|
||||
func _delta_remove_tile(chunk: Dictionary, op: Dictionary):
|
||||
var tx = int(op.get("x", -1))
|
||||
var ty = int(op.get("y", -1))
|
||||
var tiles = chunk.get("tiles", [])
|
||||
for i in range(tiles.size() - 1, -1, -1):
|
||||
var t = tiles[i]
|
||||
if int(t.get("x", t.get("tileX", -1))) == tx and int(t.get("y", t.get("tileY", -1))) == ty:
|
||||
tiles.remove_at(i)
|
||||
return
|
||||
|
||||
func _delta_upsert_by_id(chunk: Dictionary, array_name: String, op: Dictionary):
|
||||
var id = int(op.get("id", -1))
|
||||
var arr = chunk.get(array_name, [])
|
||||
for i in range(arr.size()):
|
||||
if int(arr[i].get("id", -1)) == id:
|
||||
arr[i] = op
|
||||
return
|
||||
arr.append(op)
|
||||
|
||||
func _delta_remove_by_id(chunk: Dictionary, array_name: String, id: int):
|
||||
var arr = chunk.get(array_name, [])
|
||||
for i in range(arr.size() - 1, -1, -1):
|
||||
if int(arr[i].get("id", -1)) == id:
|
||||
arr.remove_at(i)
|
||||
return
|
||||
```
|
||||
|
||||
## Performance Notes
|
||||
|
||||
### Server movement fix
|
||||
The server tick loop no longer hits the database. Movement/collision is now pure in-memory.
|
||||
The "1 tile per 3 seconds" latency was caused by 30+ DB round-trips per player per tick on the server side.
|
||||
|
||||
### LOCAL_MOVE_SPEED mismatch
|
||||
The client uses `LOCAL_MOVE_SPEED = 160.0` for local prediction, but the server walk speed
|
||||
is `120 px/s` and run speed is `180 px/s`. This causes minor rubber-banding.
|
||||
Consider changing `LOCAL_MOVE_SPEED` to `120.0` or reading the server's speed from WORLD_SPAWN.
|
||||
- **Loot tables not integrated**: WORLD_MOB_LOOT_RESULT `items` array is always empty. Only gold drops currently.
|
||||
- **Player combat stats hardcoded**: EnsurePlayersInZoneSimsAsync uses default stats (str=10, int=10, etc). Real gear-based stats not loaded yet.
|
||||
- **No zone PvP flag sent to client**: The client has no way to know if a zone is PvP-enabled. Will need a future opcode or flag in chunk/zone data.
|
||||
- **Object broken state not persisted**: Breakable objects reset on server restart.
|
||||
- **Sell action not implemented**: WORLD_NPC_SHOP_ACTION only supports `"buy"`.
|
||||
- **No world death/respawn flow**: PlayerDeath events are broadcast but there is no respawn opcode or flow yet.
|
||||
- **Mob AI abilities**: Mobs use the dungeon AI system (10 behavior patterns) but world mob abilities haven't been extensively tested.
|
||||
|
||||
+4170
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,72 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SystemRevivalServer.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class tableUpdatesForWorld : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsPvpEnabled",
|
||||
table: "world_zones",
|
||||
type: "tinyint(1)",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "ZoneZ",
|
||||
table: "world_zones",
|
||||
type: "int",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "WorldZoneZ",
|
||||
table: "dungeon_characters",
|
||||
type: "int",
|
||||
nullable: true);
|
||||
|
||||
// Drop old 3-column unique index before creating the new 4-column one
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_world_zones_RegionId_ZoneX_ZoneY",
|
||||
table: "world_zones");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_world_zones_RegionId_ZoneX_ZoneY_ZoneZ",
|
||||
table: "world_zones",
|
||||
columns: new[] { "RegionId", "ZoneX", "ZoneY", "ZoneZ" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_world_zones_RegionId_ZoneX_ZoneY_ZoneZ",
|
||||
table: "world_zones");
|
||||
|
||||
// Restore old 3-column unique index
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_world_zones_RegionId_ZoneX_ZoneY",
|
||||
table: "world_zones",
|
||||
columns: new[] { "RegionId", "ZoneX", "ZoneY" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsPvpEnabled",
|
||||
table: "world_zones");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ZoneZ",
|
||||
table: "world_zones");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "WorldZoneZ",
|
||||
table: "dungeon_characters");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -516,6 +516,9 @@ namespace SystemRevivalServer.Migrations
|
||||
b.Property<int?>("WorldZoneY")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<int?>("WorldZoneZ")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AccountId");
|
||||
@@ -3366,6 +3369,9 @@ namespace SystemRevivalServer.Migrations
|
||||
b.Property<bool>("IsEnabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsPvpEnabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
@@ -3383,9 +3389,12 @@ namespace SystemRevivalServer.Migrations
|
||||
b.Property<int>("ZoneY")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<int>("ZoneZ")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RegionId", "ZoneX", "ZoneY")
|
||||
b.HasIndex("RegionId", "ZoneX", "ZoneY", "ZoneZ")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("world_zones");
|
||||
|
||||
Reference in New Issue
Block a user