feat(server.game): route events through a InterestManager (#47)

* feat(server.game): route events through a InterestManager

* docs: explain the InterestManager and when to use it

* fix(login): carry the authenticated account to the game server so players get distinct characters

* fix(protocols.game): decode entity move from capture at opcode 0xE4 with little-endian ids and 16-bit coords

* feat(game): make the server authoritative over movement and broadcast steps and turns to nearby players

* refactor(game): drop the unused broadcastExcept and isOnline methods
This commit is contained in:
Fiereu authored and GitHub committed 2026-07-20 23:42:14 +02:00
1 parent 3cfbc2169a
commit 4b533bd099
28 files changed
+702 -341

No files matched your search

@@ -6,6 +6,8 @@ import de.fiereu.openmmo.common.auth.SessionTokenVerifier
import de.fiereu.openmmo.common.io.PemKeyLoader
import de.fiereu.openmmo.common.io.resource
import de.fiereu.openmmo.server.game.config.GameServerConfig
import de.fiereu.openmmo.server.game.world.interest.InterestPolicy
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import io.netty.channel.EventLoopGroup
import io.netty.channel.MultiThreadIoEventLoopGroup
import io.netty.channel.nio.NioIoHandler
@@ -42,4 +44,6 @@ object GameServerModule {
@Provides
@Singleton
fun coroutineScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@Provides @Singleton fun interestPolicy(impl: PassThroughInterestPolicy): InterestPolicy = impl
}
@@ -14,7 +14,6 @@ import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket
import de.fiereu.openmmo.net.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.net.game.packets.DialogChoicePacket
import de.fiereu.openmmo.net.game.packets.EntityInteractPacket
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket
import de.fiereu.openmmo.net.game.packets.FriendProfileRequestPacket
import de.fiereu.openmmo.net.game.packets.InteractiveResponsePacket
@@ -66,6 +65,7 @@ import de.fiereu.openmmo.server.game.services.InteractionService
import de.fiereu.openmmo.server.game.services.LoginService
import de.fiereu.openmmo.server.game.services.MovementService
import de.fiereu.openmmo.server.game.services.MultiplayerService
import de.fiereu.openmmo.server.game.services.PresenceService
import de.fiereu.openmmo.server.game.services.SocialService
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.SessionRegistry
@@ -84,6 +84,7 @@ constructor(
private val dialogService: DialogService,
private val interactionService: InteractionService,
private val multiplayerService: MultiplayerService,
private val presenceService: PresenceService,
private val socialService: SocialService,
private val guildService: GuildService,
private val battleService: BattleService,
@@ -158,7 +159,7 @@ constructor(
log.info { "Player ${state.characterId} disconnected." }
val charId = state.characterId
if (charId != null) {
multiplayerService.broadcastExcept(session, EntityLeavePacket(charId))
presenceService.leave(session)
sessionRegistry.unbindCharacter(charId)
}
multiplayerService.broadcastMessage(
@@ -3,9 +3,7 @@ package de.fiereu.openmmo.server.game.services
import de.fiereu.network.PacketEvent
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.EntityStatus
import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.maps.MapManager
@@ -16,7 +14,6 @@ import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.net.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.JoinResponsePacket
import de.fiereu.openmmo.net.game.packets.LoadEntityPacket
import de.fiereu.openmmo.net.game.packets.LocalPlayerStatePacket
import de.fiereu.openmmo.net.game.packets.MenuPagePayloadPacket
import de.fiereu.openmmo.net.game.packets.NewAuthData
@@ -77,6 +74,7 @@ constructor(
private val sessionRegistry: SessionRegistry,
private val mapManager: MapManager,
private val characterStore: CharacterStore,
private val presenceService: PresenceService,
) {
fun onJoinGame(event: PacketEvent<JoinPacket>) {
@@ -301,7 +299,7 @@ constructor(
log.info { "Sending LoadEntity for character '${info.name}'" }
val facing = state.facingDirection
val loadEntity = mapLoadService.createLoadEntity(info, facing)
val loadEntity = mapLoadService.createLoadEntity(info, facing, party = stored.pokemon)
ctx.send(loadEntity)
npcService.spawnNpcsForMap(ctx, info.positionBankId.toInt(), info.positionMapId.toInt())
@@ -315,58 +313,12 @@ constructor(
state.x = info.positionX
state.y = info.positionY
val currentParty = characterStore.getCharacter(charId)?.pokemon ?: emptyList()
val hasFollower = currentParty.isNotEmpty()
val followerDexId = (currentParty.firstOrNull()?.dexId ?: 0).toShort()
val others = sessionRegistry.getOthersInMap(charId, regionId, bankId, mapId)
for (other in others) {
val otherState = other.attributes[PLAYER_STATE] ?: continue
val otherCharId = otherState.characterId ?: continue
val otherStored = characterStore.getCharacter(otherCharId) ?: continue
val otherParty: List<Pokemon> = otherStored.pokemon
ctx.send(
LoadEntityPacket(
entityId = otherCharId,
skin = SkinSet(),
name = otherStored.info.name,
regionId = otherState.regionId,
bankId = otherState.bankId,
mapId = otherState.mapId,
x = otherState.x.toInt(),
y = otherState.y.toInt(),
z = 0,
facing = otherState.facingDirection,
status = EntityStatus.NONE,
hasFollower = otherParty.isNotEmpty(),
followerDexId = (otherParty.firstOrNull()?.dexId ?: 0).toShort(),
))
}
val selfEntity =
LoadEntityPacket(
entityId = charId,
skin = SkinSet(),
name = info.name,
regionId = regionId,
bankId = bankId,
mapId = mapId,
x = info.positionX.toInt(),
y = info.positionY.toInt(),
z = 0,
facing = facing,
status = EntityStatus.NONE,
hasFollower = hasFollower,
followerDexId = followerDexId,
)
for (other in others) {
other.send(selfEntity)
}
presenceService.enter(ctx)
ctx.send(RenderScreenPacket(true))
socialService.sendFriendList(ctx)
log.info { "Player $charId spawned in bank=$bankId map=$mapId; ${others.size} others present" }
log.info { "Player $charId spawned in bank=$bankId map=$mapId" }
}
}
@@ -2,6 +2,7 @@ package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.EntityStatus
import de.fiereu.openmmo.maps.MapDef
@@ -23,6 +24,7 @@ constructor(
info: CharacterInfo,
facing: Direction = Direction.DOWN,
z: Int = 0,
party: List<Pokemon> = emptyList(),
): LoadEntityPacket {
return LoadEntityPacket(
entityId = info.id,
@@ -36,8 +38,8 @@ constructor(
z = z,
facing = facing,
status = EntityStatus.NONE,
hasFollower = false,
followerDexId = 0,
hasFollower = party.isNotEmpty(),
followerDexId = (party.firstOrNull()?.dexId ?: 0).toShort(),
)
}
@@ -5,6 +5,7 @@ import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.maps.MapDef
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.packets.EntityFaceTurnPacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket
import de.fiereu.openmmo.net.game.packets.MapData
@@ -12,10 +13,8 @@ import de.fiereu.openmmo.net.game.packets.MovementPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import io.github.oshai.kotlinlogging.KotlinLogging
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.abs
private val log = KotlinLogging.logger {}
@@ -26,161 +25,115 @@ constructor(
private val warpService: WarpService,
private val mapLoadService: MapLoadService,
private val npcService: NpcService,
private val multiplayerService: MultiplayerService,
private val presenceService: PresenceService,
private val mapManager: MapManager,
private val characterStore: CharacterStore,
) {
private val sequenceCounter = AtomicInteger(0)
/** One step. The client sends the tile it left and the direction, the server derives the rest. */
fun onMovement(event: PacketEvent<MovementPacket>) {
val ctx = event.session
val state = ctx.attributes[PLAYER_STATE] ?: return
val charId = state.characterId ?: return
val msg = event.packet
log.info { "Movement: char=$charId, x=${msg.x}, y=${msg.y}, dir=${msg.direction}" }
state.facingDirection = msg.direction
log.debug { "Movement: char=$charId from (${msg.x}, ${msg.y}) dir=${msg.direction}" }
val prevStored = characterStore.getCharacter(charId)
val prevX = prevStored?.info?.positionX?.toInt()
val prevY = prevStored?.info?.positionY?.toInt()
val isWallBump = prevX == msg.x && prevY == msg.y
val stored = characterStore.getCharacter(charId) ?: return
val fromX = stored.info.positionX.toInt()
val fromY = stored.info.positionY.toInt()
val atServerTile = msg.x == fromX && msg.y == fromY
val stored = characterStore.getCharacter(charId)
if (stored != null) {
val currentMap =
mapManager.getMap(
stored.info.positionRegionId,
stored.info.positionBankId,
stored.info.positionMapId,
)
if (currentMap != null) {
if (state.justWarped) {
state.justWarped = false
} else {
val warp =
currentMap.warps.find { w ->
w.x == msg.x &&
w.y == msg.y &&
(w.facingDirection == null || w.facingDirection == msg.direction) &&
!isWallBump
}
if (warp != null) {
log.info { "DIRECT WARP at (${msg.x}, ${msg.y}) facing ${msg.direction}" }
warpService.executeWarp(ctx, charId, warp)
return
}
val adjX =
msg.x +
when (msg.direction) {
Direction.RIGHT -> 1
Direction.LEFT -> -1
else -> 0
}
val adjY =
msg.y +
when (msg.direction) {
Direction.UP -> -1
Direction.DOWN -> 1
else -> 0
}
val adjWarp =
currentMap.warps.find { w ->
w.x == adjX &&
w.y == adjY &&
(w.facingDirection == null || w.facingDirection == msg.direction)
}
if (adjWarp != null) {
log.info { "ADJACENT WARP at (${msg.x}, ${msg.y}) facing ${msg.direction}" }
warpService.executeWarp(ctx, charId, adjWarp)
return
}
}
if (prevX != null && prevY != null && !isWallBump) {
val dx = abs(msg.x - prevX)
val dy = abs(msg.y - prevY)
if (dx > 1 || dy > 1) {
val gbaDirection =
when {
prevY == 0 -> Direction.UP
prevY == currentMap.height - 1 -> Direction.DOWN
prevX == 0 -> Direction.LEFT
prevX == currentMap.width - 1 -> Direction.RIGHT
else -> null
}
if (gbaDirection != null) {
val connection = currentMap.connections.find { it.direction == gbaDirection }
if (connection != null) {
val targetMap =
mapManager.getMap(
1,
connection.targetBank.toByte(),
connection.targetMap.toByte(),
)
if (targetMap != null) {
val targetX =
when (gbaDirection) {
Direction.LEFT -> targetMap.width - 1
Direction.RIGHT -> 0
else -> (prevX - connection.unknown).coerceIn(0, targetMap.width - 1)
}
val targetY =
when (gbaDirection) {
Direction.DOWN -> 0
Direction.UP -> targetMap.height - 1
else -> (prevY - connection.unknown).coerceIn(0, targetMap.height - 1)
}
edgeTransition(
ctx,
charId,
connection,
targetX.toByte(),
targetY.toByte(),
msg.direction,
)
return
}
}
}
}
}
if (!isWallBump && !isWalkable(currentMap, msg.x, msg.y)) {
log.debug { "WALL: char=$charId blocked at (${msg.x}, ${msg.y})" }
val seq = sequenceCounter.incrementAndGet().toByte()
ctx.send(
EntityMovePacket(
entityId = charId,
x = stored.info.positionX.toByte(),
y = stored.info.positionY.toByte(),
direction = msg.direction,
seq = seq,
))
return
}
if (state.justWarped) {
// Ignore steps until the client reports the warp destination, so a packet still in flight
// from the old map is dropped rather than applied against the new one.
if (!atServerTile) return
state.justWarped = false
} else if (!atServerTile) {
log.debug {
"DESYNC: char=$charId claims (${msg.x}, ${msg.y}), server has ($fromX, $fromY), resetting"
}
sendPositionReset(ctx, charId, fromX, fromY, state.facingDirection)
return
}
characterStore.updatePosition(charId, msg.x.toShort(), msg.y.toShort())
state.x = msg.x.toShort()
state.y = msg.y.toShort()
if (!isWallBump) {
val seq = sequenceCounter.incrementAndGet().toByte()
val movePkt =
EntityMovePacket(
entityId = charId,
x = msg.x.toByte(),
y = msg.y.toByte(),
direction = msg.direction,
seq = seq,
)
ctx.send(movePkt)
multiplayerService.broadcastExcept(ctx, movePkt)
val currentMap =
mapManager.getMap(
stored.info.positionRegionId,
stored.info.positionBankId,
stored.info.positionMapId,
) ?: return
val toX = fromX + msg.direction.dx
val toY = fromY + msg.direction.dy
// Walking off the edge of a map hands the player to the neighbouring map, if there is one.
if (toX !in 0 until currentMap.width || toY !in 0 until currentMap.height) {
val connection = currentMap.connections.find { it.direction == msg.direction }
val targetMap =
connection?.let { mapManager.getMap(1, it.targetBank.toByte(), it.targetMap.toByte()) }
if (connection == null || targetMap == null) {
sendPositionReset(ctx, charId, fromX, fromY, msg.direction)
return
}
val entryX =
when (msg.direction) {
Direction.LEFT -> targetMap.width - 1
Direction.RIGHT -> 0
else -> (fromX - connection.unknown).coerceIn(0, targetMap.width - 1)
}
val entryY =
when (msg.direction) {
Direction.UP -> targetMap.height - 1
Direction.DOWN -> 0
else -> (fromY - connection.unknown).coerceIn(0, targetMap.height - 1)
}
edgeTransition(ctx, charId, connection, entryX.toByte(), entryY.toByte(), msg.direction)
return
}
// A warp fires on the tile the player steps onto, not the one it left.
val warp =
currentMap.warps.find { w ->
w.x == toX &&
w.y == toY &&
(w.facingDirection == null || w.facingDirection == msg.direction)
}
if (warp != null) {
log.info { "WARP at ($toX, $toY) facing ${msg.direction}" }
warpService.executeWarp(ctx, charId, warp)
return
}
if (!isWalkable(currentMap, toX, toY)) {
log.debug { "WALL: char=$charId blocked at ($toX, $toY)" }
sendPositionReset(ctx, charId, fromX, fromY, msg.direction)
return
}
characterStore.updatePosition(charId, toX.toShort(), toY.toShort())
state.x = toX.toShort()
state.y = toY.toShort()
// The client already walked itself there, so only the observers need telling.
presenceService.broadcastToObservers(
ctx,
EntityMovePacket(entityId = charId, x = toX, y = toY, direction = msg.direction),
)
}
/** Snap the client back to the position the server considers authoritative. */
private fun sendPositionReset(
ctx: SessionContext,
charId: Long,
x: Int,
y: Int,
direction: Direction,
) {
ctx.send(EntityMovePacket(entityId = charId, x = x, y = y, direction = direction))
}
/** Turning in place. Only observers need it, the client has already turned itself. */
fun onFaceDirection(event: PacketEvent<FaceDirectionPacket>) {
val ctx = event.session
val state = ctx.attributes[PLAYER_STATE] ?: return
@@ -188,18 +141,10 @@ constructor(
val msg = event.packet
state.facingDirection = msg.direction
val seq = sequenceCounter.incrementAndGet().toByte()
val stored = characterStore.getCharacter(charId) ?: return
val movePkt =
EntityMovePacket(
entityId = charId,
x = stored.info.positionX.toByte(),
y = stored.info.positionY.toByte(),
direction = msg.direction,
seq = seq,
)
ctx.send(movePkt)
multiplayerService.broadcastExcept(ctx, movePkt)
presenceService.broadcastToObservers(
ctx,
EntityFaceTurnPacket(entityId = charId, facing = msg.direction.ordinal.toByte()),
)
}
private fun isWalkable(map: MapDef, x: Int, y: Int): Boolean {
@@ -234,21 +179,18 @@ constructor(
targetBank,
targetMap,
)
presenceService.refresh(ctx)
mapLoadService.preloadConnectedMaps(ctx, map, depth = 1)
npcService.spawnNpcsForMap(ctx, targetBank.toInt(), targetMap.toInt())
val seq = sequenceCounter.incrementAndGet().toByte()
val movePkt =
ctx.send(
EntityMovePacket(
entityId = charId,
x = targetX,
y = targetY,
x = targetX.toInt(),
y = targetY.toInt(),
direction = direction,
seq = seq,
)
ctx.send(movePkt)
multiplayerService.broadcastExcept(ctx, movePkt)
))
log.info { "Player $charId edge-transitioned to bank=$targetBank map=$targetMap" }
}
}
@@ -1,6 +1,5 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.server.game.session.SessionRegistry
import javax.inject.Inject
import javax.inject.Singleton
@@ -20,13 +19,4 @@ constructor(
}
}
}
fun broadcastExcept(exclude: SessionContext, packet: Any) {
for (characterId in sessionRegistry.onlineCharacterIds()) {
val ctx = sessionRegistry.getByCharacterId(characterId) ?: continue
if (ctx.channel.isActive && ctx.channel != exclude.channel) {
ctx.send(packet)
}
}
}
}
@@ -0,0 +1,97 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.LoadEntityPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.server.game.world.interest.InterestPolicy
import de.fiereu.openmmo.server.game.world.interest.MapInterestKey
import javax.inject.Inject
import javax.inject.Singleton
/**
* Overworld presence built on the generic [InterestManager]. A player's map is one interest group.
* This layer adds the entity spawn/despawn semantics and the area-of-interest filter that only make
* sense for spatial presence.
*/
@Singleton
class PresenceService
@Inject
constructor(
private val interestManager: InterestManager,
private val policy: InterestPolicy,
private val mapLoadService: MapLoadService,
private val characterStore: CharacterStore,
) {
/** Spawn the player into its map group and exchange entity snapshots with its observers. */
fun enter(ctx: SessionContext) {
val key = mapKeyFor(ctx) ?: return
spawnInto(ctx, key)
}
/** Despawn the player from its map observers and drop it from the map group. */
fun leave(ctx: SessionContext) {
val key = currentMapKey(ctx) ?: mapKeyFor(ctx) ?: return
interestManager.leave(ctx, key)
val entityId = entityIdOf(ctx) ?: return
for (other in observers(ctx, key)) other.send(EntityLeavePacket(entityId))
}
/** Send a packet to everyone observing the player on its current map (excludes the player). */
fun broadcastToObservers(ctx: SessionContext, packet: Any) {
val key = currentMapKey(ctx) ?: mapKeyFor(ctx) ?: return
for (other in observers(ctx, key)) other.send(packet)
}
/**
* Recompute the player's map group from its (already updated) state: despawn it from the map it
* left, spawn it into the map it joined. Call after changing a player's map.
*/
fun refresh(ctx: SessionContext) {
val newKey = mapKeyFor(ctx)
val oldKey = currentMapKey(ctx)
if (oldKey == newKey) return
if (oldKey != null) {
interestManager.leave(ctx, oldKey)
val entityId = entityIdOf(ctx)
if (entityId != null) {
for (other in observers(ctx, oldKey)) other.send(EntityLeavePacket(entityId))
}
}
if (newKey != null) spawnInto(ctx, newKey)
}
private fun spawnInto(ctx: SessionContext, key: MapInterestKey) {
val observers = observers(ctx, key)
val self = loadEntityFor(ctx)
for (other in observers) {
if (self != null) other.send(self)
loadEntityFor(other)?.let { ctx.send(it) }
}
interestManager.join(ctx, key)
}
private fun observers(ctx: SessionContext, key: MapInterestKey): List<SessionContext> =
policy.filter(ctx, interestManager.members(key))
private fun mapKeyFor(ctx: SessionContext): MapInterestKey? {
val state = ctx.attributes[PLAYER_STATE] ?: return null
return MapInterestKey(state.regionId, state.bankId, state.mapId)
}
private fun currentMapKey(ctx: SessionContext): MapInterestKey? =
interestManager.keysOf(ctx).filterIsInstance<MapInterestKey>().firstOrNull()
private fun entityIdOf(ctx: SessionContext): Long? = ctx.attributes[PLAYER_STATE]?.characterId
private fun loadEntityFor(ctx: SessionContext): LoadEntityPacket? {
val state = ctx.attributes[PLAYER_STATE] ?: return null
val charId = state.characterId ?: return null
val stored = characterStore.getCharacter(charId) ?: return null
return mapLoadService.createLoadEntity(
stored.info, state.facingDirection, party = stored.pokemon)
}
}
@@ -4,12 +4,10 @@ import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.SessionRegistry
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.WarpExitRules
import io.github.oshai.kotlinlogging.KotlinLogging
@@ -25,7 +23,7 @@ constructor(
private val mapLoadService: MapLoadService,
private val mapManager: MapManager,
private val characterStore: CharacterStore,
private val sessionRegistry: SessionRegistry,
private val presenceService: PresenceService,
) {
fun executeWarp(ctx: SessionContext, charId: Long, warp: WarpTile) {
@@ -97,17 +95,6 @@ constructor(
)
characterStore.updateCharacter(newInfo)
val oldRegionId = state?.regionId
val oldBankId = state?.bankId
val oldMapId = state?.mapId
if (oldBankId != null && oldMapId != null) {
val oldMapPlayers =
sessionRegistry.getOthersInMap(charId, oldRegionId ?: 1, oldBankId, oldMapId)
for (other in oldMapPlayers) {
other.send(EntityLeavePacket(charId))
}
}
if (state != null) {
state.regionId = warp.targetRegionId.toInt()
state.bankId = warp.targetBankId.toInt()
@@ -130,6 +117,8 @@ constructor(
}
}
presenceService.refresh(ctx)
log.info { "Player $charId warped to bank=${warp.targetBankId} map=${warp.targetMapId}" }
}
}
@@ -34,21 +34,5 @@ class SessionRegistry @Inject constructor() {
fun getByCharacterId(id: Long): SessionContext? = sessionsByCharacter[id]
fun getOthersInMap(
excludeCharacterId: Long,
regionId: Int,
bankId: Int,
mapId: Int,
): List<SessionContext> =
sessionsByCharacter.values.filter { ctx ->
val state = ctx.attributes[PLAYER_STATE] ?: return@filter false
state.characterId != excludeCharacterId &&
state.regionId == regionId &&
state.bankId == bankId &&
state.mapId == mapId
}
fun onlineCharacterIds(): Set<Long> = sessionsByCharacter.keys
fun isOnline(id: Long): Boolean = sessionsByCharacter.containsKey(id)
}
@@ -12,15 +12,17 @@ import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import javax.inject.Singleton
// A starter party monster for the dev test character. Its uid, species, HP, and moves match the
// field state emitted by the test battle so the client can resolve the player's monster.
const val STARTER_SNIVY_UID = 0x000000000001C000L
// The starter party every new character gets.
const val SNIVY_DEX_ID = 495
// A second party monster so the switch action is selectable in the test battle.
const val STARTER_PATRAT_UID = 0x000000000002C000L
const val PATRAT_DEX_ID = 504
// Low bits tag an entity id's kind, so character and monster ids never collide.
private const val CHARACTER_ID_TAG = 0x9000L
private const val MONSTER_ID_TAG = 0xC000L
// Dev accounts, one character each.
private val DEV_CHARACTER_NAMES = mapOf(1 to "Test", 2 to "Test2")
data class StoredCharacter(
val info: CharacterInfo,
val pokemon: MutableList<Pokemon>,
@@ -32,30 +34,25 @@ data class StoredCharacter(
class CharacterStore @Inject constructor() {
private val characters = ConcurrentHashMap<Long, StoredCharacter>()
private val charactersByUser = ConcurrentHashMap<Int, MutableList<Long>>()
private val nextCharId = AtomicLong(1)
private val nextEntityId = AtomicLong(1)
init {
ensureTestCharacter()
ensureDevCharacters()
}
private fun ensureTestCharacter() {
if (characters.isEmpty()) {
val test = createCharacter(userId = 1, name = "Test")
test.pokemon.add(starterSnivy(test.info.id, test.info.name))
test.pokemon.add(starterPatrat(test.info.id, test.info.name))
}
private fun ensureDevCharacters() {
if (characters.isNotEmpty()) return
for ((userId, name) in DEV_CHARACTER_NAMES) createCharacter(userId, name)
}
private fun generateEntityId(): Long {
val uniqueId = nextCharId.getAndIncrement()
return (uniqueId shl 16) or 0x9000L
}
private fun generateEntityId(tag: Long): Long = (nextEntityId.getAndIncrement() shl 16) or tag
/** Create a character with its own entity id and a starter party with its own monster uids. */
fun createCharacter(
userId: Int,
name: String,
): StoredCharacter {
val id = generateEntityId()
val id = generateEntityId(CHARACTER_ID_TAG)
val now = LocalDateTime.now()
val info =
CharacterInfo(
@@ -84,6 +81,8 @@ class CharacterStore @Inject constructor() {
lureItemId = 0,
)
val stored = StoredCharacter(info, mutableListOf(), mutableListOf(), mutableMapOf())
stored.pokemon.add(starterSnivy(id, name))
stored.pokemon.add(starterPatrat(id, name))
characters[id] = stored
charactersByUser.getOrPut(userId) { mutableListOf() }.add(id)
return stored
@@ -121,7 +120,7 @@ class CharacterStore @Inject constructor() {
private fun starterSnivy(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = STARTER_SNIVY_UID,
id = generateEntityId(MONSTER_ID_TAG),
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 0,
@@ -152,7 +151,7 @@ class CharacterStore @Inject constructor() {
private fun starterPatrat(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = STARTER_PATRAT_UID,
id = generateEntityId(MONSTER_ID_TAG),
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 1,
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.server.game.world.interest
/**
* Identifies an interest group a session can belong to. A session may be in several groups at once
* (its map, its guild, a battle) so the same manager can drive overworld presence, guild chat, or
* battle updates. Add a variant to introduce a new group kind.
*/
sealed interface InterestKey
data class MapInterestKey(val regionId: Int, val bankId: Int, val mapId: Int) : InterestKey
data class GuildInterestKey(val guildId: Long) : InterestKey
data class BattleInterestKey(val battleId: Long) : InterestKey
@@ -0,0 +1,57 @@
package de.fiereu.openmmo.server.game.world.interest
import de.fiereu.network.SessionContext
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
/**
* Tracks which sessions belong to which interest groups and fans packets out to a group. It is
* purpose-agnostic: the same instance backs overworld presence (see [PresenceService]), guild chat,
* or battle updates depending on the [InterestKey] used. What a group *means* (spawning entities,
* area-of-interest filtering, ...) lives in the consumer, not here.
*/
@Singleton
class InterestManager @Inject constructor() {
private val buckets = ConcurrentHashMap<InterestKey, MutableSet<SessionContext>>()
private val membership = ConcurrentHashMap<SessionContext, MutableSet<InterestKey>>()
fun join(ctx: SessionContext, key: InterestKey) {
buckets.getOrPut(key) { ConcurrentHashMap.newKeySet() }.add(ctx)
membership.getOrPut(ctx) { ConcurrentHashMap.newKeySet() }.add(key)
}
fun leave(ctx: SessionContext, key: InterestKey) {
buckets[key]?.let { members ->
members.remove(ctx)
if (members.isEmpty()) buckets.remove(key, members)
}
membership[ctx]?.let { keys ->
keys.remove(key)
if (keys.isEmpty()) membership.remove(ctx, keys)
}
}
/** Drop the session from every group it belongs to (e.g. on disconnect). */
fun leaveAll(ctx: SessionContext) {
val keys: Set<InterestKey> = membership.remove(ctx) ?: return
for (key in keys) {
buckets[key]?.let { members ->
members.remove(ctx)
if (members.isEmpty()) buckets.remove(key, members)
}
}
}
/** A snapshot of the group's members. Safe to iterate while the group mutates. */
fun members(key: InterestKey): Set<SessionContext> = buckets[key]?.toSet() ?: emptySet()
/** The groups the session currently belongs to. */
fun keysOf(ctx: SessionContext): Set<InterestKey> = membership[ctx]?.toSet() ?: emptySet()
/** Send a packet to every member of the group, optionally excluding one session (the sender). */
fun broadcast(key: InterestKey, packet: Any, exclude: SessionContext? = null) {
val members: Set<SessionContext> = buckets[key] ?: return
for (ctx in members) if (ctx !== exclude) ctx.send(packet)
}
}
@@ -0,0 +1,22 @@
package de.fiereu.openmmo.server.game.world.interest
import de.fiereu.network.SessionContext
import javax.inject.Inject
import javax.inject.Singleton
/**
* Filters a subject's bucket members down to the sessions that should actually observe it. The
* default passes the whole bucket through. A radius-based policy would slot in here without
* touching callers.
*/
fun interface InterestPolicy {
fun filter(subject: SessionContext, candidates: Collection<SessionContext>): List<SessionContext>
}
@Singleton
class PassThroughInterestPolicy @Inject constructor() : InterestPolicy {
override fun filter(
subject: SessionContext,
candidates: Collection<SessionContext>,
): List<SessionContext> = candidates.filter { it !== subject }
}
@@ -0,0 +1,102 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.net.game.packets.LoadEntityPacket
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class PresenceServiceTest :
FunSpec({
val mapManager = MapManager()
fun freshPresence(): Pair<PresenceService, CharacterStore> {
val store = CharacterStore()
val presence =
PresenceService(
InterestManager(), PassThroughInterestPolicy(), MapLoadService(mapManager), store)
return presence to store
}
fun CharacterStore.session(name: String, mapId: Int = 3): FakeSession {
val character = createCharacter(userId = 1, name = name)
return FakeSession(characterId = character.info.id, mapId = mapId)
}
fun FakeSession.spawnedEntityIds(): List<Long> =
sent.filterIsInstance<LoadEntityPacket>().map { it.entityId }
fun FakeSession.id(): Long = state().characterId!!
test("entering exchanges entity snapshots with co-located observers") {
val (presence, store) = freshPresence()
val a = store.session("A")
val b = store.session("B")
presence.enter(a)
a.sent shouldBe emptyList() // nobody else here yet
presence.enter(b)
a.spawnedEntityIds() shouldBe listOf(b.id())
b.spawnedEntityIds() shouldBe listOf(a.id())
}
test("movement propagates only to observers on the same map") {
val (presence, store) = freshPresence()
val a = store.session("A", mapId = 3)
val b = store.session("B", mapId = 3)
val c = store.session("C", mapId = 9)
presence.enter(a)
presence.enter(b)
presence.enter(c)
listOf(a, b, c).forEach { it.sent.clear() }
val move = EntityMovePacket(entityId = a.id(), x = 1, y = 1, direction = Direction.DOWN)
presence.broadcastToObservers(a, move)
b.sent shouldBe listOf(move)
c.sent shouldBe emptyList()
a.sent shouldBe emptyList()
}
test("leaving despawns the player from its observers") {
val (presence, store) = freshPresence()
val a = store.session("A")
val b = store.session("B")
presence.enter(a)
presence.enter(b)
listOf(a, b).forEach { it.sent.clear() }
presence.leave(b)
a.sent shouldBe listOf(EntityLeavePacket(b.id()))
val move = EntityMovePacket(entityId = a.id(), x = 1, y = 1, direction = Direction.DOWN)
presence.broadcastToObservers(a, move)
b.sent shouldBe emptyList() // no longer observing
}
test("refresh relocates the player between maps") {
val (presence, store) = freshPresence()
val a = store.session("A", mapId = 3)
val d = store.session("D", mapId = 4)
val b = store.session("B", mapId = 3)
presence.enter(a)
presence.enter(d)
presence.enter(b)
listOf(a, b, d).forEach { it.sent.clear() }
b.state().mapId = 4
presence.refresh(b)
a.sent shouldBe listOf(EntityLeavePacket(b.id())) // despawned from the old map
d.spawnedEntityIds() shouldBe listOf(b.id()) // spawned to the new map
b.spawnedEntityIds() shouldBe listOf(d.id())
}
})
@@ -0,0 +1,81 @@
package de.fiereu.openmmo.server.game.testsupport
import de.fiereu.network.SessionAttribute
import de.fiereu.network.SessionAttributes
import de.fiereu.network.SessionContext
import de.fiereu.network.SessionPhase
import de.fiereu.network.Side
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.PlayerState
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.embedded.EmbeddedChannel
import java.net.InetSocketAddress
import java.net.SocketAddress
import java.time.Instant
/** In-memory [SessionAttributes] for tests. */
class MapAttributes : SessionAttributes {
private val map = HashMap<SessionAttribute<*>, Any>()
@Suppress("UNCHECKED_CAST")
override fun <T : Any> get(key: SessionAttribute<T>): T? = map[key] as T?
override fun <T : Any> set(key: SessionAttribute<T>, value: T) {
map[key] = value
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any> remove(key: SessionAttribute<T>): T? = map.remove(key) as T?
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getOrPut(key: SessionAttribute<T>, default: () -> T): T =
map.getOrPut(key) { default() } as T
override fun contains(key: SessionAttribute<*>): Boolean = map.containsKey(key)
}
/** A [SessionContext] that records everything sent to it, for asserting propagation. */
class FakeSession(
characterId: Long? = null,
regionId: Int = 1,
bankId: Int = 51,
mapId: Int = 3,
facing: Direction = Direction.DOWN,
) : SessionContext {
val sent = mutableListOf<Any>()
private val ch = EmbeddedChannel()
override val attributes = MapAttributes()
init {
attributes[PLAYER_STATE] =
PlayerState(
userId = 0,
characterId = characterId,
regionId = regionId,
bankId = bankId,
mapId = mapId,
facingDirection = facing,
)
}
fun state(): PlayerState = attributes[PLAYER_STATE]!!
override val side: Side = Side.SERVER
override val channel: Channel
get() = ch
override val remoteAddress: SocketAddress = InetSocketAddress("127.0.0.1", 0)
override val phase: SessionPhase = SessionPhase.ESTABLISHED
override val handshakeCompletedAt: Instant? = null
override fun send(packet: Any): ChannelFuture {
sent += packet
return ch.newSucceededFuture()
}
override fun close(reason: () -> String) {}
override fun onPhase(phase: SessionPhase, listener: () -> Unit) {}
}
@@ -0,0 +1,60 @@
package de.fiereu.openmmo.server.game.world.interest
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
import io.kotest.matchers.shouldBe
class InterestManagerTest :
FunSpec({
val map = MapInterestKey(1, 51, 3)
val guild = GuildInterestKey(7)
test("a session can belong to several groups at once and groups stay independent") {
val manager = InterestManager()
val a = FakeSession(characterId = 1)
val b = FakeSession(characterId = 2)
val c = FakeSession(characterId = 3)
manager.join(a, map)
manager.join(b, map)
manager.join(a, guild)
manager.join(c, guild)
manager.members(map) shouldContainExactlyInAnyOrder listOf(a, b)
manager.members(guild) shouldContainExactlyInAnyOrder listOf(a, c)
manager.keysOf(a) shouldContainExactlyInAnyOrder listOf(map, guild)
}
test("broadcast reaches only the group's members and can exclude the sender") {
val manager = InterestManager()
val a = FakeSession(characterId = 1)
val b = FakeSession(characterId = 2)
val c = FakeSession(characterId = 3)
manager.join(a, map)
manager.join(b, map)
manager.join(a, guild)
manager.join(c, guild)
manager.broadcast(guild, "guild-hello", exclude = a)
a.sent shouldBe emptyList()
b.sent shouldBe emptyList() // b is not in the guild group
c.sent shouldBe listOf("guild-hello")
}
test("leaveAll removes the session from every group") {
val manager = InterestManager()
val a = FakeSession(characterId = 1)
val b = FakeSession(characterId = 2)
manager.join(a, map)
manager.join(b, map)
manager.join(a, guild)
manager.leaveAll(a)
manager.keysOf(a) shouldBe emptySet()
manager.members(map) shouldContainExactlyInAnyOrder listOf(b)
manager.members(guild) shouldBe emptySet()
}
})