feat(game): stub wild battle flow with catch, bag, switching, field state, and flee

This commit is contained in:
Fiereu committed 2026-07-19 22:35:04 +02:00
1 parent 9732c9373c
commit d618cff20e
92 files changed
+1499 -272

No files matched your search

@@ -1,5 +1,8 @@
package de.fiereu.bytecodec
import java.time.LocalDateTime
import java.time.ZoneOffset
object Bool : Codec<Boolean> {
override fun read(buf: ReadBuffer): Boolean = buf.readByte() != 0.toByte()
@@ -219,6 +222,16 @@ object F64BE : Codec<Double> {
}
}
/** Unix timestamp as little-endian signed 32-bit seconds, exposed as a UTC [LocalDateTime]. */
object TimestampLE : Codec<LocalDateTime> {
override fun read(buf: ReadBuffer): LocalDateTime =
LocalDateTime.ofEpochSecond(S32LE.read(buf).toLong(), 0, ZoneOffset.UTC)
override fun write(buf: WriteBuffer, value: LocalDateTime) {
S32LE.write(buf, value.toEpochSecond(ZoneOffset.UTC).toInt())
}
}
fun fixedBytes(n: Int): Codec<ByteArray> {
require(n >= 0) { "fixedBytes negative size: $n" }
return object : Codec<ByteArray> {
@@ -8,6 +8,7 @@ import java.time.LocalDateTime
data class Pokemon(
val id: Long,
val ownerId: Long,
val container: PokemonContainer,
val containerSlot: Short,
val dexId: Int,
@@ -26,9 +27,13 @@ data class Pokemon(
val isSecret: Boolean,
val isFatefulEncounter: Boolean,
val isRaidEncounter: Boolean,
val caughtAt: LocalDateTime
val caughtAt: LocalDateTime,
val isEgg: Boolean = false
) {
val nature: PokemonNature = PokemonNature.entries[seed % PokemonNature.entries.size]
// seed is an unsigned 32-bit value on the wire, so mask before the modulo to avoid a negative
// index when the high bit is set.
val nature: PokemonNature =
PokemonNature.entries[((seed.toLong() and 0xFFFFFFFFL) % PokemonNature.entries.size).toInt()]
init {
require(moves.size <= 4) { "A Pokemon can't have more than 4 moves" }
@@ -0,0 +1,13 @@
package de.fiereu.openmmo.common.enums
/** A player's battle-turn choice. */
enum class BattleAction(val id: Byte) {
MOVE(0),
ITEM(1),
SWITCH(2),
RUN(3);
companion object {
fun fromId(id: Byte): BattleAction? = entries.firstOrNull { it.id == id }
}
}
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.common.enums
/** A rarity trait packed into a monster's flag short, one trait per bit. */
enum class PokemonRarityFlag(val bit: Int) {
SHINY(0),
HIDDEN_ABILITY(1),
ALPHA(2),
SECRET_SHINY(3),
FATEFUL_ENCOUNTER(4),
RAID_ENCOUNTER(5);
val mask: Int = 1 shl bit
fun isSet(bits: Int): Boolean = (bits and mask) != 0
}
@@ -5,6 +5,7 @@ import de.fiereu.network.bidi
import de.fiereu.network.c2s
import de.fiereu.network.s2c
import de.fiereu.openmmo.net.game.packets.*
import de.fiereu.openmmo.net.game.packets.battle.*
import de.fiereu.openmmo.net.game.packets.guild.*
object GameProtocol : Protocol() {
@@ -139,6 +140,7 @@ object GameProtocol : Protocol() {
s2c<WorldJoinConfirmPacket>(0x2Fu, WorldJoinConfirmPacketCodec)
c2s<BattleActionPacket>(0x30u, BattleActionPacketCodec)
s2c<BattleFieldStatePacket>(0x30u, BattleFieldStatePacketCodec)
s2c<BattleBulkStatePacket>(0x31u, BattleBulkStatePacketCodec)
@@ -151,10 +153,10 @@ object GameProtocol : Protocol() {
c2s<SpectateRequestPacket>(0x34u, SpectateRequestPacketCodec)
s2c<BattleSlotEventEnumPacket>(0x34u, BattleSlotEventEnumPacketCodec)
c2s<LeaveBattlePacket>(0x35u, LeaveBattlePacketCodec)
s2c<BattleSlotMoveEventPacket>(0x35u, BattleSlotMoveEventPacketCodec)
c2s<BattleLeavePacket>(0x35u, BattleLeavePacketCodec)
s2c<BattleSwitchInPacket>(0x35u, BattleSwitchInPacketCodec)
c2s<RequestNextBattleSequencePacket>(0x36u, RequestNextBattleSequencePacketCodec)
c2s<BattleSequencePacket>(0x36u, BattleSequencePacketCodec)
s2c<BattleSlotFlagEventPacket>(0x36u, BattleSlotFlagEventPacketCodec)
c2s<BattleSlotActionPacket>(0x37u, BattleSlotActionPacketCodec)
@@ -166,7 +168,7 @@ object GameProtocol : Protocol() {
c2s<BattleUseItemPacket>(0x39u, BattleUseItemPacketCodec)
s2c<BattleLabeledMoveEventPacket>(0x39u, BattleLabeledMoveEventPacketCodec)
c2s<SetBattleMonsterAppearancePacket>(0x3Au, SetBattleMonsterAppearancePacketCodec)
c2s<BattleAppearancePacket>(0x3Au, BattleAppearancePacketCodec)
s2c<BattleEnumPairEventPacket>(0x3Au, BattleEnumPairEventPacketCodec)
c2s<PrismaticPearlTransferPacket>(0x3Bu, PrismaticPearlTransferPacketCodec)
@@ -294,7 +296,7 @@ object GameProtocol : Protocol() {
c2s<InstanceReadyCheckPacket>(0x6Au, InstanceReadyCheckPacketCodec)
c2s<CancelMatchmakingSearchPacket>(0x6Bu, CancelMatchmakingSearchPacketCodec)
s2c<ActiveBattleSidePacket>(0x6Bu, ActiveBattleSidePacketCodec)
s2c<BattleSidePacket>(0x6Bu, BattleSidePacketCodec)
c2s<MatchmakingLanguagePrefsPacket>(0x6Cu, MatchmakingLanguagePrefsPacketCodec)
s2c<MountMoveCooldownPacket>(0x6Cu, MountMoveCooldownPacketCodec)
@@ -515,9 +517,9 @@ object GameProtocol : Protocol() {
s2c<FieldMapTilePaletteApplyPacket>(0xC3u, FieldMapTilePaletteApplyPacketCodec)
s2c<FieldMapBattleSlotTileMapPacket>(0xC4u, FieldMapBattleSlotTileMapPacketCodec)
s2c<BattleTileMapPacket>(0xC4u, BattleTileMapPacketCodec)
s2c<FieldMapBattleSlotMarkerPacket>(0xC5u, FieldMapBattleSlotMarkerPacketCodec)
s2c<BattleMarkerPacket>(0xC5u, BattleMarkerPacketCodec)
s2c<WorldObjectInstanceDespawnPacket>(0xC8u, WorldObjectInstanceDespawnPacketCodec)
@@ -562,6 +564,7 @@ object GameProtocol : Protocol() {
c2s<BattleRewardSelectPacket>(0xE3u, BattleRewardSelectPacketCodec)
c2s<BattleChallengeRequestPacket>(0xE4u, BattleChallengeRequestPacketCodec)
s2c<EntityCounterPulsePacket>(0xE4u, EntityCounterPulsePacketCodec)
s2c<EntityMovePacket>(0xEAu, EntityMovePacketCodec)
@@ -5,90 +5,129 @@ import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.*
private val PokemonUnknownBytes: Codec<ByteArray> = bytesPrefixed(U8)
private fun seg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private fun reserved(hex: String): Codec<Unit> =
object : Codec<Unit> {
private val bytes = seg(hex)
override fun read(buf: ReadBuffer) {
if (bytes.isNotEmpty()) buf.readBytes(ByteArray(bytes.size))
}
override fun write(buf: WriteBuffer, value: Unit) {
buf.writeBytes(bytes)
}
}
// Fixed 4-byte U8 list at the start of trailer A, purpose unknown, always zero here.
private const val LIST4 = "00000000"
// Trailer A bytes between the EVs and the IV word, purpose unknown (includes the ff/03 markers).
private const val TAIL_A_REST = "00000100000000000000040502ffffffff0300"
// Trailer B long that follows the unknown byte, purpose unknown. Species-dependent, so the captured
// value is written back for now.
private const val TRAILER_B_LONG = 0x200000L
// Record end: unknown bytes closed by a U8 list count, which is zero (empty list) in every capture.
private const val TRAILER = "00ffff00"
private fun packRarity(p: Pokemon): Int =
(if (p.isShiny) PokemonRarityFlag.SHINY.mask else 0) or
(if (p.hasHiddenAbility) PokemonRarityFlag.HIDDEN_ABILITY.mask else 0) or
(if (p.isAlpha) PokemonRarityFlag.ALPHA.mask else 0) or
(if (p.isSecret) PokemonRarityFlag.SECRET_SHINY.mask else 0) or
(if (p.isFatefulEncounter) PokemonRarityFlag.FATEFUL_ENCOUNTER.mask else 0) or
(if (p.isRaidEncounter) PokemonRarityFlag.RAID_ENCOUNTER.mask else 0)
// EVs are six raw bytes in wire order hp, atk, def, spd, spAtk, spDef. Bypasses the checked stat
// setters, which reject a zero value.
private fun evsFromWire(hp: Int, atk: Int, def: Int, spd: Int, spAtk: Int, spDef: Int): EVs =
EVs().apply {
put(PokemonStat.HP, hp.toByte())
put(PokemonStat.ATTACK, atk.toByte())
put(PokemonStat.DEFENSE, def.toByte())
put(PokemonStat.SPEED, spd.toByte())
put(PokemonStat.SP_ATTACK, spAtk.toByte())
put(PokemonStat.SP_DEFENSE, spDef.toByte())
}
// IVs are a packed 30-bit word (six 5-bit stats). The top two bits carry unidentified flags and are
// dropped on write, so they stay zero for constructed monsters. Bypasses the checked IV setters,
// which reject a zero roll.
private fun ivsFromBits(bits: Int): IVs =
IVs().apply {
put(PokemonStat.HP, ((bits shr 0) and 31).toByte())
put(PokemonStat.ATTACK, ((bits shr 5) and 31).toByte())
put(PokemonStat.DEFENSE, ((bits shr 10) and 31).toByte())
put(PokemonStat.SP_ATTACK, ((bits shr 15) and 31).toByte())
put(PokemonStat.SP_DEFENSE, ((bits shr 20) and 31).toByte())
put(PokemonStat.SPEED, ((bits shr 25) and 31).toByte())
}
/**
* The 148-byte party/PC monster record. The named fields are decoded from real captures. The
* reserved segments hold species metadata and still-unlabelled structure kept as reference bytes,
* so the layout round-trips exactly.
*/
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 }]
field(reserved("0000")) {}
val ownerId = field(S64LE, Pokemon::ownerId)
field(S64LE, Pokemon::ownerId)
field(reserved("01")) {}
val containerSlot = field(S16LE, Pokemon::containerSlot)
val dexId = field(U16LE, Pokemon::dexId)
val seed = field(S32LE, Pokemon::seed)
field(S64LE) { 0L }
field(S64LE, Pokemon::ownerId)
val ot = field(Utf16LeNullTerminated, Pokemon::ot)
val nickname = field(Utf16LeNullTerminated, Pokemon::nickname)
field(S8) { 0 }
field(S8) { 0 }
field(reserved("0000")) {}
val level = field(S8, Pokemon::level)
val currentHp = field(S16LE, Pokemon::hp)
field(S16LE) { 0 }
val hp = field(S16LE, Pokemon::hp)
field(reserved("0000")) {}
val xp = field(S32LE, Pokemon::xp)
field(S8) { 0 }
field(S16LE) { 0 }
field(reserved("003200")) {}
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 } }
field(reserved(LIST4)) {}
val evHp = field(U8) { it.eVs.hp and 0xFF }
val evAtk = field(U8) { it.eVs.atk and 0xFF }
val evDef = field(U8) { it.eVs.def and 0xFF }
val evSpd = field(U8) { it.eVs.spd and 0xFF }
val evSpAtk = field(U8) { it.eVs.spAtk and 0xFF }
val evSpDef = field(U8) { it.eVs.spDef and 0xFF }
field(reserved(TAIL_A_REST)) {}
val ivBits = field(S32LE) { it.iVs.compress() }
field(U8) { 0 }
field(S64LE) { TRAILER_B_LONG }
val rarityBits = field(U16LE) { packRarity(it) }
val caughtAt = field(TimestampLE, Pokemon::caughtAt)
val isEgg = field(Bool, Pokemon::isEgg)
field(reserved(TRAILER)) {}
return Pokemon(
id,
container,
containerSlot,
dexId,
seed,
ot,
nickname,
level,
currentHp,
xp,
eVs,
iVs,
moves,
isShiny,
hasHiddenAbility,
isAlpha,
isSecret,
isFatefulEncounter,
isRaidEncounter,
caughtAt,
id = id,
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = containerSlot,
dexId = dexId,
seed = seed,
ot = ot,
nickname = nickname,
level = level,
hp = hp,
xp = xp,
eVs = evsFromWire(evHp, evAtk, evDef, evSpd, evSpAtk, evSpDef),
iVs = ivsFromBits(ivBits),
moves = List(4) { PokemonMove(moveIds[it], movePps[it]) },
isShiny = PokemonRarityFlag.SHINY.isSet(rarityBits),
hasHiddenAbility = PokemonRarityFlag.HIDDEN_ABILITY.isSet(rarityBits),
isAlpha = PokemonRarityFlag.ALPHA.isSet(rarityBits),
isSecret = PokemonRarityFlag.SECRET_SHINY.isSet(rarityBits),
isFatefulEncounter = PokemonRarityFlag.FATEFUL_ENCOUNTER.isSet(rarityBits),
isRaidEncounter = PokemonRarityFlag.RAID_ENCOUNTER.isSet(rarityBits),
caughtAt = caughtAt,
isEgg = isEgg,
)
}
}
@@ -1,16 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S8
data class ActiveBattleSidePacket(
val side: Byte,
)
object ActiveBattleSidePacketCodec : PacketCodec<ActiveBattleSidePacket>() {
override fun CodecScope<ActiveBattleSidePacket>.body(): ActiveBattleSidePacket {
val side = field(S8) { it.side }
return ActiveBattleSidePacket(side)
}
}
@@ -1,49 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.*
data class BattleActionSelectPacket(
val slotRefPacked: Byte,
val actionKindId: Byte,
val payloadVariant: Int,
val moveOrItemId: Short,
val targetEntityId: Long,
val extraFlag: Byte,
)
private val BattleActionSelectBody: Codec<BattleActionSelectPacket> =
object : Codec<BattleActionSelectPacket> {
override fun read(buf: ReadBuffer): BattleActionSelectPacket {
val slotRefPacked = S8.read(buf)
val actionKindId = S8.read(buf)
return BattleActionSelectPacket(slotRefPacked, actionKindId, 0, 0, 0, 0)
}
override fun write(buf: WriteBuffer, value: BattleActionSelectPacket) {
S8.write(buf, value.slotRefPacked)
S8.write(buf, value.actionKindId)
when (value.payloadVariant) {
1 -> {
S16LE.write(buf, value.moveOrItemId)
S8.write(buf, value.extraFlag)
}
2,
3 -> {
S16LE.write(buf, value.moveOrItemId)
}
4 -> {
S16LE.write(buf, value.moveOrItemId)
S64LE.write(buf, value.targetEntityId)
S8.write(buf, value.extraFlag)
}
}
}
}
object BattleActionSelectPacketCodec : PacketCodec<BattleActionSelectPacket>() {
override fun CodecScope<BattleActionSelectPacket>.body(): BattleActionSelectPacket {
return field(BattleActionSelectBody) { it }
}
}
@@ -1,21 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S8
data class BattleSlotMoveEventPacket(
val slot: Byte,
val moveType: Byte,
val resolved: Boolean,
)
object BattleSlotMoveEventPacketCodec : PacketCodec<BattleSlotMoveEventPacket>() {
override fun CodecScope<BattleSlotMoveEventPacket>.body(): BattleSlotMoveEventPacket {
val slot = field(S8) { it.slot }
val moveType = field(S8) { it.moveType }
val resolved = field(Bool) { it.resolved }
return BattleSlotMoveEventPacket(slot, moveType, resolved)
}
}
@@ -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.S64LE
import de.fiereu.bytecodec.S8
import de.fiereu.bytecodec.U16LE
/**
* Opcode 0xE4 (s2c). Sent in a burst at battle resolution, once per step, all referencing the same
* transient entity. Each packet carries a sequence value that increments across the burst. Its
* meaning is not yet decoded, so the fields keep their wire names.
*/
data class EntityCounterPulsePacket(
val entityId: Long,
val tagA: Byte,
val tagB: Byte,
val sequence: Int,
val endFlag: Byte,
)
object EntityCounterPulsePacketCodec : PacketCodec<EntityCounterPulsePacket>() {
override fun CodecScope<EntityCounterPulsePacket>.body(): EntityCounterPulsePacket {
val entityId = field(S64LE) { it.entityId }
val tagA = field(S8) { it.tagA }
val tagB = field(S8) { it.tagB }
val sequence = field(U16LE) { it.sequence }
val endFlag = field(S8) { it.endFlag }
return EntityCounterPulsePacket(entityId, tagA, tagB, sequence, endFlag)
}
}
@@ -1,12 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class LeaveBattlePacket
object LeaveBattlePacketCodec : PacketCodec<LeaveBattlePacket>() {
override fun CodecScope<LeaveBattlePacket>.body(): LeaveBattlePacket {
return LeaveBattlePacket()
}
}
@@ -1,12 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class RequestNextBattleSequencePacket
object RequestNextBattleSequencePacketCodec : PacketCodec<RequestNextBattleSequencePacket>() {
override fun CodecScope<RequestNextBattleSequencePacket>.body(): RequestNextBattleSequencePacket {
return RequestNextBattleSequencePacket()
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
import de.fiereu.openmmo.common.Pokemon
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -0,0 +1,67 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
import de.fiereu.openmmo.common.enums.BattleAction
// For SWITCH, moveOrItemId carries the target party index.
data class BattleActionSelectPacket(
val slotRefPacked: Byte,
val action: BattleAction,
val moveOrItemId: Short,
val targetEntityId: Long,
val extraFlag: Byte,
)
private val BattleActionSelectBody: Codec<BattleActionSelectPacket> =
object : Codec<BattleActionSelectPacket> {
override fun read(buf: ReadBuffer): BattleActionSelectPacket {
val slotRefPacked = S8.read(buf)
val action =
BattleAction.fromId(S8.read(buf))
?: throw MalformedPacketException("unknown battle action kind")
return when (action) {
BattleAction.MOVE -> {
val moveId = S16LE.read(buf)
val extraFlag = S8.read(buf)
BattleActionSelectPacket(slotRefPacked, action, moveId, 0, extraFlag)
}
BattleAction.ITEM -> {
val itemId = S16LE.read(buf)
val targetEntityId = S64LE.read(buf)
val extraFlag = S8.read(buf)
BattleActionSelectPacket(slotRefPacked, action, itemId, targetEntityId, extraFlag)
}
BattleAction.SWITCH -> {
val partyIndex = S16LE.read(buf)
BattleActionSelectPacket(slotRefPacked, action, partyIndex, 0, 0)
}
BattleAction.RUN -> BattleActionSelectPacket(slotRefPacked, action, 0, 0, 0)
}
}
override fun write(buf: WriteBuffer, value: BattleActionSelectPacket) {
S8.write(buf, value.slotRefPacked)
S8.write(buf, value.action.id)
when (value.action) {
BattleAction.MOVE -> {
S16LE.write(buf, value.moveOrItemId)
S8.write(buf, value.extraFlag)
}
BattleAction.ITEM -> {
S16LE.write(buf, value.moveOrItemId)
S64LE.write(buf, value.targetEntityId)
S8.write(buf, value.extraFlag)
}
BattleAction.SWITCH -> S16LE.write(buf, value.moveOrItemId)
BattleAction.RUN -> {
// RUN carries no tail bytes.
}
}
}
}
object BattleActionSelectPacketCodec : PacketCodec<BattleActionSelectPacket>() {
override fun CodecScope<BattleActionSelectPacket>.body(): BattleActionSelectPacket {
return field(BattleActionSelectBody) { it }
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,8 +1,8 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
data class SetBattleMonsterAppearancePacket(
data class BattleAppearancePacket(
val partySlot: Short,
val pokemonEntityId: Long,
val shininessType: Byte,
@@ -24,13 +24,12 @@ private val ColorPaletteCodec: Codec<List<Short>> =
}
}
object SetBattleMonsterAppearancePacketCodec : PacketCodec<SetBattleMonsterAppearancePacket>() {
override fun CodecScope<SetBattleMonsterAppearancePacket>.body():
SetBattleMonsterAppearancePacket {
object BattleAppearancePacketCodec : PacketCodec<BattleAppearancePacket>() {
override fun CodecScope<BattleAppearancePacket>.body(): BattleAppearancePacket {
val partySlot = field(S16LE) { it.partySlot }
val pokemonEntityId = field(S64LE) { it.pokemonEntityId }
val shininessType = field(S8) { it.shininessType }
val colorPalette = field(ColorPaletteCodec) { it.colorPalette }
return SetBattleMonsterAppearancePacket(partySlot, pokemonEntityId, shininessType, colorPalette)
return BattleAppearancePacket(partySlot, pokemonEntityId, shininessType, colorPalette)
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -171,7 +171,35 @@ data class BattleBulkStatePacket(
val valueB: Int,
val flag: Byte,
val thirdGroup: List<BattleSerializedEntry>,
)
) {
companion object {
/**
* Terminal marker sent when a wild encounter resolves, telling the client to leave the scene.
*/
fun battleEnd(): BattleBulkStatePacket =
BattleBulkStatePacket(
phase = 0,
firstGroup = listOf(NullSerializedEntry),
secondGroup = listOf(NullSerializedEntry),
valueA = 0,
valueB = 0,
flag = 2,
thirdGroup = emptyList(),
)
/** Terminal marker sent when the player flees. */
fun fled(): BattleBulkStatePacket =
BattleBulkStatePacket(
phase = -1,
firstGroup = emptyList(),
secondGroup = emptyList(),
valueA = 0,
valueB = 0,
flag = 2,
thirdGroup = emptyList(),
)
}
}
object BattleBulkStatePacketCodec : PacketCodec<BattleBulkStatePacket>() {
override fun CodecScope<BattleBulkStatePacket>.body(): BattleBulkStatePacket {
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -0,0 +1,147 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
data class BattleFieldMon(
val entityId: Long,
val species: Short,
val hp: Short,
)
/**
* The field state for a wild encounter (opcode 0x30). Each side sends a monster count that sizes
* the client's slot array followed by that many monster blocks. A player block carries a
* per-species stat and move block with its hp and party slot filled in, so a benched monster goes
* in its own slot instead of overwriting the active one.
*/
data class BattleFieldStatePacket(
val playerName: String,
val playerId: Long,
val playerParty: List<BattleFieldMon>,
val wildMon: BattleFieldMon,
)
private fun seg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private val PREAMBLE = seg("02000000000000000000000000ff000000000016000000ff00200006")
private val AFTER_NAME = seg("00")
private val APPEARANCE = seg("ff00024c031aac0f00038001a400040000000000")
private val SIDE_HEADER = seg("01")
private val SIDE_MID = seg("00")
// A monster block starts with its slot index then a constant 01.
private val MON_CONST = seg("01")
private val ACTIVE_DETAIL = seg("0000ef010600000000000003ff000000006666666601060000000000")
private val WILD_DATA_A = seg("020000010000000e00")
private val WILD_DATA_B = seg("000000ff0300010000f8010200000000010003ff000000006666666600000000")
private const val WILD_COUNT = 1
// Per-species blocks captured from a real field state. The 9-byte stat segment is
// [prefix (7)][max hp][00] and the 17-byte move segment is [move body (16)][party slot]. Hp and
// slot are spliced in per monster.
private class SpeciesBlock(val statPrefix: ByteArray, val moveBody: ByteArray)
private val SPECIES_BLOCKS =
mapOf(
495 to SpeciesBlock(seg("06000000000000"), seg("000000ff0301410021002b0000000000")),
504 to SpeciesBlock(seg("02000001000000"), seg("000000ff030132002100000000000000")),
)
private val DEFAULT_SPECIES_BLOCK = SPECIES_BLOCKS.getValue(504)
private fun speciesBlock(species: Short): SpeciesBlock =
SPECIES_BLOCKS[species.toInt()] ?: DEFAULT_SPECIES_BLOCK
private val BattleFieldStateBody: Codec<BattleFieldStatePacket> =
object : Codec<BattleFieldStatePacket> {
override fun read(buf: ReadBuffer): BattleFieldStatePacket {
buf.readBytes(ByteArray(PREAMBLE.size))
val playerName = Utf16LeNullTerminated.read(buf)
buf.readBytes(ByteArray(AFTER_NAME.size))
val playerId = S64LE.read(buf)
buf.readBytes(ByteArray(APPEARANCE.size))
buf.readBytes(ByteArray(SIDE_HEADER.size))
val playerCount = U8.read(buf)
buf.readBytes(ByteArray(SIDE_MID.size))
val party = List(playerCount) { readMon(buf) }
buf.readBytes(ByteArray(ACTIVE_DETAIL.size))
buf.readBytes(ByteArray(SIDE_HEADER.size))
U8.read(buf) // opponent count
buf.readBytes(ByteArray(SIDE_MID.size))
val wild = readWild(buf)
return BattleFieldStatePacket(playerName, playerId, party, wild)
}
override fun write(buf: WriteBuffer, value: BattleFieldStatePacket) {
buf.writeBytes(PREAMBLE)
Utf16LeNullTerminated.write(buf, value.playerName)
buf.writeBytes(AFTER_NAME)
S64LE.write(buf, value.playerId)
buf.writeBytes(APPEARANCE)
buf.writeBytes(SIDE_HEADER)
U8.write(buf, value.playerParty.size)
buf.writeBytes(SIDE_MID)
value.playerParty.forEachIndexed { slot, mon -> writeMon(buf, slot, mon) }
buf.writeBytes(ACTIVE_DETAIL)
buf.writeBytes(SIDE_HEADER)
U8.write(buf, WILD_COUNT)
buf.writeBytes(SIDE_MID)
writeWild(buf, value.wildMon)
}
private fun readMon(buf: ReadBuffer): BattleFieldMon {
S8.read(buf) // slot index
buf.readBytes(ByteArray(MON_CONST.size))
val entityId = S64LE.read(buf)
val species = S16LE.read(buf)
val block = speciesBlock(species)
buf.readBytes(ByteArray(block.statPrefix.size))
S8.read(buf) // max hp
S8.read(buf) // stat tail
val hp = S16LE.read(buf)
buf.readBytes(ByteArray(block.moveBody.size))
S8.read(buf) // slot trailer
return BattleFieldMon(entityId, species, hp)
}
private fun writeMon(buf: WriteBuffer, slot: Int, mon: BattleFieldMon) {
S8.write(buf, slot.toByte())
buf.writeBytes(MON_CONST)
S64LE.write(buf, mon.entityId)
S16LE.write(buf, mon.species)
val block = speciesBlock(mon.species)
buf.writeBytes(block.statPrefix)
S8.write(buf, mon.hp.toByte()) // max hp
S8.write(buf, 0)
S16LE.write(buf, mon.hp)
buf.writeBytes(block.moveBody)
S8.write(buf, slot.toByte()) // slot trailer
}
private fun readWild(buf: ReadBuffer): BattleFieldMon {
S8.read(buf) // slot index
buf.readBytes(ByteArray(MON_CONST.size))
val entityId = S64LE.read(buf)
val species = S16LE.read(buf)
buf.readBytes(ByteArray(WILD_DATA_A.size))
val hp = S16LE.read(buf)
buf.readBytes(ByteArray(WILD_DATA_B.size))
return BattleFieldMon(entityId, species, hp)
}
private fun writeWild(buf: WriteBuffer, mon: BattleFieldMon) {
S8.write(buf, 0)
buf.writeBytes(MON_CONST)
S64LE.write(buf, mon.entityId)
S16LE.write(buf, mon.species)
buf.writeBytes(WILD_DATA_A)
S16LE.write(buf, mon.hp)
buf.writeBytes(WILD_DATA_B)
}
}
object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
override fun CodecScope<BattleFieldStatePacket>.body(): BattleFieldStatePacket {
return field(BattleFieldStateBody) { it }
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -0,0 +1,12 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class BattleLeavePacket
object BattleLeavePacketCodec : PacketCodec<BattleLeavePacket>() {
override fun CodecScope<BattleLeavePacket>.body(): BattleLeavePacket {
return BattleLeavePacket()
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,21 +1,21 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S16LE
import de.fiereu.bytecodec.S8
data class FieldMapBattleSlotMarkerPacket(
data class BattleMarkerPacket(
val slot: Byte,
val markerType: Byte,
val value: Short,
)
object FieldMapBattleSlotMarkerPacketCodec : PacketCodec<FieldMapBattleSlotMarkerPacket>() {
override fun CodecScope<FieldMapBattleSlotMarkerPacket>.body(): FieldMapBattleSlotMarkerPacket {
object BattleMarkerPacketCodec : PacketCodec<BattleMarkerPacket>() {
override fun CodecScope<BattleMarkerPacket>.body(): BattleMarkerPacket {
val slot = field(S8) { it.slot }
val markerType = field(S8) { it.markerType }
val value = field(S16LE) { it.value }
return FieldMapBattleSlotMarkerPacket(slot, markerType, value)
return BattleMarkerPacket(slot, markerType, value)
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -0,0 +1,12 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
class BattleSequencePacket
object BattleSequencePacketCodec : PacketCodec<BattleSequencePacket>() {
override fun CodecScope<BattleSequencePacket>.body(): BattleSequencePacket {
return BattleSequencePacket()
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S8
data class BattleSidePacket(
val side: Byte,
)
object BattleSidePacketCodec : PacketCodec<BattleSidePacket>() {
override fun CodecScope<BattleSidePacket>.body(): BattleSidePacket {
val side = field(S8) { it.side }
return BattleSidePacket(side)
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -55,6 +55,35 @@ data class BattleSidePartyPacket(
val pokemon: List<BattlePartyPokemon>,
)
/**
* A single bag item stack carried by opcode 0x40 at join. It shares the wire shape of a battle-side
* monster and decodes through the same codec. Item object ids end in 0x5000 where monster uids end
* in 0xC000.
*/
data class ItemStack(val objectId: Long, val itemId: Short, val quantity: Short)
/**
* Builds the opcode 0x40 item snapshot from bag stacks. The monster fields carry item data: entity
* id is the stack object id, front sprite the item id, back sprite the quantity.
*/
fun itemStacksPacket(stacks: List<ItemStack>): BattleSidePartyPacket =
BattleSidePartyPacket(
side = 1,
replace = true,
pokemon =
stacks.map { stack ->
BattlePartyPokemon(
entityId = stack.objectId,
frontSpriteId = stack.itemId,
backSpriteId = stack.quantity,
side = 1,
slot = 0,
partyIndex = -1,
statusEffect = null,
)
},
)
object BattleSidePartyPacketCodec : PacketCodec<BattleSidePartyPacket>() {
override fun CodecScope<BattleSidePartyPacket>.body(): BattleSidePartyPacket {
val side = field(S8) { it.side }
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -0,0 +1,127 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
data class BattleSwitchInMon(
val entityId: Long,
val species: Short,
val hp: Short,
)
/**
* Brings a monster onto the field after a switch (opcode 0x35). The header names the new and
* previous active party slots. A monster coming out for the first time carries its full block, the
* same layout as the field state. One already seen active is sent as just its 21-byte active
* detail. When [fullBlock] is false the incoming hp and entity id are left at zero on decode.
*/
data class BattleSwitchInPacket(
val newSlot: Int,
val oldSlot: Int,
val mon: BattleSwitchInMon,
val fullBlock: Boolean,
)
private fun switchSeg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private val SWITCH_HEADER = switchSeg("0000")
private val SWITCH_MON_CONST = switchSeg("01")
// A species carries a full-block stat prefix and move body (as in the field state) plus a distinct
// active-detail stat used by the switch-in and active-mon segments.
private class SwitchSpeciesBlock(
val statPrefix: ByteArray,
val moveBody: ByteArray,
val activeStat: ByteArray,
)
private val SWITCH_SPECIES_BLOCKS =
mapOf(
495 to
SwitchSpeciesBlock(
switchSeg("06000000000000"),
switchSeg("000000ff0301410021002b0000000000"),
switchSeg("06000000000000"),
),
504 to
SwitchSpeciesBlock(
switchSeg("02000001000000"),
switchSeg("000000ff030132002100000000000000"),
switchSeg("02000000000100"),
),
)
private val DEFAULT_SWITCH_BLOCK = SWITCH_SPECIES_BLOCKS.getValue(504)
private fun switchBlock(species: Short): SwitchSpeciesBlock =
SWITCH_SPECIES_BLOCKS[species.toInt()] ?: DEFAULT_SWITCH_BLOCK
// [00][slot][species][active stat (7)] then this constant tail.
private val SWITCH_ACTIVE_TAIL = switchSeg("03ff0000000066666666")
private const val SWITCH_STAT_PREFIX_SIZE = 7
private const val SWITCH_MOVE_BODY_SIZE = 16
private const val SWITCH_ACTIVE_STAT_SIZE = 7
private const val SWITCH_ACTIVE_DETAIL_SIZE = 21
private val BattleSwitchInBody: Codec<BattleSwitchInPacket> =
object : Codec<BattleSwitchInPacket> {
override fun read(buf: ReadBuffer): BattleSwitchInPacket {
buf.readBytes(ByteArray(SWITCH_HEADER.size))
val newSlot = U8.read(buf)
val oldSlot = U8.read(buf)
val fullBlock = buf.remaining() > SWITCH_ACTIVE_DETAIL_SIZE
var entityId = 0L
var blockHp: Short = 0
var blockSpecies: Short = 0
if (fullBlock) {
S8.read(buf) // slot index
buf.readBytes(ByteArray(SWITCH_MON_CONST.size))
entityId = S64LE.read(buf)
blockSpecies = S16LE.read(buf)
buf.readBytes(ByteArray(SWITCH_STAT_PREFIX_SIZE))
S8.read(buf) // max hp
S8.read(buf) // stat tail
blockHp = S16LE.read(buf)
buf.readBytes(ByteArray(SWITCH_MOVE_BODY_SIZE))
S8.read(buf) // slot trailer
}
// active detail
S8.read(buf) // constant 00
S8.read(buf) // slot
val activeSpecies = S16LE.read(buf)
buf.readBytes(ByteArray(SWITCH_ACTIVE_STAT_SIZE))
buf.readBytes(ByteArray(SWITCH_ACTIVE_TAIL.size))
val species = if (fullBlock) blockSpecies else activeSpecies
return BattleSwitchInPacket(
newSlot, oldSlot, BattleSwitchInMon(entityId, species, blockHp), fullBlock)
}
override fun write(buf: WriteBuffer, value: BattleSwitchInPacket) {
buf.writeBytes(SWITCH_HEADER)
U8.write(buf, value.newSlot)
U8.write(buf, value.oldSlot)
val block = switchBlock(value.mon.species)
if (value.fullBlock) {
S8.write(buf, value.newSlot.toByte())
buf.writeBytes(SWITCH_MON_CONST)
S64LE.write(buf, value.mon.entityId)
S16LE.write(buf, value.mon.species)
buf.writeBytes(block.statPrefix)
S8.write(buf, value.mon.hp.toByte()) // max hp
S8.write(buf, 0)
S16LE.write(buf, value.mon.hp)
buf.writeBytes(block.moveBody)
S8.write(buf, value.newSlot.toByte()) // slot trailer
}
S8.write(buf, 0)
S8.write(buf, value.newSlot.toByte())
S16LE.write(buf, value.mon.species)
buf.writeBytes(block.activeStat)
buf.writeBytes(SWITCH_ACTIVE_TAIL)
}
}
object BattleSwitchInPacketCodec : PacketCodec<BattleSwitchInPacket>() {
override fun CodecScope<BattleSwitchInPacket>.body(): BattleSwitchInPacket {
return field(BattleSwitchInBody) { it }
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
@@ -7,13 +7,13 @@ data class BattleSlotTile(
val value: Byte,
)
data class FieldMapBattleSlotTileMapPacket(
data class BattleTileMapPacket(
val groupId: Short,
val slotTiles: List<BattleSlotTile>?,
)
object FieldMapBattleSlotTileMapPacketCodec : PacketCodec<FieldMapBattleSlotTileMapPacket>() {
override fun CodecScope<FieldMapBattleSlotTileMapPacket>.body(): FieldMapBattleSlotTileMapPacket {
object BattleTileMapPacketCodec : PacketCodec<BattleTileMapPacket>() {
override fun CodecScope<BattleTileMapPacket>.body(): BattleTileMapPacket {
val groupId = field(S16LE) { it.groupId }
val present = field(U8) { if (it.slotTiles != null) 1 else 0 } == 1
val slotTiles =
@@ -25,6 +25,6 @@ object FieldMapBattleSlotTileMapPacketCodec : PacketCodec<FieldMapBattleSlotTile
BattleSlotTile(slot, value)
}
} else null
return FieldMapBattleSlotTileMapPacket(groupId, slotTiles)
return BattleTileMapPacket(groupId, slotTiles)
}
}
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -1,4 +1,4 @@
package de.fiereu.openmmo.net.game.packets
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
@@ -0,0 +1,82 @@
package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.common.enums.BattleAction
import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class BattleActionSelectPacketTest :
FunSpec({
test("decodes a captured move selection") {
val bytes = byteArrayOf(0x00, 0x00, 0x2B, 0x00, 0x00)
val decoded = BattleActionSelectPacketCodec.decodeBytes(bytes)
decoded shouldBe
BattleActionSelectPacket(
slotRefPacked = 0,
action = BattleAction.MOVE,
moveOrItemId = 43,
targetEntityId = 0,
extraFlag = 0,
)
BattleActionSelectPacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("decodes a captured item throw") {
val bytes =
byteArrayOf(
0x00,
0x01,
0x8C.toByte(),
0x13,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF.toByte())
val decoded = BattleActionSelectPacketCodec.decodeBytes(bytes)
decoded shouldBe
BattleActionSelectPacket(
slotRefPacked = 0,
action = BattleAction.ITEM,
moveOrItemId = 5004,
targetEntityId = 0,
extraFlag = -1,
)
BattleActionSelectPacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("decodes a run selection with no tail") {
val bytes = byteArrayOf(0x00, 0x03)
val decoded = BattleActionSelectPacketCodec.decodeBytes(bytes)
decoded shouldBe
BattleActionSelectPacket(
slotRefPacked = 0,
action = BattleAction.RUN,
moveOrItemId = 0,
targetEntityId = 0,
extraFlag = 0,
)
BattleActionSelectPacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("decodes a captured switch to a party index") {
val bytes = byteArrayOf(0x00, 0x02, 0x01, 0x00)
val decoded = BattleActionSelectPacketCodec.decodeBytes(bytes)
decoded shouldBe
BattleActionSelectPacket(
slotRefPacked = 0,
action = BattleAction.SWITCH,
moveOrItemId = 1,
targetEntityId = 0,
extraFlag = 0,
)
BattleActionSelectPacketCodec.encodeToBytes(decoded) shouldBe bytes
}
})
@@ -0,0 +1,28 @@
package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.util.Base64
// A two-monster party wild encounter (Snivy active, Patrat benched), scrubbed of capture data. The
// player side carries a per-species stat and move block and a per-slot trailer, all reproduced by
// the codec.
private const val CAPTURED_TWO_PARTY =
"AgAAAAAAAAAAAAAAAP8AAAAAABYAAAD/ACAABlQAZQBzAHQAAAAAAJABAAAAAAD/AAJMAxqsDwADgAGkAAQAAAAAAAECAAABAMABAAAAAADvAQYAAAAAAAAWABYAAAAA/wMBQQAhACsAAAAAAAABAQDAAgAAAAAA+AECAAABAAAADgAOAAAAAP8DATIAIQAAAAAAAAABAADvAQYAAAAAAAAD/wAAAABmZmZmAQYAAAAAAAEBAAABAMADAAAAAAD4AQIAAAEAAAAOAA4AAAAA/wMAAQAA+AECAAAAAAEAA/8AAAAAZmZmZgAAAAA="
class BattleFieldStatePacketTest :
FunSpec({
test("round-trips a two-party wild field state byte for byte") {
val bytes = Base64.getDecoder().decode(CAPTURED_TWO_PARTY)
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
decoded.playerName shouldBe "Test"
decoded.playerParty.size shouldBe 2
decoded.playerParty[0].species shouldBe 495.toShort()
decoded.playerParty[1].species shouldBe 504.toShort()
decoded.wildMon.species shouldBe 504.toShort()
BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes
}
})
@@ -0,0 +1,48 @@
package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInMon
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }
class BattleSwitchInPacketTest :
FunSpec({
// Switching back to an already-active monster sends only the 21-byte active detail.
// Reproduced
// byte for byte from a real capture (Snivy, slot 0, previous slot 1).
test("encodes a return switch-in as just the active detail") {
val packet =
BattleSwitchInPacket(
newSlot = 0,
oldSlot = 1,
mon = BattleSwitchInMon(entityId = 0, species = 495, hp = 0),
fullBlock = false,
)
val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet)
bytes.hex() shouldBe "000000010000ef010600000000000003ff0000000066666666"
}
// A benched monster coming out carries its full block then its active detail.
test("round-trips a full-block switch-in") {
val packet =
BattleSwitchInPacket(
newSlot = 1,
oldSlot = 0,
mon = BattleSwitchInMon(entityId = 0x000000000003C000L, species = 504, hp = 14),
fullBlock = true,
)
val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet)
bytes.size shouldBe 65
val decoded = BattleSwitchInPacketCodec.decodeBytes(bytes)
decoded.newSlot shouldBe 1
decoded.oldSlot shouldBe 0
decoded.fullBlock shouldBe true
decoded.mon.species shouldBe 504.toShort()
decoded.mon.hp shouldBe 14.toShort()
}
})
@@ -0,0 +1,128 @@
package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
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.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.net.game.codecs.PokemonCodec
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.time.LocalDateTime
import java.util.Base64
private fun testMon(id: Long, dex: Int, slot: Short) =
Pokemon(
id = id,
ownerId = 0x9000L,
container = PokemonContainer.PARTY,
containerSlot = slot,
dexId = dex,
seed = 0,
ot = "Test",
nickname = "",
level = 5,
hp = 20,
xp = 100,
eVs = EVs(),
iVs = IVs(),
moves = List(4) { PokemonMove(0, 0) },
isShiny = false,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = false,
isRaidEncounter = false,
caughtAt = LocalDateTime.of(2026, 1, 1, 0, 0, 0),
)
private const val CAPTURED_PARTY =
"AQEBAMABAAAAAAAAAACQAQAAAAAAAJABAAAAAAABAADvAbpwfdsAkAEAAAAAAFQAZQBzAHQAAAAAAAAABRQAAAClAAAAADIAIQArAAAAAAAjHgAAAAAAAAAAAAAAAAAAAQAAAAAAAAAEBQL/////AwDvvfceAAAAIAAAAAAAAACGhlNqAAD//wA="
class PokemonContainerPacketTest :
FunSpec({
test("round-trips a captured party container and exposes the monster fields") {
val bytes = Base64.getDecoder().decode(CAPTURED_PARTY)
val decoded = PokemonContainerPacketCodec.decodeBytes(bytes)
val mon = decoded.pokemon.single()
mon.dexId shouldBe 495
mon.ot shouldBe "Test"
mon.level shouldBe 5.toByte()
mon.hp shouldBe 20.toShort()
mon.moves.map { it.id } shouldBe listOf<Short>(33, 43, 0, 0)
mon.containerSlot shouldBe 0.toShort()
// Starter monsters roll fixed 15s across every stat.
mon.iVs.total shouldBe 90
mon.iVs.hp shouldBe 15
mon.caughtAt shouldBe LocalDateTime.of(2026, 7, 12, 12, 20, 22)
mon.isShiny shouldBe false
mon.isEgg shouldBe false
PokemonContainerPacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("EVs, rarity flags, and egg survive a monster codec round-trip") {
val mon = PokemonContainerPacketCodec.decodeBytes(bytes()).pokemon.single()
// Distinct per-stat values catch a wrong wire order (speed is the fourth EV byte).
val evs =
EVs().apply {
hp = 4
atk = 8
def = 12
spAtk = 16
spDef = 20
spd = 24
}
val rare =
mon.copy(
eVs = evs,
isShiny = true,
hasHiddenAbility = false,
isAlpha = true,
isSecret = true,
isFatefulEncounter = false,
isRaidEncounter = true,
isEgg = true,
)
val roundTripped = PokemonCodec.decodeBytes(PokemonCodec.encodeToBytes(rare))
roundTripped.eVs.hp shouldBe 4
roundTripped.eVs.atk shouldBe 8
roundTripped.eVs.def shouldBe 12
roundTripped.eVs.spAtk shouldBe 16
roundTripped.eVs.spDef shouldBe 20
roundTripped.eVs.spd shouldBe 24
roundTripped.isShiny shouldBe true
roundTripped.hasHiddenAbility shouldBe false
roundTripped.isAlpha shouldBe true
roundTripped.isSecret shouldBe true
roundTripped.isFatefulEncounter shouldBe false
roundTripped.isRaidEncounter shouldBe true
roundTripped.isEgg shouldBe true
}
test("a two-monster party container round-trips") {
val packet =
PokemonContainerPacket(
container = PokemonContainer.PARTY,
hasChange = true,
delete = false,
pokemon =
listOf(
testMon(0x000000000001C000L, dex = 495, slot = 0),
testMon(0x000000000002C000L, dex = 504, slot = 1),
),
)
val bytes = PokemonContainerPacketCodec.encodeToBytes(packet)
val decoded = PokemonContainerPacketCodec.decodeBytes(bytes)
decoded.pokemon.size shouldBe 2
decoded.pokemon[0].dexId shouldBe 495
decoded.pokemon[1].dexId shouldBe 504
decoded.pokemon[1].containerSlot shouldBe 1.toShort()
PokemonContainerPacketCodec.encodeToBytes(decoded) shouldBe bytes
}
})
private fun bytes(): ByteArray = Base64.getDecoder().decode(CAPTURED_PARTY)
@@ -10,6 +10,7 @@ import de.fiereu.openmmo.net.game.packets.AddFriendPacket
import de.fiereu.openmmo.net.game.packets.BlockPlayerPacket
import de.fiereu.openmmo.net.game.packets.CancelSocialInteractionPacket
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket
import de.fiereu.openmmo.net.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.net.game.packets.DialogChoicePacket
import de.fiereu.openmmo.net.game.packets.EntityInteractPacket
@@ -26,6 +27,28 @@ import de.fiereu.openmmo.net.game.packets.RequestPlayerPacket
import de.fiereu.openmmo.net.game.packets.RequestSocialProfilePacket
import de.fiereu.openmmo.net.game.packets.SelectCharacterPacket
import de.fiereu.openmmo.net.game.packets.UnblockPlayerPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionSubmitPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleAppearancePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleCancelRequestPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleChallengeRequestPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleChatMessagePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleLeavePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleMoveUsePacket
import de.fiereu.openmmo.net.game.packets.battle.BattlePartySlotSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattlePartySwitchPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleReadyPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleRewardSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSequencePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSimulationRequestPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSlotActionPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchSelectionsPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTargetPickPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTeamPreviewConfirmPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTierSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTransitionReadyPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleUseItemPacket
import de.fiereu.openmmo.net.game.packets.guild.GuildActivityLogPageRequestPacket
import de.fiereu.openmmo.net.game.packets.guild.GuildCreatePacket
import de.fiereu.openmmo.net.game.packets.guild.GuildDisbandPacket
@@ -36,6 +59,7 @@ import de.fiereu.openmmo.net.game.packets.guild.GuildMemberRankAssignPacket
import de.fiereu.openmmo.net.game.packets.guild.GuildMotdUpdatePacket
import de.fiereu.openmmo.net.game.packets.guild.GuildRankLabelUpdatePacket
import de.fiereu.openmmo.net.game.packets.guild.GuildRankPermissionUpdatePacket
import de.fiereu.openmmo.server.game.services.BattleService
import de.fiereu.openmmo.server.game.services.DialogService
import de.fiereu.openmmo.server.game.services.GuildService
import de.fiereu.openmmo.server.game.services.InteractionService
@@ -62,6 +86,7 @@ constructor(
private val multiplayerService: MultiplayerService,
private val socialService: SocialService,
private val guildService: GuildService,
private val battleService: BattleService,
private val sessionRegistry: SessionRegistry,
private val characterStore: CharacterStore,
scope: CoroutineScope,
@@ -100,8 +125,32 @@ constructor(
on<GuildRankLabelUpdatePacket> { event -> guildService.onRankLabelUpdate(event) }
on<GuildActivityLogPageRequestPacket> { event -> guildService.onActivityLogPageRequest(event) }
on<BattleMoveUsePacket> { event -> battleService.onBattlePacket(event) }
on<BattlePartySwitchPacket> { event -> battleService.onBattlePacket(event) }
on<BattleActionPacket> { event -> battleService.onBattlePacket(event) }
on<BattleActionSelectPacket> { event -> battleService.onBattleAction(event) }
on<BattleLeavePacket> { event -> battleService.onBattlePacket(event) }
on<BattleSequencePacket> { event -> battleService.onBattlePacket(event) }
on<BattleSlotActionPacket> { event -> battleService.onBattlePacket(event) }
on<BattleSwitchSelectionsPacket> { event -> battleService.onBattlePacket(event) }
on<BattleUseItemPacket> { event -> battleService.onBattlePacket(event) }
on<BattleAppearancePacket> { event -> battleService.onBattlePacket(event) }
on<BattleCancelRequestPacket> { event -> battleService.onBattlePacket(event) }
on<BattleSimulationRequestPacket> { event -> battleService.onBattlePacket(event) }
on<BattleReadyPacket> { event -> battleService.onBattlePacket(event) }
on<BattleActionSubmitPacket> { event -> battleService.onBattlePacket(event) }
on<BattleTierSelectPacket> { event -> battleService.onBattlePacket(event) }
on<BattleChatMessagePacket> { event -> battleService.onBattlePacket(event) }
on<BattlePartySlotSelectPacket> { event -> battleService.onBattlePacket(event) }
on<BattleTargetPickPacket> { event -> battleService.onBattlePacket(event) }
on<BattleTransitionReadyPacket> { event -> battleService.onBattlePacket(event) }
on<BattleTeamPreviewConfirmPacket> { event -> battleService.onBattlePacket(event) }
on<BattleRewardSelectPacket> { event -> battleService.onBattlePacket(event) }
on<BattleChallengeRequestPacket> { event -> battleService.onBattlePacket(event) }
on<KeepAlivePacket> { event -> event.session.send(event.packet) }
on<ChatMessagePacket> { event -> onChatMessage(event) }
on<ChatMessageSendPacket> { event -> battleService.onChatSend(event) }
}
override fun onInactive() {
@@ -0,0 +1,285 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.network.PacketEvent
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.BattleAction
import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket
import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket
import de.fiereu.openmmo.net.game.packets.EntityPresencePacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.SocialListEntryAddPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleBulkStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldMon
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleListEventDetail
import de.fiereu.openmmo.net.game.packets.battle.BattleListEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleQueuedEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSlotEventEnumPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInMon
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
private val log = KotlinLogging.logger {}
private const val TEST_BATTLE_COMMAND = "/testbattle"
// The bag is populated in the join flow, so /catch drives the catch sequence directly for testing
// even though a ball can now be thrown from the UI.
private const val CATCH_COMMAND = "/catch"
private const val PATRAT: Short = 504
private const val WILD_MON_ID = 0x000000000003C000L
private const val CAUGHT_PATRAT_UID = 0x000000000002C000L
private const val WILD_PATRAT_HP: Short = 14
private const val CAUGHT_PATRAT_LEVEL: Byte = 2
private const val CAUGHT_PATRAT_HP: Short = 8
private const val CAUGHT_PATRAT_XP = 8
private const val PATRAT_TACKLE: Short = 33
private const val PATRAT_TACKLE_PP: Byte = 35
private const val ACTION_PROMPT: Byte = -128 // 0x80
private const val ENEMY_MOVE: Short = 33
private const val MOVE_EVENT_KIND: Byte = 1
private const val POKE_BALL_ITEM: Short = 5004
// Slot-event type shown when the player gets away from a wild battle.
private const val FLED_EVENT: Byte = 0
// The player's overworld entity is hidden while the battle scene is up and shown again when it
// ends.
private const val PRESENCE_IN_BATTLE: Byte = 1
private const val PRESENCE_OVERWORLD: Byte = 0
// The active battle side reported to the client so the bag knows which monster an item targets.
private const val PLAYER_SIDE: Byte = 1
@Singleton
class BattleService
@Inject
constructor(
private val characterStore: CharacterStore,
) {
private val battleTurn = ConcurrentHashMap<Long, Int>()
// The active party slot per battle, and which slots have been sent out as active. A monster's
// first appearance carries its full block, a return only its active detail.
private val battleActiveSlot = ConcurrentHashMap<Long, Int>()
private val battleSeenActive = ConcurrentHashMap<Long, MutableSet<Int>>()
fun onBattlePacket(event: PacketEvent<*>) {
log.info { "Battle packet ${event.packet::class.simpleName} received: ${event.packet}" }
}
fun onBattleAction(event: PacketEvent<BattleActionSelectPacket>) {
val session = event.session
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return
val action = event.packet
log.info { "Battle action char=$charId: $action" }
when (action.action) {
BattleAction.MOVE -> {
playMoveAnimations(session, charId, action.moveOrItemId)
advanceTurn(session, charId)
}
BattleAction.ITEM -> catchWildMon(session, charId)
BattleAction.SWITCH -> switchMon(session, charId, action.moveOrItemId)
BattleAction.RUN -> fleeBattle(session, charId)
}
}
// The client picked a party slot to switch to. The switch-in packet (opcode 0x35) brings the new
// monster onto the field: the first time a monster comes out it carries its full block, otherwise
// just its active detail. The turn then advances and re-prompts for the next action.
private fun switchMon(session: SessionContext, charId: Long, partyIndex: Short) {
val stored = characterStore.getCharacter(charId) ?: return
val target = partyIndex.toInt()
val mon = stored.pokemon.getOrNull(target)
if (mon == null) {
log.warn { "Switch to invalid party index $partyIndex for char=$charId" }
advanceTurn(session, charId)
return
}
val oldSlot = battleActiveSlot[charId] ?: 0
if (target == oldSlot) {
advanceTurn(session, charId)
return
}
val seen = battleSeenActive.getOrPut(charId) { mutableSetOf(0) }
val fullBlock = target !in seen
log.info { "Switch char=$charId slot $oldSlot -> $target (fullBlock=$fullBlock)" }
session.send(
BattleSwitchInPacket(
newSlot = target,
oldSlot = oldSlot,
mon = BattleSwitchInMon(mon.id, mon.dexId.toShort(), mon.hp),
fullBlock = fullBlock,
),
)
seen.add(target)
battleActiveSlot[charId] = target
advanceTurn(session, charId)
}
// The player fled. The slot event shows the got-away text, the flee end marker closes the battle
// scene, and the presence toggle restores the overworld player.
private fun fleeBattle(session: SessionContext, charId: Long) {
battleTurn.remove(charId)
battleActiveSlot.remove(charId)
battleSeenActive.remove(charId)
session.send(BattleSlotEventEnumPacket(slot = 0, eventType = FLED_EVENT))
session.send(BattleBulkStatePacket.fled())
session.send(EntityPresencePacket(entityId = charId, status = PRESENCE_OVERWORLD))
}
private fun catchWildMon(session: SessionContext, charId: Long) {
log.info { "Ball thrown, catching wild Patrat for char=$charId" }
battleTurn.remove(charId)
battleActiveSlot.remove(charId)
battleSeenActive.remove(charId)
val ot = characterStore.getCharacter(charId)?.info?.name ?: ""
val patrat = caughtPatrat(charId, ot)
// The caught Patrat is sent as a full 148-byte record on opcode 0x14 before the ball-throw
// event, so the client can resolve the monster when the throw lands.
session.send(SocialListEntryAddPacket(patrat))
// "Player threw a Poke Ball" event.
session.send(
BattleListEventPacket(
kind = 0,
value = POKE_BALL_ITEM,
subKind = 4,
detail = BattleListEventDetail(listType = 1, value = 1),
),
)
endBattle(session, charId, patrat)
}
// The wild encounter is over. The bulk-state end marker tells the client to leave the battle
// scene, the presence toggle shows the overworld player again, and the party is persisted and
// resynced so the caught monster stays after the battle.
// TODO: the caught monster does not show up in the party after the battle closes.
private fun endBattle(session: SessionContext, charId: Long, caught: Pokemon) {
val stored = characterStore.getCharacter(charId) ?: return
if (stored.pokemon.none { it.id == caught.id }) {
characterStore.addPokemon(charId, caught)
}
session.send(BattleBulkStatePacket.battleEnd())
session.send(EntityPresencePacket(entityId = charId, status = PRESENCE_OVERWORLD))
session.send(
PokemonContainerPacket(
container = PokemonContainer.PARTY,
hasChange = true,
delete = false,
pokemon = characterStore.getCharacter(charId)?.pokemon ?: emptyList(),
),
)
}
private fun caughtPatrat(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = CAUGHT_PATRAT_UID,
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 1,
dexId = PATRAT.toInt(),
seed = 0,
ot = ot,
nickname = "",
level = CAUGHT_PATRAT_LEVEL,
hp = CAUGHT_PATRAT_HP,
xp = CAUGHT_PATRAT_XP,
eVs = EVs(),
iVs = IVs(),
moves =
listOf(
PokemonMove(PATRAT_TACKLE, PATRAT_TACKLE_PP),
PokemonMove(0, 0),
PokemonMove(0, 0),
PokemonMove(0, 0),
),
isShiny = false,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = false,
isRaidEncounter = false,
caughtAt = LocalDateTime.now(),
)
private fun playMoveAnimations(session: SessionContext, charId: Long, playerMove: Short) {
// The move comes from whichever monster is currently on the field, not always the lead.
val activeSlot = battleActiveSlot[charId] ?: 0
val partyMon = characterStore.getCharacter(charId)?.pokemon?.getOrNull(activeSlot) ?: return
// Decrement the used move's PP before the animation, matching the real turn order.
val slot = partyMon.moves.indexOfFirst { it.id == playerMove }
if (slot >= 0) {
val newPp = (partyMon.moves[slot].pp - 1).coerceAtLeast(0).toByte()
session.send(EntityMovePpPacket(partyMon.id, slot.toByte(), newPp))
}
session.send(BattleEntityMoveEventPacket(partyMon.id, playerMove, MOVE_EVENT_KIND, emptyList()))
session.send(BattleEntityMoveEventPacket(WILD_MON_ID, ENEMY_MOVE, MOVE_EVENT_KIND, emptyList()))
}
private fun advanceTurn(session: SessionContext, charId: Long) {
val turn = battleTurn.merge(charId, 1) { a, b -> a + b } ?: 1
session.send(BattleTileMapPacket(groupId = turn.toShort(), slotTiles = null))
session.send(BattleQueuedEventPacket(packed = ACTION_PROMPT))
}
fun onChatSend(event: PacketEvent<ChatMessageSendPacket>) {
val session = event.session
val text = (event.packet.message ?: event.packet.target).trim()
when {
text.equals(TEST_BATTLE_COMMAND, ignoreCase = true) -> startTestBattle(session)
text.equals(CATCH_COMMAND, ignoreCase = true) -> {
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return
catchWildMon(session, charId)
}
}
}
private fun startTestBattle(session: SessionContext) {
val state = session.attributes[PLAYER_STATE] ?: return
val charId = state.characterId ?: return
val stored = characterStore.getCharacter(charId) ?: return
val partyMon = stored.pokemon.firstOrNull()
if (partyMon == null) {
log.warn { "Cannot start test battle: char=$charId has no party monster" }
return
}
log.info {
"Starting test battle for char=$charId (${stored.info.name}): dex=${partyMon.dexId} vs wild Patrat"
}
battleTurn[charId] = 1
battleActiveSlot[charId] = 0
battleSeenActive[charId] = mutableSetOf(0)
// Hide the overworld player entity while the battle scene is up, matching the real enter order.
session.send(EntityPresencePacket(entityId = charId, status = PRESENCE_IN_BATTLE))
// Tell the client which side is local so the battle bag knows which monster an item targets.
// Without it, opening the bag crashes. Opcode 0x40 is left alone here, since re-sending it
// would
// wipe the balls out of the battle bag.
session.send(BattleSidePacket(side = PLAYER_SIDE))
session.send(
BattleFieldStatePacket(
playerName = stored.info.name,
playerId = charId,
playerParty = stored.pokemon.map { BattleFieldMon(it.id, it.dexId.toShort(), it.hp) },
wildMon = BattleFieldMon(WILD_MON_ID, PATRAT, WILD_PATRAT_HP),
),
)
session.send(BattleTileMapPacket(groupId = 1, slotTiles = null))
session.send(BattleQueuedEventPacket(packed = ACTION_PROMPT))
}
}
@@ -17,13 +17,23 @@ import de.fiereu.openmmo.net.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.JoinResponsePacket
import de.fiereu.openmmo.net.game.packets.LoadEntityPacket
import de.fiereu.openmmo.net.game.packets.LocalPlayerStatePacket
import de.fiereu.openmmo.net.game.packets.MenuPagePayloadPacket
import de.fiereu.openmmo.net.game.packets.NewAuthData
import de.fiereu.openmmo.net.game.packets.ObjectiveProgressBulkPacket
import de.fiereu.openmmo.net.game.packets.PokedexSpeciesResetPacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.net.game.packets.RequestCharactersPacket
import de.fiereu.openmmo.net.game.packets.RequestPlayerPacket
import de.fiereu.openmmo.net.game.packets.SelectCharacterPacket
import de.fiereu.openmmo.net.game.packets.SelectedCharacterPacket
import de.fiereu.openmmo.net.game.packets.ViewScalePacket
import de.fiereu.openmmo.net.game.packets.WorldFlagTableResetPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleRatingBulkPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleStateBytePacket
import de.fiereu.openmmo.net.game.packets.battle.ItemStack
import de.fiereu.openmmo.net.game.packets.battle.itemStacksPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.session.SessionRegistry
@@ -35,6 +45,27 @@ import javax.inject.Singleton
private val log = KotlinLogging.logger {}
private fun hexToBytes(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
// The world-flag table the client loads on join. Groups one to three are zlib streams that each
// decompress to a 67-byte flag block, the fourth is empty. The client reads real flag state while
// building the follower and party, so empty groups leave a lookup null and crash it.
private val WORLD_FLAG_GROUPS =
listOf(
"789c637060a00434a8b0320000133900ea",
"789c637060a00434303032000012c500c2",
"789c637060a00434303032000012c500c2",
"",
)
.map(::hexToBytes)
private const val POKE_BALL_ITEM_ID: Short = 5004
private const val POKE_BALL_OBJECT_ID = 0x0000000000015000L
private const val POKE_BALL_QUANTITY: Short = 10
private val STARTING_BAG =
listOf(ItemStack(POKE_BALL_OBJECT_ID, POKE_BALL_ITEM_ID, POKE_BALL_QUANTITY))
@Singleton
class LoginService
@Inject
@@ -125,6 +156,11 @@ constructor(
sessionRegistry.bindCharacter(ctx, charId)
log.info { "Player selected character '${stored.info.name}' (id=$charId)" }
// Initialise the client world-flag table before any monster or follower is built. Without it
// the table stays null and the client crashes constructing a party monster that reads a flag.
ctx.send(WorldFlagTableResetPacket(WORLD_FLAG_GROUPS))
ctx.send(buildLocalPlayerState(stored.info, stored.pokemon.map { it.dexId.toShort() }))
val info = stored.info
val now = LocalDateTime.now()
val updatedInfo = info.copy(lastLogin = now)
@@ -134,9 +170,9 @@ constructor(
mapOf(
PokemonContainer.PARTY to stored.pokemon,
PokemonContainer.PC to stored.pcStorage,
PokemonContainer.BATTLE_BOX_1 to emptyList<Pokemon>(),
PokemonContainer.BATTLE_BOX_2 to emptyList<Pokemon>(),
PokemonContainer.DAYCARE to emptyList<Pokemon>(),
PokemonContainer.BATTLE_BOX_1 to emptyList(),
PokemonContainer.BATTLE_BOX_2 to emptyList(),
PokemonContainer.DAYCARE to emptyList(),
)
for ((container, pokemon) in containers) {
ctx.send(
@@ -158,7 +194,12 @@ constructor(
))
}
// The bag item stacks (opcode 0x40). The real server sends these during join, interleaved with
// the container packets, so the client has the items before entering the world.
ctx.send(itemStacksPacket(STARTING_BAG))
ctx.send(SelectedCharacterPacket(info))
sendJoinState(ctx)
ctx.send(
ChatMessagePacket(
ChatType.GAME_NOTIFICATIONS,
@@ -170,6 +211,45 @@ constructor(
preloadMapAndJoin(ctx, state, info)
}
// The full local-player state snapshot the client loads on login. Missing it leaves player state
// uninitialised and the client crashes reading it (for example when opening the battle bag).
private fun buildLocalPlayerState(
info: CharacterInfo,
partyDex: List<Short>
): LocalPlayerStatePacket =
LocalPlayerStatePacket(
region = info.positionRegionId,
mapId = info.positionMapId.toShort(),
moveSpeed = 0.05f,
x = info.positionX,
y = info.positionY,
z = 0,
money = info.money,
gender = 0,
skinTone = 0,
hairColor = 0,
playtime = 0.0,
flags = 0,
partyDex = partyDex,
partyForms = partyDex.map { 0.toByte() },
pokedexSeen = emptyList(),
pokedexCaught = emptyList(),
badges = emptyList(),
variables = emptyList(),
)
// Small state packets the real server sends in the join flow. The battle-state byte and menu
// payloads initialise state the battle bag reads, so without them opening the bag crashes.
private fun sendJoinState(ctx: SessionContext) {
ctx.send(ViewScalePacket(viewScale = 5))
ctx.send(BattleRatingBulkPacket(emptyList()))
ctx.send(BattleStateBytePacket(state = 0x19))
ctx.send(PokedexSpeciesResetPacket(emptyList()))
ctx.send(ObjectiveProgressBulkPacket(emptyList()))
ctx.send(MenuPagePayloadPacket(menuType = 0, page = null))
ctx.send(MenuPagePayloadPacket(menuType = 1, page = null))
}
private fun preloadMapAndJoin(
ctx: SessionContext,
state: PlayerState,
@@ -58,7 +58,7 @@ constructor(
NpcEntry(9, 4, 14, 36, 1, 5121, 0, 1, 9),
NpcEntry(8, 7, 32, 36, 1, 5632, 0, 0, 8),
)
val baseEntityId = 0x1A6BFE24CC88E000L
val baseEntityId = 0x000000000001E000L
for (npc in all16) {
val entityId = baseEntityId or npc.entityIdx.toLong()
log.info {
@@ -2,12 +2,25 @@ package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo
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.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import javax.inject.Singleton
// A starter party monster for the dev test character. Its uid, species, HP, and moves match the
// field state emitted by the test battle so the client can resolve the player's monster.
const val STARTER_SNIVY_UID = 0x000000000001C000L
const val SNIVY_DEX_ID = 495
// A second party monster so the switch action is selectable in the test battle.
const val STARTER_PATRAT_UID = 0x000000000002C000L
const val PATRAT_DEX_ID = 504
data class StoredCharacter(
val info: CharacterInfo,
val pokemon: MutableList<Pokemon>,
@@ -27,7 +40,9 @@ class CharacterStore @Inject constructor() {
private fun ensureTestCharacter() {
if (characters.isEmpty()) {
createCharacter(userId = 1, name = "Test")
val test = createCharacter(userId = 1, name = "Test")
test.pokemon.add(starterSnivy(test.info.id, test.info.name))
test.pokemon.add(starterPatrat(test.info.id, test.info.name))
}
}
@@ -104,6 +119,68 @@ class CharacterStore @Inject constructor() {
characters[characterId] = stored.copy(info = newInfo)
}
private fun starterSnivy(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = STARTER_SNIVY_UID,
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 0,
dexId = SNIVY_DEX_ID,
seed = 0,
ot = ot,
nickname = "",
level = 5,
hp = 20,
xp = 165,
eVs = EVs(),
iVs = IVs(),
moves =
listOf(
PokemonMove(33, 35),
PokemonMove(43, 30),
PokemonMove(0, 0),
PokemonMove(0, 0),
),
isShiny = false,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = false,
isRaidEncounter = false,
caughtAt = LocalDateTime.now(),
)
private fun starterPatrat(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = STARTER_PATRAT_UID,
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 1,
dexId = PATRAT_DEX_ID,
seed = 0,
ot = ot,
nickname = "",
level = 3,
hp = 12,
xp = 27,
eVs = EVs(),
iVs = IVs(),
moves =
listOf(
PokemonMove(33, 35),
PokemonMove(0, 0),
PokemonMove(0, 0),
PokemonMove(0, 0),
),
isShiny = false,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = false,
isRaidEncounter = false,
caughtAt = LocalDateTime.now(),
)
fun addPokemon(characterId: Long, pokemon: Pokemon) {
characters[characterId]?.pokemon?.add(pokemon)
}
@@ -7,6 +7,8 @@ import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.KeepAlivePacket
import de.fiereu.openmmo.net.game.packets.MovementPacket
import de.fiereu.openmmo.net.game.packets.RemoveFriendPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleChallengeRequestPacket
import de.fiereu.openmmo.server.game.config.GameServerConfig
import de.fiereu.openmmo.server.game.di.DaggerGameServerComponent
import io.kotest.core.spec.style.FunSpec
@@ -32,5 +34,7 @@ class GameAppHandlerTest :
handler.isRegistered(AddFriendPacket::class) shouldBe true
handler.isRegistered(RemoveFriendPacket::class) shouldBe true
handler.isRegistered(BlockPlayerPacket::class) shouldBe true
handler.isRegistered(BattleActionPacket::class) shouldBe true
handler.isRegistered(BattleChallengeRequestPacket::class) shouldBe true
}
})