#include "game.h" #include "game_state_player.h" #include "entity_familiar.h" #include "entity_npc.h" #include "log.h" #include "manager.h" #include "platform.h" #include "room.h" #include constexpr int CHALLENGE_SPEED = 22; constexpr int ENTITY_CHARGER = 23; constexpr int CHARGER_MY_SHADOW = 1; constexpr int FAMILIAR_WISP = 206; constexpr int FAMILIAR_UMBILICAL_BABY = 240; constexpr int FAMILIAR_FORGOTTEN_BODY = 900; constexpr int COLLECTIBLE_VENTRICLE_RAZOR = 396; constexpr int REWIND_DOOR_FRAMES = 15; constexpr int ROOM_REF_MODE_SHIFT = 16; constexpr int ROOM_REF_HALF_SHIFT = 16; constexpr uint32_t ROOM_FLAG_SAVED = 0x40; constexpr uint32_t ROOM_REF_FLAGGED = 0x20000000; constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000; constexpr uint32_t ROOM_REF_MERGED = 0x80000000; // The versus rules each kind of match plays, as its slot 1 answers. static const std::array, DEATHMATCH_VENOM> DEATHMATCH_TYPE_RULES = {{ {&typeid(DeathmatchTypeNormal), DEATHMATCH_NORMAL}, {&typeid(DeathmatchTypeIpecac), DEATHMATCH_IPECAC}, {&typeid(DeathmatchTypeBomberman), DEATHMATCH_BOMBERMAN}, {&typeid(DeathmatchTypeLudovico), DEATHMATCH_LUDOVICO}, {&typeid(DeathmatchTypeSumo), DEATHMATCH_SUMO}, {&typeid(DeathmatchTypeKnockout), DEATHMATCH_KNOCKOUT}, {&typeid(DeathmatchTypeSwordFight), DEATHMATCH_SWORD_FIGHT}, {&typeid(DeathmatchTypeMachineGun), DEATHMATCH_MACHINE_GUN}, {&typeid(DeathmatchTypeIndigestion), DEATHMATCH_INDIGESTION}, {&typeid(DeathmatchTypeKnifeFight), DEATHMATCH_KNIFE_FIGHT}, {&typeid(DeathmatchTypeVenom), DEATHMATCH_VENOM}, }}; // Saves the versus rules as DeathmatchTypeBase::StoreGameState does: which kind of match the run drew (each type's // slot 1) and its players. // Offline no player ever joins a match, so its player set stays empty. A run without rules saves none. static void versus_store(DeathmatchManager& manager, GameState& state) { state.versusPlayers.clear(); if (!manager.type) return; DeathmatchTypeBase* type = manager.type.get(); const std::type_info& drawn = typeid(*type); for (auto [info, rules] : DEATHMATCH_TYPE_RULES) if (*info == drawn) state.versusRules = (uint8_t)rules; } // 006f9000 Copies the run into a game state to save: its rules and seeds, the counters and histories of the run, the // item and boss pools, the TMTRAINER seeds, the floor (after leaving the room), the players, the Ascent's saved // stages, the nightmare stage bar, the ambush wave, the score and the versus rules. // The saved flags are the first 53 of the run's state flags. void Game::store_game_state(GameState& state) { state.Clear(); state.seeds = seedEffects; state.playerManagerSeed = playerManager.rng._seed; state.fortuneSeed = fortuneRNG._seed; state.challenge = (int)challenge; state.isRerun = isRerun; state.isConsoleUsedThisRun = isConsoleUsedThisRun; state.difficulty = difficulty; state.gameStateFlags = std::bitset(gameStateFlags); state.lastDevilRoomStage = lastDevilRoomStage; state.treasureRoomsVisited = treasureRoomsVisited; state.planetariumsVisited = planetariumsVisited; state.stagesWithoutHeartsPicked = stagesWithoutHeartsPicked; state.stagesWithoutDamage = stagesWithoutDamage; state.devilRoomDeals = devilRoomDeals; state.shopVisits = shopVisits; state.donationModGreed = donationModGreed; state.donationModAngel = donationModAngel; state.reviveMachineCoinsLeft = reviveMachineCoinsLeft; state.reviveMachineUses = reviveMachineUses; state.bossRushParTime = bossRushParTime; state.blueWombParTime = blueWombParTime; state.frameCount = frameCount; state.timeCounter = timeCounter; state.stageNameNumeral = stageNameNumeral; state.victoryLap = victoryLap; state.lastLevelWithoutHalfHp = lastLevelWithoutHalfHp; state.lastLevelWithDamage = lastLevelWithDamage; state.encounteredBosses = encounteredBosses; state.pixelationTimer = pixelationTimer; state.pixelationDuration = pixelationDuration; state.magicSkinUses = magicSkinUses; state.erasedEntities = erasedEntities; itemPool.StoreGameState(state.itemPool); bossPool.store_game_state(state.bossPool); if (!proceduralItemManager.proceduralItems.empty()) reconstruction_missing("Game::store_game_state 006f9000: the TMTRAINER items' seeds (ProceduralItem +0x8)"); room->on_leave(); Level::store_game_state(state); playerManager.store_game_state(&state); state.isAscent = ascentTimer > 0; state.backwardsStages = backwardsStages; state.deathCertificateExitTimer = deathCertificateExitTimer; state.nightmareStageIcons = g_manager->nightmareScene.stageIcons; state.isAmbushActive = ambush._isActive; state.ambushWave = ambush._currentWave > 0 ? ambush._currentWave - 1 : ambush._currentWave; scoreSheet.store_state(state.scoreSheet); versus_store(deathmatchManager, state); } // 00705ee0 Saves the run for the Glowing Hourglass as the players enter a room, by the door they leave it through. // A door left again within 15 frames of entering (or the same door) keeps the saved state. Saving the room again keeps // its devil deal stage, and a new room flips to the other slot, the old one remembering the door it was left by. void Game::save_rewind_state(int leaveDoorSlot) { if (isStoringGlowingHourglassState || isRestoringGlowingHourglassState || isPocketItemRewindSaved) return; int slot = 0; bool isSameRoom = false; if (currentGlowingHourglassSlot >= 0 && glowingHourglassStates[currentGlowingHourglassSlot].isUsable) { GlowingHourglassState& current = glowingHourglassStates[currentGlowingHourglassSlot]; isSameRoom = current.gameState.currentRoomIdx == currentRoomIdx && current.gameState.stage == stage; slot = isSameRoom ? currentGlowingHourglassSlot : 1 - currentGlowingHourglassSlot; if (!isSameRoom) current.gameState.enterDoor = leaveDoor; if (isSameRoom && leaveDoorSlot >= 0) { bool isRecent = (uint32_t)(frameCount - current.timeCounter) < REWIND_DOOR_FRAMES; if (leaveDoorSlot == current.leaveDoor || (current.leaveDoor >= 0 && isRecent)) return; } } currentGlowingHourglassSlot = slot; isStoringGlowingHourglassState = true; GlowingHourglassState& state = glowingHourglassStates[slot]; int keptDevilRoomStage = state.gameState.lastDevilRoomStage; store_game_state(state.gameState); if (isSameRoom) state.gameState.lastDevilRoomStage = keptDevilRoomStage; state.isUsable = true; state.leaveDoor = leaveDoorSlot; state.timeCounter = frameCount; state.eventCounters = g_manager->persistentGameData.eventCounters; isStoringGlowingHourglassState = false; } // 00747360 Names a room's config for a saved run: its stage, mode, mirroring and flag 0x40 packed with its type and // variant, or for a merged room its shape, with its halves appended to the merged configs. Without that list a merged // room is left as it was. void room_config_ref_save(RoomConfig_Room& config, RoomConfigRef& ref, std::vector* mergedConfigs) { if (!(config.flags & ROOM_FLAG_MERGED)) { ref.packed = (uint32_t)(uint8_t)config.mode << ROOM_REF_MODE_SHIFT | (uint32_t)config.stageId; if (config.flags & ROOM_FLAG_MIRRORED) ref.packed |= ROOM_REF_MIRRORED; if (config.flags & ROOM_FLAG_SAVED) ref.packed |= ROOM_REF_FLAGGED; ref.type = config.type; ref.variant = config.variant; return; } if (!mergedConfigs) return; ref.packed = ROOM_REF_MERGED; ref.type = config.shape; ref.variant = 0; for (size_t i = 0; i < config.mergedData.size(); i++) { size_t index = mergedConfigs->size(); RoomConfigRef half; ref.variant |= (uint32_t)(uint16_t)index << (ROOM_REF_HALF_SHIFT * i); mergedConfigs->push_back({}); room_config_ref_save(*config.mergedData[i], half, mergedConfigs); (*mergedConfigs)[index] = half; } } // 00747e10 Copies the floor into a game state: its stage, curses, flags and Greed waves, its seeds, the 13x13 maps, every // room descriptor (006f8d60, a plain copy) with its config named apart (its config pointer cleared), the rooms the // players are in and came from, the room's watch speed and slowdown, the Ventricle Razor portals and bombs spawned. // The Speed! challenge saves the watch as fast. void Level::store_game_state(GameState& state) { state.stage = stage; state.stageType = stageType; state.startingRoomIdx = startingRoomIdx; state.lastBossRoomListIdx = lastBossRoomListIdx; state.curses = curses; state.isBossChallenge = isBossChallenge; state.levelStateFlags = std::bitset(levelStateFlags); state.greedModeWave = greedModeWave; state.greedWaveSeeds = greedWaveSeeds; state.greedModeTreasureRoomIdx = greedModeTreasureRoomIdx; state.greedLastBeatenWave = greedLastBeatenWave; state.greedLastPaidWave = greedLastPaidWave; state.isHeartPicked = isHeartPicked; state.isDevilRoomDisabled = isDevilRoomDisabled; state.isCanSeeEverything = isCanSeeEverything; state.dungeonPlacementSeed = dungeonPlacementSeed; state.devilAngelRoomSeed = devilAngelRoomRNG._seed; state.angelRoomChance = angelRoomChance; state.bombPickupsSpawned = bombPickupsSpawned; state.roomMap = roomMap; state.mergedRoomConfigs.clear(); state.roomCount = nbRooms; state.rooms.resize(ROOM_DESCRIPTOR_COUNT); for (int i = 0; i < ROOM_DESCRIPTOR_COUNT; i++) { SavedRoom& saved = state.rooms[i]; if (roomList[i].data) room_config_ref_save(*roomList[i].data, saved.config, &state.mergedRoomConfigs); saved.desc = roomList[i]; saved.desc.data = nullptr; } state.currentRoomIdx = currentRoomIdx; state.lastRoomIdx = lastRoomIdx; state.brokenWatchState = g_game->challenge == CHALLENGE_SPEED ? BROKEN_WATCH_FAST : room->brokenWatchState; state.slowdownDuration = room->slowdownDuration; state.currentDimensionIdx = (uint8_t)currentDimensionIdx; state.lastRoomDimensionIdx = (uint8_t)lastRoomDimensionIdx; state.dungeonReturnPosition = dungeonReturnPosition; state.dungeonReturnRoomIndex = dungeonReturnRoomIndex; state.enterDoor = enterDoor; state.ventricleRazorPortals = ventricleRazorPortals; } // 009bd150 Copies the players into a game state, each leaving the room first unless the Glowing Hourglass saves: // every main player, then its backup player (marked as one), up to 8, then the Esau Jr. players. The first player // also keeps the glitched baby seed and the random babies. Each player learns its place in the save. // A player that leaving the room removed from the list is skipped. void PlayerManager::store_game_state(GameState* state) { bool isRewind = g_game->isStoringGlowingHourglassState; std::vector& players = state->players; // Whether every place is taken, which the original logs. auto is_full = [&]() { bool isFull = players.size() >= GAME_STATE_PLAYER_LIMIT; if (isFull) log_printf(LOG_WARN, "Number of players exceeds supported player limit (%d)!\n", GAME_STATE_PLAYER_LIMIT); return isFull; }; // Saves a player into the next place. auto player_store = [&](Entity_Player& player) { player.glowingHourglassIndex = (int)players.size(); player.StoreGameState(&players.emplace_back(), true); }; players.clear(); for (size_t i = 0; i < playerList.size(); i++) { Entity_Player* player = playerList[i]; size_t count = playerList.size(); if (player->variant != PLAYER_VARIANT_PLAYER) continue; if (is_full()) break; if (!isRewind) player->room_exit(true); if (playerList.size() < count) { i--; continue; } player_store(*player); Entity_Player* backup = player->backupPlayer; if (!backup) continue; if (is_full()) break; if (!isRewind) backup->room_exit(true); player_store(*backup); players.back().isBackupPlayer = true; } for (size_t i = 0; i < esauJrState.size(); i++) { GameStatePlayer& slot = state->esauJrStates[i]; if (esauJrState[i]) esauJrState[i]->StoreGameState(&slot, true); else slot.playerType = -1; } if (players.empty()) return; GameStatePlayer& first = players.front(); first.glitchBabySeed = (int)glitchBabyRng._seed; first.randomBabies = randomBabies; first.randomBabyCount = randomBabyCount; } // 007b0b40 A co-op baby's or sub player's character (a baby's skin) and hearts, a baby without eternal hearts. static CoPlayerState co_player_save(Entity_Player& player) { bool isBaby = player.variant == PLAYER_VARIANT_COOP_BABY; return {.blackHearts = player.blackHearts, .boneHearts = player.boneHearts, .boneHeartsMask = player.boneHeartsMask, .brokenHearts = player.brokenHearts, .eternalHearts = isBaby ? 0 : player.eternalHearts, .goldenHearts = player.goldenHearts, .maxHearts = player.maxHearts, .playerType = isBaby ? player.babySkin : player.playerType, .redHearts = player.redHearts, .rottenHearts = player.rottenHearts, .soulHearts = player.soulHearts}; } // 006d0370 A charmed enemy as a player keeps it: its kind, champion and health, and whether a player controls it. static EntityDesc charmed_enemy_save(Entity_NPC& npc) { return {.health = npc.health, .maxHealth = npc.maxHitPoints, .subtype = (uint32_t)npc.subtype, .type = (uint32_t)npc.type, .variant = (uint32_t)npc.variant, .championId = npc.championColorIdx, .isPlayerControlled = npc.IsFriendly() && npc.controllerID != -1}; } // The seeds of a player's item RNGs. static void rng_seeds_save(std::vector& rngs, std::vector& seeds) { seeds.clear(); for (RNG& rng : rngs) seeds.push_back(rng._seed); } // Whether a familiar follows its player into a saved run: not the Forgotten's body, Ventricle Razor's wisp or the // Umbilical Baby, and a temporary one only when those are saved. static bool is_familiar_saved(Entity_Familiar& familiar, bool isSaveTemporaryFamiliars) { bool isRazorWisp = familiar.variant == FAMILIAR_WISP && familiar.subtype == COLLECTIBLE_VENTRICLE_RAZOR; if (familiar.variant == FAMILIAR_FORGOTTEN_BODY || isRazorWisp || familiar.variant == FAMILIAR_UMBILICAL_BABY) return false; return isSaveTemporaryFamiliars || !familiar.isNotCountedAsFollower; } // 007b0be0 Copies the player into a saved player: its character, health and consumables, its sub player and the co-op // babies that belong to the first player, history, stats and counters, items, pockets and their RNGs, costumes, the // Moving Box, the friendly enemies it charmed (up to 10, the first twin only), its familiars and persistent effects. // The fields the curated player does not have yet keep their defaults: the candy heart and soul locket stat ups, the // soul charge, the last pill color, the kill counter, the crafting pool, the later poop spells and their counters, // the last collectible frame and the unknown fields. Its Echo Chamber items are saved without their kind, and its // voided passives without their second word. The unlisted restore state is never set, so familiars come from the room. void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTemporaryFamiliars) { GameStatePlayer& state = *saveState; Game& game = *g_game; PlayerManager& players = game.playerManager; state.controllerIndex = controllerIndex; state.isHolyMantle = holyMantleState != 0; state.playerType = playerType; state.redHearts = redHearts; state.maxHearts = maxHearts; state.soulHearts = soulHearts; state.blackHearts = blackHearts; state.boneHearts = boneHearts; state.boneHeartsMask = boneHeartsMask; state.eternalHearts = eternalHearts; state.subPlayer.reset(); if (subPlayer) state.subPlayer = co_player_save(*subPlayer); state.coopBabies.clear(); for (Entity_Player* baby : players.playerList) { bool isOwnBaby = baby->variant == PLAYER_VARIANT_COOP_BABY && !baby->parent.get() && players.GetPlayer(0) == this; if (isOwnBaby) state.coopBabies.push_back(co_player_save(*baby)); } state.history = history.historyItems; state.inventory = inventory; state.jarHearts = jarHearts; state.jarFlies = jarFlies; state.numCoins = numCoins; state.numKeys = numKeys; state.numBombs = numBombs; state.hasGoldenKey = hasGoldenKey; state.hasGoldenBomb = hasGoldenBomb; state.monkeyPawCounter = (int16_t)monkeyPawCounter; state.totalDamageTaken = (int16_t)totalDamageTaken; state.speedModifier = speedModifier; state.fireDelayModifier = fireDelayModifier; state.damageModifier = damageModifier; state.tearRangeModifier = tearRangeModifier; state.shotSpeedModifier = shotSpeedModifier; state.luckModifier = luckModifier; state.donateLuck = donateLuck; state.potatoPeelerCounter = potatoPeelerCounter; state.potatoPeelerBandageCounter = potatoPeelerBandageCounter; state.brittleBonesUpgrades = brittleBonesUpgrades; state.redStewBonusDuration = redStewBonusDuration; state.brokenHearts = brokenHearts; state.rottenHearts = rottenHearts; state.effectiveSoulCharge = effectiveSoulCharge; state.urnSouls = urnSouls; state.numGigaBombs = numGigaBombs; state.rockBottomDamage = rockBottomDamage; state.rockBottomMaxFireDelay = rockBottomMaxFireDelay; state.rockBottomLuck = rockBottomLuck; state.rockBottomTearRange = rockBottomTearRange; state.rockBottomMoveSpeed = rockBottomMoveSpeed; state.rockBottomShotSpeed = rockBottomShotSpeed; state.reverseEmpressMaxHearts = reverseEmpressMaxHearts; state.reverseSunBoneHearts = reverseSunBoneHearts; state.forgottenBodyRoomIdx = forgottenBodyRoomIdx; state.forgottenBodyPos = forgottenBodyPos; state.maggyHealthDrainCooldown = maggyHealthDrainCooldown; state.echoChamberItems.clear(); for (int item : echoChamberItems) state.echoChamberItems.push_back({.id = item}); std::copy(bagOfCraftingContent.begin(), bagOfCraftingContent.end(), state.bagOfCraftingContent.begin()); std::copy(poopSpellQueue.begin(), poopSpellQueue.end(), state.poopSpellQueue.begin()); state.poopMana = poopMana; state.effectiveBloodCharge = effectiveBloodCharge; state.itemCards = itemCards; state.modelingClayEffect = modelingClayEffect; state.keepersSackBonus = keepersSackBonus; state.isLevelStartPending = isLevelStartPending; state.hasCurseMistEffect = hasCurseMistEffect; state.consumablesBackup = consumablesBackup; state.curseMistFamiliars.clear(); for (Entity_Familiar* familiar : curseMistFamiliars) familiar->store_backup(&state.curseMistFamiliars.emplace_back()); state.curseMistRedHearts = curseMistRedHearts; state.curseMistPocketItems = curseMistPocketItems; state.curseMistTrinkets = curseMistTrinkets; state.isCoopGhost = isCoopGhost; state.ghostPocketItems = ghostPocketItems; state.ghostTrinkets = ghostTrinkets; state.wildCardItemType = wildCardItemType; state.wildCardItem = wildCardItem; state.wildCardVarData = wildCardVarData; state.samsonBerserkCharge = samsonBerserkCharge; state.ibsCharge = ibsCharge; Entity* owner = parent.get(); if (owner && owner->type == ENTITY_PLAYER) state.parentIndex = static_cast(owner)->glowingHourglassIndex; Entity* esau = darkEsau.get(); state.darkEsauHealth = !esau || esau->health <= 0 ? 0 : esau->health; state.proceduralItems = proceduralItems; state.edenSpeed = edenSpeed; state.edenFireDelay = edenFireDelay; state.edenDamage = edenDamage; state.edenTearRange = edenTearRange; state.edenShotSpeed = edenShotSpeed; state.edenLuck = edenLuck; state.vampireCharmKills = vampireCharmKills; state.activeItems = activeItems; state.tonsilCounter = tonsilCounter; state.tonsilCount = tonsilCount; state.numLeprosy = numLeprosy; state.playerSpriteScale = playerSpriteScale; if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) { state.headScale = headScale; state.bodyScale = bodyScale; } state.pocketItems = pocketItems; state.playerForms = playerForms; state.playerFormsRewarded = playerFormsRewarded; state.collectibleCounts = collectibleCounts; state.voidedCollectibles = voidedCollectibles; state.voidedPassives.clear(); for (int passive : voidedPassives) state.voidedPassives.push_back({.id = passive}); state.trinkets = trinkets; state.costumes.clear(); for (CostumeSpriteDesc& costume : costumeSpriteDescs) state.costumes.push_back({costume.item->id, costume.item->type}); state.movingBoxContents = movingBoxContents; rng_seeds_save(collectibleRNGs, state.collectibleRngSeeds); rng_seeds_save(trinketRNGs, state.trinketRngSeeds); rng_seeds_save(pillRNGs, state.pillRngSeeds); rng_seeds_save(cardRNGs, state.cardRngSeeds); state.pillEffectUses = pillEffectUses; state.rUaWizardTimer = rUaWizardTimer; state.bloodLustCounter = bloodLustCounter; state.deadCatLives = deadCatLives; state.friendBallEnemy = friendBallEnemy; state.purityState = purityState; state.immaculateConceptionState = immaculateConceptionState; state.cambionConceptionState = cambionConceptionState; state.conceptionFamiliarFlags = conceptionFamiliarFlags; state.d8DamageModifier = d8DamageModifier; state.d8SpeedModifier = d8SpeedModifier; state.d8RangeModifier = d8RangeModifier; state.d8FireDelayModifier = d8FireDelayModifier; state.goldenHearts = goldenHearts; state.planCKillCountdown = planCKillCountdown; state.imExcitedSpeedupCountdown = imExcitedSpeedupCountdown; std::vector& entities = game.room->entityList.updateEL; Entity_Player* twin = static_cast(twinPlayer.get()); bool isFirstTwin = !twin || twin->playerIndex == -1 || playerIndex <= twin->playerIndex || twin == this; state.charmedEnemies.clear(); for (size_t i = 0; !replacedPlayer && isFirstTwin && i < entities.size(); i++) { if (state.charmedEnemies.size() >= SAVED_CHARMED_ENEMY_LIMIT) break; Entity_NPC* npc = dynamic_cast(entities[i]); if (!npc || !npc->IsFriendly() || npc->IsBoss()) continue; if (npc->type == ENTITY_CHARGER && npc->variant == 0 && npc->subtype == CHARGER_MY_SHADOW) continue; bool isMine = npc->controllerID == -1 ? playerIndex == 0 : controllerIndex == npc->controllerID; if (isMine) state.charmedEnemies.push_back(charmed_enemy_save(*npc)); } state.familiars.clear(); for (Entity* entity : entities) { if (entity->type != ENTITY_FAMILIAR) continue; Entity_Familiar& familiar = *static_cast(entity); if (familiar.player == this && is_familiar_saved(familiar, isSaveTemporaryFamiliars)) familiar.store_backup(&state.familiars.emplace_back()); } state.levelEffectItems = levelEffectItems; bool isBleedingOut = (flags & FLAG_BLEED_OUT) && bleedSource.entity == this; state.bleedOutHealth = isBleedingOut ? bleedOutHealth : 0; state.greedsGulletHearts = greedsGulletHearts; state.greedsGulletOverflow = greedsGulletOverflow; state.persistentEffects.clear(); for (TemporaryEffect& effect : temporaryEffects.effects) if (effect.item && effect.item->isPersistentEffect) state.persistentEffects.push_back({effect.cooldown, effect.count, effect.item->id, (int)effect.item->type}); state.holyMantleStacks = holyMantleStacks; state.ductTapeMode = (uint8_t)ductTapeMode; state.queuedItem = queuedItem; state.temporaryEffects = temporaryEffects.effects; state.strengthMaxHearts = strengthMaxHearts; }