fix(game): undo an interrupted script so a character does not lose or replay progress (#143)
* fix(game): make character store writes atomic so concurrent updates are not lost * fix(game): refuse a scripted move that would leave the map * fix(game): remember which way a character was facing across a relogin * fix(game): undo an interrupted script so the next login does not replay it * docs: record the script rollback and the atomic store writes * chore(game): cut the script recovery comments back * fix(game): roll a disconnected script back once, after the battle flush
This commit is contained in:
1 parent
94bf65e208
commit
e8baac972c
20 files changed
+540
-105
No files matched your search
+10
-3
@@ -60,6 +60,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.script.ScriptRunner
|
||||
import de.fiereu.openmmo.server.game.services.BattleService
|
||||
import de.fiereu.openmmo.server.game.services.DialogService
|
||||
import de.fiereu.openmmo.server.game.services.GuildService
|
||||
@@ -94,6 +95,7 @@ constructor(
|
||||
private val guildService: GuildService,
|
||||
private val battleService: BattleService,
|
||||
private val chatCommandService: ChatCommandService,
|
||||
private val scriptRunner: ScriptRunner,
|
||||
private val sessionRegistry: SessionRegistry,
|
||||
private val characterStore: CharacterStore,
|
||||
scope: CoroutineScope,
|
||||
@@ -172,14 +174,19 @@ constructor(
|
||||
}
|
||||
|
||||
override fun onInactive() {
|
||||
// Cancel any script coroutine still waiting on a dialog reply from this connection.
|
||||
session.attributes[SCRIPT_SCOPE]?.cancel()
|
||||
// A cancelled scope left behind would make every later launch a silent no-op.
|
||||
session.attributes.remove(SCRIPT_SCOPE)?.cancel()
|
||||
val state = session.attributes[PLAYER_STATE] ?: return
|
||||
log.info { "Player ${state.characterId} disconnected." }
|
||||
val charId = state.characterId
|
||||
if (charId != null) {
|
||||
// The battle flush must land before the unload evicts the character from the cache.
|
||||
// The battle flush must land before the unload evicts the character from the cache, and
|
||||
// before the rollback, which would otherwise be overwritten by the party it persists.
|
||||
battleService.onDisconnect(session)
|
||||
// Undo the interrupted script here rather than leaving it to the coroutine's own cleanup,
|
||||
// which runs on another thread and would race the flush below.
|
||||
scriptRunner.rollBack(session, state, entityId = -1)
|
||||
state.inDialog = false
|
||||
presenceService.leave(session)
|
||||
sessionRegistry.unbindCharacter(charId)
|
||||
characterStore.unloadCharacterAsync(charId)
|
||||
|
||||
@@ -11,6 +11,7 @@ import de.fiereu.openmmo.server.game.services.StoryPlayerService
|
||||
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 de.fiereu.openmmo.server.game.session.SCRIPT_SNAPSHOT
|
||||
import de.fiereu.openmmo.server.game.storage.CharacterStore
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import javax.inject.Inject
|
||||
@@ -19,6 +20,7 @@ import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
@@ -46,6 +48,18 @@ constructor(
|
||||
fun run(session: SessionContext, state: PlayerState, script: Script, entityId: Long) =
|
||||
runAll(session, state, listOf(script), entityId)
|
||||
|
||||
/**
|
||||
* Undoes what a script wrote when it does not reach its end. Scenes advance their story var last,
|
||||
* so leaving the earlier writes in place would let the next login replay the scene on top of
|
||||
* them, granting its rewards twice.
|
||||
*/
|
||||
fun rollBack(session: SessionContext, state: PlayerState, entityId: Long) {
|
||||
val snapshot = session.attributes.remove(SCRIPT_SNAPSHOT) ?: return
|
||||
val charId = state.characterId ?: return
|
||||
log.info { "Rolling back the unfinished script for entity $entityId on character $charId" }
|
||||
characterStore.restoreProgress(charId, snapshot)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs [scripts] in order on one coroutine so they share the dialog lock, for example a map's
|
||||
* on-transition script followed by its matching on-frame cutscene.
|
||||
@@ -57,11 +71,15 @@ constructor(
|
||||
entityId: Long,
|
||||
) {
|
||||
if (scripts.isEmpty()) return
|
||||
state.inDialog = true
|
||||
val scope =
|
||||
session.attributes.getOrPut(SCRIPT_SCOPE) {
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
}
|
||||
// A cancelled scope cannot launch, so bail before claiming the dialog lock.
|
||||
if (!scope.isActive) return
|
||||
state.inDialog = true
|
||||
val snapshot = state.characterId?.let(characterStore::getCharacter)
|
||||
if (snapshot != null) session.attributes[SCRIPT_SNAPSHOT] = snapshot
|
||||
val ctx =
|
||||
ScriptContext(
|
||||
session,
|
||||
@@ -78,15 +96,27 @@ constructor(
|
||||
entryScripts,
|
||||
)
|
||||
scope.launch {
|
||||
var finished = false
|
||||
var cancelled = false
|
||||
try {
|
||||
for (script in scripts) script.run(ctx)
|
||||
finished = true
|
||||
} catch (e: CancellationException) {
|
||||
// The disconnect that cancelled this rolls back itself, in order with the battle flush
|
||||
// and the unload. Doing it here as well would race that and lose to the eviction.
|
||||
cancelled = true
|
||||
throw e
|
||||
} catch (e: NotImplementedError) {
|
||||
log.info { "Script not ported yet for entity $entityId" }
|
||||
// A stub wrote nothing, so there is nothing to undo.
|
||||
finished = true
|
||||
} catch (e: Exception) {
|
||||
log.error(e) { "Script failed for entity $entityId" }
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
if (!finished) rollBack(session, state, entityId)
|
||||
session.attributes.remove(SCRIPT_SNAPSHOT)
|
||||
}
|
||||
dialogService.close(session, state)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,6 +255,8 @@ constructor(
|
||||
state.mapId = info.positionMapId.toInt()
|
||||
state.x = info.positionX
|
||||
state.y = info.positionY
|
||||
state.facingDirection = info.positionFacing
|
||||
state.elevation = map?.tileAt(info.positionX.toInt(), info.positionY.toInt())?.elevation ?: 0
|
||||
|
||||
multiplayerService.broadcastMessage(
|
||||
ChatMessagePacket(
|
||||
|
||||
+2
-1
@@ -179,7 +179,7 @@ constructor(
|
||||
return
|
||||
}
|
||||
|
||||
characterStore.updatePosition(charId, toX.toShort(), toY.toShort())
|
||||
characterStore.updatePosition(charId, toX.toShort(), toY.toShort(), facing = msg.direction)
|
||||
state.x = toX.toShort()
|
||||
state.y = toY.toShort()
|
||||
|
||||
@@ -251,6 +251,7 @@ constructor(
|
||||
}
|
||||
val msg = event.packet
|
||||
state.facingDirection = msg.direction
|
||||
characterStore.updatePosition(charId, state.x, state.y, facing = msg.direction)
|
||||
|
||||
presenceService.broadcastToObservers(
|
||||
ctx,
|
||||
|
||||
+30
-15
@@ -3,16 +3,20 @@ package de.fiereu.openmmo.server.game.services
|
||||
import de.fiereu.network.SessionContext
|
||||
import de.fiereu.openmmo.common.DynamicWarp
|
||||
import de.fiereu.openmmo.common.enums.Direction
|
||||
import de.fiereu.openmmo.maps.MapDef
|
||||
import de.fiereu.openmmo.maps.MapManager
|
||||
import de.fiereu.openmmo.net.game.packets.DialogDataPacket
|
||||
import de.fiereu.openmmo.net.game.packets.NpcUpdatePacket
|
||||
import de.fiereu.openmmo.server.game.script.MovementStep
|
||||
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 kotlinx.coroutines.delay
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
/**
|
||||
* Drives scripted overworld movement (the decomp applymovement/waitmovement). Steps play one tile
|
||||
* at a time with a short delay between them, so the call only returns once the whole path is done,
|
||||
@@ -108,11 +112,7 @@ constructor(
|
||||
))
|
||||
|
||||
val start = Pose(info.positionX.toInt(), info.positionY.toInt(), state.facingDirection)
|
||||
val end = applySteps(start, selfSteps)
|
||||
characterStore.updatePosition(charId, end.x.toShort(), end.y.toShort())
|
||||
state.x = end.x.toShort()
|
||||
state.y = end.y.toShort()
|
||||
state.facingDirection = end.facing
|
||||
commitPose(charId, state, map, applySteps(start, selfSteps))
|
||||
}
|
||||
|
||||
/** Show a normally hidden map npc to the player for a cutscene (the decomp addobject). */
|
||||
@@ -168,6 +168,9 @@ constructor(
|
||||
) {
|
||||
val charId = state.characterId ?: return
|
||||
val info = characterStore.getCharacter(charId)?.info ?: return
|
||||
val map =
|
||||
mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId) ?: return
|
||||
if (!commitPose(charId, state, map, Pose(x, y, facing))) return
|
||||
session.send(
|
||||
NpcUpdatePacket(
|
||||
entityId = info.id,
|
||||
@@ -179,10 +182,6 @@ constructor(
|
||||
facing = 0xF6,
|
||||
unk = facing.ordinal,
|
||||
))
|
||||
characterStore.updatePosition(charId, x.toShort(), y.toShort())
|
||||
state.x = x.toShort()
|
||||
state.y = y.toShort()
|
||||
state.facingDirection = facing
|
||||
}
|
||||
|
||||
/** Removes a cutscene NPC and its collision. */
|
||||
@@ -230,14 +229,11 @@ constructor(
|
||||
) {
|
||||
val charId = state.characterId ?: return
|
||||
val info = characterStore.getCharacter(charId)?.info ?: return
|
||||
val map =
|
||||
mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId) ?: return
|
||||
val start = Pose(info.positionX.toInt(), info.positionY.toInt(), state.facingDirection)
|
||||
val end = drive(session, info.id, start, steps)
|
||||
// Keep the server position in step with where the cutscene left the player, otherwise the next
|
||||
// move packet from the client looks like a desync and the player is snapped back.
|
||||
characterStore.updatePosition(charId, end.x.toShort(), end.y.toShort())
|
||||
state.x = end.x.toShort()
|
||||
state.y = end.y.toShort()
|
||||
state.facingDirection = end.facing
|
||||
commitPose(charId, state, map, end)
|
||||
}
|
||||
|
||||
/** Sends one packet per step from [start] and waits between them. Returns the final pose. */
|
||||
@@ -254,6 +250,25 @@ constructor(
|
||||
return applySteps(start, steps)
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits where a cutscene left the player, unless that is off the map, which would persist a
|
||||
* position every later step reads as a desync and snaps back from.
|
||||
*/
|
||||
private fun commitPose(charId: Long, state: PlayerState, map: MapDef, pose: Pose): Boolean {
|
||||
if (pose.x !in 0 until map.width || pose.y !in 0 until map.height) {
|
||||
log.warn {
|
||||
"Refused a scripted move of character $charId to (${pose.x}, ${pose.y}) on " +
|
||||
"${map.bankId}:${map.mapId}, which is outside the map"
|
||||
}
|
||||
return false
|
||||
}
|
||||
characterStore.updatePosition(charId, pose.x.toShort(), pose.y.toShort(), facing = pose.facing)
|
||||
state.x = pose.x.toShort()
|
||||
state.y = pose.y.toShort()
|
||||
state.facingDirection = pose.facing
|
||||
return true
|
||||
}
|
||||
|
||||
private fun applySteps(start: Pose, steps: List<MovementStep>): Pose {
|
||||
var pose = start
|
||||
for (step in steps) {
|
||||
|
||||
+1
@@ -54,6 +54,7 @@ constructor(
|
||||
positionMapId = destination.mapId,
|
||||
positionX = destination.x,
|
||||
positionY = destination.y,
|
||||
positionFacing = destination.facing,
|
||||
)
|
||||
|
||||
characterStore.updateCharacter(info)
|
||||
|
||||
@@ -126,6 +126,7 @@ constructor(
|
||||
positionMapId = warp.targetMapId,
|
||||
positionX = offsetX.toShort(),
|
||||
positionY = offsetY.toShort(),
|
||||
positionFacing = warpFacing,
|
||||
)
|
||||
characterStore.updateCharacter(newInfo)
|
||||
characterStore.flushCharacterAsync(charId)
|
||||
|
||||
@@ -2,6 +2,7 @@ package de.fiereu.openmmo.server.game.session
|
||||
|
||||
import de.fiereu.network.SessionAttribute
|
||||
import de.fiereu.openmmo.net.game.packets.dialog.DialogActionResponsePacket
|
||||
import de.fiereu.openmmo.server.game.storage.StoredCharacter
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
|
||||
@@ -19,3 +20,8 @@ val PENDING_MAP_LOAD = SessionAttribute.of<CompletableDeferred<Unit>>("pendingMa
|
||||
|
||||
/** Scope the connection's scripts run in. Cancelled on disconnect so a waiting script unwinds. */
|
||||
val SCRIPT_SCOPE = SessionAttribute.of<CoroutineScope>("scriptScope")
|
||||
|
||||
/**
|
||||
* The character as it was before the running script started, so an unfinished one can be undone.
|
||||
*/
|
||||
val SCRIPT_SNAPSHOT = SessionAttribute.of<StoredCharacter>("scriptSnapshot")
|
||||
+3
@@ -207,6 +207,7 @@ constructor(
|
||||
positionMapId = positionMapId.toShort(),
|
||||
positionX = positionX,
|
||||
positionY = positionY,
|
||||
positionFacing = positionFacing.ordinal.toShort(),
|
||||
repelLeft = repelLeft,
|
||||
repelItemId = repelItemId,
|
||||
lureLeft = lureLeft,
|
||||
@@ -240,6 +241,8 @@ constructor(
|
||||
positionMapId = positionMapId.toByte(),
|
||||
positionX = positionX,
|
||||
positionY = positionY,
|
||||
positionFacing =
|
||||
Direction.entries.getOrElse(positionFacing?.toInt() ?: 0) { Direction.DOWN },
|
||||
repelLeft = repelLeft,
|
||||
repelItemId = repelItemId,
|
||||
lureLeft = lureLeft,
|
||||
|
||||
+78
-51
@@ -4,6 +4,7 @@ import de.fiereu.openmmo.common.CharacterInfo
|
||||
import de.fiereu.openmmo.common.DynamicWarp
|
||||
import de.fiereu.openmmo.common.Pokemon
|
||||
import de.fiereu.openmmo.common.enums.CharacterGender
|
||||
import de.fiereu.openmmo.common.enums.Direction
|
||||
import de.fiereu.openmmo.common.enums.Region
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import java.time.LocalDateTime
|
||||
@@ -156,10 +157,34 @@ constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies [change] to the cached character under the map's own lock. Scripts run on their own
|
||||
* coroutine while packets are answered on the mailbox coroutine, so a plain read, copy and write
|
||||
* would let one thread drop the other's field.
|
||||
*/
|
||||
private fun mutate(characterId: Long, change: (StoredCharacter) -> StoredCharacter?): Boolean {
|
||||
var applied = false
|
||||
val present =
|
||||
characters.computeIfPresent(characterId) { _, stored ->
|
||||
val updated = change(stored)
|
||||
if (updated == null) {
|
||||
stored
|
||||
} else {
|
||||
applied = true
|
||||
updated
|
||||
}
|
||||
}
|
||||
if (present == null) {
|
||||
// A disconnect evicts the character, so a script finishing its last statements reaches this.
|
||||
log.warn { "Dropped a write for character $characterId, it is no longer cached" }
|
||||
return false
|
||||
}
|
||||
if (applied) markDirty(characterId)
|
||||
return applied
|
||||
}
|
||||
|
||||
fun updateCharacter(info: CharacterInfo) {
|
||||
val stored = characters[info.id] ?: return
|
||||
characters[info.id] = stored.copy(info = info)
|
||||
markDirty(info.id)
|
||||
mutate(info.id) { it.copy(info = info) }
|
||||
}
|
||||
|
||||
fun updatePosition(
|
||||
@@ -168,18 +193,20 @@ constructor(
|
||||
y: Short,
|
||||
bankId: Byte? = null,
|
||||
mapId: Byte? = null,
|
||||
facing: Direction? = null,
|
||||
) {
|
||||
val stored = characters[characterId] ?: return
|
||||
val oldInfo = stored.info
|
||||
val newInfo =
|
||||
oldInfo.copy(
|
||||
positionX = x,
|
||||
positionY = y,
|
||||
positionBankId = bankId ?: oldInfo.positionBankId,
|
||||
positionMapId = mapId ?: oldInfo.positionMapId,
|
||||
)
|
||||
characters[characterId] = stored.copy(info = newInfo)
|
||||
markDirty(characterId)
|
||||
mutate(characterId) { stored ->
|
||||
stored.copy(
|
||||
info =
|
||||
stored.info.copy(
|
||||
positionX = x,
|
||||
positionY = y,
|
||||
positionBankId = bankId ?: stored.info.positionBankId,
|
||||
positionMapId = mapId ?: stored.info.positionMapId,
|
||||
positionFacing = facing ?: stored.info.positionFacing,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** False when the monster could not be written, in which case the party is left as it was. */
|
||||
@@ -195,10 +222,10 @@ constructor(
|
||||
|
||||
/** Replace one party monster by id, for example after a battle changed hp, xp, or level. */
|
||||
fun updatePokemon(characterId: Long, updated: Pokemon) {
|
||||
val stored = characters[characterId] ?: return
|
||||
val party = stored.pokemon.map { if (it.id == updated.id) updated else it }
|
||||
characters[characterId] = stored.copy(pokemon = party.toMutableList())
|
||||
markDirty(characterId)
|
||||
mutate(characterId) { stored ->
|
||||
stored.copy(
|
||||
pokemon = stored.pokemon.map { if (it.id == updated.id) updated else it }.toMutableList())
|
||||
}
|
||||
}
|
||||
|
||||
/** False when the change could not be written, in which case the balance is left as it was. */
|
||||
@@ -233,34 +260,31 @@ constructor(
|
||||
|
||||
/** Set (or clear with null) the runtime destination for MAP_DYNAMIC warps (setdynamicwarp). */
|
||||
fun setDynamicWarp(characterId: Long, warp: DynamicWarp?) {
|
||||
val stored = characters[characterId] ?: return
|
||||
characters[characterId] = stored.copy(info = stored.info.copy(dynamicWarp = warp))
|
||||
markDirty(characterId)
|
||||
mutate(characterId) { it.copy(info = it.info.copy(dynamicWarp = warp)) }
|
||||
}
|
||||
|
||||
/** 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)
|
||||
mutate(characterId) { stored ->
|
||||
if (flag in stored.storyFlags) null
|
||||
else stored.copy(storyFlags = (stored.storyFlags + flag).toMutableSet())
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
mutate(characterId) { stored ->
|
||||
if (flag !in stored.storyFlags) null
|
||||
else stored.copy(storyFlags = (stored.storyFlags - flag).toMutableSet())
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
mutate(characterId) { stored ->
|
||||
val newVars = stored.storyVars.toMutableMap()
|
||||
if (value == 0) newVars.remove(key) else newVars[key] = value
|
||||
if (newVars == stored.storyVars) null else stored.copy(storyVars = newVars)
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces every monster, the party and the pc alike, along with the bag and story state. */
|
||||
@@ -271,17 +295,21 @@ constructor(
|
||||
storyFlags: Set<String>,
|
||||
storyVars: Map<String, Int>,
|
||||
) {
|
||||
val stored = characters[characterId] ?: return
|
||||
characters[characterId] =
|
||||
stored.copy(
|
||||
pokemon = party.toMutableList(),
|
||||
pcStorage = mutableListOf(),
|
||||
items = items.toMutableMap(),
|
||||
storyFlags = storyFlags.toMutableSet(),
|
||||
// A var of 0 is the default, so it is stored as absent everywhere else too.
|
||||
storyVars = storyVars.filterValues { it != 0 }.toMutableMap(),
|
||||
)
|
||||
markDirty(characterId)
|
||||
mutate(characterId) { stored ->
|
||||
stored.copy(
|
||||
pokemon = party.toMutableList(),
|
||||
pcStorage = mutableListOf(),
|
||||
items = items.toMutableMap(),
|
||||
storyFlags = storyFlags.toMutableSet(),
|
||||
// A var of 0 is the default, so it is stored as absent everywhere else too.
|
||||
storyVars = storyVars.filterValues { it != 0 }.toMutableMap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts a character back to a [snapshot] taken earlier. */
|
||||
fun restoreProgress(characterId: Long, snapshot: StoredCharacter) {
|
||||
mutate(characterId) { snapshot }
|
||||
}
|
||||
|
||||
fun startPeriodicFlush() {
|
||||
@@ -315,12 +343,11 @@ constructor(
|
||||
rollback: (StoredCharacter) -> StoredCharacter,
|
||||
): Boolean =
|
||||
lockFor(characterId).withLock {
|
||||
val before = characters[characterId] ?: return@withLock false
|
||||
val after = apply(before) ?: return@withLock false
|
||||
characters[characterId] = after
|
||||
markDirty(characterId)
|
||||
// Through [mutate] rather than a read and a write, so a script writing another field
|
||||
// between the two is not clobbered by the one this puts back.
|
||||
if (!mutate(characterId, apply)) return@withLock false
|
||||
if (flushLocked(characterId, allowEvict = false)) return@withLock true
|
||||
characters[characterId]?.let { characters[characterId] = rollback(it) }
|
||||
mutate(characterId, rollback)
|
||||
dirtySince.remove(characterId)
|
||||
false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- The way the character is turned, so a relogin does not always face them down. Values are
|
||||
-- Direction ordinals, and 0 is DOWN, which is what every existing row was effectively using.
|
||||
|
||||
ALTER TABLE characters
|
||||
ADD COLUMN position_facing SMALLINT NOT NULL DEFAULT 0;
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package de.fiereu.openmmo.server.game.script
|
||||
|
||||
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.server.game.session.SCRIPT_SCOPE
|
||||
import de.fiereu.openmmo.server.game.session.SCRIPT_SNAPSHOT
|
||||
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.testsupport.scriptRunner
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
|
||||
private const val FLAG = "kanto/FLAG_SYS_POKEMON_GET"
|
||||
private const val SCENE = "kanto/VAR_MAP_SCENE_PALLET_TOWN_PROFESSOR_OAKS_LAB"
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ScriptRollbackTest :
|
||||
FunSpec({
|
||||
/** A scene that writes like the real ones do: rewards first, scene var last. */
|
||||
fun grantingScript(blockOn: CompletableDeferred<Unit>?) = Script { ctx ->
|
||||
ctx.setFlag(FLAG)
|
||||
ctx.setVar(SCENE, 9)
|
||||
blockOn?.await()
|
||||
ctx.setVar(SCENE, 3)
|
||||
}
|
||||
|
||||
fun FakeSession.useScope(scope: CoroutineScope) = also { attributes[SCRIPT_SCOPE] = scope }
|
||||
|
||||
suspend fun CharacterStore.player(): Long =
|
||||
createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
|
||||
|
||||
test("a script that finishes keeps everything it wrote") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.player()
|
||||
val session = FakeSession(characterId = charId).useScope(backgroundScope)
|
||||
|
||||
scriptRunner(store).run(session, session.state(), grantingScript(null), entityId = -1)
|
||||
runCurrent()
|
||||
|
||||
val stored = store.getCharacter(charId)!!
|
||||
stored.storyFlags.contains(FLAG) shouldBe true
|
||||
stored.storyVars[SCENE] shouldBe 3
|
||||
session.attributes[SCRIPT_SNAPSHOT] shouldBe null
|
||||
}
|
||||
}
|
||||
|
||||
test("a script cancelled part way through leaves nothing behind") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.player()
|
||||
val session = FakeSession(characterId = charId).useScope(backgroundScope)
|
||||
val runner = scriptRunner(store)
|
||||
val before = store.getCharacter(charId)!!
|
||||
|
||||
runner.run(session, session.state(), grantingScript(CompletableDeferred()), entityId = -1)
|
||||
runCurrent()
|
||||
store.getCharacter(charId)!!.storyFlags.contains(FLAG) shouldBe true
|
||||
|
||||
// What onInactive does for a player who closed the client mid scene.
|
||||
runner.rollBack(session, session.state(), entityId = -1)
|
||||
|
||||
val stored = store.getCharacter(charId)!!
|
||||
stored.storyFlags shouldBe before.storyFlags
|
||||
stored.storyVars shouldBe before.storyVars
|
||||
stored.pokemon shouldBe before.pokemon
|
||||
stored.info shouldBe before.info
|
||||
}
|
||||
}
|
||||
|
||||
test("rolling back twice leaves later writes alone") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.player()
|
||||
val session = FakeSession(characterId = charId).useScope(backgroundScope)
|
||||
val runner = scriptRunner(store)
|
||||
|
||||
runner.run(session, session.state(), grantingScript(CompletableDeferred()), entityId = -1)
|
||||
runCurrent()
|
||||
runner.rollBack(session, session.state(), entityId = -1)
|
||||
store.updatePosition(charId, 9, 9, facing = Direction.LEFT)
|
||||
runner.rollBack(session, session.state(), entityId = -1)
|
||||
|
||||
store.getCharacter(charId)!!.info.positionX shouldBe 9
|
||||
}
|
||||
}
|
||||
|
||||
test("a script started on a disconnected session never claims the dialog") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.player()
|
||||
val dead = CoroutineScope(backgroundScope.coroutineContext + Job()).also { it.cancel() }
|
||||
val session = FakeSession(characterId = charId).useScope(dead)
|
||||
|
||||
scriptRunner(store).run(session, session.state(), grantingScript(null), entityId = -1)
|
||||
runCurrent()
|
||||
|
||||
session.state().inDialog shouldBe false
|
||||
store.getCharacter(charId)!!.storyFlags.contains(FLAG) shouldBe false
|
||||
}
|
||||
}
|
||||
})
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package de.fiereu.openmmo.server.game.services
|
||||
|
||||
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.server.game.script.MovementStep.WALK_UP
|
||||
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 io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.runTest
|
||||
|
||||
// Oak's lab, where the starter cutscene walks the player eight tiles up from the door.
|
||||
private const val KANTO: Byte = 0
|
||||
private const val INDOOR_PALLET_BANK: Byte = 4
|
||||
private const val OAKS_LAB_MAP: Byte = 3
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ScriptMovementBoundsTest :
|
||||
FunSpec({
|
||||
fun service(store: CharacterStore): ScriptMovementService {
|
||||
val maps = MapManager()
|
||||
return ScriptMovementService(maps, NpcService(maps, store), store)
|
||||
}
|
||||
|
||||
suspend fun CharacterStore.labCharacter(x: Short, y: Short): Long {
|
||||
val id = createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
|
||||
updatePosition(id, x, y, INDOOR_PALLET_BANK, OAKS_LAB_MAP)
|
||||
return id
|
||||
}
|
||||
|
||||
test("a scripted walk inside the map commits its final tile") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.labCharacter(x = 6, y = 12)
|
||||
val session =
|
||||
FakeSession(
|
||||
characterId = charId,
|
||||
regionId = KANTO.toInt(),
|
||||
bankId = INDOOR_PALLET_BANK.toInt(),
|
||||
mapId = OAKS_LAB_MAP.toInt(),
|
||||
)
|
||||
|
||||
service(store).moveSelf(session, session.state(), List(8) { WALK_UP })
|
||||
advanceUntilIdle()
|
||||
|
||||
store.getCharacter(charId)!!.info.positionY shouldBe 4
|
||||
}
|
||||
}
|
||||
|
||||
test("a scripted walk that would leave the map commits nothing") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
// Where an interrupted starter cutscene leaves the player before it replays.
|
||||
val charId = store.labCharacter(x = 6, y = 4)
|
||||
val session =
|
||||
FakeSession(
|
||||
characterId = charId,
|
||||
regionId = KANTO.toInt(),
|
||||
bankId = INDOOR_PALLET_BANK.toInt(),
|
||||
mapId = OAKS_LAB_MAP.toInt(),
|
||||
)
|
||||
|
||||
service(store).moveSelf(session, session.state(), List(8) { WALK_UP })
|
||||
advanceUntilIdle()
|
||||
|
||||
store.getCharacter(charId)!!.info.positionY shouldBe 4
|
||||
}
|
||||
}
|
||||
|
||||
test("repositioning off the map is refused and sends nothing") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.labCharacter(x = 6, y = 4)
|
||||
val session =
|
||||
FakeSession(
|
||||
characterId = charId,
|
||||
regionId = KANTO.toInt(),
|
||||
bankId = INDOOR_PALLET_BANK.toInt(),
|
||||
mapId = OAKS_LAB_MAP.toInt(),
|
||||
)
|
||||
|
||||
service(store).repositionSelf(session, session.state(), 99, 99, Direction.DOWN)
|
||||
|
||||
store.getCharacter(charId)!!.info.positionX shouldBe 6
|
||||
session.sent shouldBe emptyList()
|
||||
}
|
||||
}
|
||||
})
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package de.fiereu.openmmo.server.game.storage
|
||||
|
||||
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.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 CharacterFacingTest :
|
||||
FunSpec({
|
||||
test("a new character faces down") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
|
||||
|
||||
store.getCharacter(charId)!!.info.positionFacing shouldBe Direction.DOWN
|
||||
}
|
||||
}
|
||||
|
||||
test("a move commits the direction it was walked in") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
|
||||
|
||||
store.updatePosition(charId, 3, 4, facing = Direction.RIGHT)
|
||||
|
||||
val info = store.getCharacter(charId)!!.info
|
||||
info.positionX shouldBe 3
|
||||
info.positionFacing shouldBe Direction.RIGHT
|
||||
}
|
||||
}
|
||||
|
||||
test("a move that does not name a direction keeps the stored one") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
|
||||
store.updatePosition(charId, 3, 4, facing = Direction.UP)
|
||||
|
||||
store.updatePosition(charId, 5, 6)
|
||||
|
||||
store.getCharacter(charId)!!.info.positionFacing shouldBe Direction.UP
|
||||
}
|
||||
}
|
||||
})
|
||||
+3
-1
@@ -154,7 +154,8 @@ class CharacterRepositoryIT :
|
||||
val added = monster(stored.info.id, PokemonContainer.PARTY, 1)
|
||||
val current =
|
||||
stored.copy(
|
||||
info = stored.info.copy(money = 999, positionX = 12),
|
||||
info =
|
||||
stored.info.copy(money = 999, positionX = 12, positionFacing = Direction.RIGHT),
|
||||
pokemon = mutableListOf(kept.copy(hp = 3), added),
|
||||
pcStorage = mutableListOf(),
|
||||
items = mutableMapOf(4 to 9, 13 to 1),
|
||||
@@ -164,6 +165,7 @@ class CharacterRepositoryIT :
|
||||
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
|
||||
loaded.info.money shouldBe 999
|
||||
loaded.info.positionX shouldBe 12
|
||||
loaded.info.positionFacing shouldBe Direction.RIGHT
|
||||
loaded.pokemon.map { it.id } shouldBe listOf(kept.id, added.id)
|
||||
loaded.pokemon.first().hp shouldBe 3
|
||||
loaded.pcStorage.shouldBeEmpty()
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package de.fiereu.openmmo.server.game.storage
|
||||
|
||||
import de.fiereu.openmmo.common.enums.CharacterGender
|
||||
import de.fiereu.openmmo.common.enums.Region
|
||||
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runTest
|
||||
|
||||
private const val WRITES = 200
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class CharacterStoreConcurrencyTest :
|
||||
FunSpec({
|
||||
test("concurrent writers do not drop each other's update") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
|
||||
val baseline = store.getCharacter(charId)!!.storyFlags.size
|
||||
val pool = Executors.newFixedThreadPool(2)
|
||||
val start = CountDownLatch(1)
|
||||
|
||||
// Both threads add their own flags, so a lost update loses a flag and shows in the count.
|
||||
val writers =
|
||||
(0 until 2).map { thread ->
|
||||
pool.submit {
|
||||
start.await()
|
||||
repeat(WRITES) { store.setStoryFlag(charId, "kanto/FLAG_${thread}_$it") }
|
||||
}
|
||||
}
|
||||
start.countDown()
|
||||
writers.forEach { it.get() }
|
||||
pool.shutdown()
|
||||
|
||||
store.getCharacter(charId)!!.storyFlags.size shouldBe baseline + 2 * WRITES
|
||||
}
|
||||
}
|
||||
|
||||
test("a write for a character that is not cached is refused rather than lost silently") {
|
||||
runTest {
|
||||
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
|
||||
|
||||
store.addItem(404, itemId = 1, amount = 1) shouldBe false
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -46,36 +46,8 @@ fun movementService(
|
||||
val presence = PresenceService(interest, PassThroughInterestPolicy(), mapLoad, store)
|
||||
val npcs = NpcService(mapManager, store)
|
||||
val story = StoryService(store)
|
||||
val species = SpeciesRegistry()
|
||||
val moves = MoveRegistry()
|
||||
val wildMons = WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService())
|
||||
val battles =
|
||||
BattleService(
|
||||
characterStore = store,
|
||||
battles = BattleRegistry(),
|
||||
engine = TurnEngine(moves, TypeChart()),
|
||||
wildMons = wildMons,
|
||||
emitter = BattlePacketEmitter(interest),
|
||||
rewards = BattleRewards(),
|
||||
moveLearner = MoveLearner(LearnsetRegistry(), moves),
|
||||
interestManager = interest,
|
||||
speciesRegistry = species,
|
||||
moveRegistry = moves,
|
||||
trainers = TrainerRegistry(),
|
||||
)
|
||||
val battles = battleService(store, interest)
|
||||
val entryScripts = MapEntryScripts(ScriptRegistry(emptyMap()), story)
|
||||
val runner =
|
||||
ScriptRunner(
|
||||
DialogService(),
|
||||
story,
|
||||
ScriptMovementService(mapManager, npcs, store),
|
||||
ScriptWarpService(mapManager, mapLoad, store, presence),
|
||||
StoryPlayerService(store, wildMons, species, moves),
|
||||
battles,
|
||||
store,
|
||||
mapManager,
|
||||
entryScripts,
|
||||
)
|
||||
return MovementService(
|
||||
WarpService(mapLoad, mapManager, store, presence),
|
||||
mapLoad,
|
||||
@@ -84,6 +56,54 @@ fun movementService(
|
||||
mapManager,
|
||||
store,
|
||||
EncounterService(store, battles),
|
||||
MapScriptService(entryScripts, runner),
|
||||
MapScriptService(entryScripts, scriptRunner(store, mapManager, interest, battles)),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A real [ScriptRunner]. It launches on whatever scope the session carries under SCRIPT_SCOPE, so
|
||||
* put the test's own scope there to be able to step a script.
|
||||
*/
|
||||
fun scriptRunner(
|
||||
store: CharacterStore,
|
||||
mapManager: MapManager = MapManager(),
|
||||
interest: InterestManager = InterestManager(),
|
||||
battles: BattleService = battleService(store, interest),
|
||||
): ScriptRunner {
|
||||
val mapLoad = MapLoadService(mapManager)
|
||||
val presence = PresenceService(interest, PassThroughInterestPolicy(), mapLoad, store)
|
||||
val npcs = NpcService(mapManager, store)
|
||||
val story = StoryService(store)
|
||||
val species = SpeciesRegistry()
|
||||
val moves = MoveRegistry()
|
||||
val wildMons = WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService())
|
||||
return ScriptRunner(
|
||||
DialogService(),
|
||||
story,
|
||||
ScriptMovementService(mapManager, npcs, store),
|
||||
ScriptWarpService(mapManager, mapLoad, store, presence),
|
||||
StoryPlayerService(store, wildMons, species, moves),
|
||||
battles,
|
||||
store,
|
||||
mapManager,
|
||||
MapEntryScripts(ScriptRegistry(emptyMap()), story),
|
||||
)
|
||||
}
|
||||
|
||||
private fun battleService(store: CharacterStore, interest: InterestManager): BattleService {
|
||||
val species = SpeciesRegistry()
|
||||
val moves = MoveRegistry()
|
||||
return BattleService(
|
||||
characterStore = store,
|
||||
battles = BattleRegistry(),
|
||||
engine = TurnEngine(moves, TypeChart()),
|
||||
wildMons = WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService()),
|
||||
emitter = BattlePacketEmitter(interest),
|
||||
rewards = BattleRewards(),
|
||||
moveLearner = MoveLearner(LearnsetRegistry(), moves),
|
||||
interestManager = interest,
|
||||
speciesRegistry = species,
|
||||
moveRegistry = moves,
|
||||
trainers = TrainerRegistry(),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user