feat(game): keep the appearance the client picks at character creation (#145)

This commit is contained in:
Fiereu authored and GitHub committed 2026-08-09 22:08:48 +02:00
1 parent 0dab4b16fa
commit 0200858be9
14 files changed
+234 -18

No files matched your search

@@ -9,6 +9,8 @@ data class CharacterInfo(
val namePrefix: String = "",
val userId: Int,
val rivalSex: Byte,
/** Leading byte of the skin set on the wire. */
val skinRegionSelectionIndex: Int = 0,
val lastLogin: LocalDateTime,
val createdAt: LocalDateTime,
val money: Int,
@@ -0,0 +1,5 @@
package de.fiereu.openmmo.common
import de.fiereu.openmmo.common.enums.SkinSlot
data class Skin(val slot: SkinSlot, val type: UShort?, val color: UByte?)
@@ -1,12 +1,22 @@
package de.fiereu.openmmo.net.game.codecs
import de.fiereu.bytecodec.*
import de.fiereu.openmmo.common.Skin
import de.fiereu.openmmo.common.enums.SkinSlot
import java.util.*
data class Skin(val slot: SkinSlot, val type: UShort?, val color: UByte?)
// Type and color share one 16 bit word.
private const val TYPE_MASK = 0x3FF
private const val COLOR_SHIFT = 10
private const val COLOR_MASK = 0x3F
class SkinSet(var regionSelectionIndex: Int = 0, skins: Map<SkinSlot, Skin> = emptyMap()) :
EnumMap<SkinSlot, Skin>(SkinSlot::class.java) {
init {
putAll(skins)
}
class SkinSet(var regionSelectionIndex: Int = 0) : EnumMap<SkinSlot, Skin>(SkinSlot::class.java) {
fun put(skin: Skin) {
this[skin.slot] = skin
}
@@ -33,14 +43,14 @@ class SkinSetCodec(
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 = (skin.type ?: TYPE_MASK.toUShort()).toInt()
val color = (skin.color ?: COLOR_MASK.toUByte()).toInt()
require(type <= TYPE_MASK) { "Skin type too large: ${skin.type}" }
require(color <= COLOR_MASK) { "Skin color too large: ${skin.color}" }
type or (color shl COLOR_SHIFT)
}
val type = (compressed and 0x3FFF).toUShort()
val color = ((compressed shr 10) and 0x3F).toUByte()
val type = (compressed and TYPE_MASK).toUShort()
val color = ((compressed shr COLOR_SHIFT) and COLOR_MASK).toUByte()
skins.put(Skin(slot, type, color))
}
}
@@ -8,6 +8,8 @@ import de.fiereu.openmmo.net.game.codecs.*
data class CharacterEntry(
val characterInfo: CharacterInfo,
val skinSet: SkinSet,
/** A second set of the same shape, empty in every capture and still unidentified. */
val secondarySkinSet: SkinSet = SkinSet(),
val guildId: Int? = null,
val pokemon: List<Pokemon>,
) {
@@ -31,7 +33,7 @@ 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 secondarySkin = field(SkinSetCodecNoLeading, CharacterEntry::secondarySkinSet)
val hasGuild = field(Bool) { it.guildId != null }
val guildId =
if (hasGuild) {
@@ -42,7 +44,7 @@ private object CharacterEntryCodec : PacketCodec<CharacterEntry>() {
}
val partySize = field(U8) { it.pokemon.size }
val party = List(partySize) { field(PokemonCodec) { entry -> entry.pokemon[it] } }
return CharacterEntry(info, skin, guildId, party)
return CharacterEntry(info, skin, secondarySkin, guildId, party)
}
}
@@ -7,6 +7,7 @@ import de.fiereu.openmmo.net.game.codecs.DefaultSkinSetCodec
import de.fiereu.openmmo.net.game.codecs.PokemonCodec
import de.fiereu.openmmo.net.game.codecs.SkinSetCodecNoLeading
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.maps.shouldBeEmpty
import io.kotest.matchers.shouldBe
class CharactersListPacketTest :
@@ -15,10 +16,11 @@ class CharactersListPacketTest :
val buf = fixtureBuffer("game/s2c/02/character_list_32710.bin")
val names = mutableListOf<String>()
val parties = mutableListOf<Int>()
val skinSlotCounts = mutableListOf<Int>()
repeat(U8.read(buf)) {
names += CharacterInfoCodecShort.read(buf).name
DefaultSkinSetCodec.read(buf)
SkinSetCodecNoLeading.read(buf)
skinSlotCounts += DefaultSkinSetCodec.read(buf).size
SkinSetCodecNoLeading.read(buf).shouldBeEmpty()
val hasGuild = buf.readByte().toInt() != 0
hasGuild shouldBe false
val party = U8.read(buf)
@@ -28,6 +30,7 @@ class CharactersListPacketTest :
names shouldBe listOf("MacherRin", "astridefour", "MacherDer")
parties shouldBe listOf(0, 1, 0)
skinSlotCounts shouldBe listOf(5, 5, 5)
buf.remaining() shouldBe 0
}
@@ -30,6 +30,19 @@ class CreateCharacterPacketTest :
CreateCharacterPacketCodec.encodeToBytes(packet).toHex() shouldBe bytes.toHex()
}
test("splits a packed slot into a ten bit type and a six bit color") {
val bytes = fixture("game/c2s/03/female_hoenn.bin")
val packet = CreateCharacterPacketCodec.decodeBytes(bytes)
val hair = packet.appearance[SkinSlot.HAIR]!!
hair.type shouldBe 4.toUShort()
hair.color shouldBe 24.toUByte()
val leggings = packet.appearance[SkinSlot.LEGGINGS]!!
leggings.type shouldBe 0.toUShort()
leggings.color shouldBe 33.toUByte()
}
test("roundtrips the new male Hoenn character creation capture") {
val bytes = fixture("game/c2s/03/male_hoenn_32710.bin")
@@ -128,7 +128,15 @@ constructor(
ctx.send(buildCharacterList(state.userId))
return
}
characterStore.createCharacter(state.userId, name, gender, startingRegion)
val appearance = event.packet.appearance
characterStore.createCharacter(
state.userId,
name,
gender,
startingRegion,
skins = appearance.toMap(),
skinRegionSelectionIndex = appearance.regionSelectionIndex,
)
ctx.send(buildCharacterList(state.userId))
}
@@ -167,7 +175,7 @@ constructor(
characters.map { stored ->
CharacterEntry(
characterInfo = stored.info,
skinSet = SkinSet(),
skinSet = SkinSet(stored.info.skinRegionSelectionIndex, stored.skins),
guildId = null,
// Character selection shows the complete party.
pokemon = stored.pokemon,
@@ -295,7 +303,8 @@ constructor(
log.info { "Sending LoadEntity for character '${info.name}'" }
val facing = state.facingDirection
val loadEntity =
mapLoadService.createLoadEntity(info, facing, state.elevation, party = stored.pokemon)
mapLoadService.createLoadEntity(
info, facing, state.elevation, party = stored.pokemon, skins = stored.skins)
ctx.send(loadEntity)
npcService.spawnNpcsForMap(
@@ -3,8 +3,10 @@ package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.Skin
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.EntityStatus
import de.fiereu.openmmo.common.enums.SkinSlot
import de.fiereu.openmmo.maps.MapDef
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.codecs.SkinSet
@@ -27,10 +29,11 @@ constructor(
facing: Direction = Direction.DOWN,
z: Int = 0,
party: List<Pokemon> = emptyList(),
skins: Map<SkinSlot, Skin> = emptyMap(),
): LoadEntityPacket {
return LoadEntityPacket(
entityId = info.id,
skin = SkinSet(),
skin = SkinSet(info.skinRegionSelectionIndex, skins),
name = info.name,
regionId = info.positionRegionId.toInt(),
bankId = info.positionBankId.toInt(),
@@ -92,6 +92,6 @@ constructor(
val charId = state.characterId ?: return null
val stored = characterStore.getCharacter(charId) ?: return null
return mapLoadService.createLoadEntity(
stored.info, state.facingDirection, party = stored.pokemon)
stored.info, state.facingDirection, party = stored.pokemon, skins = stored.skins)
}
}
@@ -4,18 +4,22 @@ import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.Skin
import de.fiereu.openmmo.common.enums.Direction
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.common.enums.SkinSlot
import de.fiereu.openmmo.db.game.tables.records.CharacterFlagsRecord
import de.fiereu.openmmo.db.game.tables.records.CharacterItemsRecord
import de.fiereu.openmmo.db.game.tables.records.CharacterSkinsRecord
import de.fiereu.openmmo.db.game.tables.records.CharacterVarsRecord
import de.fiereu.openmmo.db.game.tables.records.CharactersRecord
import de.fiereu.openmmo.db.game.tables.records.PokemonRecord
import de.fiereu.openmmo.db.game.tables.references.CHARACTERS
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_FLAGS
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_ITEMS
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_SKINS
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_VARS
import de.fiereu.openmmo.db.game.tables.references.POKEMON
import javax.inject.Inject
@@ -110,6 +114,12 @@ constructor(
{ CHARACTER_VARS.CHARACTER_ID.eq(id).and(CHARACTER_VARS.VAR_KEY.eq(it)) },
{ key, value -> CharacterVarsRecord(id, key, value) },
)
tx.writeDelta(
CHARACTER_SKINS,
rowDelta(previous?.skins.orEmpty(), current.skins),
{ CHARACTER_SKINS.CHARACTER_ID.eq(id).and(CHARACTER_SKINS.SLOT.eq(it.name)) },
{ slot, skin -> skin.toRecord(id, slot) },
)
}
private fun StoredCharacter?.monstersById(): Map<Long, Pokemon> =
@@ -141,6 +151,10 @@ constructor(
.set(CHARACTER_VARS.VAR_VALUE, value)
.execute()
}
if (stored.skins.isNotEmpty()) {
tx.batchInsert(stored.skins.map { (slot, skin) -> skin.toRecord(stored.info.id, slot) })
.execute()
}
}
/** Loads pokemon and items for all rows in one query each instead of per character. */
@@ -172,6 +186,12 @@ constructor(
.fetch()
.groupBy({ it.characterId }, { it.varKey to it.varValue })
.mapValues { (_, pairs) -> pairs.toMap() }
val skinsByOwner: Map<Long, Map<SkinSlot, Skin>> =
dsl.selectFrom(CHARACTER_SKINS)
.where(CHARACTER_SKINS.CHARACTER_ID.`in`(ids))
.fetch()
.groupBy({ it.characterId }, { it.toSkin() })
.mapValues { (_, skins) -> skins.associateBy { it.slot } }
return rows.map { row ->
val monsters = monstersByOwner[row.id].orEmpty()
val (party, pc) = monsters.partition { it.container == PokemonContainer.PARTY }
@@ -182,6 +202,7 @@ constructor(
items = itemsByOwner[row.id].orEmpty().toMutableMap(),
storyFlags = flagsByOwner[row.id].orEmpty().toMutableSet(),
storyVars = varsByOwner[row.id].orEmpty().toMutableMap(),
skins = skinsByOwner[row.id].orEmpty(),
)
}
}
@@ -193,6 +214,7 @@ constructor(
name = name,
namePrefix = namePrefix,
rivalSex = rivalSex.toShort(),
skinRegionSelectionIndex = skinRegionSelectionIndex.toShort(),
lastLogin = lastLogin,
createdAt = createdAt,
money = money,
@@ -227,6 +249,7 @@ constructor(
namePrefix = namePrefix ?: "",
userId = userId,
rivalSex = rivalSex.toByte(),
skinRegionSelectionIndex = skinRegionSelectionIndex?.toInt() ?: 0,
lastLogin = lastLogin,
createdAt = createdAt,
money = money,
@@ -267,6 +290,21 @@ constructor(
)
}
private fun Skin.toRecord(characterId: Long, slot: SkinSlot): CharacterSkinsRecord =
CharacterSkinsRecord(
characterId = characterId,
slot = slot.name,
skinType = type?.toShort(),
skinColor = color?.toShort(),
)
private fun CharacterSkinsRecord.toSkin(): Skin =
Skin(
slot = SkinSlot.valueOf(slot),
type = skinType?.toUShort(),
color = skinColor?.toUByte(),
)
private fun Pokemon.toRecord(): PokemonRecord =
PokemonRecord(
id = id,
@@ -3,9 +3,11 @@ package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.Skin
import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.common.enums.SkinSlot
import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
@@ -38,6 +40,7 @@ data class StoredCharacter(
// Keys are opaque strings supplied by the content layer, so the store stays game agnostic.
val storyFlags: MutableSet<String> = mutableSetOf(),
val storyVars: MutableMap<String, Int> = mutableMapOf(),
val skins: Map<SkinSlot, Skin> = emptyMap(),
)
/**
@@ -73,6 +76,8 @@ constructor(
name: String,
gender: CharacterGender,
startingRegion: Region,
skins: Map<SkinSlot, Skin> = emptyMap(),
skinRegionSelectionIndex: Int = 0,
): StoredCharacter {
val female = gender == CharacterGender.FEMALE
val start = NewGameStarts.forRegion(startingRegion, female)
@@ -86,6 +91,7 @@ constructor(
userId = userId,
// This historical field stores the player's gender.
rivalSex = gender.wireValue,
skinRegionSelectionIndex = skinRegionSelectionIndex,
lastLogin = now,
createdAt = now,
money = 30000,
@@ -114,6 +120,7 @@ constructor(
mutableMapOf(),
storyFlags = start.storyFlags.toMutableSet(),
storyVars = start.storyVars.toMutableMap(),
skins = skins.toMap(),
)
repository.insertAggregate(stored)
characters[id] = stored
@@ -0,0 +1,14 @@
-- The appearance picked in the character creator. One row per occupied slot, keyed by the SkinSlot
-- enum name. Renaming an enum entry breaks stored data. Type and color are the packed 10 and 6 bit
-- fields the client sends.
CREATE TABLE character_skins (
character_id BIGINT NOT NULL REFERENCES characters (id) ON DELETE CASCADE,
slot VARCHAR(16) NOT NULL,
skin_type SMALLINT,
skin_color SMALLINT,
PRIMARY KEY (character_id, slot)
);
ALTER TABLE characters
ADD COLUMN skin_region_selection_index SMALLINT NOT NULL DEFAULT 0;
@@ -4,10 +4,12 @@ import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.Skin
import de.fiereu.openmmo.common.enums.Direction
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.common.enums.SkinSlot
import de.fiereu.openmmo.common.test.DockerAvailable
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_ITEMS
import de.fiereu.openmmo.db.game.tables.references.POKEMON
@@ -240,6 +242,44 @@ class CharacterRepositoryIT :
loaded.items shouldBe stored.items
}
test("insert and load round-trips the appearance") {
val stored =
aggregate(userId = 97).let {
it.copy(
info = it.info.copy(skinRegionSelectionIndex = 3),
skins =
mapOf(
SkinSlot.HAIR to Skin(SkinSlot.HAIR, 4u, 24u),
SkinSlot.EYES to Skin(SkinSlot.EYES, 15u, 0u),
),
)
}
repository.insertAggregate(stored)
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.info.skinRegionSelectionIndex shouldBe 3
loaded.skins shouldBe stored.skins
}
test("saveChanges rewrites a changed slot and drops a removed one") {
val stored =
aggregate(userId = 98).let {
it.copy(
skins =
mapOf(
SkinSlot.HAIR to Skin(SkinSlot.HAIR, 4u, 24u),
SkinSlot.HAT to Skin(SkinSlot.HAT, 2u, 7u),
))
}
repository.insertAggregate(stored)
val current = stored.copy(skins = mapOf(SkinSlot.HAIR to Skin(SkinSlot.HAIR, 9u, 24u)))
repository.saveChanges(stored, current)
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.skins shouldBe mapOf(SkinSlot.HAIR to Skin(SkinSlot.HAIR, 9u, 24u))
}
test("loadById returns null for an unknown id") {
repository.loadById(entityIds.newCharacterId()).shouldBeNull()
}
@@ -0,0 +1,70 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.Skin
import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.common.enums.SkinSlot
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.maps.shouldBeEmpty
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
private val CREATOR_SKINS =
mapOf(
SkinSlot.HAIR to Skin(SkinSlot.HAIR, 4u, 24u),
SkinSlot.EYES to Skin(SkinSlot.EYES, 15u, 0u),
SkinSlot.TOP to Skin(SkinSlot.TOP, 3u, 2u),
)
@OptIn(ExperimentalCoroutinesApi::class)
class CharacterSkinsTest :
FunSpec({
test("creation keeps the appearance the client picked") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val stored =
store.createCharacter(
1,
"Red",
CharacterGender.MALE,
Region.KANTO,
skins = CREATOR_SKINS,
skinRegionSelectionIndex = 3,
)
val cached = store.getCharacter(stored.info.id)!!
cached.skins shouldBe CREATOR_SKINS
cached.info.skinRegionSelectionIndex shouldBe 3
}
}
test("creation writes the appearance out with the rest of the aggregate") {
runTest {
val repository = FakeCharacterRepository()
val store = CharacterStore(repository, EntityIdService(), backgroundScope)
val id =
store
.createCharacter(
1, "Red", CharacterGender.MALE, Region.KANTO, skins = CREATOR_SKINS)
.info
.id
repository.saved[id]!!.skins shouldBe CREATOR_SKINS
}
}
test("a character created without an appearance has no slots") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val stored = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO)
stored.skins.shouldBeEmpty()
stored.info.skinRegionSelectionIndex shouldBe 0
}
}
})