diff --git a/codegen/src/generator/jte/maps/MapDef.jte b/codegen/src/generator/jte/maps/MapDef.jte index 8f4dbec..69976f8 100644 --- a/codegen/src/generator/jte/maps/MapDef.jte +++ b/codegen/src/generator/jte/maps/MapDef.jte @@ -45,4 +45,5 @@ internal val ${objectName}: MapDef = warps = ${RenderUtil.INSTANCE.warps(map.getWarps())}, npcs = ${RenderUtil.INSTANCE.npcs(map.getVisibleNpcs())}, bgEvents = ${RenderUtil.INSTANCE.bgEvents(map.getBgEvents())}, + onTransitionScript = "${map.getOnTransitionScript()}", ) diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/ParsedModel.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/ParsedModel.kt index c70c93f..1ea9ac7 100644 --- a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/ParsedModel.kt +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/ParsedModel.kt @@ -26,6 +26,8 @@ data class ParsedMap( val warps: List, val visibleNpcs: List, val bgEvents: List, + // Decomp label of the map's ON_TRANSITION script, or "" when the map has none. + val onTransitionScript: String, ) data class ParsedConnection( diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/PretGbaParser.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/PretGbaParser.kt index 1a13c28..4ba31b0 100644 --- a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/PretGbaParser.kt +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/maps/PretGbaParser.kt @@ -192,9 +192,20 @@ class PretGbaParser( warps = parseWarps(mapJson, ctx), visibleNpcs = parseNpcs(mapJson, mapDirName, ctx), bgEvents = parseBgEvents(mapJson), + onTransitionScript = parseOnTransitionScript(mapDirName), ) } + // The map's ON_TRANSITION script runs whenever the player enters the map. It sits in the map's + // scripts.inc _MapScripts table as a direct label, unlike the ON_FRAME/ON_WARP conditional + // tables. + private fun parseOnTransitionScript(mapDirName: String): String { + val file = File(rootDir, "data/maps/$mapDirName/scripts.inc") + if (!file.exists()) return "" + val re = Regex("""map_script\s+MAP_SCRIPT_ON_TRANSITION\s*,\s*(\w+)""") + return re.find(file.readText())?.groupValues?.get(1) ?: "" + } + private fun parseConnections(mapJson: JsonObject, ctx: Context): List = mapJson["connections"]?.jsonArrayOrNull()?.mapNotNull { conn -> val obj = conn.jsonObject diff --git a/codegen/src/main/kotlin/de/fiereu/openmmo/maps/MapDef.kt b/codegen/src/main/kotlin/de/fiereu/openmmo/maps/MapDef.kt index d9b5eb1..57dbdc1 100644 --- a/codegen/src/main/kotlin/de/fiereu/openmmo/maps/MapDef.kt +++ b/codegen/src/main/kotlin/de/fiereu/openmmo/maps/MapDef.kt @@ -32,6 +32,8 @@ class MapDef( val warps: List = emptyList(), val npcs: List = emptyList(), val bgEvents: List = emptyList(), + /** Decomp label of the script that runs when a player enters this map, or "" if none. */ + val onTransitionScript: String = "", private val blockData: String = "", private val behaviorData: String = "", ) { diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/ScriptRunner.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/ScriptRunner.kt new file mode 100644 index 0000000..c772b71 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/ScriptRunner.kt @@ -0,0 +1,53 @@ +package de.fiereu.openmmo.server.game.script + +import de.fiereu.network.SessionContext +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.SCRIPT_SCOPE +import io.github.oshai.kotlinlogging.KotlinLogging +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +private val log = KotlinLogging.logger {} + +/** + * Launches a [Script] on the connection's own coroutine scope so it can wait on a dialog without + * blocking packet handling. Shared by every script trigger (npc/sign interactions and map entry). + * Claiming the dialog first stops a second trigger from starting a parallel script on the same + * player, and the dialog is always closed when the script ends. + */ +@Singleton +class ScriptRunner +@Inject +constructor( + private val dialogService: DialogService, + private val storyService: StoryService, +) { + fun run(session: SessionContext, state: PlayerState, script: Script, entityId: Long) { + state.inDialog = true + val scope = + session.attributes.getOrPut(SCRIPT_SCOPE) { + CoroutineScope(SupervisorJob() + Dispatchers.Default) + } + val ctx = ScriptContext(session, state, entityId, dialogService, storyService) + scope.launch { + try { + script.run(ctx) + } catch (e: CancellationException) { + throw e + } catch (e: NotImplementedError) { + log.info { "Script not ported yet for entity $entityId" } + } catch (e: Exception) { + log.error(e) { "Script failed for entity $entityId" } + } finally { + dialogService.close(session, state) + } + } + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/generated/hoenn/LittlerootTown.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/generated/hoenn/LittlerootTown.kt index 0b1603b..e917fd9 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/generated/hoenn/LittlerootTown.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/generated/hoenn/LittlerootTown.kt @@ -3,6 +3,7 @@ package de.fiereu.openmmo.server.game.script.generated.hoenn import de.fiereu.openmmo.dialog.generated.hoenn.LittlerootTown import de.fiereu.openmmo.server.game.script.Script import de.fiereu.openmmo.server.game.script.ScriptContext +import de.fiereu.openmmo.story.generated.hoenn.HoennFlags /** * Not ported yet. Decomp body: @@ -21,6 +22,23 @@ internal object LittlerootTown_EventScript_Twin : Script { override suspend fun run(ctx: ScriptContext) = TODO("port LittlerootTown_EventScript_Twin") } +/** + * Runs whenever the player enters Littleroot Town. Decomp body: + * ``` + * setflag FLAG_VISITED_LITTLEROOT_TOWN + * call Common_EventScript_SetupRivalGfxId + * call_if_eq VAR_LITTLEROOT_INTRO_STATE, 2, LittlerootTown_EventScript_MoveMomToMaysDoor + * ``` + * + * The two calls set the rival's sprite and move mom for the intro, which need object and movement + * scripting that does not exist yet, so only the flag is ported for now. + */ +internal object LittlerootTown_OnTransition : Script { + override suspend fun run(ctx: ScriptContext) { + ctx.setFlag(HoennFlags.FLAG_VISITED_LITTLEROOT_TOWN) + } +} + internal object LittlerootTown_EventScript_FatMan : Script { override suspend fun run(ctx: ScriptContext) = ctx.say(LittlerootTown.CanUsePCToStoreItems) } @@ -97,6 +115,7 @@ internal object LittlerootTown_EventScript_MaysHouseSign : Script { internal val LittlerootTownScripts: Map = mapOf( + "LittlerootTown_OnTransition" to LittlerootTown_OnTransition, "LittlerootTown_EventScript_Twin" to LittlerootTown_EventScript_Twin, "LittlerootTown_EventScript_FatMan" to LittlerootTown_EventScript_FatMan, "LittlerootTown_EventScript_Boy" to LittlerootTown_EventScript_Boy, diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/InteractionService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/InteractionService.kt index ff6a216..87c800c 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/InteractionService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/InteractionService.kt @@ -7,21 +7,15 @@ import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.net.game.packets.EntityInteractPacket import de.fiereu.openmmo.net.game.packets.TileInteractPacket import de.fiereu.openmmo.server.game.script.Script -import de.fiereu.openmmo.server.game.script.ScriptContext import de.fiereu.openmmo.server.game.script.ScriptRegistry +import de.fiereu.openmmo.server.game.script.ScriptRunner import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.session.PlayerState -import de.fiereu.openmmo.server.game.session.SCRIPT_SCOPE import de.fiereu.openmmo.server.game.storage.CharacterStore import de.fiereu.openmmo.server.game.storage.StoredCharacter import io.github.oshai.kotlinlogging.KotlinLogging import javax.inject.Inject import javax.inject.Singleton -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.launch private val log = KotlinLogging.logger {} @@ -32,9 +26,8 @@ constructor( private val npcService: NpcService, private val mapManager: MapManager, private val characterStore: CharacterStore, - private val dialogService: DialogService, private val scriptRegistry: ScriptRegistry, - private val storyService: StoryService, + private val scriptRunner: ScriptRunner, ) { /** The player pressed the action button on a specific entity, that is an npc. */ @@ -122,32 +115,10 @@ constructor( (eventDir == "BG_EVENT_PLAYER_FACING_WEST" && facing == Direction.LEFT) || (eventDir == "BG_EVENT_PLAYER_FACING_EAST" && facing == Direction.RIGHT) - /** Runs [script] on the connection scope so it can wait on a dialog without blocking packets. */ private fun runScript( session: SessionContext, state: PlayerState, script: Script, entityId: Long, - ) { - // Claim the dialog now so a second interaction cannot launch a parallel script. - state.inDialog = true - val scope = - session.attributes.getOrPut(SCRIPT_SCOPE) { - CoroutineScope(SupervisorJob() + Dispatchers.Default) - } - val ctx = ScriptContext(session, state, entityId, dialogService, storyService) - scope.launch { - try { - script.run(ctx) - } catch (e: CancellationException) { - throw e - } catch (e: NotImplementedError) { - log.info { "Script not ported yet for entity $entityId" } - } catch (e: Exception) { - log.error(e) { "Script failed for entity $entityId" } - } finally { - dialogService.close(session, state) - } - } - } + ) = scriptRunner.run(session, state, script, entityId) } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt index 2a878ff..5b2da38 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt @@ -73,6 +73,7 @@ constructor( private val mapManager: MapManager, private val characterStore: CharacterStore, private val presenceService: PresenceService, + private val mapScriptService: MapScriptService, ) { fun onJoinGame(event: PacketEvent) { @@ -330,6 +331,10 @@ constructor( ctx.send(RenderScreenPacket(true)) + mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId)?.let { map -> + mapScriptService.onMapEnter(ctx, state, map) + } + socialService.sendFriendList(ctx) log.info { "Player $charId spawned in bank=$bankId map=$mapId" } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MapScriptService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MapScriptService.kt new file mode 100644 index 0000000..f24db94 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MapScriptService.kt @@ -0,0 +1,38 @@ +package de.fiereu.openmmo.server.game.services + +import de.fiereu.network.SessionContext +import de.fiereu.openmmo.maps.MapDef +import de.fiereu.openmmo.server.game.script.ScriptRegistry +import de.fiereu.openmmo.server.game.script.ScriptRunner +import de.fiereu.openmmo.server.game.session.PlayerState +import io.github.oshai.kotlinlogging.KotlinLogging +import javax.inject.Inject +import javax.inject.Singleton + +private val log = KotlinLogging.logger {} + +/** + * Runs a map's scripts when a player enters it. Today that is the decomp ON_TRANSITION script, + * which fires on every entry however the player got there (login, a warp, or walking across a map + * connection). The conditional ON_FRAME and ON_WARP tables are a later addition. + */ +@Singleton +class MapScriptService +@Inject +constructor( + private val scriptRegistry: ScriptRegistry, + private val scriptRunner: ScriptRunner, +) { + fun onMapEnter(session: SessionContext, state: PlayerState, map: MapDef) { + // A script is already running for this player, do not start a second one on top of it. + if (state.inDialog) return + val label = map.onTransitionScript + if (label.isEmpty()) return + val script = scriptRegistry.forLabel(label) + if (script == null) { + log.debug { "Map ${map.bankId}:${map.mapId} on-transition script $label is not ported yet" } + return + } + scriptRunner.run(session, state, script, entityId = -1) + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt index 45795f7..09d5009 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt @@ -29,6 +29,7 @@ constructor( private val mapManager: MapManager, private val characterStore: CharacterStore, private val encounterService: EncounterService, + private val mapScriptService: MapScriptService, ) { /** One step. The client sends the tile it left and the direction, the server derives the rest. */ @@ -195,6 +196,9 @@ constructor( y = targetY.toInt(), direction = direction, )) + + if (state != null) mapScriptService.onMapEnter(ctx, state, map) + log.info { "Player $charId edge-transitioned to bank=$targetBank map=$targetMap" } } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt index e1fa912..ed247bd 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt @@ -24,6 +24,7 @@ constructor( private val mapManager: MapManager, private val characterStore: CharacterStore, private val presenceService: PresenceService, + private val mapScriptService: MapScriptService, ) { fun executeWarp(ctx: SessionContext, charId: Long, warp: WarpTile) { @@ -120,6 +121,8 @@ constructor( presenceService.refresh(ctx) + if (state != null && destMap != null) mapScriptService.onMapEnter(ctx, state, destMap) + log.info { "Player $charId warped to bank=${warp.targetBankId} map=${warp.targetMapId}" } } } diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/script/MapTransitionScriptTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/script/MapTransitionScriptTest.kt new file mode 100644 index 0000000..6065ce9 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/script/MapTransitionScriptTest.kt @@ -0,0 +1,35 @@ +package de.fiereu.openmmo.server.game.script + +import de.fiereu.openmmo.server.game.script.generated.hoenn.LittlerootTown_OnTransition +import de.fiereu.openmmo.server.game.services.DialogService +import de.fiereu.openmmo.server.game.services.StoryService +import de.fiereu.openmmo.server.game.session.PLAYER_STATE +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 de.fiereu.openmmo.server.game.testsupport.FakeSession +import de.fiereu.openmmo.story.generated.hoenn.HoennFlags +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 MapTransitionScriptTest : + FunSpec({ + test("Littleroot on-transition sets the visited flag on the player") { + runTest { + val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope) + val charId = store.createCharacter(1, "Ash").info.id + val story = StoryService(store) + + val session = FakeSession(characterId = charId) + val state = session.attributes[PLAYER_STATE]!! + val ctx = ScriptContext(session, state, entityId = -1, DialogService(), story) + + LittlerootTown_OnTransition.run(ctx) + + story.isFlagSet(charId, HoennFlags.FLAG_VISITED_LITTLEROOT_TOWN) shouldBe true + } + } + })