refactor(game): split protocol handler into focused services

This commit is contained in:
LananaHWP authored and Fiereu committed 2026-05-26 16:15:38 +02:00
1 parent 80db48878c
commit 4e367fb5bb
15 files changed
+8697 -14435

No files matched your search

@@ -4,5 +4,13 @@ enum class Direction {
DOWN, DOWN,
UP, UP,
LEFT, LEFT,
RIGHT RIGHT;
fun opposite(): Direction =
when (this) {
DOWN -> UP
UP -> DOWN
LEFT -> RIGHT
RIGHT -> LEFT
}
} }
+67 -80
View File
@@ -41,77 +41,55 @@ function resolveMap(name) {
return mapToAddress[name] || mapNameLookup[normalizeMapName(name)]; return mapToAddress[name] || mapNameLookup[normalizeMapName(name)];
} }
// ---- Known palette mappings from capture ---- // ---- Music ID lookup (from songs.h) ----
// tileset_pair_key (primary_secondary) -> [paletteIdx1, paletteIdx2] const musicIds = {};
const knownPalettes = { (function buildMusicTable() {
'gTileset_Building_gTileset_BrendansMaysHouse': [116, 142], const songsH = fs.readFileSync(`${POKEEMERALD}/include/constants/songs.h`, 'utf-8');
'gTileset_Building_gTileset_Lab': [116, 143], for (const line of songsH.split('\n')) {
'gTileset_Building_gTileset_ContestHall': [106, 123], const m = line.match(/^#define\s+(MUS_\w+)\s+(\d+)/);
'gTileset_Building_gTileset_GenericBuilding': [98, 128], if (m) musicIds[m[1]] = parseInt(m[2], 10);
'gTileset_Building_gTileset_PlayersRoom': [100, 134],
'gTileset_Building_gTileset_PokemonCenter': [87, 121],
'gTileset_Building_gTileset_PokemonCenterHoenn': [87, 121],
'gTileset_Building_gTileset_PokemonCenterContest': [87, 121],
'gTileset_Building_gTileset_MauvilleGym': [84, 120],
'gTileset_Building_gTileset_DewfordGym': [90, 124],
'gTileset_Building_gTileset_RustboroGym': [82, 118],
'gTileset_Building_gTileset_LilycoveContestLobby': [104, 136],
'gTileset_Building_gTileset_MossdeepGym': [108, 138],
'gTileset_Building_gTileset_SootopolisGym': [110, 140],
'gTileset_Building_gTileset_SlateportGym': [86, 122],
'gTileset_Building_gTileset_FortreeGym': [94, 126],
'gTileset_Building_gTileset_LavaridgeGym': [92, 128],
'gTileset_Building_gTileset_ShoalCaveGym': [96, 130],
'gTileset_Building_gTileset_Cave': [82, 144],
'gTileset_Building_gTileset_SeaCave': [82, 144],
'gTileset_Building_gTileset_OceanicMuseum': [102, 135],
'gTileset_Building_gTileset_ArtisanCave': [84, 146],
'gTileset_General_gTileset_Petalburg': [100, 101],
'gTileset_General_gTileset_Route104': [92, 113],
'gTileset_General_gTileset_Route110': [92, 115],
'gTileset_General_gTileset_Route119': [94, 117],
'gTileset_General_gTileset_Fortree': [94, 126],
'gTileset_General_gTileset_Mauville': [84, 120],
'gTileset_General_gTileset_Slateport': [86, 122],
'gTileset_General_gTileset_Lilycove': [104, 136],
'gTileset_General_gTileset_Mossdeep': [108, 138],
'gTileset_General_gTileset_Pacifidlog': [112, 148],
'gTileset_General_gTileset_Sootopolis': [110, 140],
'gTileset_General_gTileset_EverGrande': [96, 130],
'gTileset_General_gTileset_Rustboro': [82, 118],
'gTileset_General_gTileset_Dewford': [90, 124],
'gTileset_General_gTileset_Lavaridge': [92, 128],
'gTileset_General_gTileset_Fallarbor': [88, 126],
'gTileset_General_gTileset_Verdanturf': [96, 132],
'gTileset_General_gTileset_PacifidlogWait': [112, 148],
'gTileset_General_gTileset_BattleFrontier': [114, 150],
'gTileset_General_gTileset_Oldale': [98, 128],
'gTileset_Cave_gTileset_Cave': [82, 144],
'gTileset_Cave_gTileset_SeaCave': [82, 144],
'gTileset_Cave_gTileset_IcyCave': [80, 140],
'gTileset_Cave_gTileset_Desert': [88, 146],
'gTileset_Cave_gTileset_Underwater': [86, 148],
'gTileset_Cave_gTileset_GraniteCave': [84, 146],
'gTileset_Cave_gTileset_MagmaHideout': [85, 147],
'gTileset_Cave_gTileset_AquaHideout': [86, 148],
};
// Map type -> default palette ranges
function guessPalette(primaryTileset, secondaryTileset, mapType) {
const key = `${primaryTileset}_${secondaryTileset}`;
if (knownPalettes[key]) return knownPalettes[key];
// Assign unique IDs based on tileset names (stable hash-like)
let h1 = 0, h2 = 0;
const s = key;
for (let i = 0; i < s.length; i++) {
h1 = (h1 * 31 + s.charCodeAt(i)) & 0xFFFF;
h2 = (h2 * 17 + s.charCodeAt(i)) & 0xFFFF;
} }
return [80 + (h1 % 60), 80 + (h2 % 60)]; })();
// ---- MAPSEC index lookup (from region_map_sections.json) ----
const mapsecIds = {};
(function buildMapsecTable() {
const sectionsJson = JSON.parse(fs.readFileSync(`${POKEEMERALD}/src/data/region_map/region_map_sections.json`, 'utf-8'));
const sections = sectionsJson.map_sections || [];
for (let i = 0; i < sections.length; i++) {
mapsecIds[sections[i].id] = i;
}
})();
// ---- Tileset palette index lookup (from headers.h order, starting at 100) ----
const tilesetPaletteIds = {};
(function buildTilesetPaletteTable() {
const headersH = fs.readFileSync(`${POKEEMERALD}/src/data/tilesets/headers.h`, 'utf-8');
let index = 0;
for (const line of headersH.split('\n')) {
const m = line.match(/^const struct Tileset\s+(gTileset_\w+)\s*=/);
if (m) {
tilesetPaletteIds[m[1]] = 100 + index;
index++;
}
}
})();
function getPalette(primaryTileset, secondaryTileset) {
const pal1 = tilesetPaletteIds[primaryTileset];
const pal2 = tilesetPaletteIds[secondaryTileset];
if (pal1 !== undefined && pal2 !== undefined) return [pal1, pal2];
// Fallback for unknown tilesets
return [80, 82];
}
// Map type -> default palette ranges (fallback only)
function guessPalette(primaryTileset, secondaryTileset, mapType) {
return getPalette(primaryTileset, secondaryTileset);
} }
// ---- Direction mapping ---- // ---- Direction mapping ----
const dirMap = { south: 1, north: 2, west: 3, east: 4 }; const dirMap = { down: 1, up: 2, left: 3, right: 4, dive: 5, emerge: 6 };
// Movement type name -> value lookup // Movement type name -> value lookup
const movementTypes = { const movementTypes = {
@@ -213,8 +191,14 @@ const gfxIds = {};
const facingDirection = { south: 0, north: 1, west: 2, east: 3 }; const facingDirection = { south: 0, north: 1, west: 2, east: 3 };
function movementToFaceDir(movementType) { function movementToFaceDir(movementType) {
// Extract initial facing direction from movement type // Extract initial facing direction from movement type.
if (movementType >= 7 && movementType <= 10) return movementType - 7; // FACE_UP=7→1, FACE_DOWN=8→0, FACE_LEFT=9→2, FACE_RIGHT=10→3 // GBA facing values: DOWN=0, UP=1, LEFT=2, RIGHT=3
if (movementType >= 7 && movementType <= 10) {
// FACE_UP=7→UP(1), FACE_DOWN=8→DOWN(0), FACE_LEFT=9→LEFT(2), FACE_RIGHT=10→RIGHT(3)
if (movementType == 7) return 1; // UP → north
if (movementType == 8) return 0; // DOWN → south
return movementType - 7; // 9→2 (west), 10→3 (east)
}
if (movementType >= 64 && movementType <= 67) return movementType - 64; // WALK_IN_PLACE_DOWN=64→0, etc. if (movementType >= 64 && movementType <= 67) return movementType - 64; // WALK_IN_PLACE_DOWN=64→0, etc.
if (movementType >= 68 && movementType <= 71) return movementType - 68; // JOG_IN_PLACE_DOWN=68→0, etc. if (movementType >= 68 && movementType <= 71) return movementType - 68; // JOG_IN_PLACE_DOWN=68→0, etc.
if (movementType >= 72 && movementType <= 75) return movementType - 72; // RUN_IN_PLACE_DOWN=72→0, etc. if (movementType >= 72 && movementType <= 75) return movementType - 72; // RUN_IN_PLACE_DOWN=72→0, etc.
@@ -255,7 +239,7 @@ const lightingMap = {
}; };
const mapTypeMap = { const mapTypeMap = {
MAP_TYPE_INDOOR: 'MapType.INSIDE', MAP_TYPE_INDOOR: 'MapType.INSIDE',
MAP_TYPE_TOWN: 'MapType.CITY', MAP_TYPE_TOWN: 'MapType.UNKNOWN_0x01',
MAP_TYPE_CITY: 'MapType.CITY', MAP_TYPE_CITY: 'MapType.CITY',
MAP_TYPE_ROUTE: 'MapType.ROUTE', MAP_TYPE_ROUTE: 'MapType.ROUTE',
MAP_TYPE_UNDERGROUND: 'MapType.UNDERGROUND', MAP_TYPE_UNDERGROUND: 'MapType.UNDERGROUND',
@@ -265,8 +249,8 @@ const mapTypeMap = {
}; };
const encounterMap = { const encounterMap = {
MAP_TYPE_INDOOR: 'EncounterType.RANDOM', MAP_TYPE_INDOOR: 'EncounterType.RANDOM',
MAP_TYPE_TOWN: 'EncounterType.GYM_STYLE', MAP_TYPE_TOWN: 'EncounterType.RANDOM',
MAP_TYPE_CITY: 'EncounterType.GYM_STYLE', MAP_TYPE_CITY: 'EncounterType.RANDOM',
MAP_TYPE_ROUTE: 'EncounterType.RANDOM', MAP_TYPE_ROUTE: 'EncounterType.RANDOM',
MAP_TYPE_UNDERGROUND: 'EncounterType.RANDOM', MAP_TYPE_UNDERGROUND: 'EncounterType.RANDOM',
MAP_TYPE_UNDERWATER: 'EncounterType.UNKNOWN_0x03', MAP_TYPE_UNDERWATER: 'EncounterType.UNKNOWN_0x03',
@@ -309,12 +293,11 @@ for (let gi = 0; gi < groupOrder.length; gi++) {
// Palette // Palette
const [pal1, pal2] = guessPalette(primaryTileset, secondaryTileset, mapType); const [pal1, pal2] = guessPalette(primaryTileset, secondaryTileset, mapType);
// Per-map overrides (from real server captures) // Music → unknownShort, MAPSEC → unknownByte
let mapUnknownShort = 405; const musicStr = mapJson.music || 'MUS_NONE';
let mapUnknownByte = 0; const mapsecStr = mapJson.region_map_section || 'MAPSEC_NONE';
if (mapJson.id === 'MAP_LITTLEROOT_TOWN_PROFESSOR_BIRCHS_LAB') { const mapUnknownShort = musicIds[musicStr] !== undefined ? musicIds[musicStr] : 405;
mapUnknownShort = 383; const mapUnknownByte = mapsecIds[mapsecStr] !== undefined ? mapsecIds[mapsecStr] : 0;
}
// Border tiles // Border tiles
let borderTilesStr = 'listOf(Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0))'; let borderTilesStr = 'listOf(Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0))';
@@ -328,12 +311,16 @@ for (let gi = 0; gi < groupOrder.length; gi++) {
// Connections // Connections
const connections = mapJson.connections || []; const connections = mapJson.connections || [];
const connStrs = connections.map(c => { const connStrs = connections.map(c => {
const dir = dirMap[c.direction] || 2; const dir = dirMap[c.direction];
if (dir === undefined) {
throw new Error(`Unknown connection direction "${c.direction}" in ${mapName}`);
}
const addr = resolveMap(c.map); const addr = resolveMap(c.map);
if (!addr) return null; if (!addr) return null;
const bank = addr.groupIndex + 50; const bank = addr.groupIndex + 50;
const mapNum = addr.mapIndex; const mapNum = addr.mapIndex;
return `GbaConnection(direction = ${dir}, unknown = 0, targetBank = ${bank}, targetMap = ${mapNum})`; const offset = Number.isInteger(c.offset) ? c.offset : parseInt(c.offset || 0, 10) || 0;
return `GbaConnection(direction = ${dir}, unknown = ${offset}, targetBank = ${bank}, targetMap = ${mapNum})`;
}).filter(Boolean); }).filter(Boolean);
// Warps // Warps
@@ -0,0 +1,113 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.protocols.game.packets.DialogChoicePacket
import de.fiereu.openmmo.protocols.game.packets.DialogStatePacket
import de.fiereu.openmmo.protocols.game.packets.InteractiveResponsePacket
import de.fiereu.openmmo.server.game.session.ScriptPage
import de.fiereu.openmmo.server.game.session.SessionManager
import de.fiereu.openmmo.server.protocol.PacketEvent
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
private val log = KotlinLogging.logger {}
class DialogService(
private val packetSender: PacketSender,
) {
fun scriptParams(script: String): List<ScriptPage>? {
if (script == "0x0") return null
val known =
mapOf<String, List<ScriptPage>>(
"LittlerootTown_ProfessorBirchsLab_EventScript_Birch" to
listOf(ScriptPage(type = 0x04, unk1 = 0xAA74, unk2 = 0x1F10, unk3 = 0x0708)),
"LittlerootTown_ProfessorBirchsLab_EventScript_Aide" to
listOf(ScriptPage(type = 0x04, unk1 = 0xA6CE, unk2 = 0x1F10, unk3 = 0x04B0)),
"PlayersHouse_1F_EventScript_Mom" to
listOf(
ScriptPage(type = 0x04, unk1 = 0x087D, unk2 = 0x1F10, unk3 = 0x04B0),
ScriptPage(type = 0x04, unk1 = 0x7D5C, unk2 = 0x1F10, unk3 = 0x02BC),
),
"RivalsHouse_1F_EventScript_RivalMom" to
listOf(ScriptPage(type = 0x04, unk1 = 0x8CE3, unk2 = 0x1E10, unk3 = 0x02BC)),
"RivalsHouse_1F_EventScript_RivalSibling" to
listOf(ScriptPage(type = 0x04, unk1 = 0x8B25, unk2 = 0x1E10, unk3 = 0x0708)),
"LittlerootTown_EventScript_Twin" to
listOf(ScriptPage(type = 0x04, unk1 = 0x6292, unk2 = 0x1F10, unk3 = 0x04B0)),
"LittlerootTown_EventScript_Boy" to
listOf(ScriptPage(type = 0x04, unk1 = 0x938D, unk2 = 0x1F10, unk3 = 0x04B0)),
)
return known[script]
}
fun sendInteractive(
ctx: ChannelHandlerContext,
id: Int,
entityId: Long,
type: Int = 0x04,
unk1: Int = 0xAA74,
unk2: Int = 0x1F10,
unk3: Int = 0x0708,
) {
val buf = Unpooled.buffer(19)
buf.writeByte(id)
buf.writeByte(type)
buf.writeShortLE(unk1)
buf.writeShortLE(unk2)
buf.writeLongLE(entityId)
buf.writeShortLE(unk3)
buf.writeShortLE(0)
buf.writeByte(0)
val raw = ByteArray(buf.readableBytes())
buf.readBytes(raw)
buf.release()
packetSender.sendRaw(ctx, 0x21u, raw)
}
fun onInteractive(event: PacketEvent<InteractiveResponsePacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) return
val charId = session.characterId ?: return
if (session.inDialog) {
val respId = event.packet.id
log.info {
"Interactive response: id=$respId for char $charId (page ${session.dialogPageIndex + 1}/${session.dialogPages.size})"
}
val nextPageIndex = session.dialogPageIndex + 1
if (nextPageIndex < session.dialogPages.size) {
val seqId = session.dialogSeqId++
val page = session.dialogPages[nextPageIndex]
session.dialogPageIndex = nextPageIndex
sendInteractive(
event.ctx,
seqId,
session.dialogNpcEntityId,
page.type,
page.unk1,
page.unk2,
page.unk3,
)
event.ctx.channel().flush()
} else {
event.ctx.channel().writeAndFlush(DialogStatePacket(false))
session.inDialog = false
session.dialogNpcEntityId = 0
session.dialogPages = emptyList()
session.dialogPageIndex = 0
}
}
}
fun onDialogChoice(event: PacketEvent<DialogChoicePacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) return
log.info { "Dialog choice received: unk1=${event.packet.unk1}, unk2=${event.packet.unk2}" }
if (session.inDialog) {
event.ctx.channel().writeAndFlush(DialogStatePacket(false))
session.inDialog = false
session.dialogNpcEntityId = 0
}
}
}
@@ -0,0 +1,148 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.game.packets.DialogStatePacket
import de.fiereu.openmmo.protocols.game.packets.EntityInteractPacket
import de.fiereu.openmmo.server.game.session.SessionManager
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.MapManager
import de.fiereu.openmmo.server.protocol.PacketEvent
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.Unpooled
private val log = KotlinLogging.logger {}
class InteractionService(
private val npcService: NpcService,
private val dialogService: DialogService,
private val packetSender: PacketSender,
) {
fun onEntityInteract(event: PacketEvent<EntityInteractPacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) return
val charId = session.characterId ?: return
val npcEntityId = event.packet.entityId
val stored = CharacterStore.getCharacter(charId) ?: return
val currentMap =
MapManager.getMap(
stored.info.positionRegionId,
stored.info.positionBankId,
stored.info.positionMapId,
)
if (currentMap == null) return
// Find which NPC this entityId belongs to
val bankId = stored.info.positionBankId.toInt()
val mapId = stored.info.positionMapId.toInt()
for (npc in currentMap.npcs) {
val expectedId = npcService.getNpcEntityId(bankId, mapId, npc.entityIdx)
if (expectedId == npcEntityId) {
log.info {
"Entity interaction: NPC entityIdx=${npc.entityIdx} entityId=$npcEntityId script=${npc.script}"
}
if (npc.script != "0x0") {
val params = dialogService.scriptParams(npc.script)
if (params != null) {
log.info {
"NPC entityIdx=${npc.entityIdx} script=${npc.script} — starting dialog (${params.size} pages)"
}
session.inDialog = true
session.dialogNpcEntityId = npcEntityId
session.dialogPages = params
session.dialogPageIndex = 0
val seqId = session.dialogSeqId++
val page = params[0]
event.ctx.channel().write(DialogStatePacket(true))
val confirmBuf = Unpooled.buffer(9)
confirmBuf.writeLongLE(npcEntityId)
confirmBuf.writeByte(0xFF)
val confirmBytes = ByteArray(9)
confirmBuf.readBytes(confirmBytes)
confirmBuf.release()
packetSender.sendRaw(event.ctx, 0x07u, confirmBytes)
dialogService.sendInteractive(
event.ctx,
seqId,
npcEntityId,
page.type,
page.unk1,
page.unk2,
page.unk3,
)
event.ctx.channel().flush()
} else {
log.info { "NPC entityIdx=${npc.entityIdx} script=${npc.script} — no known params" }
}
} else {
log.info { "NPC entityIdx=${npc.entityIdx} has no script (0x0) — no interaction" }
}
return
}
}
// No NPC found — check for bg_event at tile player is facing
val facingX =
when (session.facingDirection) {
Direction.RIGHT -> stored.info.positionX.toInt() + 1
Direction.LEFT -> stored.info.positionX.toInt() - 1
else -> stored.info.positionX.toInt()
}
val facingY =
when (session.facingDirection) {
Direction.UP -> stored.info.positionY.toInt() - 1
Direction.DOWN -> stored.info.positionY.toInt() + 1
else -> stored.info.positionY.toInt()
}
val facingDirOk: (String) -> Boolean = { dir ->
dir == "BG_EVENT_PLAYER_FACING_ANY" ||
(dir == "BG_EVENT_PLAYER_FACING_NORTH" && session.facingDirection == Direction.UP) ||
(dir == "BG_EVENT_PLAYER_FACING_SOUTH" && session.facingDirection == Direction.DOWN) ||
(dir == "BG_EVENT_PLAYER_FACING_WEST" && session.facingDirection == Direction.LEFT) ||
(dir == "BG_EVENT_PLAYER_FACING_EAST" && session.facingDirection == Direction.RIGHT)
}
val bgEvent =
currentMap.bgEvents.find { it.x == facingX && it.y == facingY && facingDirOk(it.facingDir) }
if (bgEvent != null) {
val params = dialogService.scriptParams(bgEvent.script)
if (params != null) {
log.info {
"BG event script=${bgEvent.script} at ($facingX,$facingY) — starting dialog (${params.size} pages)"
}
session.inDialog = true
session.dialogNpcEntityId = npcEntityId
session.dialogPages = params
session.dialogPageIndex = 0
val seqId = session.dialogSeqId++
val page = params[0]
event.ctx.channel().write(DialogStatePacket(true))
val confirmBuf = Unpooled.buffer(9)
confirmBuf.writeLongLE(npcEntityId)
confirmBuf.writeByte(0xFF)
val confirmBytes = ByteArray(9)
confirmBuf.readBytes(confirmBytes)
confirmBuf.release()
packetSender.sendRaw(event.ctx, 0x07u, confirmBytes)
dialogService.sendInteractive(
event.ctx,
seqId,
npcEntityId,
page.type,
page.unk1,
page.unk2,
page.unk3,
)
event.ctx.channel().flush()
} else {
log.info {
"BG event interaction: script=${bgEvent.script} at ($facingX,$facingY) — no known params"
}
}
return
}
log.info { "Entity interaction for entity $npcEntityId — not found on current map" }
}
}
@@ -0,0 +1,380 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.protocols.game.packets.CharacterEntry
import de.fiereu.openmmo.protocols.game.packets.CharacterListPacket
import de.fiereu.openmmo.protocols.game.packets.ChatMessagePacket
import de.fiereu.openmmo.protocols.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.protocols.game.packets.JoinGamePacket
import de.fiereu.openmmo.protocols.game.packets.LoadEntityPacket
import de.fiereu.openmmo.protocols.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.protocols.game.packets.RenderScreenPacket
import de.fiereu.openmmo.protocols.game.packets.RequestCharactersPacket
import de.fiereu.openmmo.protocols.game.packets.RequestPlayerPacket
import de.fiereu.openmmo.protocols.game.packets.SelectCharacterPacket
import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterPacket
import de.fiereu.openmmo.protocols.game.packets.codecs.SkinSet
import de.fiereu.openmmo.server.game.protocol.game.ext.accept
import de.fiereu.openmmo.server.game.protocol.game.ext.buildAndRespond
import de.fiereu.openmmo.server.game.session.SessionManager
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.MapManager
import de.fiereu.openmmo.server.protocol.PacketEvent
import de.fiereu.openmmo.server.protocol.respond
import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime
private val log = KotlinLogging.logger {}
class LoginService(
private val mapLoadService: MapLoadService,
private val npcService: NpcService,
private val multiplayerService: MultiplayerService,
private val packetSender: PacketSender,
) {
fun onJoinGame(event: PacketEvent<JoinGamePacket>) {
val join = event.packet
log.info { "Player joined the game." }
val authData = join.authData
var userId = 0
if (authData is de.fiereu.openmmo.protocols.game.packets.NewAuthData) {
userId = authData.userId
log.info { "User $userId joined with session key (${authData.sessionKey.size} bytes)" }
}
if (userId > 0) {
SessionManager.createSession(event.ctx.channel(), userId)
log.info { "Session created for user $userId" }
}
event.accept().withPlaytime(1337).withRewardPoints(420).withBalance(187).buildAndRespond(event)
}
fun onCreateCharacter(event: PacketEvent<CreateCharacterPacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) {
log.warn { "Create character from unknown session" }
return
}
val name = event.packet.name
log.info { "Creating character '$name' for userId=${session.userId}" }
CharacterStore.createCharacter(session.userId, name)
log.info { "Created character '$name'" }
event.respond(buildCharacterList(session.userId))
}
fun onCharacterRequest(event: PacketEvent<RequestCharactersPacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session != null) {
event.respond(buildCharacterList(session.userId))
} else {
log.warn { "Character request from unauthenticated session" }
event.respond(CharacterListPacket(emptyList()))
}
}
private fun buildCharacterList(userId: Int): CharacterListPacket {
val characters = CharacterStore.getCharactersByUser(userId)
val entries =
characters.map { stored ->
CharacterEntry(
characterInfo = stored.info,
skinSet = SkinSet(),
guildId = null,
pokemon = stored.pokemon.take(1),
)
}
return CharacterListPacket(entries)
}
fun onCharacterSelected(event: PacketEvent<SelectCharacterPacket>) {
val charId = event.packet.characterId
val stored = CharacterStore.getCharacter(charId)
if (stored == null) {
log.warn { "Character $charId not found" }
return
}
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) {
log.warn { "No session for channel" }
return
}
SessionManager.setActiveCharacter(event.ctx.channel(), charId)
log.info { "Player selected character '${stored.info.name}' (id=$charId)" }
val info = stored.info
val now = LocalDateTime.now()
val updatedInfo = info.copy(lastLogin = now)
CharacterStore.updateCharacter(updatedInfo)
val containers =
mapOf(
PokemonContainer.PARTY to stored.pokemon,
PokemonContainer.PC to stored.pcStorage,
PokemonContainer.BATTLE_BOX_1 to emptyList<de.fiereu.openmmo.common.Pokemon>(),
PokemonContainer.BATTLE_BOX_2 to emptyList<de.fiereu.openmmo.common.Pokemon>(),
PokemonContainer.DAYCARE to emptyList<de.fiereu.openmmo.common.Pokemon>(),
)
for ((container, pokemon) in containers) {
event.respond(
PokemonContainerPacket(
container = container,
hasChange = true,
delete = false,
pokemon = pokemon,
))
}
sendRawPackets(event, info)
preloadMapAndJoin(event, charId, session)
}
private fun sendRawPackets(
event: PacketEvent<SelectCharacterPacket>,
info: de.fiereu.openmmo.common.CharacterInfo
) {
packetSender.sendRaw(event.ctx, 0x40u, bytesOf(0x01, 0x01, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x55u, bytesOf(0x00, 0x00, 0x00))
listOf(PokemonContainer.UNKNOWN_13, PokemonContainer.UNKNOWN_14).forEach { container ->
event.respond(
PokemonContainerPacket(
container = container,
hasChange = true,
delete = false,
pokemon = emptyList(),
))
}
packetSender.sendRaw(event.ctx, 0x67u, bytesOf(0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x63u, bytesOf(0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x98u, bytesOf(0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
packetSender.sendRaw(
event.ctx, 0x0Au, bytesOf(0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x29u, bytesOf(0x00, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x29u, hexToBytes("0101006F080100"))
packetSender.sendRaw(event.ctx, 0x29u, bytesOf(0x02, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x29u, bytesOf(0x03, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x29u, bytesOf(0x04, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x29u, bytesOf(0x0A, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x29u, bytesOf(0x80, 0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x1Cu, bytesOf(0x00, 0x00))
event.respond(SelectedCharacterPacket(info))
packetSender.sendRaw(event.ctx, 0xF1u, bytesOf(0x05))
packetSender.sendRaw(event.ctx, 0x4Au, bytesOf(0x00))
packetSender.sendRaw(event.ctx, 0x4Du, bytesOf(0x18))
event.respond(
ChatMessagePacket(
ChatType.GAME_NOTIFICATIONS,
Language.EN,
"Welcome to OpenMMO!",
"",
))
packetSender.sendRaw(
event.ctx,
0xF5u,
bytesOf(
0x77,
0x1A,
0x00,
0x00,
0x81,
0x00,
0x05,
0x4A,
0x00,
0x6F,
0x00,
0x73,
0x00,
0x75,
0x00,
0x6B,
0x00,
0x65,
0x00,
0x00,
0x00,
0x10,
))
packetSender.sendRaw(
event.ctx,
0x4Fu,
hexToBytes(
"B8009502029202019102029002008F02008C02008902008802028702008602008502008402008302008202008102008002027F02017E02027D02017B02017802037602037402037102026D02026C02016402026102015C02035602015102014F02014302013D02033B02033302023102022B02022902022102021602011202010E0202F10101F00103EE0100ED0100EC0102EB0100EA0100E90100E80101E70100E60100E50101E40100E30100E20100E10100E00100DF0103DE0102DB0103DA0102D90101D80101D50102D40101D10102D00102CE0102CD0101CC0103C60103C20102C00101BD0101BA0102B50101B40103B30103AE0102AD0102A80103A701029701038E01018B01028801018501038201008101018001007F01007E01007D01007C01007B01007A01007901007801017501016401035E01035601014E01034A01024401023F01033401022E01012901032301021E01011A0103170101100103040103010103FE0003FB0000FA0000F90000F80001F50001F40002F30001F20002ED0003E90002E80002E60001E30001E20003DD0003D60002D40001D30003D00003CF0002CD0002C70002C50002C40002C30002BA0002B20003AB0003A90002A000029700009600009500019200039100018F00038D00038700038600038200017900017100016E00016B00036500035E00015B00025200035000014C00034900024400024100033E00033B00033700033100032A00032600022400032200021F0002090003030002080600000F00000C00000B00000D00000700000800000E0000"))
packetSender.sendRaw(event.ctx, 0xD3u, bytesOf(0x00))
packetSender.sendRaw(
event.ctx,
0xFCu,
hexToBytes(
"10D6B660234D938A916F030CD1B64F9CDD0100040100007F0601000000000000000000000000000000621E0A"))
packetSender.sendRaw(event.ctx, 0x59u, bytesOf(0x00, 0x00))
packetSender.sendRaw(event.ctx, 0x59u, bytesOf(0x01, 0x00))
packetSender.sendRaw(
event.ctx,
0x6Eu,
bytesOf(
0x05,
0x92,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xF5,
0x00,
0x00))
packetSender.sendRaw(event.ctx, 0xB9u, bytesOf(0x00))
}
private fun preloadMapAndJoin(
event: PacketEvent<SelectCharacterPacket>,
charId: Long,
session: de.fiereu.openmmo.server.game.session.Session,
) {
val info = CharacterStore.getCharacter(charId)?.info ?: return
val map = MapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId)
if (map != null) {
event.respond(MapManager.createLoadMapPacket(map, reloadPlayer = true, deleteCache = true))
mapLoadService.preloadConnectedMaps(event.ctx, map)
} else {
log.warn {
"Map not found for position ${info.positionRegionId}:${info.positionBankId}:${info.positionMapId}"
}
}
session.regionId = info.positionRegionId.toInt()
session.bankId = info.positionBankId.toInt()
session.mapId = info.positionMapId.toInt()
session.x = info.positionX
session.y = info.positionY
multiplayerService.broadcastMessage(
ChatMessagePacket(
ChatType.GAME_NOTIFICATIONS,
Language.EN,
"Player ${info.name} joined the game.",
"",
))
}
fun onRequestPlayer(event: PacketEvent<RequestPlayerPacket>) {
log.info { "Received RequestPlayerPacket" }
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) {
log.warn { "RequestPlayer from unknown session" }
return
}
val charId = session.characterId
if (charId == null) {
log.warn { "RequestPlayer without active character" }
return
}
val stored = CharacterStore.getCharacter(charId)
if (stored == null) {
log.warn { "RequestPlayer for unknown character $charId" }
return
}
val info = stored.info
log.info { "Sending LoadEntity + 0x90 for character '${info.name}'" }
val facing = session.facingDirection
val loadEntity = mapLoadService.createLoadEntity(info, facing)
event.ctx.channel().writeAndFlush(loadEntity)
mapLoadService.send90(event.ctx, loadEntity.entityId, loadEntity.skin)
npcService.spawnNpcsForMap(event.ctx, info.positionBankId.toInt(), info.positionMapId.toInt())
val bankId = info.positionBankId.toInt()
val mapId = info.positionMapId.toInt()
val regionId = info.positionRegionId.toInt()
session.regionId = regionId
session.bankId = bankId
session.mapId = mapId
session.x = info.positionX
session.y = info.positionY
val currentParty = CharacterStore.getCharacter(charId)?.pokemon ?: emptyList()
val hasFollower = currentParty.isNotEmpty()
val followerDexId = (currentParty.firstOrNull()?.dexId ?: 0).toShort()
// Send LoadEntity of each existing player in this map to the new player
val others = SessionManager.getOthersInMap(charId, regionId, bankId, mapId)
for (other in others) {
val otherStored = CharacterStore.getCharacter(other.characterId ?: continue) ?: continue
val otherParty = otherStored.pokemon
event.ctx
.channel()
.write(
LoadEntityPacket(
entityId = other.characterId!!,
skin = SkinSet(),
name = otherStored.info.name,
regionId = other.regionId,
bankId = other.bankId,
mapId = other.mapId,
x = other.x.toInt(),
y = other.y.toInt(),
facing = other.facingDirection,
status = de.fiereu.openmmo.common.enums.EntityStatus.NONE,
hasFollower = otherParty.isNotEmpty(),
followerDexId = (otherParty.firstOrNull()?.dexId ?: 0).toShort(),
))
}
// Broadcast LoadEntity of new player to all existing players in this map
val selfEntity =
LoadEntityPacket(
entityId = charId,
skin = SkinSet(),
name = info.name,
regionId = regionId,
bankId = bankId,
mapId = mapId,
x = info.positionX.toInt(),
y = info.positionY.toInt(),
facing = facing,
status = de.fiereu.openmmo.common.enums.EntityStatus.NONE,
hasFollower = hasFollower,
followerDexId = followerDexId,
)
for (other in others) {
other.channel.writeAndFlush(selfEntity)
}
event.ctx.channel().writeAndFlush(RenderScreenPacket(true))
log.info { "Player $charId spawned in bank=$bankId map=$mapId; ${others.size} others present" }
}
private fun bytesOf(vararg ints: Int) = ByteArray(ints.size) { ints[it].toByte() }
private fun hexToBytes(hex: String): ByteArray {
val hexStr = hex.replace(" ", "").replace("\n", "")
return ByteArray(hexStr.length / 2) { hexStr.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
}
}
@@ -0,0 +1,99 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.game.packets.LoadEntityPacket
import de.fiereu.openmmo.protocols.game.packets.MapData
import de.fiereu.openmmo.protocols.game.packets.codecs.SkinSet
import de.fiereu.openmmo.server.game.world.MapDef
import de.fiereu.openmmo.server.game.world.MapManager
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
private val log = KotlinLogging.logger {}
class MapLoadService(private val packetSender: PacketSender) {
fun createLoadEntity(
info: CharacterInfo,
facing: Direction = Direction.DOWN,
): LoadEntityPacket {
return LoadEntityPacket(
entityId = info.id,
skin = SkinSet(),
name = info.name,
regionId = info.positionRegionId.toInt(),
bankId = info.positionBankId.toInt(),
mapId = info.positionMapId.toInt(),
x = info.positionX.toInt(),
y = info.positionY.toInt(),
facing = facing,
status = de.fiereu.openmmo.common.enums.EntityStatus.NONE,
hasFollower = false,
followerDexId = 0,
)
}
fun send90(ctx: ChannelHandlerContext, entityId: Long, skin: SkinSet) {
val raw90Buf = Unpooled.buffer()
raw90Buf.writeLongLE(entityId)
raw90Buf.writeByte(0x01)
raw90Buf.writeByte(0x00)
raw90Buf.writeByte(0x4C)
raw90Buf.writeByte(0x03)
raw90Buf.writeBytes(
byteArrayOf(
0x13,
0xA8.toByte(),
0x0A,
0x00,
0x03,
0x8C.toByte(),
0x01,
0x38.toByte(),
0x02,
0x4C,
0x01))
val raw90 = ByteArray(raw90Buf.readableBytes())
raw90Buf.readBytes(raw90)
raw90Buf.release()
log.info {
">> TX 0x90 payload (${raw90.size}b): ${raw90.joinToString("") { "%02X".format(it) }}"
}
packetSender.sendRaw(ctx, 0x90u, raw90)
}
fun preloadConnectedMaps(
ctx: ChannelHandlerContext,
map: MapDef,
depth: Int = 2,
reloadPlayer: Boolean = false,
flush: Boolean = true,
) {
val loaded = mutableSetOf<String>()
loaded.add("${map.bankId}:${map.mapId}")
fun preload(connections: List<MapData.GbaConnection>, remaining: Int) {
if (remaining <= 0) return
for (conn in connections) {
val key = "${conn.targetBank}:${conn.targetMap}"
if (!loaded.add(key)) continue
val connected = MapManager.getMap(1, conn.targetBank.toByte(), conn.targetMap.toByte())
if (connected != null) {
ctx.channel()
.write(
MapManager.createLoadMapPacket(
connected,
reloadPlayer = reloadPlayer,
deleteCache = false,
))
preload(connected.connections, remaining - 1)
}
}
}
preload(map.connections, depth)
if (flush) {
ctx.channel().flush()
}
}
}
@@ -0,0 +1,255 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.game.packets.EntityMovePacket
import de.fiereu.openmmo.protocols.game.packets.FaceDirectionPacket
import de.fiereu.openmmo.protocols.game.packets.MapData
import de.fiereu.openmmo.protocols.game.packets.MovementPacket
import de.fiereu.openmmo.server.game.session.SessionManager
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.MapManager
import de.fiereu.openmmo.server.protocol.PacketEvent
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.channel.ChannelHandlerContext
import java.util.concurrent.atomic.AtomicInteger
private val log = KotlinLogging.logger {}
class MovementService(
private val warpService: WarpService,
private val mapLoadService: MapLoadService,
private val npcService: NpcService,
private val multiplayerService: MultiplayerService,
) {
private val sequenceCounter = AtomicInteger(0)
fun onMovement(event: PacketEvent<MovementPacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) return
val charId = session.characterId ?: return
val msg = event.packet
log.info { "Movement: char=$charId, x=${msg.x}, y=${msg.y}, dir=${msg.direction}" }
session.facingDirection = msg.direction
// Store previous position for detecting wall bumps
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
// Check for warps and edge transitions BEFORE updating position.
val stored = CharacterStore.getCharacter(charId)
if (stored != null) {
val currentMap =
MapManager.getMap(
stored.info.positionRegionId,
stored.info.positionBankId,
stored.info.positionMapId,
)
if (currentMap != null) {
// Skip warp check for the first movement after a warp
if (session.justWarped) {
session.justWarped = false
} else {
// Direct warp: player walked onto a warp tile (not just standing on it)
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} → ${warp.targetRegionId}:${warp.targetBankId}:${warp.targetMapId} (${warp.targetX}, ${warp.targetY})"
}
warpService.executeWarp(event.ctx, charId, warp)
return
}
// Adjacent warp: player is standing in front of a door tile, facing it
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} → tile ($adjX, $adjY) → ${adjWarp.targetRegionId}:${adjWarp.targetBankId}:${adjWarp.targetMapId} (${adjWarp.targetX}, ${adjWarp.targetY})"
}
warpService.executeWarp(event.ctx, charId, adjWarp)
return
}
}
// Map edge transition
if (prevX != null && prevY != null && !isWallBump) {
val dx = kotlin.math.abs(msg.x - prevX)
val dy = kotlin.math.abs(msg.y - prevY)
log.info {
"EDGE CHECK: prev=($prevX, $prevY) msg=(${msg.x}, ${msg.y}) dx=$dx dy=$dy map=${currentMap.bankId}:${currentMap.mapId} h=${currentMap.height} w=${currentMap.width}"
}
if (dx > 1 || dy > 1) {
val gbaDirection =
when {
prevY == 0 -> 2 // North
prevY == currentMap.height - 1 -> 1 // South
prevX == 0 -> 3 // West
prevX == currentMap.width - 1 -> 4 // East
else -> null
}
log.info { "BIG JUMP: gbaDirection=$gbaDirection" }
if (gbaDirection != null) {
val connection = currentMap.connections.find { it.direction == gbaDirection }
log.info { "Connection found: $connection" }
if (connection != null) {
val targetMap =
MapManager.getMap(
1,
connection.targetBank.toByte(),
connection.targetMap.toByte(),
)
if (targetMap != null) {
val targetX =
when (gbaDirection) {
3 -> targetMap.width - 1
4 -> 0
else ->
(prevX - connection.unknown).coerceIn(
0,
targetMap.width - 1,
)
}
val targetY =
when (gbaDirection) {
1 -> 0
2 -> targetMap.height - 1
else ->
(prevY - connection.unknown).coerceIn(
0,
targetMap.height - 1,
)
}
log.info {
"MAP TRANSITION prev=($prevX, $prevY) dir=${msg.direction} → bank=${connection.targetBank} map=${connection.targetMap} ($targetX, $targetY)"
}
edgeTransition(
event.ctx,
charId,
connection,
targetX.toByte(),
targetY.toByte(),
msg.direction,
)
return
}
}
}
}
}
}
}
// No transition: normal movement update + EntityMove broadcast
CharacterStore.updatePosition(charId, msg.x.toShort(), msg.y.toShort())
session.x = msg.x.toShort()
session.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,
)
event.ctx.channel().writeAndFlush(movePkt)
multiplayerService.broadcastExcept(event.ctx.channel(), movePkt)
}
}
fun onFaceDirection(event: PacketEvent<FaceDirectionPacket>) {
val session = SessionManager.getSessionByChannel(event.ctx.channel())
if (session == null) return
val charId = session.characterId ?: return
val msg = event.packet
session.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,
)
event.ctx.channel().writeAndFlush(movePkt)
multiplayerService.broadcastExcept(event.ctx.channel(), movePkt)
}
private fun edgeTransition(
ctx: ChannelHandlerContext,
charId: Long,
connection: MapData.GbaConnection,
targetX: Byte,
targetY: Byte,
direction: Direction,
) {
val targetBank = connection.targetBank.toByte()
val targetMap = connection.targetMap.toByte()
val map = MapManager.getMap(1, targetBank, targetMap) ?: return
val session = SessionManager.getSessionByCharacterId(charId)
session?.bankId = targetBank.toInt()
session?.mapId = targetMap.toInt()
session?.x = targetX.toShort()
session?.y = targetY.toShort()
CharacterStore.updatePosition(
charId,
targetX.toShort(),
targetY.toShort(),
targetBank,
targetMap,
)
ctx.channel()
.write(MapManager.createLoadMapPacket(map, reloadPlayer = false, deleteCache = false))
mapLoadService.preloadConnectedMaps(ctx, map, depth = 1, flush = false)
npcService.spawnNpcsForMap(ctx, targetBank.toInt(), targetMap.toInt())
val seq = sequenceCounter.incrementAndGet().toByte()
val movePkt =
EntityMovePacket(
entityId = charId,
x = targetX,
y = targetY,
direction = direction,
seq = seq,
)
ctx.channel().write(movePkt)
multiplayerService.broadcastExcept(ctx.channel(), movePkt)
ctx.channel().flush()
log.info { "Player $charId edge-transitioned to bank=$targetBank map=$targetMap" }
}
}
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.server.game.session.SessionManager
import io.netty.channel.Channel
class MultiplayerService {
fun broadcastMessage(packet: Any) {
for (characterId in SessionManager.getOnlineCharacterIds()) {
val s = SessionManager.getSessionByCharacterId(characterId) ?: continue
if (s.channel.isActive) {
s.channel.writeAndFlush(packet)
}
}
}
fun broadcastExcept(channel: Channel, packet: Any) {
for (characterId in SessionManager.getOnlineCharacterIds()) {
val s = SessionManager.getSessionByCharacterId(characterId) ?: continue
if (s.channel.isActive && s.channel != channel) {
s.channel.writeAndFlush(packet)
}
}
}
}
@@ -0,0 +1,117 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.protocols.game.packets.NpcSpawnPacket
import de.fiereu.openmmo.server.game.world.MapManager
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.channel.ChannelHandlerContext
import java.util.concurrent.atomic.AtomicLong
private val log = KotlinLogging.logger {}
class NpcService {
private val npcEntityIdCounter = AtomicLong(0x1A69000000000000L)
private val npcEntityIds = mutableMapOf<String, Long>()
fun getNpcEntityId(bankId: Int, mapId: Int, entityIdx: Int): Long? {
return npcEntityIds["$bankId:$mapId:$entityIdx"]
}
fun spawnNpcsForMap(ctx: ChannelHandlerContext, bankId: Int, mapId: Int) {
val map = MapManager.getMap(1, bankId.toByte(), mapId.toByte())
if (map == null) return
val entityIds = mutableListOf<Long>()
// Petalburg Woods (bank=74, map=11) — send all 16 NPCs (0-15),
// using exact values from real server packets.db rows 3895-3910
if (bankId == 74 && mapId == 11) {
data class NpcEntry(
val entityIdx: Int,
val x: Int,
val y: Int,
val gfx: Int,
val unk1: Int,
val unk3: Int,
val unk4: Int,
val facing: Int,
val unk6: Int
)
val all16 =
listOf(
NpcEntry(7, 15, 19, 9, 1, 768, 513, 0, 8),
NpcEntry(6, 4, 8, 59, 1, 256, 0, 0, 8),
NpcEntry(5, 35, 20, 59, 1, 2048, 0, 0, 8),
NpcEntry(4, 45, 7, 59, 1, 2048, 0, 0, 8),
NpcEntry(3, 26, 20, 23, 1, 256, 0, 0, 0),
NpcEntry(2, 26, 17, 117, 1, 2563, 0, 3, 0),
NpcEntry(1, 19, 11, 82, 1, 256, 0, 0, 8),
NpcEntry(0, 19, 10, 82, 1, 256, 0, 0, 8),
NpcEntry(15, 16, 24, 0, 10, 25600, 0, 0, 8),
NpcEntry(14, 15, 24, 600, 10, 0, 0, 0, 0),
NpcEntry(13, 36, 23, 246, 10, 0, 0, 0, 8),
NpcEntry(12, 33, 5, 10, 1, 256, 257, 0, 8),
NpcEntry(11, 4, 26, 59, 1, 256, 257, 0, 8),
NpcEntry(10, 30, 34, 13, 1, 512, 258, 0, 8),
NpcEntry(9, 4, 14, 36, 1, 5121, 0, 1, 9),
NpcEntry(8, 7, 32, 36, 1, 5632, 0, 0, 8),
)
val baseEntityId = 0x1A6BFE24CC88E000L
for (npc in all16) {
val entityId = baseEntityId or npc.entityIdx.toLong()
log.info {
">> Petalburg NpcSpawn[${npc.entityIdx}] entId=0x${entityId.toString(16)} pos=(${npc.x},${npc.y}) gfx=${npc.gfx} unk3=${npc.unk3} unk4=${npc.unk4}"
}
val spawnPacket =
NpcSpawnPacket(
entityId = entityId,
unk1 = npc.unk1,
unk2 = npc.gfx,
unk3 = npc.unk3,
unk4 = npc.unk4,
regionId = 1,
bankId = bankId,
mapId = mapId,
x = npc.x,
y = npc.y,
facing = npc.facing,
unk5 = 2,
unk6 = npc.unk6,
)
ctx.channel().write(spawnPacket)
entityIds.add(entityId)
}
return
}
// All other maps: send visible NPCs from MapDef
for (npc in map.npcs) {
val key = "$bankId:$mapId:${npc.entityIdx}"
val entityId = npcEntityIds.getOrPut(key) { npcEntityIdCounter.incrementAndGet() }
val unk3 = ((npc.movementType and 0xFF) shl 8) or 0x02
val unk4 =
if (npc.movementType in 1..6 || (npc.movementType in 25..52)) {
((npc.movementRangeX and 0xFF) shl 8) or (npc.movementRangeY and 0xFF)
} else {
0
}
val spawnPacket =
NpcSpawnPacket(
entityId = entityId,
unk1 = 1,
unk2 = npc.graphicsId,
unk3 = unk3,
unk4 = unk4,
regionId = 1,
bankId = bankId,
mapId = mapId,
x = npc.x,
y = npc.y,
facing = npc.facing,
unk5 = 2,
unk6 = 8,
)
ctx.channel().write(spawnPacket)
entityIds.add(entityId)
}
}
}
@@ -0,0 +1,24 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.server.netty.Compressor
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
class PacketSender(private val compressor: Compressor) {
fun sendRaw(ctx: ChannelHandlerContext, opcode: UByte, data: ByteArray) {
val buffer = ctx.alloc().buffer()
buffer.writeByte(opcode.toInt())
val dataBuf = Unpooled.wrappedBuffer(data)
buffer.writeBytes(compressor.compress(dataBuf))
ctx.write(buffer)
}
fun sendRawAndFlush(ctx: ChannelHandlerContext, opcode: UByte, data: ByteArray) {
val buffer = ctx.alloc().buffer()
buffer.writeByte(opcode.toInt())
val dataBuf = Unpooled.wrappedBuffer(data)
buffer.writeBytes(compressor.compress(dataBuf))
ctx.writeAndFlush(buffer)
}
}
@@ -0,0 +1,133 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.game.packets.EntityLeavePacket
import de.fiereu.openmmo.protocols.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.protocols.game.packets.MapTransitionPacket
import de.fiereu.openmmo.protocols.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.SessionManager
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.MapManager
import de.fiereu.openmmo.server.game.world.WarpExitRules
import de.fiereu.openmmo.server.game.world.WarpTile
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.channel.ChannelHandlerContext
private val log = KotlinLogging.logger {}
class WarpService(
private val mapLoadService: MapLoadService,
) {
fun executeWarp(ctx: ChannelHandlerContext, charId: Long, warp: WarpTile) {
val session = SessionManager.getSessionByCharacterId(charId)
if (session != null) {
session.justWarped = true
}
val stored = CharacterStore.getCharacter(charId) ?: return
val destMap = MapManager.getMap(warp.targetRegionId, warp.targetBankId, warp.targetMapId)
val sourceMap =
MapManager.getMap(
stored.info.positionRegionId, stored.info.positionBankId, stored.info.positionMapId)
val knownOverride =
WarpExitRules.getKnownOverride(sourceMap, destMap, warp.targetX, warp.targetY)
val warpFacing =
knownOverride?.facing
?: WarpExitRules.inferExitFacing(
destTileBehavior = null,
destMap = destMap,
destX = warp.targetX,
destY = warp.targetY,
sourceMap = sourceMap)
session?.facingDirection = warpFacing
var offsetX = warp.targetX
var offsetY = warp.targetY
val shouldAutoStepOffWarp =
knownOverride?.autoStep
?: WarpExitRules.shouldAutoStep(
sourceMap = sourceMap,
destMap = destMap,
)
if (shouldAutoStepOffWarp) {
val destWarp = destMap?.warps?.find { it.x == offsetX && it.y == offsetY }
if (destWarp != null) {
when (warpFacing) {
Direction.UP -> offsetY--
Direction.DOWN -> offsetY++
Direction.LEFT -> offsetX--
Direction.RIGHT -> offsetX++
}
offsetX = offsetX.coerceIn(0, destMap!!.width - 1)
offsetY = offsetY.coerceIn(0, destMap!!.height - 1)
}
}
log.info {
"WARP EXIT: source=${sourceMap?.bankId}:${sourceMap?.mapId} ${sourceMap?.mapType} " +
"dest=${destMap?.bankId}:${destMap?.mapId} ${destMap?.mapType} " +
"target=(${warp.targetX},${warp.targetY}) final=($offsetX,$offsetY) " +
"facing=$warpFacing autoStep=$shouldAutoStepOffWarp"
}
val newInfo =
stored.info.copy(
positionRegionId = warp.targetRegionId,
positionBankId = warp.targetBankId,
positionMapId = warp.targetMapId,
positionX = offsetX.toShort(),
positionY = offsetY.toShort(),
)
CharacterStore.updateCharacter(newInfo)
// Multiplayer: broadcast EntityLeave to old-map players before position update
val oldRegionId = session?.regionId
val oldBankId = session?.bankId
val oldMapId = session?.mapId
if (oldBankId != null && oldMapId != null) {
val oldMapPlayers =
SessionManager.getOthersInMap(charId, oldRegionId ?: 1, oldBankId, oldMapId)
for (other in oldMapPlayers) {
other.channel.writeAndFlush(EntityLeavePacket(charId))
}
}
// Update session position for multiplayer tracking
if (session != null) {
session.regionId = warp.targetRegionId.toInt()
session.bankId = warp.targetBankId.toInt()
session.mapId = warp.targetMapId.toInt()
session.x = offsetX.toShort()
session.y = offsetY.toShort()
}
// Real server warp sequence (from packets.db):
ctx.channel().writeAndFlush(MapTransitionPacket())
ctx.channel().writeAndFlush(RenderScreenPacket(false))
ctx.channel().writeAndFlush(mapLoadService.createLoadEntity(newInfo, warpFacing))
ctx.channel().writeAndFlush(MapTransitionAckPacket(0))
if (destMap != null) {
ctx.channel()
.writeAndFlush(
MapManager.createLoadMapPacket(
destMap,
reloadPlayer = true,
deleteCache = true,
))
mapLoadService.preloadConnectedMaps(ctx, destMap, depth = 1, reloadPlayer = true)
} else {
log.warn {
"Map not found for warp target ${warp.targetRegionId}:${warp.targetBankId}:${warp.targetMapId}"
}
}
log.info { "Player $charId warped to bank=${warp.targetBankId} map=${warp.targetMapId}" }
}
}
@@ -87,6 +87,8 @@ object CharacterStore {
characterId: Long, characterId: Long,
x: Short, x: Short,
y: Short, y: Short,
bankId: Byte? = null,
mapId: Byte? = null,
) { ) {
val stored = characters[characterId] ?: return val stored = characters[characterId] ?: return
val oldInfo = stored.info val oldInfo = stored.info
@@ -94,6 +96,8 @@ object CharacterStore {
oldInfo.copy( oldInfo.copy(
positionX = x, positionX = x,
positionY = y, positionY = y,
positionBankId = bankId ?: oldInfo.positionBankId,
positionMapId = mapId ?: oldInfo.positionMapId,
) )
characters[characterId] = stored.copy(info = newInfo) characters[characterId] = stored.copy(info = newInfo)
} }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,143 @@
package de.fiereu.openmmo.server.game.world
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.MapType
data class WarpExitOverride(
val facing: Direction,
val autoStep: Boolean,
)
object WarpExitRules {
fun inferExitFacing(
destTileBehavior: String?,
destMap: MapDef?,
destX: Int,
destY: Int,
sourceMap: MapDef?,
): Direction {
if (destMap == null) return Direction.DOWN
// Future proper tile-behavior support.
when (destTileBehavior) {
"MB_NON_ANIMATED_DOOR",
"MB_ANIMATED_DOOR" -> return Direction.DOWN
"MB_NORTH_ARROW_WARP" -> return Direction.DOWN
"MB_SOUTH_ARROW_WARP" -> return Direction.UP
"MB_WEST_ARROW_WARP" -> return Direction.RIGHT
"MB_EAST_ARROW_WARP" -> return Direction.LEFT
}
val sourceMapType = sourceMap?.mapType
// Temporary hardcoded special cases until tile behavior is parsed.
getKnownOverride(sourceMap, destMap, destX, destY)?.let {
return it.facing
}
// Entering a cave/tunnel from outside.
if (isUndergroundMap(destMap.mapType) && !isUndergroundMap(sourceMapType)) {
return Direction.UP
}
// Entering a building from outside.
if (isBuildingMap(destMap.mapType) && !isBuildingMap(sourceMapType)) {
return Direction.UP
}
// Exiting a building to outside.
if (isBuildingMap(sourceMapType) && !isBuildingMap(destMap.mapType)) {
return Direction.DOWN
}
// Room-to-room.
if (isBuildingMap(sourceMapType) && isBuildingMap(destMap.mapType)) {
return Direction.DOWN
}
return inferFacingFromExactEdge(destMap, destX, destY)
}
fun getKnownOverride(
sourceMap: MapDef?,
destMap: MapDef?,
destX: Int,
destY: Int,
): WarpExitOverride? {
if (destMap == null) return null
// Rusturf Tunnel: face UP into the tunnel, no auto-step.
if (destMap.bankId.toInt() == 74 && destMap.mapId.toInt() == 4) {
return when {
destX == 4 && destY == 10 -> WarpExitOverride(Direction.UP, autoStep = false)
destX == 29 && destY == 16 -> WarpExitOverride(Direction.UP, autoStep = false)
destX == 18 && destY == 20 -> WarpExitOverride(Direction.UP, autoStep = false)
else -> null
}
}
// Petalburg Woods: facing only, no auto-step.
if (destMap.bankId.toInt() == 74 && destMap.mapId.toInt() == 11) {
return when {
(destX == 14 && destY == 5) || (destX == 15 && destY == 5) ->
WarpExitOverride(Direction.DOWN, autoStep = false)
(destX == 16 && destY == 38) ||
(destX == 17 && destY == 38) ||
(destX == 36 && destY == 38) ||
(destX == 37 && destY == 38) -> WarpExitOverride(Direction.UP, autoStep = false)
else -> null
}
}
return null
}
private fun inferFacingFromExactEdge(
destMap: MapDef,
destX: Int,
destY: Int,
): Direction {
return when {
destY <= 1 -> Direction.DOWN
destY >= destMap.height - 2 -> Direction.UP
destX <= 1 -> Direction.RIGHT
destX >= destMap.width - 2 -> Direction.LEFT
else -> Direction.DOWN
}
}
fun shouldAutoStep(
sourceMap: MapDef?,
destMap: MapDef?,
): Boolean {
if (sourceMap == null || destMap == null) return false
val sourceBuilding =
sourceMap.mapType == MapType.INSIDE || sourceMap.mapType == MapType.SECRET_BASE
val destBuilding = destMap.mapType == MapType.INSIDE || destMap.mapType == MapType.SECRET_BASE
val enteringUnderground =
destMap.mapType == MapType.UNDERGROUND && sourceMap.mapType != MapType.UNDERGROUND
// House/building exit to outside.
if (sourceBuilding && !destBuilding) return true
// Cave/tunnel entrance from outside.
if (enteringUnderground) return true
return false
}
fun isBuildingMap(type: MapType?): Boolean {
return type == MapType.INSIDE || type == MapType.SECRET_BASE
}
fun isUndergroundMap(type: MapType?): Boolean {
return type == MapType.UNDERGROUND
}
}