feat(game): persist per-character story flags and vars

This commit is contained in:
Fiereu committed 2026-07-26 14:36:07 +02:00
1 parent 4879082eb0
commit 023f4eb305
13 files changed
+347 -2

No files matched your search

+12
View File
@@ -53,6 +53,18 @@ jteCodegen {
inputDirs.from(sourceDecompDir) inputDirs.from(sourceDecompDir)
extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath)) extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath))
} }
// Per region flag and var key constants for scripts. Names come from each decomp, so this is by
// region like maps. The generic story store in server.game does not depend on these, they are the
// GBA adapter that gives ported scripts readable keys.
register("story") {
mainClass.set("de.fiereu.openmmo.codegen.story.Main")
inputDirs.from(
regionSources.values.map { rootProject.layout.projectDirectory.dir("decomp/$it") })
extraArgs.set(
regionSources.map { (region, decomp) ->
"$region|${rootProject.layout.projectDirectory.dir("decomp/$decomp").asFile.absolutePath}"
})
}
register("typechart") { register("typechart") {
mainClass.set("de.fiereu.openmmo.codegen.typechart.Main") mainClass.set("de.fiereu.openmmo.codegen.typechart.Main")
inputDirs.from(sourceDecompDir) inputDirs.from(sourceDecompDir)
@@ -0,0 +1,17 @@
@import java.util.List
@param String pkg
@param String objectName
@param String namespace
@param List<String> names
package ${pkg}
/**
* Story keys generated from the GBA decomp. Each value is the region namespaced key a script hands
* to ScriptContext (setFlag/isFlagSet, setVar/getVar). Generated, do not edit by hand.
*/
object ${objectName} {
@for(String name : names)
const val ${name} = "${namespace}/${name}"
@endfor
}
@@ -0,0 +1,23 @@
package de.fiereu.openmmo.codegen.story
import java.io.File
/**
* Pulls the flag and var names out of a GBA decomp. Only the names matter here, the numeric values
* are the client's concern and are not needed to key the game agnostic story store. The FLAG_/VAR_
* prefix match skips the range markers like TEMP_FLAGS_START and FLAGS_COUNT on its own.
*/
object FlagVarParser {
fun flags(decompDir: File): List<String> =
names(File(decompDir, "include/constants/flags.h"), "FLAG_")
fun vars(decompDir: File): List<String> =
names(File(decompDir, "include/constants/vars.h"), "VAR_")
private fun names(file: File, prefix: String): List<String> {
require(file.exists()) { "Missing ${file.path}" }
val re = Regex("""^#define\s+($prefix\w+)\b""")
return file.readLines().mapNotNull { re.find(it.trim())?.groupValues?.get(1) }.distinct()
}
}
@@ -0,0 +1,23 @@
@file:JvmName("Main")
package de.fiereu.openmmo.codegen.story
import java.io.File
fun main(args: Array<String>) {
require(args.size >= 4) {
"Usage: <output-dir> <templates-dir> <class-cache-dir> <region|decomp>... got ${args.toList()}"
}
val outputDir = File(args[0])
val templatesDir = File(args[1])
val classCacheDir = File(args[2])
for (spec in args.drop(3)) {
val (region, decomp) = spec.split("|")
val decompDir = File(decomp)
val flags = FlagVarParser.flags(decompDir)
val vars = FlagVarParser.vars(decompDir)
println("[story] $region: parsed ${flags.size} flags, ${vars.size} vars from $decompDir")
StoryConstantsRenderer(region, templatesDir, outputDir, classCacheDir).render(flags, vars)
}
}
@@ -0,0 +1,61 @@
package de.fiereu.openmmo.codegen.story
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.FileOutput
import gg.jte.resolve.DirectoryCodeResolver
import java.io.File
/**
* Emits one Kotlin object of flag key constants and one of var key constants per region. Each
* constant value is the region namespaced story key ("hoenn/FLAG_ADVENTURE_STARTED") that scripts
* hand to [de.fiereu.openmmo.server.game.script.ScriptContext]. The namespace keeps the two
* regions' overlapping names from colliding in the store.
*/
class StoryConstantsRenderer(
region: String,
private val templatesDir: File,
private val outputDir: File,
private val classCacheDir: File,
) {
private val namespace = region
private val basePackage = "de.fiereu.openmmo.story.generated.$region"
private val objectPrefix = region.replaceFirstChar { it.uppercase() }
fun render(flags: List<String>, vars: List<String>) {
classCacheDir.mkdirs()
val engine =
TemplateEngine.create(
DirectoryCodeResolver(templatesDir.toPath()),
classCacheDir.toPath(),
ContentType.Plain,
)
val packageRoot = File(outputDir, basePackage.replace('.', '/'))
if (packageRoot.exists()) packageRoot.deleteRecursively()
packageRoot.mkdirs()
write(engine, packageRoot, "${objectPrefix}Flags", flags)
write(engine, packageRoot, "${objectPrefix}Vars", vars)
}
private fun write(
engine: TemplateEngine,
packageRoot: File,
objectName: String,
names: List<String>,
) {
FileOutput(File(packageRoot, "$objectName.kt").toPath()).use { out ->
engine.render(
"StoryConstants.jte",
mapOf(
"pkg" to basePackage,
"objectName" to objectName,
"namespace" to namespace,
"names" to names,
),
out,
)
}
}
}
@@ -3,9 +3,10 @@ package de.fiereu.openmmo.server.game.script
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.dialog.DialogLine import de.fiereu.openmmo.common.dialog.DialogLine
import de.fiereu.openmmo.server.game.services.DialogService import de.fiereu.openmmo.server.game.services.DialogService
import de.fiereu.openmmo.server.game.services.StoryService
import de.fiereu.openmmo.server.game.session.PlayerState import de.fiereu.openmmo.server.game.session.PlayerState
/** What a [Script] uses to show dialog to the player it interacted with. */ /** What a [Script] uses to talk to the player it interacted with and read or write story state. */
class ScriptContext class ScriptContext
internal constructor( internal constructor(
private val session: SessionContext, private val session: SessionContext,
@@ -13,13 +14,35 @@ internal constructor(
/** The npc the player talked to, or -1 for a sign. */ /** The npc the player talked to, or -1 for a sign. */
val entityId: Long, val entityId: Long,
private val dialog: DialogService, private val dialog: DialogService,
private val story: StoryService,
) { ) {
private val characterId: Long?
get() = state.characterId
/** Show [line] as a sign and wait for the player to close it. */ /** Show [line] as a sign and wait for the player to close it. */
suspend fun sign(line: DialogLine) = dialog.showAndWait(session, state, line.textId, SIGN, -1) suspend fun sign(line: DialogLine) = dialog.showAndWait(session, state, line.textId, SIGN, -1)
/** Show [line] from the interacted entity and wait for the player to go on. */ /** Show [line] from the interacted entity and wait for the player to go on. */
suspend fun say(line: DialogLine) = dialog.showAndWait(session, state, line.textId, NPC, entityId) suspend fun say(line: DialogLine) = dialog.showAndWait(session, state, line.textId, NPC, entityId)
/** True if the story [flag] is set. Keys come from the content layer, for example HoennFlags. */
fun isFlagSet(flag: String): Boolean = characterId?.let { story.isFlagSet(it, flag) } ?: false
fun setFlag(flag: String) {
characterId?.let { story.setFlag(it, flag) }
}
fun clearFlag(flag: String) {
characterId?.let { story.clearFlag(it, flag) }
}
/** The story var [key], or 0 if it was never set. */
fun getVar(key: String): Int = characterId?.let { story.getVar(it, key) } ?: 0
fun setVar(key: String, value: Int) {
characterId?.let { story.setVar(it, key, value) }
}
private companion object { private companion object {
// Sign boxes have no speaker, npc boxes point at the entity. // Sign boxes have no speaker, npc boxes point at the entity.
const val SIGN = 3 const val SIGN = 3
@@ -34,6 +34,7 @@ constructor(
private val characterStore: CharacterStore, private val characterStore: CharacterStore,
private val dialogService: DialogService, private val dialogService: DialogService,
private val scriptRegistry: ScriptRegistry, private val scriptRegistry: ScriptRegistry,
private val storyService: StoryService,
) { ) {
/** The player pressed the action button on a specific entity, that is an npc. */ /** The player pressed the action button on a specific entity, that is an npc. */
@@ -134,7 +135,7 @@ constructor(
session.attributes.getOrPut(SCRIPT_SCOPE) { session.attributes.getOrPut(SCRIPT_SCOPE) {
CoroutineScope(SupervisorJob() + Dispatchers.Default) CoroutineScope(SupervisorJob() + Dispatchers.Default)
} }
val ctx = ScriptContext(session, state, entityId, dialogService) val ctx = ScriptContext(session, state, entityId, dialogService, storyService)
scope.launch { scope.launch {
try { try {
script.run(ctx) script.run(ctx)
@@ -213,6 +213,15 @@ constructor(
preloadMapAndJoin(ctx, state, info) preloadMapAndJoin(ctx, state, info)
} }
// TODO Sync persisted story flags and vars to the client
// The server now owns per character story flags and vars (see StoryService), but the client
// still
// gets the hardcoded WORLD_FLAG_GROUPS blob and empty badges/variables below. Map the stored
// flags into the world-flag table and the stored vars into LocalPlayerStatePacket.variables so
// the
// overworld (hidden or shown npcs, map states, badges) reflects real progress. This needs the
// GBA
// numeric flag/var ids, so extend the story codegen to also emit the name to id map per region.
// The full local-player state snapshot the client loads on login. Missing it leaves player state // 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). // uninitialised and the client crashes reading it (for example when opening the battle bag).
private fun buildLocalPlayerState( private fun buildLocalPlayerState(
@@ -0,0 +1,29 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.server.game.storage.CharacterStore
import javax.inject.Inject
import javax.inject.Singleton
/**
* Reads and writes a character's story progression: boolean flags and named integer vars. This is
* the game agnostic story state. Keys are opaque strings, so any content source (the GBA decomp
* scripts today, a hand authored or non GBA game later) can drive it through the same api.
*
* Missing flag means unset, missing var means 0, matching how the decomp scripts treat them.
*/
@Singleton
class StoryService @Inject constructor(private val characterStore: CharacterStore) {
fun isFlagSet(characterId: Long, flag: String): Boolean =
characterStore.getCharacter(characterId)?.storyFlags?.contains(flag) ?: false
fun setFlag(characterId: Long, flag: String) = characterStore.setStoryFlag(characterId, flag)
fun clearFlag(characterId: Long, flag: String) = characterStore.clearStoryFlag(characterId, flag)
fun getVar(characterId: Long, key: String): Int =
characterStore.getCharacter(characterId)?.storyVars?.get(key) ?: 0
fun setVar(characterId: Long, key: String, value: Int) =
characterStore.setStoryVar(characterId, key, value)
}
@@ -9,7 +9,9 @@ import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.db.game.tables.records.CharactersRecord 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.records.PokemonRecord
import de.fiereu.openmmo.db.game.tables.references.CHARACTERS 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_ITEMS
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_VARS
import de.fiereu.openmmo.db.game.tables.references.POKEMON import de.fiereu.openmmo.db.game.tables.references.POKEMON
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Named import javax.inject.Named
@@ -75,6 +77,19 @@ constructor(
.set(CHARACTER_ITEMS.QUANTITY, quantity) .set(CHARACTER_ITEMS.QUANTITY, quantity)
.execute() .execute()
} }
for (flag in stored.storyFlags) {
tx.insertInto(CHARACTER_FLAGS)
.set(CHARACTER_FLAGS.CHARACTER_ID, stored.info.id)
.set(CHARACTER_FLAGS.FLAG_KEY, flag)
.execute()
}
for ((key, value) in stored.storyVars) {
tx.insertInto(CHARACTER_VARS)
.set(CHARACTER_VARS.CHARACTER_ID, stored.info.id)
.set(CHARACTER_VARS.VAR_KEY, key)
.set(CHARACTER_VARS.VAR_VALUE, value)
.execute()
}
} }
/** Loads pokemon and items for all rows in one query each instead of per character. */ /** Loads pokemon and items for all rows in one query each instead of per character. */
@@ -94,6 +109,18 @@ constructor(
.fetch() .fetch()
.groupBy({ it.characterId }, { it.itemId to it.quantity }) .groupBy({ it.characterId }, { it.itemId to it.quantity })
.mapValues { (_, pairs) -> pairs.toMap() } .mapValues { (_, pairs) -> pairs.toMap() }
val flagsByOwner: Map<Long, Set<String>> =
dsl.selectFrom(CHARACTER_FLAGS)
.where(CHARACTER_FLAGS.CHARACTER_ID.`in`(ids))
.fetch()
.groupBy({ it.characterId }, { it.flagKey })
.mapValues { (_, keys) -> keys.toSet() }
val varsByOwner: Map<Long, Map<String, Int>> =
dsl.selectFrom(CHARACTER_VARS)
.where(CHARACTER_VARS.CHARACTER_ID.`in`(ids))
.fetch()
.groupBy({ it.characterId }, { it.varKey to it.varValue })
.mapValues { (_, pairs) -> pairs.toMap() }
return rows.map { row -> return rows.map { row ->
val monsters = monstersByOwner[row.id].orEmpty() val monsters = monstersByOwner[row.id].orEmpty()
val (party, pc) = monsters.partition { it.container == PokemonContainer.PARTY } val (party, pc) = monsters.partition { it.container == PokemonContainer.PARTY }
@@ -102,6 +129,8 @@ constructor(
pokemon = party.toMutableList(), pokemon = party.toMutableList(),
pcStorage = pc.toMutableList(), pcStorage = pc.toMutableList(),
items = itemsByOwner[row.id].orEmpty().toMutableMap(), items = itemsByOwner[row.id].orEmpty().toMutableMap(),
storyFlags = flagsByOwner[row.id].orEmpty().toMutableSet(),
storyVars = varsByOwner[row.id].orEmpty().toMutableMap(),
) )
} }
} }
@@ -27,6 +27,10 @@ data class StoredCharacter(
val pokemon: MutableList<Pokemon>, val pokemon: MutableList<Pokemon>,
val pcStorage: MutableList<Pokemon>, val pcStorage: MutableList<Pokemon>,
val items: MutableMap<Int, Int>, val items: MutableMap<Int, Int>,
// Story progression. Flags are set/unset booleans, vars are named integers that default to 0.
// 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(),
) )
/** /**
@@ -165,6 +169,31 @@ constructor(
markDirty(characterId) markDirty(characterId)
} }
/** Set a story flag. Copies the set so flusher snapshots never see a half-updated collection. */
fun setStoryFlag(characterId: Long, flag: String) {
val stored = characters[characterId] ?: return
if (flag in stored.storyFlags) return
characters[characterId] = stored.copy(storyFlags = (stored.storyFlags + flag).toMutableSet())
markDirty(characterId)
}
fun clearStoryFlag(characterId: Long, flag: String) {
val stored = characters[characterId] ?: return
if (flag !in stored.storyFlags) return
characters[characterId] = stored.copy(storyFlags = (stored.storyFlags - flag).toMutableSet())
markDirty(characterId)
}
/** Set a story var. A value of 0 is the default, so it drops the row instead of storing it. */
fun setStoryVar(characterId: Long, key: String, value: Int) {
val stored = characters[characterId] ?: return
val newVars = stored.storyVars.toMutableMap()
if (value == 0) newVars.remove(key) else newVars[key] = value
if (newVars == stored.storyVars) return
characters[characterId] = stored.copy(storyVars = newVars)
markDirty(characterId)
}
fun startPeriodicFlush() { fun startPeriodicFlush() {
periodicJob = periodicJob =
flushScope.launch { flushScope.launch {
@@ -0,0 +1,16 @@
-- Per character story progression. A flag is a boolean (a row means the flag is set) and a var is
-- a named integer. Keys are opaque strings owned by the content layer (the GBA decomp adapter today,
-- other games later), so the schema stays game agnostic and never encodes GBA flag/var numbering.
CREATE TABLE character_flags (
character_id BIGINT NOT NULL REFERENCES characters (id) ON DELETE CASCADE,
flag_key VARCHAR(128) NOT NULL,
PRIMARY KEY (character_id, flag_key)
);
CREATE TABLE character_vars (
character_id BIGINT NOT NULL REFERENCES characters (id) ON DELETE CASCADE,
var_key VARCHAR(128) NOT NULL,
var_value INT NOT NULL,
PRIMARY KEY (character_id, var_key)
);
@@ -0,0 +1,73 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class StoryServiceTest :
FunSpec({
test("flags default unset, can be set and cleared") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
val story = StoryService(store)
story.isFlagSet(id, "hoenn/FLAG_ADVENTURE_STARTED") shouldBe false
story.setFlag(id, "hoenn/FLAG_ADVENTURE_STARTED")
story.isFlagSet(id, "hoenn/FLAG_ADVENTURE_STARTED") shouldBe true
story.clearFlag(id, "hoenn/FLAG_ADVENTURE_STARTED")
story.isFlagSet(id, "hoenn/FLAG_ADVENTURE_STARTED") shouldBe false
}
}
test("vars default to 0, store a value, and drop back to default on 0") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
val story = StoryService(store)
story.getVar(id, "hoenn/VAR_LITTLEROOT_TOWN_STATE") shouldBe 0
story.setVar(id, "hoenn/VAR_LITTLEROOT_TOWN_STATE", 3)
story.getVar(id, "hoenn/VAR_LITTLEROOT_TOWN_STATE") shouldBe 3
story.setVar(id, "hoenn/VAR_LITTLEROOT_TOWN_STATE", 0)
story.getVar(id, "hoenn/VAR_LITTLEROOT_TOWN_STATE") shouldBe 0
store.getCharacter(id)!!.storyVars.containsKey("hoenn/VAR_LITTLEROOT_TOWN_STATE") shouldBe
false
}
}
test("setFlag copies instead of mutating the cached set") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
val before = store.getCharacter(id)!!.storyFlags
StoryService(store).setFlag(id, "hoenn/FLAG_RESCUED_BIRCH")
before.size shouldBe 0
store.getCharacter(id)!!.storyFlags.size shouldBe 1
}
}
test("flags and vars persist through a flush") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
val story = StoryService(store)
story.setFlag(id, "hoenn/FLAG_ADVENTURE_STARTED")
story.setVar(id, "hoenn/VAR_LITTLEROOT_TOWN_STATE", 4)
store.flushAll()
repo.saved[id]!!.storyFlags shouldBe setOf("hoenn/FLAG_ADVENTURE_STARTED")
repo.saved[id]!!.storyVars shouldBe mapOf("hoenn/VAR_LITTLEROOT_TOWN_STATE" to 4)
}
}
})