refactor(network): rework network module, use new bytecodec module and introduce proper packet events

This commit is contained in:
Fiereu committed 2026-05-30 10:13:12 +02:00
1 parent 8048827121
commit d27a54f360
340 files changed
+7462 -62719

No files matched your search

@@ -0,0 +1,129 @@
package de.fiereu.openmmo.net.game
import de.fiereu.network.Protocol
import de.fiereu.network.bidi
import de.fiereu.network.c2s
import de.fiereu.network.s2c
import de.fiereu.openmmo.net.game.packets.CharactersListPacket
import de.fiereu.openmmo.net.game.packets.CharactersListPacketCodec
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.net.game.packets.ChatMessagePacketCodec
import de.fiereu.openmmo.net.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.net.game.packets.CreateCharacterPacketCodec
import de.fiereu.openmmo.net.game.packets.DialogChoicePacket
import de.fiereu.openmmo.net.game.packets.DialogChoicePacketCodec
import de.fiereu.openmmo.net.game.packets.DialogDataPacket
import de.fiereu.openmmo.net.game.packets.DialogDataPacketCodec
import de.fiereu.openmmo.net.game.packets.DialogOptionPacket
import de.fiereu.openmmo.net.game.packets.DialogOptionPacketCodec
import de.fiereu.openmmo.net.game.packets.DialogStatePacket
import de.fiereu.openmmo.net.game.packets.DialogStatePacketCodec
import de.fiereu.openmmo.net.game.packets.EntityInteractPacket
import de.fiereu.openmmo.net.game.packets.EntityInteractPacketCodec
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.EntityLeavePacketCodec
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacketCodec
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacketCodec
import de.fiereu.openmmo.net.game.packets.InteractivePacket
import de.fiereu.openmmo.net.game.packets.InteractivePacketCodec
import de.fiereu.openmmo.net.game.packets.InteractiveResponsePacket
import de.fiereu.openmmo.net.game.packets.InteractiveResponsePacketCodec
import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.JoinPacketCodec
import de.fiereu.openmmo.net.game.packets.JoinResponsePacket
import de.fiereu.openmmo.net.game.packets.JoinResponsePacketCodec
import de.fiereu.openmmo.net.game.packets.KeepAlivePacket
import de.fiereu.openmmo.net.game.packets.KeepAlivePacketCodec
import de.fiereu.openmmo.net.game.packets.LoadEntityPacket
import de.fiereu.openmmo.net.game.packets.LoadEntityPacketCodec
import de.fiereu.openmmo.net.game.packets.LoadMapPacket
import de.fiereu.openmmo.net.game.packets.LoadMapPacketCodec
import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacketCodec
import de.fiereu.openmmo.net.game.packets.MapTransitionPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionPacketCodec
import de.fiereu.openmmo.net.game.packets.MovementPacket
import de.fiereu.openmmo.net.game.packets.MovementPacketCodec
import de.fiereu.openmmo.net.game.packets.NpcAnimationPacket
import de.fiereu.openmmo.net.game.packets.NpcAnimationPacketCodec
import de.fiereu.openmmo.net.game.packets.NpcSpawnPacket
import de.fiereu.openmmo.net.game.packets.NpcSpawnPacketCodec
import de.fiereu.openmmo.net.game.packets.NpcUpdatePacket
import de.fiereu.openmmo.net.game.packets.NpcUpdatePacketCodec
import de.fiereu.openmmo.net.game.packets.NullPacket
import de.fiereu.openmmo.net.game.packets.NullPacketCodec
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacketCodec
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacketCodec
import de.fiereu.openmmo.net.game.packets.RequestCharactersPacket
import de.fiereu.openmmo.net.game.packets.RequestCharactersPacketCodec
import de.fiereu.openmmo.net.game.packets.RequestPlayerPacket
import de.fiereu.openmmo.net.game.packets.RequestPlayerPacketCodec
import de.fiereu.openmmo.net.game.packets.SelectCharacterPacket
import de.fiereu.openmmo.net.game.packets.SelectCharacterPacketCodec
import de.fiereu.openmmo.net.game.packets.SelectedCharacterPacket
import de.fiereu.openmmo.net.game.packets.SelectedCharacterPacketCodec
import de.fiereu.openmmo.net.game.packets.TokenPayloadPacket
import de.fiereu.openmmo.net.game.packets.TokenPayloadPacketCodec
object GameProtocol : Protocol() {
override val compressed: Boolean = true
init {
c2s<JoinPacket>(0x01u, JoinPacketCodec)
s2c<JoinResponsePacket>(0x01u, JoinResponsePacketCodec)
c2s<RequestCharactersPacket>(0x02u, RequestCharactersPacketCodec)
s2c<CharactersListPacket>(0x02u, CharactersListPacketCodec)
c2s<CreateCharacterPacket>(0x03u, CreateCharacterPacketCodec)
c2s<SelectCharacterPacket>(0x04u, SelectCharacterPacketCodec)
s2c<SelectedCharacterPacket>(0x04u, SelectedCharacterPacketCodec)
c2s<RequestPlayerPacket>(0x05u, RequestPlayerPacketCodec)
s2c<LoadEntityPacket>(0x05u, LoadEntityPacketCodec)
c2s<MovementPacket>(0x06u, MovementPacketCodec)
c2s<FaceDirectionPacket>(0x07u, FaceDirectionPacketCodec)
s2c<EntityLeavePacket>(0x08u, EntityLeavePacketCodec)
bidi<ChatMessagePacket>(0x09u, ChatMessagePacketCodec)
bidi<DialogDataPacket>(0x0Du, DialogDataPacketCodec)
bidi<DialogStatePacket>(0x0Eu, DialogStatePacketCodec)
bidi<LoadMapPacket>(0x10u, LoadMapPacketCodec)
s2c<NpcUpdatePacket>(0x11u, NpcUpdatePacketCodec)
bidi<NpcSpawnPacket>(0x12u, NpcSpawnPacketCodec)
bidi<PokemonContainerPacket>(0x13u, PokemonContainerPacketCodec)
bidi<MapTransitionPacket>(0x1Bu, MapTransitionPacketCodec)
c2s<NullPacket>(0x20u, NullPacketCodec)
s2c<TokenPayloadPacket>(0x20u, TokenPayloadPacketCodec)
s2c<InteractivePacket>(0x21u, InteractivePacketCodec)
c2s<InteractiveResponsePacket>(0x21u, InteractiveResponsePacketCodec)
bidi<EntityInteractPacket>(0x22u, EntityInteractPacketCodec)
bidi<DialogChoicePacket>(0x25u, DialogChoicePacketCodec)
bidi<DialogOptionPacket>(0x26u, DialogOptionPacketCodec)
bidi<NpcAnimationPacket>(0xB2u, NpcAnimationPacketCodec)
bidi<RenderScreenPacket>(0xB4u, RenderScreenPacketCodec)
bidi<MapTransitionAckPacket>(0xB9u, MapTransitionAckPacketCodec)
bidi<KeepAlivePacket>(0xC2u, KeepAlivePacketCodec)
s2c<EntityMovePacket>(0xEAu, EntityMovePacketCodec)
}
}
@@ -0,0 +1,100 @@
package de.fiereu.openmmo.net.game.codecs
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.bytecodec.bytesPrefixed
import de.fiereu.bytecodec.imap
import de.fiereu.openmmo.common.CharacterInfo
import java.time.LocalDateTime
import java.time.ZoneOffset
internal val EpochSecondsS32LE: Codec<LocalDateTime> =
S32LE.imap(
decode = { LocalDateTime.ofEpochSecond(it.toLong(), 0, ZoneOffset.UTC) },
encode = { it.toEpochSecond(ZoneOffset.UTC).toInt() },
)
private val TrailingBytes = bytesPrefixed(U16LE)
class CharacterInfoCodec(private val withExtraLong: Boolean) : PacketCodec<CharacterInfo>() {
override fun CodecScope<CharacterInfo>.body(): CharacterInfo {
val id = field(S64LE, CharacterInfo::id)
val name = field(Utf16LeNullTerminated, CharacterInfo::name)
val namePrefix = field(Utf16LeNullTerminated) { "" }
val userId = field(S32LE, CharacterInfo::userId)
val rivalSex = field(S8, CharacterInfo::rivalSex)
val lastLogin = field(EpochSecondsS32LE, CharacterInfo::lastLogin)
if (withExtraLong) field(S64LE) { 0L }
val createdAt = field(EpochSecondsS32LE, CharacterInfo::createdAt)
field(S32LE) { 0 }
field(S8) { 0 }
field(S32LE) { 0 }
val money = field(S32LE, CharacterInfo::money)
field(S16LE) { 0 }
field(S32LE) { 0 }
val permissions = field(U8) { it.permissions and 0xFF }
field(S8) { 0 }
field(S8) { 0 }
field(S32LE) { 0 }
repeat(8) { field(S8) { 0 } }
val remainingSafariSteps = field(S16LE, CharacterInfo::remainingSafariSteps)
val remainingSafariBalls = field(S8, CharacterInfo::remainingSafariBalls)
field(S32LE) { 0 }
val pcExtraSlots = field(S8, CharacterInfo::pcExtraSlots)
val battleBoxExtraSlots = field(S8, CharacterInfo::battleBoxExtraSlots)
val templateAmount = field(S8, CharacterInfo::templateAmount)
field(S8) { 0 }
field(S8) { 0 }
field(S8) { 0 }
val positionRegionId = field(S8, CharacterInfo::positionRegionId)
val positionBankId = field(S8, CharacterInfo::positionBankId)
val positionMapId = field(S8, CharacterInfo::positionMapId)
field(S8) { 0 }
val positionX = field(S16LE, CharacterInfo::positionX)
val positionY = field(S16LE, CharacterInfo::positionY)
field(S8) { 0 }
field(S8) { 0 }
val repelLeft = field(S16LE, CharacterInfo::repelLeft)
val repelItemId = field(S16LE, CharacterInfo::repelItemId)
field(S8) { 0 }
val lureItemId = field(S16LE, CharacterInfo::lureItemId)
val lureLeft = field(S16LE, CharacterInfo::lureLeft)
field(TrailingBytes) { ByteArray(0) }
return CharacterInfo(
id = id,
name = name,
namePrefix = namePrefix,
userId = userId,
rivalSex = rivalSex,
lastLogin = lastLogin,
createdAt = createdAt,
money = money,
permissions = permissions,
remainingSafariSteps = remainingSafariSteps,
remainingSafariBalls = remainingSafariBalls,
pcExtraSlots = pcExtraSlots,
battleBoxExtraSlots = battleBoxExtraSlots,
templateAmount = templateAmount,
positionRegionId = positionRegionId,
positionBankId = positionBankId,
positionMapId = positionMapId,
positionX = positionX,
positionY = positionY,
repelLeft = repelLeft,
repelItemId = repelItemId,
lureLeft = lureLeft,
lureItemId = lureItemId,
)
}
}
val CharacterInfoCodecShort: Codec<CharacterInfo> = CharacterInfoCodec(withExtraLong = false)
val CharacterInfoCodecLong: Codec<CharacterInfo> = CharacterInfoCodec(withExtraLong = true)
@@ -0,0 +1,108 @@
package de.fiereu.openmmo.net.game.codecs
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.bytecodec.bytesPrefixed
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.PokemonRarity
import de.fiereu.openmmo.common.enums.compress
import de.fiereu.openmmo.common.enums.decompressIVs
private val PokemonUnknownBytes: Codec<ByteArray> = bytesPrefixed(U8)
object PokemonCodec : PacketCodec<Pokemon>() {
override fun CodecScope<Pokemon>.body(): Pokemon {
val id = field(S64LE, Pokemon::id)
field(S8) { 0 }
field(S64LE) { 0L }
field(S64LE) { 0L }
val container = PokemonContainer.entries[field(U8) { it.container.ordinal }]
val containerSlot = field(S16LE, Pokemon::containerSlot)
val dexId = field(U16LE, Pokemon::dexId)
val seed = field(S32LE, Pokemon::seed)
field(S64LE) { 0L }
val ot = field(Utf16LeNullTerminated, Pokemon::ot)
val nickname = field(Utf16LeNullTerminated, Pokemon::nickname)
field(S8) { 0 }
field(S8) { 0 }
val level = field(S8, Pokemon::level)
val currentHp = field(S16LE, Pokemon::hp)
field(S16LE) { 0 }
val xp = field(S32LE, Pokemon::xp)
field(S8) { 0 }
field(S16LE) { 0 }
val moveIds = List(4) { i -> field(S16LE) { it.moves[i].id } }
val movePps = List(4) { i -> field(S8) { it.moves[i].pp } }
val moves = List(4) { PokemonMove(moveIds[it], movePps[it]) }
repeat(4) { field(S16LE) { 0 } }
val eVs =
EVs().apply {
hp = field(U8) { it.eVs.hp }
atk = field(U8) { it.eVs.atk }
def = field(U8) { it.eVs.def }
spd = field(U8) { it.eVs.spd }
spAtk = field(U8) { it.eVs.spAtk }
spDef = field(U8) { it.eVs.spDef }
}
repeat(11) { field(S8) { 0 } }
val iVs = decompressIVs(field(S32LE) { it.iVs.compress() })
field(S8) { 0 }
field(S64LE) { 0L }
val rarityMask =
field(U16LE) {
var m = 0
if (it.isShiny) m = m or (1 shl PokemonRarity.SHINY.ordinal)
if (it.hasHiddenAbility) m = m or (1 shl PokemonRarity.HIDDEN_ABILITY.ordinal)
if (it.isAlpha) m = m or (1 shl PokemonRarity.ALPHA.ordinal)
if (it.isSecret) m = m or (1 shl PokemonRarity.SECRET.ordinal)
if (it.isFatefulEncounter) m = m or (1 shl PokemonRarity.FATEFUL_ENCOUNTER.ordinal)
if (it.isRaidEncounter) m = m or (1 shl PokemonRarity.RAID_ENCOUNTER.ordinal)
m
}
val isShiny = (rarityMask and (1 shl PokemonRarity.SHINY.ordinal)) != 0
val hasHiddenAbility = (rarityMask and (1 shl PokemonRarity.HIDDEN_ABILITY.ordinal)) != 0
val isAlpha = (rarityMask and (1 shl PokemonRarity.ALPHA.ordinal)) != 0
val isSecret = (rarityMask and (1 shl PokemonRarity.SECRET.ordinal)) != 0
val isFatefulEncounter = (rarityMask and (1 shl PokemonRarity.FATEFUL_ENCOUNTER.ordinal)) != 0
val isRaidEncounter = (rarityMask and (1 shl PokemonRarity.RAID_ENCOUNTER.ordinal)) != 0
val caughtAt = field(EpochSecondsS32LE, Pokemon::caughtAt)
field(S16LE) { 0 }
field(S8) { 0 }
field(S8) { 0 }
field(PokemonUnknownBytes) { ByteArray(0) }
repeat(12) { field(S8) { 0 } }
return Pokemon(
id,
container,
containerSlot,
dexId,
seed,
ot,
nickname,
level,
currentHp,
xp,
eVs,
iVs,
moves,
isShiny,
hasHiddenAbility,
isAlpha,
isSecret,
isFatefulEncounter,
isRaidEncounter,
caughtAt,
)
}
}
@@ -0,0 +1,53 @@
package de.fiereu.openmmo.net.game.codecs
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
import de.fiereu.openmmo.common.enums.SkinSlot
import java.util.EnumMap
data class Skin(val slot: SkinSlot, val type: UShort?, val color: UByte?)
class SkinSet : EnumMap<SkinSlot, Skin>(SkinSlot::class.java) {
fun put(skin: Skin) {
this[skin.slot] = skin
}
override fun put(key: SkinSlot, value: Skin): Skin? {
require(key == value.slot) { "Slot mismatch: $key != ${value.slot}" }
return super.put(key, value)
}
}
class SkinSetCodec(
private val slots: List<SkinSlot> = SkinSlot.entries,
private val withLeadingByte: Boolean = true,
) : PacketCodec<SkinSet>() {
override fun CodecScope<SkinSet>.body(): SkinSet {
if (withLeadingByte) field(U8) { 0 }
val mask = field(U16LE) { slots.fold(0) { acc, slot -> acc or (1 shl slot.ordinal) } }
val skins = SkinSet()
slots.forEach { slot ->
if ((mask and (1 shl slot.ordinal)) != 0) {
val compressed =
field(U16LE) {
val skin = it[slot] ?: Skin(slot, 0u, 0u)
val type = skin.type ?: 0x3FFFu
val color = skin.color ?: 0x3Fu
require(type <= 0x3FFFu) { "Skin type too large: ${skin.type}" }
require(color <= 0x3Fu) { "Skin color too large: ${skin.color}" }
(type and 0x3FFFu).toInt() or ((color and 0x3Fu).toInt() shl 10)
}
val type = (compressed and 0x3FFF).toUShort()
val color = ((compressed shr 10) and 0x3F).toUByte()
skins.put(Skin(slot, type, color))
}
}
return skins
}
}
val DefaultSkinSetCodec: Codec<SkinSet> = SkinSetCodec()
val SkinSetCodecNoLeading: Codec<SkinSet> = SkinSetCodec(withLeadingByte = false)
@@ -0,0 +1,19 @@
package de.fiereu.openmmo.net.game.codecs
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.imap
import de.fiereu.openmmo.common.Tile2D
val Tile2DCodec: Codec<Tile2D> =
U16LE.imap(
decode = { raw ->
Tile2D(
material = (raw and 0x3FF).toShort(),
collision = ((raw shr 10) and 0x3F).toByte(),
)
},
encode = { tile ->
((tile.collision.toInt() and 0x3F) shl 10) or (tile.material.toInt() and 0x3FF)
},
)
@@ -0,0 +1,80 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.bytecodec.WriteBuffer
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.net.game.codecs.CharacterInfoCodecLong
import de.fiereu.openmmo.net.game.codecs.CharacterInfoCodecShort
import de.fiereu.openmmo.net.game.codecs.DefaultSkinSetCodec
import de.fiereu.openmmo.net.game.codecs.PokemonCodec
import de.fiereu.openmmo.net.game.codecs.SkinSet
import de.fiereu.openmmo.net.game.codecs.SkinSetCodecNoLeading
data class CharacterEntry(
val characterInfo: CharacterInfo,
val skinSet: SkinSet,
val guildId: Int? = null,
val pokemon: List<Pokemon>,
) {
init {
require(pokemon.size <= 6) { "Party size can't be more than 6 pokemon" }
}
}
data class CharactersListPacket(val characters: List<CharacterEntry>)
private val CharacterInfoAsymmetric: Codec<CharacterInfo> =
object : Codec<CharacterInfo> {
override fun read(buf: ReadBuffer): CharacterInfo = CharacterInfoCodecLong.read(buf)
override fun write(buf: WriteBuffer, value: CharacterInfo) {
CharacterInfoCodecShort.write(buf, value)
}
}
private object CharacterEntryCodec : PacketCodec<CharacterEntry>() {
override fun CodecScope<CharacterEntry>.body(): CharacterEntry {
val info = field(CharacterInfoAsymmetric, CharacterEntry::characterInfo)
val skin = field(DefaultSkinSetCodec, CharacterEntry::skinSet)
field(SkinSetCodecNoLeading, CharacterEntry::skinSet)
val hasGuild = field(Bool) { it.guildId != null }
val guildId =
if (hasGuild) {
field(Utf16LeNullTerminated) { "" }
field(S32LE) { it.guildId!! }
} else {
null
}
val partySize = field(U8) { it.pokemon.size }
val party = List(partySize) { field(PokemonCodec) { entry -> entry.pokemon[it] } }
return CharacterEntry(info, skin, guildId, party)
}
}
private val CharacterEntryListPrefixedU8: Codec<List<CharacterEntry>> =
object : Codec<List<CharacterEntry>> {
override fun read(buf: ReadBuffer): List<CharacterEntry> {
val n = U8.read(buf)
return List(n) { CharacterEntryCodec.read(buf) }
}
override fun write(buf: WriteBuffer, value: List<CharacterEntry>) {
U8.write(buf, value.size)
value.forEach { CharacterEntryCodec.write(buf, it) }
}
}
object CharactersListPacketCodec : PacketCodec<CharactersListPacket>() {
override fun CodecScope<CharactersListPacket>.body() =
CharactersListPacket(
characters = field(CharacterEntryListPrefixedU8, CharactersListPacket::characters),
)
}
@@ -0,0 +1,52 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.MalformedPacketException
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.Language
data class ChatMessagePacket(
val type: ChatType,
val language: Language?,
val message: String,
val sender: String?,
)
object ChatMessagePacketCodec : PacketCodec<ChatMessagePacket>() {
override fun CodecScope<ChatMessagePacket>.body(): ChatMessagePacket {
val type = ChatType.entries[field(U8) { it.type.ordinal }]
return if (type == ChatType.TEAM) {
ChatMessagePacket(
type = type,
language = null,
message = field(Utf16LeNullTerminated, ChatMessagePacket::message),
sender = null,
)
} else {
field(S64LE) { 0L }
val sender =
field(Utf16LeNullTerminated) {
it.sender ?: throw MalformedPacketException("sender must not be null")
}
val language =
Language.entries[
field(U8) {
(it.language ?: throw MalformedPacketException("language must not be null"))
.ordinal
}]
field(S8) { -1 }
val message = field(Utf16LeNullTerminated, ChatMessagePacket::message)
ChatMessagePacket(
type = type,
language = language,
message = message,
sender = sender,
)
}
}
}
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.Utf16LeNullTerminated
data class CreateCharacterPacket(val name: String)
object CreateCharacterPacketCodec : PacketCodec<CreateCharacterPacket>() {
override fun CodecScope<CreateCharacterPacket>.body(): CreateCharacterPacket {
val name = field(Utf16LeNullTerminated) { it.name }
return CreateCharacterPacket(name)
}
}
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
data class DialogChoicePacket(val unk1: Int, val unk2: Int)
object DialogChoicePacketCodec : PacketCodec<DialogChoicePacket>() {
override fun CodecScope<DialogChoicePacket>.body(): DialogChoicePacket {
val unk1 = field(U8) { it.unk1 }
val unk2 = field(U16LE) { it.unk2 }
return DialogChoicePacket(unk1, unk2)
}
}
@@ -0,0 +1,54 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.WriteBuffer
data class DialogDataPacket(
val entityId: Long,
val unk1: Int,
val type: Int,
val data: ByteArray,
) {
override fun equals(other: Any?): Boolean =
other is DialogDataPacket &&
entityId == other.entityId &&
unk1 == other.unk1 &&
type == other.type &&
data.contentEquals(other.data)
override fun hashCode(): Int {
var result = entityId.hashCode()
result = 31 * result + unk1
result = 31 * result + type
result = 31 * result + data.contentHashCode()
return result
}
}
private object RemainingBytes : Codec<ByteArray> {
override fun read(buf: ReadBuffer): ByteArray {
val n = buf.remaining()
val arr = ByteArray(n)
if (n > 0) buf.readBytes(arr)
return arr
}
override fun write(buf: WriteBuffer, value: ByteArray) {
if (value.isNotEmpty()) buf.writeBytes(value)
}
}
object DialogDataPacketCodec : PacketCodec<DialogDataPacket>() {
override fun CodecScope<DialogDataPacket>.body(): DialogDataPacket {
val entityId = field(S64LE) { it.entityId }
val unk1 = field(U8) { it.unk1 }
val type = field(U8) { it.type }
val data = field(RemainingBytes) { it.data }
return DialogDataPacket(entityId, unk1, type, data)
}
}
@@ -0,0 +1,13 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.imap
data class DialogOptionPacket(val data: Int)
val DialogOptionPacketCodec: Codec<DialogOptionPacket> =
S32LE.imap(
decode = { DialogOptionPacket(it) },
encode = { it.data },
)
@@ -0,0 +1,13 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.imap
data class DialogStatePacket(val active: Boolean)
val DialogStatePacketCodec: Codec<DialogStatePacket> =
Bool.imap(
decode = { DialogStatePacket(it) },
encode = { it.active },
)
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64LE
data class EntityInteractPacket(val entityId: Long, val token: Long)
object EntityInteractPacketCodec : PacketCodec<EntityInteractPacket>() {
override fun CodecScope<EntityInteractPacket>.body(): EntityInteractPacket {
val entityId = field(S64LE) { it.entityId }
val token = field(S64LE) { it.token }
return EntityInteractPacket(entityId, token)
}
}
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64BE
data class EntityLeavePacket(val entityId: Long)
object EntityLeavePacketCodec : PacketCodec<EntityLeavePacket>() {
override fun CodecScope<EntityLeavePacket>.body(): EntityLeavePacket {
val entityId = field(S64BE) { it.entityId }
return EntityLeavePacket(entityId)
}
}
@@ -0,0 +1,33 @@
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.S8
import de.fiereu.bytecodec.enumByOrdinalByte
import de.fiereu.openmmo.common.enums.Direction
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 direction: Direction,
)
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 direction = field(DirectionCodec) { it.direction }
return EntityMovePacket(entityId, marker, subtype, seq, x, y, direction)
}
}
@@ -0,0 +1,17 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.enumByOrdinalByte
import de.fiereu.openmmo.common.enums.Direction
data class FaceDirectionPacket(val direction: Direction)
object FaceDirectionPacketCodec : PacketCodec<FaceDirectionPacket>() {
private val DirectionCodec = enumByOrdinalByte<Direction>()
override fun CodecScope<FaceDirectionPacket>.body(): FaceDirectionPacket {
val direction = field(DirectionCodec) { it.direction }
return FaceDirectionPacket(direction)
}
}
@@ -0,0 +1,31 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
data class InteractivePacket(
val id: Int,
val type: Int,
val unk1: Int,
val unk2: Int,
val targetEntityId: Long,
val unk3: Int,
val unk4: Int,
)
object InteractivePacketCodec : PacketCodec<InteractivePacket>() {
override fun CodecScope<InteractivePacket>.body(): InteractivePacket {
val id = field(U8) { it.id }
val type = field(U8) { it.type }
val unk1 = field(S32LE) { it.unk1 }
val unk2 = field(S32LE) { it.unk2 }
val targetEntityId = field(S64LE) { it.targetEntityId }
val unk3 = field(U16LE) { it.unk3 }
val unk4 = field(U16LE) { it.unk4 }
return InteractivePacket(id, type, unk1, unk2, targetEntityId, unk3, unk4)
}
}
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U8
data class InteractiveResponsePacket(val id: Int, val unk: Int)
object InteractiveResponsePacketCodec : PacketCodec<InteractiveResponsePacket>() {
override fun CodecScope<InteractiveResponsePacket>.body(): InteractiveResponsePacket {
val id = field(U8) { it.id }
val unk = field(U8) { it.unk }
return InteractiveResponsePacket(id, unk)
}
}
@@ -0,0 +1,203 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.bytecodec.bytesPrefixed
import de.fiereu.bytecodec.choose
import de.fiereu.bytecodec.enumByOrdinalByte
import de.fiereu.bytecodec.fixedBytes
import de.fiereu.bytecodec.imap
import de.fiereu.bytecodec.listPrefixed
import de.fiereu.bytecodec.then
import de.fiereu.openmmo.common.enums.Arch
import de.fiereu.openmmo.common.enums.Bitness
import de.fiereu.openmmo.common.enums.Platform
data class RomInfo(val code: String, val id: Byte, val type: Byte)
sealed class GameAuthenticationData
data class ReconnectAuthData(val sessionId: Long, val sessionKey: ByteArray) :
GameAuthenticationData() {
override fun equals(other: Any?): Boolean =
other is ReconnectAuthData &&
sessionId == other.sessionId &&
sessionKey.contentEquals(other.sessionKey)
override fun hashCode(): Int = sessionId.hashCode() * 31 + sessionKey.contentHashCode()
}
data class NewAuthData(val userId: Int, val sessionKey: ByteArray) : GameAuthenticationData() {
override fun equals(other: Any?): Boolean =
other is NewAuthData && userId == other.userId && sessionKey.contentEquals(other.sessionKey)
override fun hashCode(): Int = userId * 31 + sessionKey.contentHashCode()
}
data class JoinPacket(
val authData: GameAuthenticationData,
val mac: ByteArray,
val clientRevision: Int,
val installationRevision: Int,
val currentChatLanguage: Byte,
val chatLanguages: Short,
val matchmakingLanguages: Short,
val romMask: Byte,
val roms: List<RomInfo>,
val clientInfo: Map<Byte, String>,
val platform: Platform,
val arch: Arch,
val bitness: Bitness,
val unk1: ByteArray,
val unk2: ByteArray,
) {
override fun equals(other: Any?): Boolean =
other is JoinPacket &&
authData == other.authData &&
mac.contentEquals(other.mac) &&
clientRevision == other.clientRevision &&
installationRevision == other.installationRevision &&
currentChatLanguage == other.currentChatLanguage &&
chatLanguages == other.chatLanguages &&
matchmakingLanguages == other.matchmakingLanguages &&
romMask == other.romMask &&
roms == other.roms &&
clientInfo == other.clientInfo &&
platform == other.platform &&
arch == other.arch &&
bitness == other.bitness &&
unk1.contentEquals(other.unk1) &&
unk2.contentEquals(other.unk2)
override fun hashCode(): Int {
var r = authData.hashCode()
r = r * 31 + mac.contentHashCode()
r = r * 31 + clientRevision
r = r * 31 + installationRevision
r = r * 31 + currentChatLanguage
r = r * 31 + chatLanguages
r = r * 31 + matchmakingLanguages
r = r * 31 + romMask
r = r * 31 + roms.hashCode()
r = r * 31 + clientInfo.hashCode()
r = r * 31 + platform.hashCode()
r = r * 31 + arch.hashCode()
r = r * 31 + bitness.hashCode()
r = r * 31 + unk1.contentHashCode()
r = r * 31 + unk2.contentHashCode()
return r
}
}
private val SessionKey = bytesPrefixed(U8)
private object NewAuthDataCodec : PacketCodec<NewAuthData>() {
override fun CodecScope<NewAuthData>.body(): NewAuthData {
val userId = field(S32LE) { it.userId }
val sessionKey = field(SessionKey) { it.sessionKey }
return NewAuthData(userId, sessionKey)
}
}
private object ReconnectAuthDataCodec : PacketCodec<ReconnectAuthData>() {
override fun CodecScope<ReconnectAuthData>.body(): ReconnectAuthData {
val sessionId = field(S64LE) { it.sessionId }
val sessionKey = field(SessionKey) { it.sessionKey }
return ReconnectAuthData(sessionId, sessionKey)
}
}
private val AuthDataCodec: Codec<GameAuthenticationData> =
choose(
tag = U8,
identify = { data ->
when (data) {
is NewAuthData -> 0x00
is ReconnectAuthData -> 0x01
}
},
0x00 to NewAuthDataCodec,
0x01 to ReconnectAuthDataCodec,
)
private val PlatformCodec: Codec<Platform> =
U8.imap(
decode = { Platform.from(it) },
encode = { p ->
when (p) {
Platform.WINDOWS -> 0x00
Platform.LINUX -> 0x01
Platform.MACOS -> 0x02
Platform.IOS -> 0x03
Platform.ANDROID -> 0x04
Platform.UNKNOWN -> 0xFF
}
},
)
private val ArchCodec: Codec<Arch> = enumByOrdinalByte<Arch>()
private val BitnessCodec: Codec<Bitness> = enumByOrdinalByte<Bitness>()
private val RomInfoCodec: Codec<RomInfo> =
object : PacketCodec<RomInfo>() {
override fun CodecScope<RomInfo>.body(): RomInfo {
val code = field(Utf16LeNullTerminated) { it.code }
val id = field(S8) { it.id }
val type = field(S8) { it.type }
return RomInfo(code, id, type)
}
}
private val ClientInfoEntryCodec: Codec<Pair<Byte, String>> = S8.then(Utf16LeNullTerminated)
private val ClientInfoMapCodec: Codec<Map<Byte, String>> =
ClientInfoEntryCodec.listPrefixed(U8)
.imap(decode = { it.toMap() }, encode = { it.entries.map { e -> e.key to e.value } })
private val MacBytes = fixedBytes(6)
private val Unk1Bytes = bytesPrefixed(U8)
private val Unk2Bytes = fixedBytes(32)
object JoinPacketCodec : PacketCodec<JoinPacket>() {
override fun CodecScope<JoinPacket>.body(): JoinPacket {
val authData = field(AuthDataCodec) { it.authData }
val mac = field(MacBytes) { it.mac }
val clientRevision = field(S32LE) { it.clientRevision }
val installationRevision = field(S32LE) { it.installationRevision }
val currentChatLanguage = field(S8) { it.currentChatLanguage }
val chatLanguages = field(S16LE) { it.chatLanguages }
val matchmakingLanguages = field(S16LE) { it.matchmakingLanguages }
val romMask = field(S8) { it.romMask }
val roms = field(RomInfoCodec.listPrefixed(U8)) { it.roms }
val clientInfo = field(ClientInfoMapCodec) { it.clientInfo }
val platform = field(PlatformCodec) { it.platform }
val arch = field(ArchCodec) { it.arch }
val bitness = field(BitnessCodec) { it.bitness }
val unk1 = field(Unk1Bytes) { it.unk1 }
val unk2 = field(Unk2Bytes) { it.unk2 }
return JoinPacket(
authData = authData,
mac = mac,
clientRevision = clientRevision,
installationRevision = installationRevision,
currentChatLanguage = currentChatLanguage,
chatLanguages = chatLanguages,
matchmakingLanguages = matchmakingLanguages,
romMask = romMask,
roms = roms,
clientInfo = clientInfo,
platform = platform,
arch = arch,
bitness = bitness,
unk1 = unk1,
unk2 = unk2,
)
}
}
@@ -0,0 +1,75 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.MalformedPacketException
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import java.time.LocalDate
import java.time.ZoneId
data class JoinResponsePacket(
val canJoin: Boolean,
val stats: GameStats? = null,
val time: TimeInfo? = null,
) {
data class GameStats(val playtime: Int, val rewardPoints: Int, val balance: Int)
data class TimeInfo(val serverDayStartSecond: Int, val serverCurrentSecond: Int)
companion object {
fun reject(): JoinResponsePacket = JoinResponsePacket(false)
fun accept(stats: GameStats, time: TimeInfo? = null): JoinResponsePacket =
JoinResponsePacket(true, stats, time)
fun acceptNow(playtime: Int, rewardPoints: Int, balance: Int): JoinResponsePacket {
val dayStart = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond().toInt()
val now = (System.currentTimeMillis() / 1000).toInt()
return JoinResponsePacket(
canJoin = true,
stats = GameStats(playtime, rewardPoints, balance),
time = TimeInfo(dayStart, now),
)
}
}
}
private fun nowTimeInfo(): JoinResponsePacket.TimeInfo =
JoinResponsePacket.TimeInfo(
serverDayStartSecond =
LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond().toInt(),
serverCurrentSecond = (System.currentTimeMillis() / 1000).toInt(),
)
object JoinResponsePacketCodec : PacketCodec<JoinResponsePacket>() {
override fun CodecScope<JoinResponsePacket>.body(): JoinResponsePacket {
val canJoin = field(Bool, JoinResponsePacket::canJoin)
if (!canJoin) return JoinResponsePacket(false)
field(Utf16LeNullTerminated) { "" }
field(S8) { 0 }
val playtime =
field(S32LE) {
(it.stats
?: throw MalformedPacketException("stats must be provided when canJoin is true"))
.playtime
}
val rewardPoints = field(S32LE) { it.stats!!.rewardPoints }
val balance = field(S32LE) { it.stats!!.balance }
var resolvedTime: JoinResponsePacket.TimeInfo? = null
val dayStart =
field(S32LE) {
val t = it.time ?: nowTimeInfo()
resolvedTime = t
t.serverDayStartSecond
}
val now = field(S32LE) { resolvedTime!!.serverCurrentSecond }
return JoinResponsePacket(
canJoin = true,
stats = JoinResponsePacket.GameStats(playtime, rewardPoints, balance),
time = JoinResponsePacket.TimeInfo(dayStart, now),
)
}
}
@@ -0,0 +1,38 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.WriteBuffer
data class KeepAlivePacket(val canJoin: Boolean, val sessionData: ByteArray) {
override fun equals(other: Any?): Boolean =
other is KeepAlivePacket &&
canJoin == other.canJoin &&
sessionData.contentEquals(other.sessionData)
override fun hashCode(): Int = canJoin.hashCode() * 31 + sessionData.contentHashCode()
}
private val KeepAliveSessionDataBytes: Codec<ByteArray> =
object : Codec<ByteArray> {
override fun read(buf: ReadBuffer): ByteArray {
val data = ByteArray(buf.remaining())
if (data.isNotEmpty()) buf.readBytes(data)
return data
}
override fun write(buf: WriteBuffer, value: ByteArray) {
if (value.isNotEmpty()) buf.writeBytes(value)
}
}
object KeepAlivePacketCodec : PacketCodec<KeepAlivePacket>() {
override fun CodecScope<KeepAlivePacket>.body() =
KeepAlivePacket(
canJoin = field(Bool, KeepAlivePacket::canJoin),
sessionData = field(KeepAliveSessionDataBytes, KeepAlivePacket::sessionData),
)
}
@@ -0,0 +1,82 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.bytecodec.reserved
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.EntityStatus
import de.fiereu.openmmo.net.game.codecs.DefaultSkinSetCodec
import de.fiereu.openmmo.net.game.codecs.SkinSet
data class LoadEntityPacket(
val entityId: Long,
val skin: SkinSet,
val name: String,
val regionId: Int,
val bankId: Int,
val mapId: Int,
val x: Int,
val y: Int,
val z: Int,
val facing: Direction,
val transportation: Int = 0,
val entityNameplateType: Int = 0,
val status: EntityStatus = EntityStatus.NONE,
val hasFollower: Boolean,
val followerDexId: Short,
)
object LoadEntityPacketCodec : PacketCodec<LoadEntityPacket>() {
override fun CodecScope<LoadEntityPacket>.body(): LoadEntityPacket {
val entityId = field(S64LE, LoadEntityPacket::entityId)
reserved(byte = 0)
val skin = field(DefaultSkinSetCodec, LoadEntityPacket::skin)
val name = field(Utf16LeNullTerminated, LoadEntityPacket::name)
val regionId = field(U8, LoadEntityPacket::regionId)
val bankId = field(U8, LoadEntityPacket::bankId)
val mapId = field(U8, LoadEntityPacket::mapId)
val x = field(S16LE) { it.x.toShort() }.toInt()
val y = field(S16LE) { it.y.toShort() }.toInt()
val z = field(U8, LoadEntityPacket::z)
val facing = Direction.entries[field(U8) { it.facing.ordinal }]
val transportation = field(U8, LoadEntityPacket::transportation)
val entityNameplateType = field(U8, LoadEntityPacket::entityNameplateType)
val flags = field(U16LE) { if (it.hasFollower) 0x04 else 0 }
if (flags and 0x01 != 0) field(S8) { 0 }
if (flags and 0x02 != 0) {
field(S8) { 0 }
field(U16LE) { 0 }
}
val hasFollower = (flags and 0x04) != 0
val followerDexId: Short = if (hasFollower) field(S16LE, LoadEntityPacket::followerDexId) else 0
if (flags and 0x08 != 0) field(S8) { 0 }
if (flags and 0x10 != 0) {
field(S32LE) { 0 }
field(Utf16LeNullTerminated) { "" }
}
return LoadEntityPacket(
entityId = entityId,
skin = skin,
name = name,
regionId = regionId,
bankId = bankId,
mapId = mapId,
x = x,
y = y,
z = z,
facing = facing,
transportation = transportation,
entityNameplateType = entityNameplateType,
status = EntityStatus.NONE,
hasFollower = hasFollower,
followerDexId = followerDexId,
)
}
}
@@ -0,0 +1,191 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.MalformedPacketException
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S32LE
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.Utf16LeNullTerminated
import de.fiereu.bytecodec.WriteBuffer
import de.fiereu.openmmo.common.Tile2D
import de.fiereu.openmmo.common.enums.EncounterType
import de.fiereu.openmmo.common.enums.Lighting
import de.fiereu.openmmo.common.enums.MapType
import de.fiereu.openmmo.common.enums.Weather
import de.fiereu.openmmo.common.utils.gzipDecompress
import de.fiereu.openmmo.common.utils.isNdsRegion
import de.fiereu.openmmo.net.game.codecs.Tile2DCodec
sealed interface MapData {
data class NdsMapData(val lighting: Lighting, val weather: Weather, val mapType: MapType) :
MapData
data class GbaConnection(
val direction: Int,
val unknown: Int,
val targetBank: Int,
val targetMap: Int,
)
data class GbaMapData(
val width: Int,
val height: Int,
val paletteIdx1: Int,
val paletteIdx2: Int,
val borderWidth: Int,
val borderHeight: Int,
val unknownShort: Int = 0,
val unknownByte: Int = 0,
val borderTiles: List<Tile2D>,
val lighting: Lighting,
val weather: Weather,
val mapType: MapType,
val encounterType: EncounterType,
val connections: List<GbaConnection> = emptyList(),
) : MapData {
init {
require(borderWidth * borderHeight == borderTiles.size) {
"borderTiles size doesnt match dimensions"
}
require(borderWidth * borderHeight > 0) { "BorderWidth & Height must be greater than zero" }
}
}
}
data class LoadMapPacket(
val reloadPlayer: Boolean,
val deleteCache: Boolean,
val regionId: Int,
val bankId: Int,
val mapId: Int,
val mapData: MapData,
) {
init {
when (mapData) {
is MapData.NdsMapData -> require(isNdsRegion(regionId)) { "MapData is invalid" }
is MapData.GbaMapData -> require(!isNdsRegion(regionId)) { "MapData is invalid" }
}
}
}
private object GbaConnectionCodec : PacketCodec<MapData.GbaConnection>() {
override fun CodecScope<MapData.GbaConnection>.body() =
MapData.GbaConnection(
direction = field(U8, MapData.GbaConnection::direction),
unknown = field(S32LE, MapData.GbaConnection::unknown),
targetBank = field(U8, MapData.GbaConnection::targetBank),
targetMap = field(U8, MapData.GbaConnection::targetMap),
)
}
private val GbaConnectionListPrefixedU8: Codec<List<MapData.GbaConnection>> =
object : Codec<List<MapData.GbaConnection>> {
override fun read(buf: ReadBuffer): List<MapData.GbaConnection> {
val n = U8.read(buf)
return List(n) { GbaConnectionCodec.read(buf) }
}
override fun write(buf: WriteBuffer, value: List<MapData.GbaConnection>) {
U8.write(buf, value.size)
value.forEach { GbaConnectionCodec.write(buf, it) }
}
}
object LoadMapPacketCodec : PacketCodec<LoadMapPacket>() {
override fun CodecScope<LoadMapPacket>.body(): LoadMapPacket {
val flags =
field(U8) {
var f = 0
if (it.deleteCache) f = f or 1
if (it.reloadPlayer) f = f or 2
f
}
val deleteCache = (flags and 1) != 0
val reloadPlayer = (flags and 2) != 0
val regionId = field(U8, LoadMapPacket::regionId)
val bankId = field(U8, LoadMapPacket::bankId)
val mapId = field(U8, LoadMapPacket::mapId)
field(S8) { 0 }
val mapData: MapData =
if (isNdsRegion(regionId)) {
field(S16LE) { 0 }
field(U8) { 0 }
val lighting =
Lighting.entries[field(U8) { (it.mapData as MapData.NdsMapData).lighting.ordinal }]
val weather =
Weather.entries[field(U8) { (it.mapData as MapData.NdsMapData).weather.ordinal }]
val mapType =
MapType.entries[field(U8) { (it.mapData as MapData.NdsMapData).mapType.ordinal }]
MapData.NdsMapData(lighting, weather, mapType)
} else {
val getGba: (LoadMapPacket) -> MapData.GbaMapData = {
it.mapData as? MapData.GbaMapData
?: throw MalformedPacketException("expected GbaMapData for region $regionId")
}
val width = field(S32LE) { getGba(it).width }
val height = field(S32LE) { getGba(it).height }
val paletteIdx1 = field(S32LE) { getGba(it).paletteIdx1 }
val paletteIdx2 = field(S32LE) { getGba(it).paletteIdx2 }
val borderWidth = field(U8) { getGba(it).borderWidth }
val borderHeight = field(U8) { getGba(it).borderHeight }
val unknownShort = field(S16LE) { getGba(it).unknownShort.toShort() }.toInt()
val unknownByte = field(U8) { getGba(it).unknownByte }
val lighting = Lighting.entries[field(U8) { getGba(it).lighting.ordinal }]
val weather = Weather.entries[field(U8) { getGba(it).weather.ordinal }]
val mapType = MapType.entries[field(U8) { getGba(it).mapType.ordinal }]
val encounterType = EncounterType.entries[field(U8) { getGba(it).encounterType.ordinal }]
val borderTiles =
List(borderWidth * borderHeight) {
field(Tile2DCodec) { entry -> getGba(entry).borderTiles[it] }
}
val hasCompressed = field(Bool) { false }
if (hasCompressed) {
val size = field(S32LE) { 0 }
val compressed = field(FixedReadBytes(size)) { ByteArray(0) }
compressed.gzipDecompress()
}
val connections = field(GbaConnectionListPrefixedU8) { getGba(it).connections }
val hasTrailer = field(Bool) { false }
if (hasTrailer) {
field(S64LE) { 0L }
field(Utf16LeNullTerminated) { "" }
}
MapData.GbaMapData(
width = width,
height = height,
paletteIdx1 = paletteIdx1,
paletteIdx2 = paletteIdx2,
borderWidth = borderWidth,
borderHeight = borderHeight,
unknownShort = unknownShort,
unknownByte = unknownByte,
borderTiles = borderTiles,
lighting = lighting,
weather = weather,
mapType = mapType,
encounterType = encounterType,
connections = connections,
)
}
return LoadMapPacket(reloadPlayer, deleteCache, regionId, bankId, mapId, mapData)
}
}
private fun FixedReadBytes(n: Int): Codec<ByteArray> =
object : Codec<ByteArray> {
override fun read(buf: ReadBuffer): ByteArray {
val arr = ByteArray(n)
if (n > 0) buf.readBytes(arr)
return arr
}
override fun write(buf: WriteBuffer, value: ByteArray) {
error("FixedReadBytes is read-only")
}
}
@@ -0,0 +1,13 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.imap
data class MapTransitionAckPacket(val unk: Int = 0)
val MapTransitionAckPacketCodec: Codec<MapTransitionAckPacket> =
U8.imap(
decode = { MapTransitionAckPacket(it) },
encode = { it.unk },
)
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class MapTransitionPacket {
override fun equals(other: Any?): Boolean = other is MapTransitionPacket
override fun hashCode(): Int = MapTransitionPacket::class.hashCode()
}
object MapTransitionPacketCodec : PacketCodec<MapTransitionPacket>() {
override fun CodecScope<MapTransitionPacket>.body() = MapTransitionPacket()
}
@@ -0,0 +1,20 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.enumByOrdinalByte
import de.fiereu.openmmo.common.enums.Direction
data class MovementPacket(val x: Int, val y: Int, val direction: Direction)
object MovementPacketCodec : PacketCodec<MovementPacket>() {
private val DirectionCodec = enumByOrdinalByte<Direction>()
override fun CodecScope<MovementPacket>.body(): MovementPacket {
val x = field(S16LE) { it.x.toShort() }
val y = field(S16LE) { it.y.toShort() }
val direction = field(DirectionCodec) { it.direction }
return MovementPacket(x.toInt(), y.toInt(), direction)
}
}
@@ -0,0 +1,16 @@
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.U8
data class NpcAnimationPacket(val entityId: Long, val animation: Int)
object NpcAnimationPacketCodec : PacketCodec<NpcAnimationPacket>() {
override fun CodecScope<NpcAnimationPacket>.body(): NpcAnimationPacket {
val entityId = field(S64LE) { it.entityId }
val animation = field(U8) { it.animation }
return NpcAnimationPacket(entityId, animation)
}
}
@@ -0,0 +1,43 @@
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.U16LE
import de.fiereu.bytecodec.U8
data class NpcSpawnPacket(
val entityId: Long,
val unk1: Int,
val unk2: Int,
val unk3: Int,
val unk4: Int,
val regionId: Int,
val bankId: Int,
val mapId: Int,
val x: Int,
val y: Int,
val facing: Int,
val unk5: Int,
val unk6: Int,
)
object NpcSpawnPacketCodec : PacketCodec<NpcSpawnPacket>() {
override fun CodecScope<NpcSpawnPacket>.body(): NpcSpawnPacket {
val entityId = field(S64LE) { it.entityId }
val unk1 = field(U8) { it.unk1 }
val unk2 = field(U16LE) { it.unk2 }
val unk3 = field(U16LE) { it.unk3 }
val unk4 = field(U16LE) { it.unk4 }
val regionId = field(U8) { it.regionId }
val bankId = field(U8) { it.bankId }
val mapId = field(U8) { it.mapId }
val x = field(U16LE) { it.x }
val y = field(U16LE) { it.y }
val unk5 = field(U8) { it.unk5 }
val facing = field(U8) { it.facing }
val unk6 = field(U16LE) { it.unk6 }
return NpcSpawnPacket(
entityId, unk1, unk2, unk3, unk4, regionId, bankId, mapId, x, y, facing, unk5, unk6)
}
}
@@ -0,0 +1,32 @@
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.U16LE
import de.fiereu.bytecodec.U8
data class NpcUpdatePacket(
val entityId: Long,
val regionId: Int,
val bankId: Int,
val mapId: Int,
val x: Int,
val y: Int,
val facing: Int,
val unk: Int,
)
object NpcUpdatePacketCodec : PacketCodec<NpcUpdatePacket>() {
override fun CodecScope<NpcUpdatePacket>.body(): NpcUpdatePacket {
val entityId = field(S64LE) { it.entityId }
val regionId = field(U8) { it.regionId }
val bankId = field(U8) { it.bankId }
val mapId = field(U8) { it.mapId }
val x = field(U16LE) { it.x }
val y = field(U16LE) { it.y }
val facing = field(U8) { it.facing }
val unk = field(U8) { it.unk }
return NpcUpdatePacket(entityId, regionId, bankId, mapId, x, y, facing, unk)
}
}
@@ -0,0 +1,24 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.WriteBuffer
class NullPacket
private object DrainRemaining : Codec<Unit> {
override fun read(buf: ReadBuffer) {
if (buf.remaining() > 0) buf.skip(buf.remaining())
}
override fun write(buf: WriteBuffer, value: Unit) {}
}
object NullPacketCodec : PacketCodec<NullPacket>() {
override fun CodecScope<NullPacket>.body(): NullPacket {
structural(DrainRemaining)
return NullPacket()
}
}
@@ -0,0 +1,60 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.WriteBuffer
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.net.game.codecs.PokemonCodec
data class PokemonContainerPacket(
val container: PokemonContainer,
val hasChange: Boolean,
val delete: Boolean,
val pokemon: List<Pokemon>,
) {
init {
if (delete)
require(hasChange) {
"Pokemon container cannot be deleted if the packet doesn't change anything"
}
if (delete)
require(pokemon.isEmpty()) { "Deleting a Pokemon container shouldn't have any pokemon" }
}
}
private val PokemonListPrefixedU8: Codec<List<Pokemon>> =
object : Codec<List<Pokemon>> {
override fun read(buf: ReadBuffer): List<Pokemon> {
val n = U8.read(buf)
return List(n) { PokemonCodec.read(buf) }
}
override fun write(buf: WriteBuffer, value: List<Pokemon>) {
U8.write(buf, value.size)
value.forEach { PokemonCodec.write(buf, it) }
}
}
object PokemonContainerPacketCodec : PacketCodec<PokemonContainerPacket>() {
override fun CodecScope<PokemonContainerPacket>.body(): PokemonContainerPacket {
val container = PokemonContainer.entries[field(U8) { it.container.ordinal }]
val flags =
field(U8) {
var f = 0
if (it.hasChange) f = f or 1
if (it.delete) f = f or 2
f
}
val hasChange = (flags and 1) != 0
val delete = (flags and 2) != 0
if (delete) {
return PokemonContainerPacket(container, hasChange, true, emptyList())
}
val pokemon = field(PokemonListPrefixedU8, PokemonContainerPacket::pokemon)
return PokemonContainerPacket(container, hasChange, false, pokemon)
}
}
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
data class RenderScreenPacket(val renderScreen: Boolean)
object RenderScreenPacketCodec : PacketCodec<RenderScreenPacket>() {
override fun CodecScope<RenderScreenPacket>.body(): RenderScreenPacket {
val renderScreen = field(Bool) { it.renderScreen }
return RenderScreenPacket(renderScreen)
}
}
@@ -0,0 +1,10 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class RequestCharactersPacket
object RequestCharactersPacketCodec : PacketCodec<RequestCharactersPacket>() {
override fun CodecScope<RequestCharactersPacket>.body() = RequestCharactersPacket()
}
@@ -0,0 +1,10 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class RequestPlayerPacket
object RequestPlayerPacketCodec : PacketCodec<RequestPlayerPacket>() {
override fun CodecScope<RequestPlayerPacket>.body() = RequestPlayerPacket()
}
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64LE
data class SelectCharacterPacket(val characterId: Long, val characterIdHash: Long)
object SelectCharacterPacketCodec : PacketCodec<SelectCharacterPacket>() {
override fun CodecScope<SelectCharacterPacket>.body(): SelectCharacterPacket {
val characterId = field(S64LE) { it.characterId }
val characterIdHash = field(S64LE) { it.characterIdHash }
return SelectCharacterPacket(characterId, characterIdHash)
}
}
@@ -0,0 +1,18 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.optional
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.net.game.codecs.CharacterInfoCodecShort
data class SelectedCharacterPacket(val character: CharacterInfo?)
private val OptionalCharacterInfo = CharacterInfoCodecShort.optional()
object SelectedCharacterPacketCodec : PacketCodec<SelectedCharacterPacket>() {
override fun CodecScope<SelectedCharacterPacket>.body() =
SelectedCharacterPacket(
character = field(OptionalCharacterInfo, SelectedCharacterPacket::character),
)
}
@@ -0,0 +1,34 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.WriteBuffer
data class TokenPayloadPacket(val payload: ByteArray) {
override fun equals(other: Any?): Boolean =
other is TokenPayloadPacket && payload.contentEquals(other.payload)
override fun hashCode(): Int = payload.contentHashCode()
}
private val TokenPayloadBytes: Codec<ByteArray> =
object : Codec<ByteArray> {
override fun read(buf: ReadBuffer): ByteArray {
val data = ByteArray(buf.remaining())
if (data.isNotEmpty()) buf.readBytes(data)
return data
}
override fun write(buf: WriteBuffer, value: ByteArray) {
if (value.isNotEmpty()) buf.writeBytes(value)
}
}
object TokenPayloadPacketCodec : PacketCodec<TokenPayloadPacket>() {
override fun CodecScope<TokenPayloadPacket>.body() =
TokenPayloadPacket(
payload = field(TokenPayloadBytes, TokenPayloadPacket::payload),
)
}
@@ -0,0 +1,46 @@
package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.net.game.packets.DialogStatePacket
import de.fiereu.openmmo.net.game.packets.DialogStatePacketCodec
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.EntityLeavePacketCodec
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacketCodec
import de.fiereu.openmmo.net.game.packets.MovementPacket
import de.fiereu.openmmo.net.game.packets.MovementPacketCodec
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class GameCodecRoundtripTest :
FunSpec({
test("RenderScreenPacket roundtrip") {
RenderScreenPacketCodec.encodeToBytes(RenderScreenPacket(true)) shouldBe byteArrayOf(1)
RenderScreenPacketCodec.decodeBytes(byteArrayOf(0)) shouldBe RenderScreenPacket(false)
}
test("EntityLeavePacket roundtrip") {
val pkt = EntityLeavePacket(entityId = 0x0102030405060708L)
EntityLeavePacketCodec.decodeBytes(EntityLeavePacketCodec.encodeToBytes(pkt)) shouldBe pkt
}
test("FaceDirectionPacket roundtrip") {
val pkt = FaceDirectionPacket(direction = Direction.UP)
FaceDirectionPacketCodec.decodeBytes(FaceDirectionPacketCodec.encodeToBytes(pkt)) shouldBe
pkt
}
test("MovementPacket roundtrip") {
val pkt = MovementPacket(x = 100, y = 250, direction = Direction.DOWN)
MovementPacketCodec.decodeBytes(MovementPacketCodec.encodeToBytes(pkt)) shouldBe pkt
}
test("DialogStatePacket roundtrip") {
DialogStatePacketCodec.encodeToBytes(DialogStatePacket(true)) shouldBe byteArrayOf(1)
DialogStatePacketCodec.decodeBytes(byteArrayOf(0)) shouldBe DialogStatePacket(false)
}
})
@@ -0,0 +1,87 @@
package de.fiereu.openmmo.net.game
import de.fiereu.network.Direction
import de.fiereu.network.Side
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.JoinResponsePacket
import de.fiereu.openmmo.net.game.packets.KeepAlivePacket
import de.fiereu.openmmo.net.game.packets.LoadMapPacket
import de.fiereu.openmmo.net.game.packets.NullPacket
import de.fiereu.openmmo.net.game.packets.TokenPayloadPacket
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class GameProtocolTest :
FunSpec({
test("at least one registration per known opcode") {
val opcodes = GameProtocol.registrations.map { it.opcode }.toSet()
opcodes shouldBe
setOf(
0x01u.toUByte(),
0x02u.toUByte(),
0x03u.toUByte(),
0x04u.toUByte(),
0x05u.toUByte(),
0x06u.toUByte(),
0x07u.toUByte(),
0x08u.toUByte(),
0x09u.toUByte(),
0x0Du.toUByte(),
0x0Eu.toUByte(),
0x10u.toUByte(),
0x11u.toUByte(),
0x12u.toUByte(),
0x13u.toUByte(),
0x1Bu.toUByte(),
0x20u.toUByte(),
0x21u.toUByte(),
0x22u.toUByte(),
0x25u.toUByte(),
0x26u.toUByte(),
0xB2u.toUByte(),
0xB4u.toUByte(),
0xB9u.toUByte(),
0xC2u.toUByte(),
0xEAu.toUByte(),
)
}
test("compressed flag is set") { GameProtocol.compressed shouldBe true }
test("0x01 split: client outgoing JoinPacket, server outgoing JoinResponsePacket") {
GameProtocol.outgoingRegistration(Side.CLIENT, JoinPacket::class)?.opcode shouldBe 0x01u
GameProtocol.outgoingRegistration(Side.SERVER, JoinResponsePacket::class)?.opcode shouldBe
0x01u
}
test("0xEA EntityMovePacket is S2C only") {
GameProtocol.outgoingRegistration(Side.SERVER, EntityMovePacket::class)?.opcode shouldBe
0xEAu
GameProtocol.outgoingRegistration(Side.CLIENT, EntityMovePacket::class) shouldBe null
}
test("0x20 split: NullPacket C2S, TokenPayloadPacket S2C") {
GameProtocol.incomingRegistration(Side.SERVER, 0x20u)?.type shouldBe NullPacket::class
GameProtocol.incomingRegistration(Side.CLIENT, 0x20u)?.type shouldBe
TokenPayloadPacket::class
}
test("bidi packets are registered both directions") {
val bidi =
listOf(
ChatMessagePacket::class,
LoadMapPacket::class,
KeepAlivePacket::class,
)
for (type in bidi) {
val serverOut = GameProtocol.outgoingRegistration(Side.SERVER, type)
val clientOut = GameProtocol.outgoingRegistration(Side.CLIENT, type)
(serverOut != null && clientOut != null) shouldBe true
serverOut?.direction shouldBe Direction.S2C
clientOut?.direction shouldBe Direction.C2S
serverOut?.opcode shouldBe clientOut?.opcode
}
}
})