#include "persistent_game_data.h" #include "game.h" #include "info_display.h" #include "manager.h" #include #include #include #include #include #include #include #include #include #include constexpr int ACHIEVEMENT_NEVER = -2; constexpr int CUTSCENE_CREDITS = 2; constexpr int CUTSCENE_EPILOGUE = 3; constexpr int MOM_KILL_CUTSCENE_FIRST = 4; constexpr int MOM_KILL_CUTSCENE_COUNT = 11; constexpr int ACHIEVEMENT_EPILOGUE = 4; constexpr int ACHIEVEMENT_BESTIARY_COMPLETE = 324; constexpr int ACHIEVEMENT_ANGEL_KILLS = 373; constexpr int ACHIEVEMENT_PORTAL_KILLS = 349; constexpr int ACHIEVEMENT_LITTLE_HORN_KILLS = 356; constexpr int ACHIEVEMENT_RUN_MASK = 323; constexpr int ANGEL_KILLS_NEEDED = 10; constexpr int BOSS_KILLS_NEEDED = 20; constexpr int RUN_MASK_BITS = 41; constexpr int RUN_MASK_NEEDED = 5; constexpr int ENTITY_TYPE_MOMS_HEART = 78; constexpr int ENTITY_TYPE_URIEL = 271; constexpr int ENTITY_TYPE_GABRIEL = 272; constexpr int ENTITY_TYPE_PORTAL = 306; constexpr int ENTITY_TYPE_LITTLE_HORN = 404; constexpr int EVENT_COUNTER_MOM_KILLS = 1; constexpr int EVENT_COUNTER_ISAAC_KILLS = 11; constexpr int EVENT_COUNTER_SATAN_KILLS = 13; constexpr int EVENT_COUNTER_BLUE_BABY_KILLS = 24; constexpr int EVENT_COUNTER_LAMB_KILLS = 25; constexpr int EVENT_COUNTER_MEGA_SATAN_KILLS = 26; constexpr int EVENT_COUNTER_GREED_DONATIONS = 115; constexpr int EVENT_COUNTER_HUSH_KILLS = 158; constexpr int EVENT_COUNTER_DELIRIUM_KILLS = 187; constexpr int EVENT_COUNTER_RUN_MASK_LOW = 188; constexpr int EVENT_COUNTER_DAILIES_PLAYED = 190; constexpr int EVENT_COUNTER_MOTHER_KILLS = 491; constexpr int EVENT_COUNTER_BEAST_KILLS = 492; constexpr int EVENT_COUNTER_RUN_MASK_HIGH = 496; constexpr int GREED_DONATION_STEP = 1000; constexpr int GREED_DONATION_HALF = 500; constexpr uint32_t DAILIES_PLAYED_NEEDED = 31; constexpr int ACHIEVEMENT_DAILIES_PLAYED = 325; // The save versions' 16-byte headers, oldest first, and the version each stands for. Only the last is read. constexpr std::array SAVE_HEADERS = {"ISAACNGSAVE06R ", "ISAACNGSAVE07R ", "ISAACNGSAVE08R ", "ISAACNGSAVE09R "}; constexpr size_t SAVE_HEADER_SIZE = 16; constexpr int SAVE_VERSION_FIRST = 6; constexpr int SAVE_VERSION_READ = 9; // The chunks of a save, by the id the file gives them. enum SaveChunk { CHUNK_ACHIEVEMENTS = 1, CHUNK_COUNTERS, CHUNK_LEVEL_COUNTERS, CHUNK_COLLECTIBLES, CHUNK_MINIBOSSES, CHUNK_BOSSES, CHUNK_CHALLENGES, CHUNK_CUTSCENES, CHUNK_GAME_SETTINGS, CHUNK_SPECIAL_SEEDS, CHUNK_BESTIARY, CHUNK_LIMIT = CHUNK_BESTIARY }; // The bestiary chunk's lists, by the id the file gives them. enum BestiaryList { BESTIARY_ENCOUNTERS = 1, BESTIARY_KILLS, BESTIARY_HITS, BESTIARY_DEATHS, BESTIARY_LIST_COUNT = BESTIARY_DEATHS }; // Whether a chunk with more entries than the game keeps reads only those (GameSettings) or reads on. enum ChunkCount { CHUNK_COUNT_AS_FILED, CHUNK_COUNT_CLAMPED }; // How the logs name a chunk: as its title, and in the count mismatch warning. struct ChunkName { const char* title; const char* noun; ChunkCount count = CHUNK_COUNT_AS_FILED; }; // The bit of a completion mark set by a win on hard. constexpr int COMPLETION_HARD_BIT = 2; // The marks counted toward a character's full set, all twelve on hard for the HARD achievement. constexpr std::array COMPLETION_FULL_SET = { COMPLETION_MOMS_HEART, COMPLETION_ISAAC, COMPLETION_SATAN, COMPLETION_BOSS_RUSH, COMPLETION_BLUE_BABY, COMPLETION_LAMB, COMPLETION_MEGA_SATAN, COMPLETION_ULTRA_GREED, COMPLETION_HUSH, COMPLETION_DELIRIUM, COMPLETION_MOTHER, COMPLETION_BEAST}; // The characters the completion achievements count, the regular ones then the tainted ones, by player type. constexpr int COMPLETION_REGULAR_COUNT = 17; constexpr std::array COMPLETION_PLAYER_TYPES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37}; constexpr int BLUE_BABY_CHARACTERS_FIRST = 3; constexpr int BLUE_BABY_CHARACTERS_SECOND = 6; constexpr int ACHIEVEMENT_BLUE_BABY_FIRST = 346; constexpr int ACHIEVEMENT_BLUE_BABY_SECOND = 347; constexpr int ACHIEVEMENT_MEGA_SATAN_ALL = 276; constexpr int ACHIEVEMENT_HARD_ALL_REGULAR = 547; constexpr int ACHIEVEMENT_HARD_ALL = 636; // An achievement an event counter unlocks once it reaches minimum. Counters compare unsigned, as the game does. struct CounterUnlock { int counter; uint32_t minimum; int achievement; }; // The counter unlocks IncreaseEventCounter checks, in its order, split where it checks something else. constexpr CounterUnlock COUNTER_UNLOCKS_FIRST[] = { {202, 1, 359}, {202, 10, 385}, {200, 10, 377}, {201, 5, 382}, {2, 100, 85}, {2, 500, 350}, {3, 10, 28}, {3, 100, 12}, {7, 4, 36}, {9, 10, 26}, {5, 100, 145}, {194, 5, 353}, {11, 10, 68}, {11, 5, 57}, {13, 5, 78}}; constexpr CounterUnlock COUNTER_UNLOCKS_SECOND[] = { {10, 100, 30}, {1, 1, 81}, {1, 2, 150}, {1, 3, 8}, {1, 4, 139}, {1, 5, 33}, {1, 6, 140}, {1, 7, 141}, {1, 8, 10}, {1, 9, 11}, {1, 10, 32}, {1, 10, 234}, {1, 11, 34}, {1, 11, 342}, {1, 16, 343}, {1, 21, 344}, {1, 30, 345}, {12, 20, 61}, {14, 100, 64}, {15, 10, 66}, {15, 25, 380}, {16, 20, 142}, {16, 25, 376}, {16, 50, 383}, {17, 30, 147}, {18, 30, 148}}; constexpr CounterUnlock COUNTER_UNLOCKS_LAST[] = { {192, 5, 336}, {193, 7, 354}, {195, 20, 358}, {196, 20, 362}, {197, 50, 364}, {198, 20, 371}, {199, 50, 375}, {493, 10, 409}, {494, 10, 545}, {495, 5, 523}, {158, 3, 407}}; constexpr int ACHIEVEMENT_BLUE_BABY_AND_LAMB = 41; // The achievement each challenge unlocks when won, by challenge id. constexpr std::array CHALLENGE_WIN_ACHIEVEMENTS = { 0, 89, 90, 91, 92, 93, 94, 120, 96, 97, 98, 99, 100, 60, 63, 101, 102, 103, 104, 62, 95, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 331, 332, 333, 334, 335, 517, 518, 519, 520, 521, 522, 531, 532, 533, 538}; // The achievement each challenge unlocks once every achievement its challenges.xml entry lists is unlocked. constexpr std::array CHALLENGE_LIST_ACHIEVEMENTS = { 0, 0, 0, 0, 157, 158, 159, 160, 161, 162, 163, 164, 0, 0, 0, 0, 0, 0, 0, 165, 166, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 277, 278, 279, 280, 281, 0, 508, 509, 510, 511, 512, 513, 514, 515, 516}; // The collection unlocks: sets of items seen together, and the counts of items seen and achievements unlocked. constexpr std::array COLLECTION_SET_FIRST = {116, 63, 356}; constexpr std::array COLLECTION_SET_SECOND = {337, 232}; constexpr int ACHIEVEMENT_COLLECTION_SET_FIRST = 381; constexpr int ACHIEVEMENT_COLLECTION_SET_SECOND = 363; constexpr std::array COLLECTION_UNOBTAINABLE = {276, 333, 334, 335, 283, 331}; constexpr std::array COLLECTION_ACHIEVEMENTS_EXEMPT = {129, 130, 131, 132, 133, 156, 82, 84, 175}; constexpr int COLLECTION_BASE_LAST = 346; constexpr int COLLECTION_BASE_NEEDED = 346; constexpr int COLLECTION_BASE_ACHIEVEMENTS_END = 179; constexpr int COLLECTION_BASE_ACHIEVEMENTS_NEEDED = 177; constexpr int ACHIEVEMENT_BASE_COLLECTION = 69; constexpr int ACHIEVEMENT_BASE_EVERYTHING = 84; constexpr int COLLECTION_SEEN_NEEDED = 510; constexpr int COLLECTION_SEEN_ALL = 732; constexpr int ACHIEVEMENTS_FIRST_NEEDED = 275; constexpr int ACHIEVEMENTS_SECOND_NEEDED = 402; constexpr int ACHIEVEMENTS_ALL_NEEDED = 640; constexpr int ACHIEVEMENT_COLLECTION_FIRST = 235; constexpr int ACHIEVEMENT_COLLECTION_SECOND = 339; constexpr int ACHIEVEMENT_COLLECTION_ALL = 637; // The load-time unlocks for saves from before their checks existed. constexpr std::array FIRST_KILL_COUNTERS = {40, 82, 96, 110, 54, 68, 157, 129, 143, 186}; constexpr int ACHIEVEMENT_FIRST_KILL = 340; constexpr int ACHIEVEMENT_GREED_DONATIONS = 341; constexpr int ACHIEVEMENT_GREED_DONATIONS_ALT = 249; constexpr std::array LOAD_COUNTER_UNLOCKS = {{{25, 1, 348}, {187, 1, 357}}}; constexpr std::array, 5> LOAD_ACHIEVEMENT_UNLOCKS = { {{37, 351}, {38, 365}, {39, 368}, {40, 374}, {337, 360}}}; // The counters shared between netplay saves, and the achievements. constexpr std::array SHARED_COUNTERS = {114, 115, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 212, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403}; constexpr std::array SHARED_ACHIEVEMENTS = {242, 243, 244, 245, 275, 246, 247, 248, 341, 249, 250, 251}; // The folder names of the earlier games' saves, swapped into this game's save path to find them. constexpr std::string_view SAVE_FOLDER = "Binding of Isaac Repentance+"; constexpr std::string_view SAVE_FOLDER_AFTERBIRTH = "Binding of Isaac Afterbirth"; constexpr std::string_view SAVE_FOLDER_AFTERBIRTH_PLUS = "Binding of Isaac Afterbirth+"; constexpr std::string_view SAVE_FOLDER_REBIRTH = "Binding of Isaac Rebirth"; constexpr std::string_view SAVE_FOLDER_REPENTANCE = "Binding of Isaac Repentance"; constexpr std::string_view SAVE_FILE_PREFIX_CLOUD = "rep+"; constexpr int BACKUP_YEAR_BASE = 1900; constexpr int BACKUP_DIGITS = 100; // The CRC-32 table for the reflected polynomial, as the game builds it: its shifts after the first are arithmetic, // so it is not the standard table, and saves only check against this one. constexpr uint32_t CRC32_POLYNOMIAL = 0xedb88320; constexpr std::array CRC32_TABLE = [] { std::array table{}; for (uint32_t index = 0; index < table.size(); index++) { uint32_t value = index; for (int bit = 0; bit < 8; bit++) { uint32_t shifted = bit == 0 ? value >> 1 : (uint32_t)((int32_t)value >> 1); value = (value & 1 ? CRC32_POLYNOMIAL : 0) ^ shifted; } table[index] = value; } return table; }(); // Reads a save from memory as the game's file stream does, leaving a value as it was when the file ends first. struct SaveReader { std::span data; size_t position = 0; template void read(Value& value) { if (data.size() - position < sizeof(Value)) return; std::memcpy(&value, data.data() + position, sizeof(Value)); position += sizeof(Value); } bool is_end() { return position >= data.size(); } }; // Whether a list holds a value. template static bool is_listed(List& list, int value) { return std::ranges::find(list, value) != std::ranges::end(list); } // 00683410 Folds bytes into the checksum. void Checksum::Update(std::span data) { if (mode == CHECKSUM_CRC32) { uint32_t crc = ~state; for (uint8_t byte : data) crc = crc >> 8 ^ CRC32_TABLE[(byte ^ crc) & 0xff]; state = ~crc; return; } for (uint8_t byte : data) { word |= (uint32_t)byte << (wordSize * 8); if (++wordSize < sizeof(word)) continue; state = std::rotr(state, 1) + word; word = 0; wordSize = 0; } } // The checksum so far, a part word padded with zeroes, as the game finishes it in checksum_stream. uint32_t Checksum::value_get() { return mode == CHECKSUM_ROTATE_ADD && wordSize ? std::rotr(state, 1) + word : state; } // The checksum a save ends with: CRC-32 from the seed over everything between the header and itself. static uint32_t save_checksum_get(std::span data) { Checksum checksum; checksum.Update(data); return checksum.value_get(); } // Appends a value's bytes to a file being written. template static void value_append(std::vector& file, Value value) { uint8_t* bytes = (uint8_t*)&value; file.insert(file.end(), bytes, bytes + sizeof(Value)); } // Appends a chunk of flags (one byte each) or counters, after its id, its size (entrySize per entry) and its count. template static void chunk_append(std::vector& file, SaveChunk id, Entries& entries, uint32_t entrySize = sizeof(int)) { value_append(file, (int)id); value_append(file, (uint32_t)(entries.size() * entrySize)); value_append(file, (uint32_t)entries.size()); for (auto entry : entries) { if constexpr (std::is_same_v) value_append(file, (uint8_t)entry); else value_append(file, entry); } } // Reads a chunk of flags (a byte above zero is set) or counters, up to the count the game keeps and the chunk's size. template static void chunk_read(SaveReader& reader, uint32_t chunkSize, Entries& entries, ChunkName name) { using Stored = typename Entries::value_type; using Filed = std::conditional_t, int8_t, int>; uint32_t count = 0; Filed value = 0; log_printf(LOG_INFO, "Reading %s\n", name.title); reader.read(count); if (count != entries.size()) log_printf(LOG_WARN, "Different number of %s %d/%d\n", name.noun, (int)count, (int)entries.size()); if (name.count == CHUNK_COUNT_CLAMPED && count > entries.size()) count = entries.size(); for (uint32_t index = 0; index < count && index * sizeof(Filed) < chunkSize; index++) { reader.read(value); if (index >= entries.size()) continue; if constexpr (std::is_same_v) entries[index] = value > 0; else entries[index] = value; } log_printf(LOG_INFO, "Done Reading %s\n", name.title); } // Loads a whole file, false when it cannot be opened. bool file_load(std::string_view path, std::vector& data) { size_t size = 0; void* bytes = SDL_LoadFile(std::string(path).c_str(), &size); if (!bytes) return false; data.assign((uint8_t*)bytes, (uint8_t*)bytes + size); SDL_free(bytes); return true; } // The save path with the last occurrence of this game's folder name swapped for another game's. static std::string save_folder_swap(std::string_view path, std::string_view folder) { std::string swapped(path); size_t position = swapped.rfind(SAVE_FOLDER); if (position != std::string::npos) swapped.replace(position, SAVE_FOLDER.size(), folder); return swapped; } // The key the bestiary files an entity under. static int bestiary_key_get(EntityConfig_Entity& entity) { return (int)entity_key(entity.id, entity.variant, 0); } // The bestiary entry for an entity, or null when it has no bestiary page. static EntityConfig_Entity* bestiary_entity_get(int type, int variant) { EntityConfig_Entity* entity = g_manager->entityConfig.GetBestiaryConfig(type, variant); return entity && entity->isBestiary ? entity : nullptr; } // A bestiary count for an entity, 0 when it has none or no bestiary page. static int bestiary_count_get(std::map& counts, int type, int variant) { EntityConfig_Entity* entity = bestiary_entity_get(type, variant); if (!entity) return 0; auto found = counts.find(bestiary_key_get(*entity)); return found == counts.end() ? 0 : found->second; } // The bestiary list a save file's list id names, or null for an id it does not know. static std::map* bestiary_list_get(PersistentGameData_Bestiary& bestiary, uint32_t list) { switch (list) { case BESTIARY_ENCOUNTERS: return &bestiary.encounters; case BESTIARY_KILLS: return &bestiary.kills; case BESTIARY_HITS: return &bestiary.hits; case BESTIARY_DEATHS: return &bestiary.deaths; default: return nullptr; } } // Reads the bestiary chunk, replacing every count: its lists of key and count pairs, each sized at 4 bytes a pair. static void bestiary_read(SaveReader& reader, PersistentGameData_Bestiary& bestiary) { uint32_t listCount = 0; uint32_t listId = 0; int key = 0; int listSize = 0; int value = 0; log_printf(LOG_INFO, "Reading Bestiary Counters\n"); bestiary = {}; reader.read(listCount); for (uint32_t list = 0; list < listCount; list++) { reader.read(listId); std::map* counts = bestiary_list_get(bestiary, listId); if (!counts) continue; reader.read(listSize); for (int entry = 0; listSize > 0 && entry < (int)((uint32_t)listSize / sizeof(int)); entry++) { reader.read(key); reader.read(value); (*counts)[key] = value; } } log_printf(LOG_INFO, "Done Reading Bestiary Counters\n"); } // Appends the bestiary chunk, its lists in the game's order (deaths, kills, hits, encounters). static void bestiary_append(std::vector& file, PersistentGameData_Bestiary& bestiary) { std::array lists = {BESTIARY_DEATHS, BESTIARY_KILLS, BESTIARY_HITS, BESTIARY_ENCOUNTERS}; size_t count = bestiary.encounters.size() + bestiary.hits.size() + bestiary.deaths.size() + bestiary.kills.size(); value_append(file, (int)CHUNK_BESTIARY); value_append(file, (uint32_t)(count * sizeof(int))); value_append(file, (uint32_t)lists.size()); for (BestiaryList list : lists) { std::map& counts = *bestiary_list_get(bestiary, list); value_append(file, (int)list); value_append(file, (uint32_t)(counts.size() * sizeof(int))); for (auto [key, value] : counts) { value_append(file, key); value_append(file, value); } } } // Checks counter unlocks in order. static void counter_unlocks_check(PersistentGameData& data, std::span unlocks) { for (CounterUnlock unlock : unlocks) if ((uint32_t)data.eventCounters[unlock.counter] >= unlock.minimum) data.TryUnlock(unlock.achievement); } // Marks a cutscene as seen at least once, and with it the credits. static void cutscene_seen_mark(PersistentGameData& data, int cutscene) { data.cutsceneCounters[cutscene] = std::max(data.cutsceneCounters[cutscene], 1); data.cutsceneCounters[CUTSCENE_CREDITS] = std::max(data.cutsceneCounters[CUTSCENE_CREDITS], 1); } // Whether an achievement is unlocked, false for an id past the table. static bool is_achievement_set(PersistentGameData& data, int achievement) { return achievement >= 0 && achievement < ACHIEVEMENT_COUNT && data.achievements[achievement]; } // 0091b720 Copies the counters and achievements netplay shares from one save to another. void PersistentGameData::copy_shared_progress(PersistentGameData& destination, PersistentGameData& source) { for (int counter : SHARED_COUNTERS) destination.eventCounters[counter] = source.eventCounters[counter]; for (int achievement : SHARED_ACHIEVEMENTS) destination.achievements[achievement] = source.achievements[achievement]; } // 009262b0 Forgets all progress, keeping the file path, and the save count unless clearing all. void PersistentGameData::Clear(ClearMode mode) { uint32_t keptSaveCount = mode == CLEAR_ALL ? 0 : saveCount; std::string keptFilePath = std::move(filePath); *this = {}; filePath = std::move(keptFilePath); saveCount = keptSaveCount; } // An earlier game's save Load imports when this game has none: the folder it sits in, how it is read and the logs. enum SaveFormat { SAVE_FORMAT_REPENTANCE, SAVE_FORMAT_AFTERBIRTH, SAVE_FORMAT_REBIRTH }; struct SaveImport { std::string_view folder; SaveFormat format; const char* name; const char* success; const char* failure; }; // The imports Load tries in order. Afterbirth+ is read as a Repentance save, so its version 8 file never imports. constexpr SaveImport SAVE_IMPORTS[] = { {SAVE_FOLDER_REPENTANCE, SAVE_FORMAT_REPENTANCE, "Repentance", "Successfully imported!\n", "No Repentance PersistentGameData, trying to import AB+ save.\n"}, {SAVE_FOLDER_AFTERBIRTH_PLUS, SAVE_FORMAT_REPENTANCE, "AB+", "Successfully imported from AB+!\n", "No AB+ PersistentGameData, trying to import AB save.\n"}, {SAVE_FOLDER_AFTERBIRTH, SAVE_FORMAT_AFTERBIRTH, "AB", "Successfully imported from AB!\n", "No AB PersistentGameData, trying to import Rebirth save.\n"}, {SAVE_FOLDER_REBIRTH, SAVE_FORMAT_REBIRTH, nullptr, "Successfully imported Rebirth save!!\n", "No PersistentGameData found for any version of Isaac, creating new one.\n"}, }; // 00926a50 Loads the save at path. Without one it imports the save of Repentance, Afterbirth+, Afterbirth or Rebirth // beside it, or starts a new one, and writes it. bool PersistentGameData::Load(std::string_view path) { std::vector file; filePath = path; log_printf(LOG_INFO, "Loading Repentance PersistentGameData from disk: %s.\n", filePath.c_str()); if (file_load(path, file)) { isFileLoaded = stream_load(file); return isFileLoaded; } Clear(CLEAR_ALL); for (const SaveImport& import : SAVE_IMPORTS) { if (!TryImportLocalSave(path, import)) { log_printf(LOG_INFO, "%s", import.failure); continue; } log_printf(LOG_INFO, "%s", import.success); if (!isFileLoaded) return false; Save(); return isFileLoaded; } Clear(CLEAR_ALL); Save(); return false; } // (0092c7e0, 0092c550, 0092c2c0, 0092b2e0, 0092b930) Imports an earlier game's save, found by swapping its folder // into the save path (and dropping a "rep+" prefix for Rebirth), false when there is none. bool PersistentGameData::TryImportLocalSave(std::string_view path, const SaveImport& import) { std::string importPath(path); std::vector file; if (import.format == SAVE_FORMAT_REBIRTH) { size_t prefix = importPath.find(SAVE_FILE_PREFIX_CLOUD); if (prefix != std::string::npos) importPath.erase(prefix, SAVE_FILE_PREFIX_CLOUD.size()); } importPath = save_folder_swap(importPath, import.folder); if (import.format == SAVE_FORMAT_REBIRTH) log_printf(LOG_INFO, "Loading RebirthPersistentGameData from disk: %s.\n", importPath.c_str()); if (!file_load(importPath, file)) { if (import.name) log_printf(LOG_INFO, "No %s save found! (%s)\n", import.name, importPath.c_str()); return false; } if (import.format == SAVE_FORMAT_AFTERBIRTH) reconstruction_missing("PersistentGameData::import_afterbirth_save 0092b930"); if (import.format == SAVE_FORMAT_REBIRTH) reconstruction_missing("RebirthSaveData load 009e4260"); isFileLoaded = read(file); return isFileLoaded; } // 00926e90 Reads a save, completes what older saves lack, and writes it back (with a backup) if that changed it. bool PersistentGameData::stream_load(std::span file) { if (!read(file)) return false; backfill_cutscene_counters(); check_counter_unlocks(); check_collection_unlocks(); if (isChangesMade && isFileLoaded) { isChangesMade = false; BackupSaveFile(); Save(); } return true; } // 00926f10 Reads a save's chunks into this, after checking its header and checksum. Only version 9 is read. // A file too short to hold a checksum fails the check, where the game read before its start. bool PersistentGameData::read(std::span file) { SaveReader reader{file}; std::string_view header((const char*)file.data(), std::min(file.size(), SAVE_HEADER_SIZE)); auto version = std::ranges::find(SAVE_HEADERS, header); uint32_t storedChecksum = 0; int chunkId = 0; if (version == SAVE_HEADERS.end()) { log_printf(LOG_INFO, "PersistentGameData wrong file header (%.16s)\n", std::string(header).c_str()); return false; } if (file.size() >= SAVE_HEADER_SIZE + sizeof(storedChecksum)) std::memcpy(&storedChecksum, file.data() + file.size() - sizeof(storedChecksum), sizeof(storedChecksum)); if (file.size() < SAVE_HEADER_SIZE + sizeof(storedChecksum) || storedChecksum != save_checksum_get(file.subspan(SAVE_HEADER_SIZE, file.size() - SAVE_HEADER_SIZE - 4))) { log_printf(LOG_INFO, "[warn] PersistentGameData checksum invalid!\n"); return false; } if (version - SAVE_HEADERS.begin() + SAVE_VERSION_FIRST < SAVE_VERSION_READ) { log_printf(LOG_INFO, "[warn] Unsuported save version (probably an AB or Rebirth save)!\n"); return false; } reader.position = SAVE_HEADER_SIZE; reader.read(gameStateChecksum); while (!reader.is_end() && chunkId >= 0 && chunkId < CHUNK_LIMIT) { uint32_t chunkSize = 0; auto entries_read = [&](auto& entries, ChunkName name) { chunk_read(reader, chunkSize, entries, name); }; reader.read(chunkId); log_printf(LOG_INFO, "Reading chunk %d\n", chunkId); reader.read(chunkSize); if (chunkSize == 0) continue; switch (chunkId) { case CHUNK_ACHIEVEMENTS: entries_read(achievements, {"Achievements", "achievements"}); break; case CHUNK_COUNTERS: entries_read(eventCounters, {"Counters", "counters"}); break; case CHUNK_LEVEL_COUNTERS: entries_read(levelCounters, {"Level Counters", "counters"}); break; case CHUNK_COLLECTIBLES: entries_read(itemsCollection, {"Collectibles", "collectibles in collection"}); break; case CHUNK_MINIBOSSES: entries_read(miniBosses, {"Mini Bosses", "minibosses"}); break; case CHUNK_BOSSES: entries_read(bosses, {"Bosses", "minibosses"}); break; case CHUNK_CHALLENGES: entries_read(challenges, {"Challenge Counters", "challenges"}); break; case CHUNK_CUTSCENES: entries_read(cutsceneCounters, {"Cutscene Counters", "cutscenes"}); break; case CHUNK_GAME_SETTINGS: { std::array settings = {lastDifficulty, characterMenuShown}; entries_read(settings, {"GameSettings", "settings", CHUNK_COUNT_CLAMPED}); lastDifficulty = settings[0]; characterMenuShown = settings[1]; break; } case CHUNK_SPECIAL_SEEDS: entries_read(specialSeeds, {"Special Seed Counters", "special seeds"}); break; case CHUNK_BESTIARY: bestiary_read(reader, bestiary); break; default: break; } } reader.read(saveCount); return true; } // 009282e0 The save file's bytes: the version 9 header, every chunk, the save count (counting this one) and the // checksum. std::vector PersistentGameData::write() { std::vector file(SAVE_HEADERS.back().begin(), SAVE_HEADERS.back().end()); std::array settings = {lastDifficulty, characterMenuShown}; value_append(file, gameStateChecksum); chunk_append(file, CHUNK_ACHIEVEMENTS, achievements, sizeof(bool)); chunk_append(file, CHUNK_COUNTERS, eventCounters); chunk_append(file, CHUNK_LEVEL_COUNTERS, levelCounters); chunk_append(file, CHUNK_COLLECTIBLES, itemsCollection); chunk_append(file, CHUNK_MINIBOSSES, miniBosses); chunk_append(file, CHUNK_BOSSES, bosses); chunk_append(file, CHUNK_CHALLENGES, challenges); chunk_append(file, CHUNK_CUTSCENES, cutsceneCounters); chunk_append(file, CHUNK_GAME_SETTINGS, settings); chunk_append(file, CHUNK_SPECIAL_SEEDS, specialSeeds); bestiary_append(file, bestiary); value_append(file, ++saveCount); value_append(file, save_checksum_get(std::span(file).subspan(SAVE_HEADER_SIZE))); return file; } // 009294f0 Writes the save to its file. Netplay's shared save is not written, since online play is offline. void PersistentGameData::Save() { if (filePath.empty()) { log_printf(LOG_INFO, "PersistentGameData no filename supplied\n"); return; } write_file(filePath); } // 009293d0 Writes the save to path, making its folders. void PersistentGameData::write_file(std::string_view path) { std::string pathText(path); std::error_code error; std::filesystem::create_directories(std::filesystem::path(pathText).parent_path(), error); SDL_IOStream* stream = SDL_IOFromFile(pathText.c_str(), "wb"); if (!stream) { log_printf(LOG_INFO, "Could not open %s for writing!\n", pathText.c_str()); return; } std::vector file = write(); SDL_WriteIO(stream, file.data(), file.size()); SDL_CloseIO(stream); } // 009292c0 Writes a copy of the save to save_backups/, named by today's date (YYYYMMDD) and the save's file name. void PersistentGameData::BackupSaveFile() { if (g_manager->netplayManager.is_online()) return; std::time_t now = std::time(nullptr); std::tm* date = std::localtime(&now); int stamp = ((date->tm_year + BACKUP_YEAR_BASE) * BACKUP_DIGITS + date->tm_mon + 1) * BACKUP_DIGITS + date->tm_mday; write_file(platform.userDataDirectory + "save_backups/" + std::to_string(stamp) + "." + get_save_file_name()); } // 00929240 The save's file name, without its folders. std::string PersistentGameData::get_save_file_name() { return filePath.substr(filePath.rfind('/') + 1); } // 009299e0 Freezes or unfreezes the save. void PersistentGameData::SetReadOnly(bool isEnabled) { log_printf(LOG_INFO, "Setting PersistentGameData ReadOnly to %s\n", isEnabled ? "True" : "False"); isReadOnly = isEnabled; } // 00927d20 Marks as seen the cutscenes older saves played before cutscenes were counted, from the kills and // achievements that show them. void PersistentGameData::backfill_cutscene_counters() { // The cutscene each kill counter shows once it is above zero. constexpr std::pair KILL_CUTSCENES[] = { {EVENT_COUNTER_SATAN_KILLS, 15}, {EVENT_COUNTER_ISAAC_KILLS, 16}, {EVENT_COUNTER_LAMB_KILLS, 18}, {EVENT_COUNTER_BLUE_BABY_KILLS, 17}, {EVENT_COUNTER_MEGA_SATAN_KILLS, 19}, {EVENT_COUNTER_HUSH_KILLS, 20}, {EVENT_COUNTER_DELIRIUM_KILLS, 22}}; constexpr int CUTSCENE_MOTHER = 24; constexpr int CUTSCENE_BEAST = 25; constexpr int CUTSCENE_BEAST_ENDING = 26; int momKills = eventCounters[EVENT_COUNTER_MOM_KILLS]; if (achievements[ACHIEVEMENT_EPILOGUE]) cutscene_seen_mark(*this, CUTSCENE_EPILOGUE); for (int kill = 0; kill < MOM_KILL_CUTSCENE_COUNT && kill < momKills; kill++) cutscene_seen_mark(*this, MOM_KILL_CUTSCENE_FIRST + kill); for (auto [counter, cutscene] : KILL_CUTSCENES) if (eventCounters[counter] > 0) cutscene_seen_mark(*this, cutscene); if (eventCounters[EVENT_COUNTER_MOTHER_KILLS] != 0) cutscene_seen_mark(*this, CUTSCENE_MOTHER); if (eventCounters[EVENT_COUNTER_BEAST_KILLS] == 0) return; cutscene_seen_mark(*this, CUTSCENE_BEAST); cutscene_seen_mark(*this, CUTSCENE_BEAST_ENDING); } // 00929820 Checks the unlocks older saves may have earned before their checks existed, without popups. void PersistentGameData::check_counter_unlocks() { OptionsConfig& options = g_manager->optionsConfig; int popupsMode = options.popupsMode; uint32_t greedDonations = eventCounters[EVENT_COUNTER_GREED_DONATIONS]; options.popupsMode = 0; IncreaseEventCounter(0, 0); if (!isReadOnly) check_collection_set_unlocks(); if (!achievements[ACHIEVEMENT_FIRST_KILL] && std::ranges::any_of(FIRST_KILL_COUNTERS, [&](int counter) { return eventCounters[counter] != 0; })) TryUnlock(ACHIEVEMENT_FIRST_KILL); if (!achievements[ACHIEVEMENT_GREED_DONATIONS] && (greedDonations % GREED_DONATION_STEP >= GREED_DONATION_HALF || achievements[ACHIEVEMENT_GREED_DONATIONS_ALT])) TryUnlock(ACHIEVEMENT_GREED_DONATIONS); counter_unlocks_check(*this, LOAD_COUNTER_UNLOCKS); for (auto [required, achievement] : LOAD_ACHIEVEMENT_UNLOCKS) if (achievements[required]) TryUnlock(achievement); options.popupsMode = popupsMode; } // 009296c0 Unlocks each challenge's achievement once every achievement its challenges.xml entry lists is unlocked. void PersistentGameData::check_challenge_unlocks() { for (int challenge = 1; challenge < CHALLENGE_COUNT; challenge++) { std::vector& required = g_manager->GetChallengeParams(challenge).achievementList; auto isUnlocked = [&](int achievement) { return is_achievement_set(*this, achievement); }; if (CHALLENGE_LIST_ACHIEVEMENTS[challenge] && std::ranges::all_of(required, isUnlocked)) TryUnlock(CHALLENGE_LIST_ACHIEVEMENTS[challenge]); } } // 00929790 Logs a Steam achievement unlock. Steam is offline, so nothing is sent. void PersistentGameData::UnlockSteamAchievement(int achievementID) { if (isSteamAchievementsEnabled) log_printf(LOG_INFO, "unlock steam achievement '%d'\n", achievementID); } // 00929a20 Unlocks an achievement, with its popup, and checks the unlocks that depend on it. False when frozen or // already unlocked. An id past the table is refused, where the game wrote past it. bool PersistentGameData::TryUnlock(int achievementID) { if (isReadOnly || achievementID <= 0 || achievementID >= ACHIEVEMENT_COUNT || achievements[achievementID]) return false; achievements[achievementID] = true; if ((!g_manager->netplayManager.is_online() || !Manager::AchievementUnlocksDisallowed()) && isSteamAchievementsEnabled) { UnlockSteamAchievement(achievementID); Manager::queue_achievement_popup(achievementID); } isChangesMade = true; check_challenge_unlocks(); check_collection_unlocks(); return true; } // 00929aa0 Whether an achievement counts as unlocked: none (below 0, but for ACHIEVEMENT_NEVER) always does, and // everything does during a daily challenge or a debug run. bool PersistentGameData::Unlocked(int achievementID) { if (achievementID == ACHIEVEMENT_NEVER || achievementID >= ACHIEVEMENT_COUNT) return false; if (achievementID <= 0 || achievements[achievementID]) return true; return g_manager->state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug); } // 00929b40 Adds to an event counter (which stops at 0) and checks every unlock counters and completion marks give. // An id past the counters is ignored, where the game wrote past them. void PersistentGameData::IncreaseEventCounter(int eventCounter, int num) { if (isReadOnly || eventCounter < 0 || eventCounter >= EVENT_COUNTER_COUNT) return; int& counter = eventCounters[eventCounter]; counter = (int)std::max((int64_t)counter + num, 0); isChangesMade = true; counter_unlocks_check(*this, COUNTER_UNLOCKS_FIRST); if (eventCounters[EVENT_COUNTER_BLUE_BABY_KILLS] && eventCounters[EVENT_COUNTER_LAMB_KILLS]) TryUnlock(ACHIEVEMENT_BLUE_BABY_AND_LAMB); counter_unlocks_check(*this, COUNTER_UNLOCKS_SECOND); if ((uint32_t)eventCounters[EVENT_COUNTER_DAILIES_PLAYED] >= DAILIES_PLAYED_NEEDED && g_manager->state == MANAGER_STATE_MENU) TryUnlock(ACHIEVEMENT_DAILIES_PLAYED); counter_unlocks_check(*this, COUNTER_UNLOCKS_LAST); int blueBabyCount = 0; int fullCount = 0; int fullRegularCount = 0; bool isMegaSatanAll = true; for (size_t index = 0; index < COMPLETION_PLAYER_TYPES.size(); index++) { auto& marks = COMPLETION_MARKS[COMPLETION_PLAYER_TYPES[index]]; auto mark = [&](CompletionType type) { return eventCounters[marks[type].counter]; }; auto isHard = [&](CompletionType type) { return marks[type].counter && mark(type) & COMPLETION_HARD_BIT; }; bool isFullHard = std::ranges::all_of(COMPLETION_FULL_SET, isHard); if (mark(COMPLETION_ISAAC) && mark(COMPLETION_BLUE_BABY) && mark(COMPLETION_SATAN) && mark(COMPLETION_LAMB)) TryUnlock(marks[COMPLETION_TAINTED_GROUP1].achievement); if (mark(COMPLETION_BOSS_RUSH) && mark(COMPLETION_HUSH)) TryUnlock(marks[COMPLETION_TAINTED_GROUP2].achievement); if (isFullHard) TryUnlock(marks[COMPLETION_HARD].achievement); if (index < COMPLETION_REGULAR_COUNT) { blueBabyCount += mark(COMPLETION_BLUE_BABY) != 0; isMegaSatanAll &= mark(COMPLETION_MEGA_SATAN) != 0; fullRegularCount += isFullHard; } fullCount += isFullHard; } if (blueBabyCount >= BLUE_BABY_CHARACTERS_FIRST) TryUnlock(ACHIEVEMENT_BLUE_BABY_FIRST); if (blueBabyCount >= BLUE_BABY_CHARACTERS_SECOND) TryUnlock(ACHIEVEMENT_BLUE_BABY_SECOND); if (isMegaSatanAll) TryUnlock(ACHIEVEMENT_MEGA_SATAN_ALL); if (fullRegularCount >= COMPLETION_REGULAR_COUNT) TryUnlock(ACHIEVEMENT_HARD_ALL_REGULAR); if (fullCount >= (int)COMPLETION_PLAYER_TYPES.size()) TryUnlock(ACHIEVEMENT_HARD_ALL); } // 0092a2d0 Adds a collectible to the collection page and checks the unlocks that depend on it. void PersistentGameData::AddToCollection(int collectibleID) { if (isReadOnly || collectibleID < 0 || collectibleID >= COLLECTIBLE_SEEN_COUNT) return; if (collectibleID != 0 && !itemsCollection[collectibleID]) { itemsCollection[collectibleID] = true; isChangesMade = true; check_collection_unlocks(); } check_collection_set_unlocks(); } // Unlocks the achievements for having seen certain collectibles together. void PersistentGameData::check_collection_set_unlocks() { auto isSeen = [&](int collectible) { return itemsCollection[collectible]; }; if (std::ranges::all_of(COLLECTION_SET_FIRST, isSeen)) TryUnlock(ACHIEVEMENT_COLLECTION_SET_FIRST); if (std::ranges::all_of(COLLECTION_SET_SECOND, isSeen)) TryUnlock(ACHIEVEMENT_COLLECTION_SET_SECOND); } // 0092a350 Unlocks the collection achievements, counting missing and hidden collectibles as seen and, for the // base game ones, the unobtainable ones as owed. void PersistentGameData::check_collection_unlocks() { int baseCount = 0; int seenCount = 0; int unobtainableCount = 0; for (int collectible = 1; collectible < COLLECTIBLE_SEEN_COUNT; collectible++) { bool isCounted = itemsCollection[collectible]; if (!isCounted && is_listed(COLLECTION_UNOBTAINABLE, collectible)) { unobtainableCount++; continue; } if (!isCounted) { ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectible); isCounted = !item || item->isHidden; } if (!isCounted) continue; seenCount++; baseCount += collectible <= COLLECTION_BASE_LAST; } if (unobtainableCount + baseCount >= COLLECTION_BASE_NEEDED) { int exemptCount = 0; int unlockedCount = 0; for (int achievement = 1; achievement < COLLECTION_BASE_ACHIEVEMENTS_END; achievement++) { if (achievements[achievement]) unlockedCount++; else exemptCount += is_listed(COLLECTION_ACHIEVEMENTS_EXEMPT, achievement); } if (exemptCount + unlockedCount >= COLLECTION_BASE_ACHIEVEMENTS_NEEDED) TryUnlock(ACHIEVEMENT_BASE_COLLECTION); if (unlockedCount >= COLLECTION_BASE_ACHIEVEMENTS_NEEDED && unobtainableCount == 0) TryUnlock(ACHIEVEMENT_BASE_EVERYTHING); } if (seenCount < COLLECTION_SEEN_NEEDED) return; int unlockedCount = (int)std::count(achievements.begin() + 1, achievements.end(), true); if (unlockedCount >= ACHIEVEMENTS_FIRST_NEEDED) TryUnlock(ACHIEVEMENT_COLLECTION_FIRST); if (unlockedCount >= ACHIEVEMENTS_SECOND_NEEDED) TryUnlock(ACHIEVEMENT_COLLECTION_SECOND); if (seenCount >= COLLECTION_SEEN_ALL && unlockedCount >= ACHIEVEMENTS_ALL_NEEDED) TryUnlock(ACHIEVEMENT_COLLECTION_ALL); } // 0092a7b0 Marks a challenge as won and unlocks its achievement. void PersistentGameData::AddChallenge(int challengeID) { if (isReadOnly || challengeID < 0 || challengeID >= CHALLENGE_COUNT) return; challenges[challengeID] = true; TryUnlock(CHALLENGE_WIN_ACHIEVEMENTS[challengeID]); } // 0092b270 Stores the characters run with as a bit mask, unlocking an achievement once five have been. void PersistentGameData::set_run_mask(uint64_t mask) { eventCounters[EVENT_COUNTER_RUN_MASK_LOW] = (int)(uint32_t)mask; eventCounters[EVENT_COUNTER_RUN_MASK_HIGH] = (int)(mask >> 32); if (std::popcount(mask & ((1ull << RUN_MASK_BITS) - 1)) >= RUN_MASK_NEEDED) TryUnlock(ACHIEVEMENT_RUN_MASK); isChangesMade = true; } // 0092acb0 Counts a kill in the bestiary, unlocking the achievements for killing enough angels, portals and // Little Horns. False when frozen or the entity has no bestiary page. bool PersistentGameData::AddBestiaryKill(int type, int variant) { EntityConfig_Entity* entity = isReadOnly ? nullptr : bestiary_entity_get(type, variant); if (!entity) return false; PersistentGameData& data = g_manager->persistentGameData; bestiary.kills[bestiary_key_get(*entity)]++; uint32_t killCount = data.GetBestiaryKillCount(entity->id, entity->variant); switch (entity->id) { case ENTITY_TYPE_URIEL: case ENTITY_TYPE_GABRIEL: if ((uint32_t)(data.GetBestiaryKillCount(ENTITY_TYPE_GABRIEL, 0) + data.GetBestiaryKillCount(ENTITY_TYPE_URIEL, 0)) >= ANGEL_KILLS_NEEDED) data.TryUnlock(ACHIEVEMENT_ANGEL_KILLS); break; case ENTITY_TYPE_PORTAL: if (killCount >= BOSS_KILLS_NEEDED) data.TryUnlock(ACHIEVEMENT_PORTAL_KILLS); break; case ENTITY_TYPE_LITTLE_HORN: if (killCount >= BOSS_KILLS_NEEDED) data.TryUnlock(ACHIEVEMENT_LITTLE_HORN_KILLS); break; default: break; } return true; } // 0092aea0 Counts an encounter in the bestiary, unlocking its achievement once every bestiary entity has been met. // Meeting a Mom's Heart variant also meets and kills the plain one. False when frozen or there is no page. bool PersistentGameData::TryAddBestiaryEncounter(int type, int variant) { static uint32_t bestiaryEntityCount = 0; EntityConfig_Entity* entity = isReadOnly ? nullptr : bestiary_entity_get(type, variant); if (!entity) return false; bestiary.encounters[bestiary_key_get(*entity)]++; if (bestiaryEntityCount == 0) bestiaryEntityCount = (uint32_t)std::ranges::count_if(g_manager->entityConfig.entities, [](auto& entry) { return entry.second.portrait >= 0 && !(entry.second.baseHP == 0) && entry.second.isBestiary; }); if (bestiary.encounters.size() >= bestiaryEntityCount) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_BESTIARY_COMPLETE); if (entity->id == ENTITY_TYPE_MOMS_HEART && entity->variant != 0 && GetBestiaryEncounterCount(ENTITY_TYPE_MOMS_HEART, 0) == 0) { TryAddBestiaryEncounter(ENTITY_TYPE_MOMS_HEART, 0); AddBestiaryKill(ENTITY_TYPE_MOMS_HEART, 0); } return true; } // 0092b070 How many times the player died to an entity. int PersistentGameData::GetBestiaryDeathCount(int type, int variant) { return bestiary_count_get(bestiary.deaths, type, variant); } // 0092b190 How many times the player met an entity. int PersistentGameData::GetBestiaryEncounterCount(int type, int variant) { return bestiary_count_get(bestiary.encounters, type, variant); } // 0092b100 How many times the player killed an entity. int PersistentGameData::GetBestiaryKillCount(int type, int variant) { return bestiary_count_get(bestiary.kills, type, variant); }