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

@@ -1,12 +1,12 @@
package de.fiereu.openmmo.common.enums
enum class Direction {
DOWN,
UP,
LEFT,
RIGHT,
DIVE,
EMERGE;
enum class Direction(val dx: Int, val dy: Int) {
DOWN(0, 1),
UP(0, -1),
LEFT(-1, 0),
RIGHT(1, 0),
DIVE(0, 0),
EMERGE(0, 0);
fun opposite(): Direction =
when (this) {
+4
View File
@@ -19,6 +19,10 @@ export default defineConfig({
},
],
sidebar: [
{
label: "Concepts",
items: [{ autogenerate: { directory: "concepts" } }],
},
{ label: "Guides", items: [{ autogenerate: { directory: "guides" } }] },
],
}),
+9
View File
@@ -0,0 +1,9 @@
---
title: Concepts
description: Short explanations of the systems that make up OpenMMO.
---
Short explanations of the systems that make up OpenMMO.
- [The InterestManager](interest-manager/): how packets reach the right
players instead of everyone online.
@@ -0,0 +1,73 @@
---
title: The InterestManager
description: How the server decides which players receive a packet.
---
When a player does something, other players need to hear about it. A player
walking across Slateport should show up on the screens of the players standing
there, and nobody else. Sending every packet to every online player would be
wasteful and leak things players should not see.
The `InterestManager` solves this. It lives in
`server.game/src/main/kotlin/de/fiereu/openmmo/server/game/world/interest/`.
## The idea
Players are grouped into **interest groups**. A group is identified by an
`InterestKey`, a small value like "this map" or "this guild". A session can be
in several groups at the same time: its current map, its guild, and a running
battle all at once.
The manager itself is intentionally dumb. It only knows three things:
- `join(ctx, key)` / `leave(ctx, key)`: put a session into a group or take it out.
- `members(key)`: who is in a group right now.
- `broadcast(key, packet, exclude)`: send a packet to everyone in a group,
usually excluding the sender.
It does not know what a map, a guild, or a battle is. What a group *means* is
decided by the service that uses it.
## Movement, as an example
Overworld presence is built on top of the manager by `PresenceService`
(`server.game/.../services/PresenceService.kt`). Each map is one interest
group (`MapInterestKey`). When a player spawns, `PresenceService.enter` joins
them to their map's group and exchanges entity snapshots with the players
already there. When a `MovementPacket` comes in, `MovementService` calls
`presenceService.broadcastMove(ctx, movePkt)`, which fans the move out to that
map's group only. Warping or walking off a map edge calls `refresh`, which
despawns the player from the old group and spawns them into the new one.
## When to use it
Use the `InterestManager` whenever one player's action should reach a
*specific set* of other players:
- guild chat and guild notifications
- battle updates to the participants and spectators
- trade windows, parties, and similar shared sessions
Do not use it for truly global traffic (server announcements, global chat).
That is what `MultiplayerService` is for.
## How to use it
1. Pick or add a key. `InterestKey` is a sealed interface in `InterestKey.kt`.
`MapInterestKey`, `GuildInterestKey`, and `BattleInterestKey` already exist.
Add a new data class variant for a new kind of group.
2. Inject the `InterestManager` (it is a Dagger `@Singleton`) into your service.
3. Call `join` when a player enters your group (logs in, joins the guild,
enters the battle) and `leave` when they exit. `leaveAll(ctx)` removes a
session from every group on disconnect.
4. Call `broadcast(key, packet, exclude = sender)` to notify the group.
```kotlin
// Guild chat, sketched:
interestManager.join(ctx, GuildInterestKey(guildId)) // on login
interestManager.broadcast(GuildInterestKey(guildId), chatPkt) // on message
```
If your feature needs more than membership, for example spawn and despawn
packets when players come and go, follow the `PresenceService` pattern: build
a small service on top of the manager and put the semantics there.
+1
View File
@@ -8,6 +8,7 @@ project is built and how to work on it.
## Sections
- [Concepts](concepts/): short explanations of the systems that make up OpenMMO.
- [Guides](guides/): step-by-step how-tos for common tasks.
More sections will be added over time.
@@ -564,9 +564,7 @@ object GameProtocol : Protocol() {
c2s<BattleRewardSelectPacket>(0xE3u, BattleRewardSelectPacketCodec)
c2s<BattleChallengeRequestPacket>(0xE4u, BattleChallengeRequestPacketCodec)
s2c<EntityCounterPulsePacket>(0xE4u, EntityCounterPulsePacketCodec)
s2c<EntityMovePacket>(0xEAu, EntityMovePacketCodec)
s2c<EntityMovePacket>(0xE4u, EntityMovePacketCodec)
s2c<QueuePositionPacket>(0xF0u, QueuePositionPacketCodec)
@@ -1,31 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U16LE
/**
* Opcode 0xE4 (s2c). Sent in a burst at battle resolution, once per step, all referencing the same
* transient entity. Each packet carries a sequence value that increments across the burst. Its
* meaning is not yet decoded, so the fields keep their wire names.
*/
data class EntityCounterPulsePacket(
val entityId: Long,
val tagA: Byte,
val tagB: Byte,
val sequence: Int,
val endFlag: Byte,
)
object EntityCounterPulsePacketCodec : PacketCodec<EntityCounterPulsePacket>() {
override fun CodecScope<EntityCounterPulsePacket>.body(): EntityCounterPulsePacket {
val entityId = field(S64LE) { it.entityId }
val tagA = field(S8) { it.tagA }
val tagB = field(S8) { it.tagB }
val sequence = field(U16LE) { it.sequence }
val endFlag = field(S8) { it.endFlag }
return EntityCounterPulsePacket(entityId, tagA, tagB, sequence, endFlag)
}
}
@@ -2,13 +2,13 @@ package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64BE
import de.fiereu.bytecodec.S64LE
data class EntityLeavePacket(val entityId: Long)
object EntityLeavePacketCodec : PacketCodec<EntityLeavePacket>() {
override fun CodecScope<EntityLeavePacket>.body(): EntityLeavePacket {
val entityId = field(S64BE) { it.entityId }
val entityId = field(S64LE) { it.entityId }
return EntityLeavePacket(entityId)
}
}
@@ -1,15 +1,17 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.*
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.enumByOrdinalByte
import de.fiereu.openmmo.common.enums.Direction
/** Opcode 0xE4 (s2c). Another entity's tile after one step and the direction it walked. */
data class EntityMovePacket(
val entityId: Long,
val marker: Byte = 0x33,
val subtype: Byte = 0x03,
val seq: Byte = 0,
val x: Byte,
val y: Byte,
val x: Int,
val y: Int,
val direction: Direction,
)
@@ -17,13 +19,10 @@ object EntityMovePacketCodec : PacketCodec<EntityMovePacket>() {
private val DirectionCodec = enumByOrdinalByte<Direction>()
override fun CodecScope<EntityMovePacket>.body(): EntityMovePacket {
val entityId = field(S64BE) { it.entityId }
val marker = field(S8) { it.marker }
val subtype = field(S8) { it.subtype }
val seq = field(S8) { it.seq }
val x = field(S8) { it.x }
val y = field(S8) { it.y }
val entityId = field(S64LE) { it.entityId }
val x = field(S16LE) { it.x.toShort() }.toInt()
val y = field(S16LE) { it.y.toShort() }.toInt()
val direction = field(DirectionCodec) { it.direction }
return EntityMovePacket(entityId, marker, subtype, seq, x, y, direction)
return EntityMovePacket(entityId, x, y, direction)
}
}
@@ -45,7 +45,7 @@ class GameProtocolTest :
0xB4u.toUByte(),
0xB9u.toUByte(),
0xC2u.toUByte(),
0xEAu.toUByte(),
0xE4u.toUByte(),
)
}
@@ -57,9 +57,9 @@ class GameProtocolTest :
0x01u
}
test("0xEA EntityMovePacket is S2C only") {
test("0xE4 EntityMovePacket is S2C only") {
GameProtocol.outgoingRegistration(Side.SERVER, EntityMovePacket::class)?.opcode shouldBe
0xEAu
0xE4u
GameProtocol.outgoingRegistration(Side.CLIENT, EntityMovePacket::class) shouldBe null
}
@@ -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()
}
})
@@ -16,6 +16,7 @@ import de.fiereu.openmmo.net.login.packets.PasswordLogin
import de.fiereu.openmmo.net.login.packets.RequestGameServerListPacket
import de.fiereu.openmmo.server.login.auth.UserService
import de.fiereu.openmmo.server.login.catalog.GameServerCatalog
import de.fiereu.openmmo.server.login.session.AUTHED_USER_ID
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
@@ -47,6 +48,9 @@ constructor(
}
val result = users.authenticate(packet.username, method.password)
log.info { "Login attempt for ${packet.username}: ${result.state}" }
if (result.state == LoginState.AUTHED && result.userId != null) {
event.session.attributes[AUTHED_USER_ID] = result.userId
}
event.session.send(LoginResponsePacket(result.state))
}
@@ -61,11 +65,17 @@ constructor(
event.session.send(GameServerNodesPacket(LoginState.NO_GS_AVAILABLE))
return
}
val token = tokenIssuer.issue(userId = ANONYMOUS_USER_ID)
val userId = event.session.attributes[AUTHED_USER_ID]
if (userId == null) {
log.warn { "Join game server without a completed login" }
event.session.send(GameServerNodesPacket(LoginState.INVALID_SAVED_CREDENTIALS))
return
}
val token = tokenIssuer.issue(userId = userId.toLong())
val data =
GameServerData(
gameServerId = entry.server.id,
userId = ANONYMOUS_USER_ID.toInt(),
userId = userId,
sessionToken = token.bytes,
localAddress = entry.localAddress,
localHostname = entry.localHostname,
@@ -79,8 +89,4 @@ constructor(
),
)
}
companion object {
private const val ANONYMOUS_USER_ID = 1L
}
}
@@ -0,0 +1,6 @@
package de.fiereu.openmmo.server.login.session
import de.fiereu.network.SessionAttribute
/** The account id a login session authenticated as, sent on to the game server when it joins. */
val AUTHED_USER_ID = SessionAttribute.of<Int>("authedUserId")