fix(game): stop running the warp arrival twice (#94)

* fix(game): use the npc's own region for map and sprite lookups

* fix(game): trigger warps by their tile behaviour

* fix(game): classify every warp metatile behaviour the decomp accepts

* fix(game): stop running the warp arrival twice

* fix(game): stop a failed warp from freezing the player and leaking its old map

* fix(game): give every warp a deadline and hand the map group over on arrival

* fix(game): check the warp target first and stop the deadline outliving the session
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-07 16:14:51 +02:00
1 parent 085407ccf1
commit b615b65334
8 files changed
+472 -51

No files matched your search

@@ -184,7 +184,7 @@ internal constructor(
regionId.toByte(), bankId.toByte(), mapId.toByte(), x.toShort(), y.toShort(), facing))
/** Warps the player without door movement. */
fun warp(regionId: Int, bankId: Int, mapId: Int, x: Int, y: Int, facing: Direction) {
suspend fun warp(regionId: Int, bankId: Int, mapId: Int, x: Int, y: Int, facing: Direction) {
checkNotNull(warp) { "Script warp service is unavailable" }
.warp(
session,
@@ -34,6 +34,7 @@ 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.server.game.session.PENDING_MAP_LOAD
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
@@ -330,6 +331,11 @@ constructor(
log.warn { "RequestPlayer without active character" }
return
}
// The client asks for its player once a map transition is done, so the warp ends here. The
// waiter is only cleared at the end, so a throw in between leaves the deadline to rescue it.
state.justWarped = false
val pendingLoad = ctx.attributes[PENDING_MAP_LOAD]
val stored = characterStore.getCharacter(charId)
if (stored == null) {
log.warn { "RequestPlayer for unknown character $charId" }
@@ -339,7 +345,8 @@ constructor(
log.info { "Sending LoadEntity for character '${info.name}'" }
val facing = state.facingDirection
val loadEntity = mapLoadService.createLoadEntity(info, facing, party = stored.pokemon)
val loadEntity =
mapLoadService.createLoadEntity(info, facing, state.elevation, party = stored.pokemon)
ctx.send(loadEntity)
npcService.spawnNpcsForMap(
@@ -358,15 +365,19 @@ constructor(
state.x = info.positionX
state.y = info.positionY
// The client dropped its entities with the map cache, so always re-exchange snapshots.
presenceService.enter(ctx)
ctx.send(RenderScreenPacket(true))
// An entry script may fade back out, so it runs after the fade this arrival owns.
mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId)?.let { map ->
mapScriptService.onMapEnter(ctx, state, map)
}
socialService.sendFriendList(ctx)
if (ctx.attributes[PENDING_MAP_LOAD] === pendingLoad) ctx.attributes.remove(PENDING_MAP_LOAD)
pendingLoad?.complete(Unit)
log.info { "Player $charId spawned in bank=$bankId map=$mapId" }
}
@@ -95,9 +95,9 @@ constructor(
val atServerTile = msg.x == fromX && msg.y == fromY
if (state.justWarped) {
// Drop movement packets sent before the warp completed.
if (!atServerTile) return
state.justWarped = false
// Drop every step until the client asks for its player, else one left over from the old map
// can fire a second warp.
return
} else if (!atServerTile) {
log.debug {
"DESYNC: char=$charId claims (${msg.x}, ${msg.y}), server has ($fromX, $fromY), resetting"
@@ -7,10 +7,20 @@ import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionKind
import de.fiereu.openmmo.net.game.packets.MapTransitionPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.storage.CharacterStore
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeoutOrNull
private val log = KotlinLogging.logger {}
// A cutscene must not hang if the client never answers the transition.
private val MAP_LOAD_TIMEOUT = 10.seconds
/** A direct, no-auto-step warp for cutscenes (the decomp's `warpsilent`). */
@Singleton
@@ -21,17 +31,22 @@ constructor(
private val mapLoadService: MapLoadService,
private val characterStore: CharacterStore,
private val presenceService: PresenceService,
private val npcService: NpcService,
) {
fun warp(
/** Warps and waits until the client has loaded the destination, so the script can go on. */
suspend fun warp(
session: SessionContext,
state: PlayerState,
destination: DynamicWarp,
) {
val characterId = state.characterId ?: return
val stored = characterStore.getCharacter(characterId) ?: return
val map =
mapManager.getMap(destination.regionId, destination.bankId, destination.mapId) ?: return
val map = mapManager.getMap(destination.regionId, destination.bankId, destination.mapId)
if (map == null) {
log.warn {
"Map not found for scripted warp ${destination.regionId}:${destination.bankId}:${destination.mapId}"
}
return
}
val info =
stored.info.copy(
positionRegionId = destination.regionId,
@@ -44,27 +59,40 @@ constructor(
characterStore.updateCharacter(info)
characterStore.flushCharacterAsync(characterId)
state.justWarped = true
// Leave now, so the old map's observers do not keep a ghost for the whole transition.
presenceService.leave(session)
state.regionId = destination.regionId.toInt()
state.bankId = destination.bankId.toInt()
state.mapId = destination.mapId.toInt()
state.x = destination.x
state.y = destination.y
state.elevation = map.tileAt(destination.x.toInt(), destination.y.toInt())?.elevation ?: 0
state.facingDirection = destination.facing
val loaded = CompletableDeferred<Unit>()
session.attributes[PENDING_MAP_LOAD] = loaded
session.send(MapTransitionPacket())
session.send(RenderScreenPacket(false))
session.send(MapTransitionAckPacket(MapTransitionKind.WARP))
mapLoadService.resetClientCache(session, map)
session.send(mapManager.createLoadMapPacket(map, reloadPlayer = true, deleteCache = true))
mapLoadService.preloadConnectedMaps(session, map, depth = 1, reloadPlayer = true)
session.send(mapLoadService.createLoadEntity(info, destination.facing))
npcService.spawnNpcsForMap(
session,
destination.bankId.toInt(),
destination.mapId.toInt(),
destination.regionId.toInt(),
)
presenceService.refresh(session)
try {
if (withTimeoutOrNull(MAP_LOAD_TIMEOUT) { loaded.await() } == null) {
log.warn {
"Character $characterId did not load ${destination.bankId}:${destination.mapId}"
}
// No arrival will follow, so give the screen and the map group back here.
state.justWarped = false
session.send(RenderScreenPacket(true))
presenceService.enter(session)
}
} finally {
if (session.attributes[PENDING_MAP_LOAD] === loaded) {
session.attributes.remove(PENDING_MAP_LOAD)
}
}
}
}
@@ -8,15 +8,28 @@ import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionKind
import de.fiereu.openmmo.net.game.packets.MapTransitionPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
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.world.WarpExitRules
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
private val log = KotlinLogging.logger {}
// A player must not stay gated if the client never answers the transition.
private val ARRIVAL_TIMEOUT = 10.seconds
@Singleton
class WarpService
@Inject
@@ -25,22 +38,32 @@ 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) {
val state = ctx.attributes[PLAYER_STATE]
state?.justWarped = true
val stored = characterStore.getCharacter(charId) ?: return
// Check the map first. Moving the player onto one we do not have would strand it there.
val destMap = mapManager.getMap(warp.targetRegionId, warp.targetBankId, warp.targetMapId)
if (destMap == null) {
log.warn {
"Map not found for warp target ${warp.targetRegionId}:${warp.targetBankId}:${warp.targetMapId}"
}
return
}
state?.justWarped = true
// Leave now, so the old map's observers do not keep a ghost for the whole transition.
presenceService.leave(ctx)
val sourceMap =
mapManager.getMap(
stored.info.positionRegionId, stored.info.positionBankId, stored.info.positionMapId)
val knownOverride =
WarpExitRules.getKnownOverride(sourceMap, destMap, warp.targetX, warp.targetY)
val destBehavior = destMap?.tileAt(warp.targetX, warp.targetY)?.behavior
val destBehavior = destMap.tileAt(warp.targetX, warp.targetY)?.behavior
val warpFacing =
warp.exitFacing
@@ -65,7 +88,7 @@ constructor(
destMap = destMap,
destTileBehavior = destBehavior,
)
if (shouldAutoStepOffWarp && destMap != null) {
if (shouldAutoStepOffWarp) {
val destWarp = destMap.warps.find { it.x == offsetX && it.y == offsetY }
if (destWarp != null) {
offsetX +=
@@ -86,11 +109,11 @@ constructor(
}
val playerZ =
destMap?.warps?.find { it.x == warp.targetX && it.y == warp.targetY }?.elevation
destMap.warps.find { it.x == warp.targetX && it.y == warp.targetY }?.elevation
?: warp.targetElevation
log.info {
"WARP EXIT: source=${sourceMap?.bankId}:${sourceMap?.mapId} dest=${destMap?.bankId}:${destMap?.mapId} target=(${warp.targetX},${warp.targetY}) final=($offsetX,$offsetY) z=$playerZ facing=$warpFacing autoStep=$shouldAutoStepOffWarp"
"WARP EXIT: source=${sourceMap?.bankId}:${sourceMap?.mapId} dest=${destMap.bankId}:${destMap.mapId} target=(${warp.targetX},${warp.targetY}) final=($offsetX,$offsetY) z=$playerZ facing=$warpFacing autoStep=$shouldAutoStepOffWarp"
}
val newInfo =
@@ -110,31 +133,44 @@ constructor(
state.mapId = warp.targetMapId.toInt()
state.x = offsetX.toShort()
state.y = offsetY.toShort()
state.elevation = playerZ
}
// Only fade out and send the map. onRequestPlayer does the arrival and fades back in.
ctx.send(MapTransitionPacket())
ctx.send(RenderScreenPacket(false))
ctx.send(MapTransitionAckPacket(MapTransitionKind.WARP))
if (destMap != null) {
mapLoadService.resetClientCache(ctx, destMap)
ctx.send(mapManager.createLoadMapPacket(destMap, reloadPlayer = true, deleteCache = true))
mapLoadService.preloadConnectedMaps(ctx, destMap, depth = 1, reloadPlayer = true)
} else {
log.warn {
"Map not found for warp target ${warp.targetRegionId}:${warp.targetBankId}:${warp.targetMapId}"
}
}
// Release the fade after loading the destination.
ctx.send(mapLoadService.createLoadEntity(newInfo, warpFacing, playerZ))
presenceService.refresh(ctx)
if (state != null && destMap != null) mapScriptService.onMapEnter(ctx, state, destMap)
ctx.send(RenderScreenPacket(true))
if (state != null) awaitArrival(ctx, state, charId)
log.info { "Player $charId warped to bank=${warp.targetBankId} map=${warp.targetMapId}" }
}
/**
* Releases the player if the client never asks for it. Without this a lost RequestPlayer leaves
* the player faded out and unable to move for the rest of the session.
*/
private fun awaitArrival(ctx: SessionContext, state: PlayerState, charId: Long) {
val loaded = CompletableDeferred<Unit>()
ctx.attributes[PENDING_MAP_LOAD] = loaded
// The session's own scope, so a disconnect cancels this instead of reviving a dead session.
val scope =
ctx.attributes.getOrPut(SCRIPT_SCOPE) {
CoroutineScope(SupervisorJob() + Dispatchers.Default)
}
scope.launch {
if (withTimeoutOrNull(ARRIVAL_TIMEOUT) { loaded.await() } != null) return@launch
// A newer warp owns the gate now, leave it to its own deadline.
if (ctx.attributes[PENDING_MAP_LOAD] !== loaded) return@launch
if (!ctx.channel.isActive) return@launch
ctx.attributes.remove(PENDING_MAP_LOAD)
log.warn { "Character $charId never asked for its player after a warp" }
state.justWarped = false
ctx.send(RenderScreenPacket(true))
presenceService.enter(ctx)
}
}
}
@@ -1,24 +1,30 @@
package de.fiereu.openmmo.server.game.session
import de.fiereu.openmmo.common.enums.Direction
import java.util.concurrent.ConcurrentHashMap
/**
* Per-session player state. Scripts run on their own coroutine while packets are answered on the
* mailbox coroutine, and both threads touch every field here, so all of them are volatile.
*/
data class PlayerState(
val userId: Int,
var characterId: Long? = null,
var justWarped: Boolean = false,
var facingDirection: Direction = Direction.DOWN,
var inDialog: Boolean = false,
var dialogNpcEntityId: Long = 0,
var dialogSeqId: Int = 0,
var regionId: Int = 1,
var bankId: Int = 51,
var mapId: Int = 3,
var x: Short = 4,
var y: Short = 2,
@field:Volatile var characterId: Long? = null,
@field:Volatile var justWarped: Boolean = false,
@field:Volatile var facingDirection: Direction = Direction.DOWN,
@field:Volatile var inDialog: Boolean = false,
@field:Volatile var dialogNpcEntityId: Long = 0,
@field:Volatile var dialogSeqId: Int = 0,
@field:Volatile var regionId: Int = 1,
@field:Volatile var bankId: Int = 51,
@field:Volatile var mapId: Int = 3,
@field:Volatile var x: Short = 4,
@field:Volatile var y: Short = 2,
@field:Volatile var elevation: Int = 0,
/** Trusts one source tile after scripted movement. */
var acceptNextMoveSource: Boolean = false,
@field:Volatile var acceptNextMoveSource: Boolean = false,
/** Maps the client already holds. A warp sends deleteCache, which empties this. */
val loadedMaps: MutableSet<Int> = mutableSetOf(),
val loadedMaps: MutableSet<Int> = ConcurrentHashMap.newKeySet(),
)
/** Packs a map address into one key for [PlayerState.loadedMaps]. */
@@ -14,5 +14,8 @@ val PENDING_DIALOG = SessionAttribute.of<CompletableDeferred<Unit>>("pendingDial
val PENDING_DIALOG_RESPONSE =
SessionAttribute.of<CompletableDeferred<DialogActionResponsePacket>>("pendingDialogResponse")
/** Completed when the client has asked for its player again, which ends a map transition. */
val PENDING_MAP_LOAD = SessionAttribute.of<CompletableDeferred<Unit>>("pendingMapLoad")
/** Scope the connection's scripts run in. Cancelled on disconnect so a waiting script unwinds. */
val SCRIPT_SCOPE = SessionAttribute.of<CoroutineScope>("scriptScope")
@@ -0,0 +1,337 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.DynamicWarp
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.maps.MapManager
import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.LoadMapPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
import de.fiereu.openmmo.server.game.session.SCRIPT_SCOPE
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.server.game.world.interest.InterestManager
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
// No map is registered here, so a warp aimed at it cannot complete.
private const val MISSING_BANK: Byte = 120
private const val MISSING_MAP: Byte = 120
// Longer than either warp service waits for the client.
private val ARRIVAL_DEADLINE_PASSED = 15.seconds
private fun littlerootTown() =
DynamicWarp(
regionId = 1,
bankId = 50,
mapId = 9,
x = 5,
y = 8,
facing = Direction.DOWN,
)
private fun warpTo(bankId: Byte, mapId: Byte) =
WarpTile(
x = 0,
y = 0,
targetRegionId = 1,
targetBankId = bankId,
targetMapId = mapId,
targetX = 5,
targetY = 8,
)
@OptIn(ExperimentalCoroutinesApi::class)
class WarpArrivalTest :
FunSpec({
/** Every service a warp touches, sharing one interest manager. */
class Fixture(store: CharacterStore) {
val mapManager = MapManager()
val mapLoad = MapLoadService(mapManager)
val presence =
PresenceService(InterestManager(), PassThroughInterestPolicy(), mapLoad, store)
val warps = WarpService(mapLoad, mapManager, store, presence)
val scriptWarps = ScriptWarpService(mapManager, mapLoad, store, presence)
}
/** The warp deadline runs on the session's scope, which a disconnect cancels. */
fun FakeSession.useScope(scope: CoroutineScope) = also { attributes[SCRIPT_SCOPE] = scope }
suspend fun CharacterStore.player(name: String = "May") =
createCharacter(1, name, CharacterGender.FEMALE, Region.HOENN).info.id
test("a warp gates movement until the client asks for its player") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
session.state().justWarped shouldBe true
session.sent.filterIsInstance<RenderScreenPacket>() shouldBe
listOf(RenderScreenPacket(false))
}
}
test("a warp the client never answers gives movement back") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
advanceTimeBy(ARRIVAL_DEADLINE_PASSED)
runCurrent()
session.state().justWarped shouldBe false
session.attributes[PENDING_MAP_LOAD] shouldBe null
session.sent.filterIsInstance<RenderScreenPacket>().last() shouldBe
RenderScreenPacket(true)
}
}
test("an arrival cancels the deadline of the warp it belongs to") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
// What onRequestPlayer does on arrival.
session.state().justWarped = false
session.attributes.remove(PENDING_MAP_LOAD)!!.complete(Unit)
advanceUntilIdle()
session.state().justWarped shouldBe false
session.sent.filterIsInstance<RenderScreenPacket>() shouldBe
listOf(RenderScreenPacket(false))
}
}
test("a second warp keeps the gate its predecessor's deadline would have opened") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
val first = session.attributes[PENDING_MAP_LOAD]
f.warps.executeWarp(session, charId, warpTo(51, 3))
runCurrent()
(session.attributes[PENDING_MAP_LOAD] === first) shouldBe false
// The second warp arrives, then the first one's deadline passes.
session.state().justWarped = false
session.attributes.remove(PENDING_MAP_LOAD)!!.complete(Unit)
session.sent.clear()
advanceTimeBy(ARRIVAL_DEADLINE_PASSED)
runCurrent()
session.sent shouldBe emptyList()
}
}
test("a warp to a map that is not loaded leaves the player where it was") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.mapManager.getMap(1, MISSING_BANK, MISSING_MAP) shouldBe null
val before = store.getCharacter(charId)!!.info
f.warps.executeWarp(session, charId, warpTo(MISSING_BANK, MISSING_MAP))
advanceUntilIdle()
session.state().justWarped shouldBe false
session.state().mapId shouldBe 3
store.getCharacter(charId)!!.info.positionMapId shouldBe before.positionMapId
session.sent shouldBe emptyList()
}
}
test("a warp for an unknown character does not gate movement") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val session = FakeSession(characterId = 404).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, 404, warpTo(50, 9))
advanceUntilIdle()
session.state().justWarped shouldBe false
session.sent shouldBe emptyList()
}
}
test("a disconnect during the transition cancels the deadline") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val scope = CoroutineScope(backgroundScope.coroutineContext + Job())
val session = FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(scope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
// What onInactive does.
scope.cancel()
session.sent.clear()
advanceTimeBy(ARRIVAL_DEADLINE_PASSED)
runCurrent()
session.sent shouldBe emptyList()
}
}
test("a warp carries the elevation of its destination to the arrival") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
val stairs = f.mapManager.getMap(1, 51, 3)!!.warps.first()
f.warps.executeWarp(
session,
charId,
warpTo(51, 3).copy(targetX = stairs.x, targetY = stairs.y, targetElevation = 3),
)
runCurrent()
session.state().elevation shouldBe (stairs.elevation)
}
}
test("warping despawns the player from the map it left right away") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player("May")
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val watcher = FakeSession(characterId = store.player("Brendan"), bankId = 51, mapId = 3)
val f = Fixture(store)
f.presence.enter(session)
f.presence.enter(watcher)
watcher.sent.clear()
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
watcher.sent shouldBe listOf(EntityLeavePacket(charId))
}
}
test("arriving on the same map still re-exchanges entity snapshots") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player("May")
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val watcher = FakeSession(characterId = store.player("Brendan"), bankId = 51, mapId = 3)
val f = Fixture(store)
f.presence.enter(session)
f.presence.enter(watcher)
session.sent.clear()
// The arrival re-enters the map the player never really left.
f.presence.enter(session)
session.sent.map { it::class } shouldBe listOf(watcher.sent.first()::class)
}
}
test("a scripted warp resumes once the client has loaded the map") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
val cutscene = launch { f.scriptWarps.warp(session, session.state(), littlerootTown()) }
// Not advanceUntilIdle, that would run the clock past the load timeout.
runCurrent()
session.state().justWarped shouldBe true
session.sent.filterIsInstance<LoadMapPacket>().isEmpty() shouldBe false
session.attributes.remove(PENDING_MAP_LOAD)!!.complete(Unit)
runCurrent()
cutscene.join()
session.attributes[PENDING_MAP_LOAD] shouldBe null
session.sent.filterIsInstance<RenderScreenPacket>() shouldBe
listOf(RenderScreenPacket(false))
}
}
test("a scripted warp the client never answers gives movement back") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
val cutscene = launch { f.scriptWarps.warp(session, session.state(), littlerootTown()) }
advanceUntilIdle()
cutscene.join()
session.state().justWarped shouldBe false
session.attributes[PENDING_MAP_LOAD] shouldBe null
session.sent.filterIsInstance<RenderScreenPacket>().last() shouldBe
RenderScreenPacket(true)
}
}
test("a scripted warp to a map that is not loaded does nothing") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.scriptWarps.warp(
session,
session.state(),
littlerootTown().copy(bankId = MISSING_BANK, mapId = MISSING_MAP),
)
session.state().justWarped shouldBe false
session.sent shouldBe emptyList()
}
}
})