#include "item_pool.h" #include "data.h" #include "entity_config.h" #include "game.h" #include "lua_engine.h" #include "manager.h" #include "platform.h" #include "room_config.h" #include #include #include // An outcome of a weighted draw and its weight, as WeightedOutcomePicker holds them. struct WeightedOutcome { int id; int weight; }; constexpr std::string_view POOL_NAMES[POOL_COUNT] = { "treasure", "shop", "boss", "devil", "angel", "secret", "library", "shellGame", "goldenChest", "redChest", "beggar", "demonBeggar", "curse", "keyMaster", "batteryBum", "momsChest", "greedTreasure", "greedBoss", "greedShop", "greedDevil", "greedAngel", "greedCurse", "greedSecret", "craneGame", "ultraSecret", "bombBum", "planetarium", "oldChest", "babyShop", "woodenChest", "rottenBeggar"}; constexpr int ROOM_TYPE_SLOTS = 31; constexpr int ROOM_ERROR = 3; constexpr int ROOM_TREASURE = 4; constexpr int ROOM_BOSS = 5; constexpr int ROOM_CHALLENGE = 11; constexpr int ROOM_DEVIL = 14; constexpr int ROOM_DEFAULT = 1; constexpr int ROOM_ERROR_POOLS = 30; // The pool each room type draws from, normally and in Greed mode (set up by Game's constructor). constexpr std::array ROOM_POOLS = { POOL_NONE, POOL_NONE, POOL_SHOP, POOL_NONE, POOL_TREASURE, POOL_BOSS, POOL_NONE, POOL_SECRET, POOL_SECRET, POOL_NONE, POOL_CURSE, POOL_TREASURE, POOL_LIBRARY, POOL_NONE, POOL_DEVIL, POOL_ANGEL, POOL_TREASURE, POOL_TREASURE, POOL_TREASURE, POOL_TREASURE, POOL_GOLDEN_CHEST, POOL_TREASURE, POOL_SHOP, POOL_NONE, POOL_PLANETARIUM, POOL_NONE, POOL_NONE, POOL_NONE, POOL_NONE, POOL_ULTRA_SECRET, POOL_NONE}; constexpr std::array GREED_ROOM_POOLS = [] { std::array pools = ROOM_POOLS; constexpr std::pair GREED_SWAPS[] = { {POOL_TREASURE, POOL_GREED_TREASURE}, {POOL_SHOP, POOL_GREED_SHOP}, {POOL_BOSS, POOL_GREED_BOSS}, {POOL_DEVIL, POOL_GREED_DEVIL}, {POOL_ANGEL, POOL_GREED_ANGEL}, {POOL_SECRET, POOL_GREED_SECRET}, {POOL_CURSE, POOL_GREED_CURSE}}; for (int& pool : pools) for (auto [normal, greed] : GREED_SWAPS) if (pool == normal) pool = greed; return pools; }(); constexpr uint32_t POOL_SHIFT = 35; constexpr uint32_t ITEM_POOL_SHIFT = 3; constexpr uint32_t TRINKET_POOL_SHIFT = 2; constexpr uint32_t CHAOS_SHIFT = 22; constexpr uint32_t DRAW_SHIFT = 4; constexpr uint32_t DAILY_SHIFT = 2; constexpr uint32_t LIST_SHIFT = 17; constexpr uint32_t ERROR_ROOM_SHIFT = 7; constexpr uint32_t MAGIC_SKIN_SHIFT = 55; constexpr uint32_t GOLDEN_SHIFT = 19; constexpr uint32_t PILL_SHIFT = 12; constexpr float CHAOS_WEIGHT_SCALE = 100; constexpr float MAGIC_SKIN_CHANCE_PER_USE = 0.01f; constexpr int MAGIC_SKIN_ROLL_BASE = 4; constexpr int REROLLS = 20; constexpr int REPICKS = 10; constexpr int REPICKS_BAN_ACTIVES = 20; constexpr int QUALITY_COUNT = 5; constexpr int QUALITY_REPICKS[QUALITY_COUNT] = {6, 5, 4, 3, 2}; constexpr float REPICK_EDGE_DIVISOR = 3.37317f; constexpr int MAX_DEFAULT_ITEM = 732; constexpr int ROSARY_CHANCE_PER_MULTIPLIER = 2; constexpr int GOLDEN_TRINKET_ODDS = 50; constexpr uint32_t DEBUG_GOLDEN_TRINKETS = 0x8; constexpr uint32_t TRINKET_GOLDEN = 0x8000; constexpr uint32_t TRINKET_ID_MASK = 0x7fff; constexpr uint32_t STATE_SATANIC_BIBLE_USED = 0x20000; constexpr uint32_t DESCRIPTOR_DEVIL_TREASURE = 0x800; constexpr int BOSS_THE_FALLEN = 23; constexpr int STAGE_HOME = 35; constexpr int HOME_CHEST_SUBTYPE = 2; constexpr int COLLECTIBLE_BREAKFAST = 25; constexpr int COLLECTIBLE_ROTTEN_MEAT = 26; constexpr int COLLECTIBLE_BIBLE = 33; constexpr int COLLECTIBLE_ROSARY = 72; constexpr int COLLECTIBLE_PHD = 75; constexpr int COLLECTIBLE_LUCKY_FOOT = 46; constexpr int COLLECTIBLE_PYROMANIAC = 223; constexpr int COLLECTIBLE_BUTTER_BEAN = 294; constexpr int COLLECTIBLE_VIRGO = 303; constexpr int COLLECTIBLE_HOST_HAT = 375; constexpr int COLLECTIBLE_CHAOS = 402; constexpr int COLLECTIBLE_APPLE = 443; constexpr int COLLECTIBLE_WAIT_WHAT = 484; constexpr int COLLECTIBLE_MAGIC_SKIN = 642; constexpr int COLLECTIBLE_FALSE_PHD = 654; constexpr int COLLECTIBLE_TMTRAINER = 721; constexpr int TRINKET_ROSARY_BEAD = 7; constexpr int TRINKET_NO = 88; constexpr int TRINKET_BUTTER = 122; constexpr int TRINKET_PERFECTION = 145; constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; constexpr uint32_t CHALLENGE_PICA_RUN = 41; constexpr uint32_t CHALLENGE_CANTRIPPED = 43; constexpr int ACHIEVEMENT_GOLDEN_TRINKETS = 617; constexpr int ACHIEVEMENT_GOLD_PILLS = 603; constexpr int ACHIEVEMENT_HORSE_PILLS = 606; // The daily challenges that change what pools give. constexpr uint32_t DAILY_TREASURE_LIST = 1; constexpr uint32_t DAILY_ROTTEN_BOSSES = 16; constexpr uint32_t DAILY_TREASURE_LIST_SHORT = 18; constexpr uint32_t DAILY_EXPLOSIVE_PILLS = 41; constexpr uint32_t DAILY_APPLE_BOSSES = 44; constexpr uint32_t DAILY_TREASURE_RANDOM = 46; constexpr uint32_t DAILY_TREASURE_FOUR = 50; constexpr uint32_t DAILY_HOST_HAT = 52; constexpr int DAILY_TREASURE_LIST_ITEMS[] = {37, 125, 106, 19, 190, 140, 220, 65, 42, 137, 250, 131, 209, 52, 256, 344, 223, 353, 371, 432, 366, 367, 563, 583, 614, 727}; constexpr int DAILY_TREASURE_LIST_SHORT_ITEMS[] = {282, 382, 210, 60, 338, 12, 121, 120, 71, 243, 54, 415, 21, 164, 289, 579, 604}; constexpr int DAILY_TREASURE_RANDOM_ITEMS[] = {209, 220, 140, 131, 125, 106, 19, 401, 378, 371, 367, 256, 353, 432, 517, 483, 137, 37, 563, 583, 614, 727}; constexpr int DAILY_TREASURE_RANDOM_PASSIVES = 20; constexpr int DAILY_TREASURE_FOUR_ITEMS[] = {334, 335, 333, 331}; constexpr int ONANS_STREAK_BANNED[] = {68, 118, 329, 52, 168, 114, 395, 394, 55, 87, 229}; constexpr int PILL_COLOR_MASK = 0x7ff; constexpr int PILL_HORSE = 0x800; constexpr int PILL_COLORS = 13; constexpr int PILL_GOLD = 14; constexpr int PILL_GOLD_ODDS = 140; constexpr int PILL_HORSE_ODDS = 70; constexpr int PILL_EFFECT_NONE = -1; constexpr int PILLEFFECT_BAD_TRIP = 1; constexpr int PILLEFFECT_EXPLOSIVE_DIARRHEA = 4; constexpr int PILLEFFECT_FULL_HEALTH = 5; constexpr int PILLEFFECT_HEALTH_DOWN = 6; constexpr int PILLEFFECT_HEALTH_UP = 7; constexpr int PILLEFFECT_I_FOUND_PILLS = 8; constexpr int PILL_GET_COLOR_CALLBACK = 9; // The effect class each shuffled color slot must have, or -1 for any. constexpr int PILL_SLOT_CLASSES[PILL_COLOR_SLOTS - 1] = {3, 3, 3, 3, 2, 1, 0, -1, -1, 3, 2, 1, -1, -1}; // PHD's good side of a bad pill (0x00b6a240), and False PHD's bad side of a good one (its jump table at 0x00734c40). constexpr std::pair PHD_EFFECTS[] = {{6, 7}, {17, 18}, {13, 14}, {11, 12}, {15, 16}, {25, 23}, {1, 2}, {27, 36}, {29, 28}, {31, 19}, {37, 23}, {22, 24}, {39, 40}, {42, 41}, {47, 48}}; constexpr std::pair FALSE_PHD_EFFECTS[] = { {0, 6}, {7, 6}, {38, 6}, {2, 1}, {5, 1}, {21, 1}, {3, 15}, {16, 15}, {34, 15}, {4, 11}, {12, 11}, {32, 11}, {10, 17}, {18, 17}, {35, 17}, {14, 13}, {20, 13}, {33, 13}, {19, 31}, {23, 25}, {26, 25}, {24, 22}, {28, 29}, {36, 27}, {40, 39}, {41, 42}, {43, 44}, {46, 44}, {45, 37}, {48, 47}}; static RNG rng_make(uint32_t seed, uint32_t shift) { RNG rng; rng.SetSeed(seed, shift); return rng; } static bool is_unlocked(int achievementId) { return achievementId < 0 || g_manager->persistentGameData.Unlocked(achievementId); } // A collectible's bit in one of the pool's masks. The original reads and writes outside them for an id past them. // Here such ids read as clear and are not written. static bool is_marked(std::vector& mask, int id) { return id >= 0 && (size_t)id < mask.size() && mask[id]; } static void mark_set(std::vector& mask, int id, bool isSet) { if (id >= 0 && (size_t)id < mask.size()) mask[id] = isSet; } static ItemConfig_Item* collectible_get(int id) { return g_manager->itemConfig.GetCollectible(id); } // Whether the flags ban an item's quality. A missing item bans none. static bool is_quality_banned(ItemConfig_Item* item, uint32_t flags) { return item && (flags & (POOL_FLAG_BAN_QUALITY_0 << (item->quality & 31))); } // Whether a draw may give a collectible: it exists, may appear, and the flags ban neither its kind nor its quality. static bool is_kind_allowed(ItemConfig_Item* item, uint32_t flags) { bool isActive = item->type == ITEM_ACTIVE; if (!item->IsAvailableEx(AVAILABLE_ALL)) return false; return !((flags & POOL_FLAG_BAN_ACTIVES) && isActive) && !((flags & POOL_FLAG_BAN_PASSIVES) && !isActive); } // An attribute's text, or nothing when the element lacks it. static std::optional attr_find(DataNode node, std::string_view name) { std::string_view text; if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt; return text; } // The children of node from the first with a tag on, as rapidxml's first_node(tag) then next_sibling() walks them. static std::vector elements_from(DataNode node, std::string_view tag) { std::vector elements; for (DataNode child : node_children(node)) if (!elements.empty() || node_tag(child) == tag) elements.push_back(child); return elements; } // Reads one Item of itempools.xml in attribute order: its id (or the collectible a Name names), weight and decay. static PoolItem pool_item_parse(DataNode node) { PoolItem item; simdjson::dom::object attrs; if (node["attrs"].get(attrs) == simdjson::SUCCESS) for (auto [name, value] : attrs) { std::string_view text; if (value.get(text) != simdjson::SUCCESS) continue; auto& names = g_manager->itemConfig.collectibleNameMap; if (name == "Id") item.itemId = std::atoi(text.data()); if (name == "Weight") item.initialWeight = item.weight = (float)std::atof(text.data()); if (name == "DecreaseBy") item.decreaseBy = (float)std::atof(text.data()); if (name == "RemoveOn") item.removeOn = (float)std::atof(text.data()); if (name == "Name" && names.contains(text)) item.itemId = names.find(text)->second; } ItemConfig_Item* config = collectible_get(item.itemId); item.isSpecial = config && config->isSpecial; item.isUnlocked = config && is_unlocked(config->achievementId); return item; } // 00732c20 ItemPool_Item::ItemPool_Item() { rng1.SetSeed(RNG_SEED_DEFAULT, POOL_SHIFT); rng2.SetSeed(RNG_SEED_DEFAULT, POOL_SHIFT); } // The item pool part of Game's constructor, before Init seeds it. ItemPool::ItemPool() { itemPoolRNG.SetSeed(RNG_SEED_DEFAULT, POOL_SHIFT); trinketPoolRNG.SetSeed(RNG_SEED_DEFAULT, POOL_SHIFT); } // 00734f30 Starts the run's pools from its seed: reads itempools.xml and the mods', shuffles them, bans Onan's Streak's // items, fills the trinket pool, gives each pill color an effect, and preloads the announcer lines of pills and cards. // The first nine shuffled colors after the gold one are held to effect classes, the rest are random. void ItemPool::Init(uint32_t startSeed, std::string_view path) { ItemConfig& config = g_manager->itemConfig; seed = startSeed; itemPoolRNG.SetSeed(startSeed, ITEM_POOL_SHIFT); trinketPoolRNG.SetSeed(itemPoolRNG.Next(), TRINKET_POOL_SHIFT); lastPool = POOL_TREASURE; removedCollectibles.assign(config.collectibles.size(), false); roomBlacklistedCollectibles.assign(config.collectibles.size(), false); trinketPoolItems.resize(config.trinkets.size()); unkFloat674 = 1; unkFloat678 = 1; load_pools(path, POOLS_REPLACE); g_manager->modManager.LoadModItemPools(); shuffle_pools(); if (g_game->challenge == CHALLENGE_ONANS_STREAK) for (int id : ONANS_STREAK_BANNED) RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY); ResetTrinkets(); std::vector colors; std::vector effects; for (int color = 1; color <= PILL_COLORS; color++) colors.push_back(color); RNG::Shuffle(&itemPoolRNG, colors.data(), colors.data() + colors.size()); colors.push_back(PILL_GOLD); for (auto& pill : config.pillEffects) { if (!pill || (!pill->isGreedModeAllowed && g_game && g_game->IsGreedMode())) continue; if (g_game && g_game->deathmatchManager.is_active()) reconstruction_missing("DeathmatchType pill ban, vtable slot 10"); if (!is_unlocked(pill->achievementId)) continue; effects.push_back(pill->id); g_manager->sfxManager.Preload(pill->announcerVoice); } RNG::Shuffle(&itemPoolRNG, effects.data(), effects.data() + effects.size()); for (size_t slot = 0; slot < colors.size(); slot++) { int effectClass = slot < std::size(PILL_SLOT_CLASSES) ? PILL_SLOT_CLASSES[slot] : -1; auto effect = std::ranges::find_if(effects, [&](int id) { ItemConfig_Pill* pill = config.GetPillEffect(id); return effectClass >= 0 && pill && pill->effectClass == effectClass; }); if (effect == effects.end()) { uint32_t roll = itemPoolRNG.Next(); if (effects.empty()) continue; effect = effects.begin() + roll % effects.size(); } pillEffects[colors[slot]] = *effect; effects.erase(effect); } pillEffects[0] = PILL_EFFECT_NONE; for (auto& card : config.cards) if (card) g_manager->sfxManager.Preload(card->announcerVoice); identifiedPillEffects = {}; remainingGenesisItems = {}; } // 00735a30 Reads an itempools.xml into the pools by their names. Replacing empties every pool and reseeds its RNGs // from the item pool's first. Mods append to the pools instead. // The original crashes without the root element. Here that only asserts. void ItemPool::load_pools(std::string_view path, PoolsLoad load) { Data data; std::optional root; if (load == POOLS_REPLACE) for (ItemPool_Item& pool : pools) { pool.poolList.clear(); pool.totalWeight = 0; pool.rng1.SetSeed(itemPoolRNG.Next(), POOL_SHIFT); pool.rng2.SetSeed(itemPoolRNG.Next(), POOL_SHIFT); pool.bibleUpgrade = 0; } data_load(data, path); if (!data.isLoaded) return; if (node_tag(data.root) == "ItemPools") root = data.root; for (DataNode node : node_children(data.root)) if (!root && node_tag(node) == "ItemPools") root = node; if (!root) return log_printf(LOG_ASSERT, "Could not find root node 'ItemPools' in %s\n", std::string(path).c_str()); for (DataNode node : elements_from(*root, "Pool")) { std::optional name = attr_find(node, "Name"); if (!name) continue; auto found = std::ranges::find(POOL_NAMES, *name); if (found == std::end(POOL_NAMES)) { std::string text(*name); log_printf(LOG_INFO, "Pool %s not found, please recheck config or item pool list", text.c_str()); continue; } ItemPool_Item& pool = pools[found - std::begin(POOL_NAMES)]; for (DataNode item : elements_from(node, "Item")) { pool.poolList.push_back(pool_item_parse(item)); pool.totalWeight += pool.poolList.back().initialWeight; } } } // 00735910 Shuffles every pool's items from the item pool's seed, with the Mersenne Twister. void ItemPool::shuffle_pools() { std::mt19937 twister(itemPoolRNG._seed); for (ItemPool_Item& pool : pools) for (size_t last = pool.poolList.size() - std::min(pool.poolList.size(), 1); last > 0; last--) std::swap(pool.poolList[last], pool.poolList[twister() % (last + 1)]); } // (007367d0) Saves the pools into a game state. GameStateItemPool is not modelled yet. void ItemPool::StoreGameState(GameStateItemPool&) { reconstruction_missing("ItemPool::StoreGameState 007367d0"); } // (00736530) Restores the pools from a game state. GameStateItemPool is not modelled yet. void ItemPool::RestoreGameState(GameStateItemPool&) { reconstruction_missing("ItemPool::RestoreGameState 00736530"); } // 00732c70 ItemPool_Item& ItemPool::GetPool(ItemPoolType poolType) { return pools[poolType]; } // 006dac50 The pool the last collectible was drawn from. int ItemPool::GetLastPool() { return lastPool; } // 00732dc0 The pool a room type draws from, Greed mode's for Greed. An error room draws from a random room type's. // The original reads past its table for a type out of range. Here that gives no pool. int ItemPool::GetPoolForRoom(int roomType, uint32_t roomSeed) { const std::array& table = g_game->IsGreedMode() ? GREED_ROOM_POOLS : ROOM_POOLS; if (roomType < 0 || roomType >= ROOM_TYPE_SLOTS) { log_printf(LOG_ASSERT, "RoomType out of bounds\n"); return POOL_NONE; } if (roomType != ROOM_ERROR) return table[roomType]; return table[rng_make(roomSeed, ERROR_ROOM_SHIFT).Next() % ROOM_ERROR_POOLS]; } // 007ebe20 The pool a room's collectible comes from. A boss room asks its last boss with an id, unless one is given: // The Fallen and the Satanic Bible give the devil pool. A Greed treasure room other than the floor's gives the boss // pool, a devil treasure room the devil pool, and a boss challenge room the boss pool. Home's chest room gives Mom's // Chest pool. // The original reads before a spawn whose entries all weigh nothing. Here such a spawn is passed over. int ItemPool::get_pool_from_room_entities(uint32_t roomSeed, RoomDescriptor& room, int bossId) { RoomConfig_Room& data = *room.Data; int roomType = data.type; if (roomType == ROOM_BOSS && bossId == 0) for (auto spawn = data.spawns.rbegin(); spawn != data.spawns.rend() && bossId == 0; spawn++) { RoomEntry* best = nullptr; for (RoomEntry& entry : spawn->entries) if (entry.weight > (best ? best->weight : 0)) best = &entry; EntityConfig_Entity* boss = best ? g_manager->entityConfig.GetEntity(best->type, best->variant, best->subtype) : nullptr; if (boss) bossId = boss->bossID; } bool isFallen = bossId == BOSS_THE_FALLEN; bool isGreedSide = g_game->IsGreedMode() && room.GridIndex != (int)g_game->greedModeTreasureRoomIdx; if (isFallen || (roomType == ROOM_BOSS && (g_game->levelStateFlags & STATE_SATANIC_BIBLE_USED))) roomType = ROOM_DEVIL; else if (roomType == ROOM_TREASURE && isGreedSide) roomType = ROOM_BOSS; else if (roomType == ROOM_TREASURE && (room.Flags & DESCRIPTOR_DEVIL_TREASURE)) roomType = ROOM_DEVIL; else if (roomType == ROOM_CHALLENGE && data.subtype == 1) roomType = ROOM_BOSS; int pool = GetPoolForRoom(roomType, roomSeed); bool isHomeChest = data.type == ROOM_DEFAULT && data.stageId == STAGE_HOME && data.subtype == HOME_CHEST_SUBTYPE; return isHomeChest ? POOL_MOMS_CHEST : pool; } // The id an outcome's weight lands on, as WeightedOutcomePicker::PickOutcome draws: a roll below the total // weight, or the first outcome when no weight was added. static int outcome_pick(std::vector& outcomes, RNG rng) { uint32_t total = 0; int sum = 0; for (WeightedOutcome& outcome : outcomes) total += outcome.weight; uint32_t roll = rng.Next(); roll = total ? roll % total : 0; for (WeightedOutcome& outcome : outcomes) if ((int)roll < (sum += outcome.weight)) return outcome.id; if (sum <= 0) log_printf(LOG_ASSERT, "No weights were added. At least one outcome needs weight."); return 0; } // 00737010 A pool for Chaos, drawn by the pools' total weights: the Greed pools in Greed mode, every other otherwise. int ItemPool::get_chaos_pool(RNG& rng) { std::vector outcomes; bool isGreed = g_game->IsGreedMode(); for (int id = 0; id < POOL_COUNT; id++) { bool isGreedPool = id >= POOL_GREED_TREASURE && id <= POOL_GREED_SECRET; int weight = (int)(pools[id].totalWeight * CHAOS_WEIGHT_SCALE); if (isGreedPool == isGreed && weight > 0) outcomes.push_back({id, weight}); } rng.Next(); return outcome_pick(outcomes, rng_make(rng._seed, POOL_SHIFT)); } // 00732e90 Every pool holding the collectible, once per copy it holds. std::vector ItemPool::GetItemPoolsForCollectible(int collectible) { std::vector found; for (int id = 0; id < POOL_COUNT; id++) for (PoolItem& item : pools[id].poolList) if (item.itemId == collectible) found.push_back(id); return found; } // 00732ef0 The first pool holding the collectible, or the treasure pool. int ItemPool::GetFirstItemPoolForCollectible(int collectible) { std::vector found = GetItemPoolsForCollectible(collectible); return found.empty() ? POOL_TREASURE : found[0]; } // 00733610 Draws a collectible from a pool. TMTRAINER makes a glitched one and Chaos a random pool. Some daily // challenges give fixed items. A locked pick is drawn again up to 20 times. The Bible may stand in for a pick, and // Magic Skin and the Rosary Bead may replace it unless the flags ignore modifiers. With nothing drawn it gives the // default item, a fallback pool's draw, or Breakfast. Lua's MC_PRE and MC_POST_GET_COLLECTIBLE may override it. // After 20 redraws an unlocked pick gives the default and a locked one is kept, as in the original. int ItemPool::GetCollectible(ItemPoolType poolType, uint32_t drawSeed, uint32_t flags, int defaultItem, int fallbackPool) { PlayerManager& players = g_game->playerManager; uint32_t daily = g_game->dailyChallenge._specialDailyId; if (drawSeed == 0) log_printf(LOG_ASSERT, "ItemPool::GetCollectible Seed is 0\n"); if (poolType < 0 || poolType >= POOL_COUNT || drawSeed == 0) return 0; if (defaultItem < 0 || defaultItem > MAX_DEFAULT_ITEM) defaultItem = 0; bool isDecrease = !(flags & POOL_FLAG_NO_DECREASE); if (players.AnyoneHasTrinket(TRINKET_NO)) flags |= POOL_FLAG_BAN_ACTIVES; bool isBanActives = flags & POOL_FLAG_BAN_ACTIVES; if (players.AnyoneHasCollectible(COLLECTIBLE_TMTRAINER)) return CreateGlitchedCollectible(drawSeed, 0); RNG poolRng = rng_make(drawSeed, CHAOS_SHIFT); bool isChaos = players.AnyoneHasCollectible(COLLECTIBLE_CHAOS) || g_game->room->_temporaryEffects.HasCollectibleEffect(COLLECTIBLE_CHAOS); int pool = isChaos ? get_chaos_pool(poolRng) : poolType; lastPool = pool; if (int item = (int)FUN_00865dc0(poolType, isDecrease, drawSeed)) return item; RNG dailyRng = rng_make(drawSeed, DAILY_SHIFT); if (daily == DAILY_APPLE_BOSSES && poolType == POOL_BOSS) return COLLECTIBLE_APPLE; if (daily == DAILY_TREASURE_RANDOM && poolType == POOL_TREASURE) return DAILY_TREASURE_RANDOM_ITEMS[dailyRng.RandomInt( isBanActives ? DAILY_TREASURE_RANDOM_PASSIVES : std::size(DAILY_TREASURE_RANDOM_ITEMS))]; if (daily == DAILY_TREASURE_FOUR && poolType == POOL_TREASURE) return DAILY_TREASURE_FOUR_ITEMS[dailyRng.RandomInt(std::size(DAILY_TREASURE_FOUR_ITEMS))]; RNG pickRng = rng_make(drawSeed, DRAW_SHIFT); uint32_t listFlags = LIST_PICK_BLACKLIST | (isBanActives ? LIST_PICK_BAN_ACTIVES : 0); std::span list; if (daily == DAILY_ROTTEN_BOSSES && pool == POOL_BOSS) return COLLECTIBLE_ROTTEN_MEAT; if (daily == DAILY_TREASURE_LIST && pool == POOL_TREASURE) list = DAILY_TREASURE_LIST_ITEMS; if (daily == DAILY_TREASURE_LIST_SHORT && pool == POOL_TREASURE) list = DAILY_TREASURE_LIST_SHORT_ITEMS; if (!list.empty()) if (int item = GetCollectibleFromList(list, pickRng.Next(), 0, listFlags)) return item; ItemPool_Item* items = &pools[pool]; PoolItem* pick = pick_weighted(*items, flags, pickRng.RandomFloat() * items->totalWeight); std::optional drawn; for (int rerolls = REROLLS; pick && !drawn;) { bool isKept = pick->isUnlocked ? rerolls != 0 : rerolls-- <= 0; if (pick->isUnlocked && !isKept) break; if (!isKept) { if (isChaos) items = &pools[lastPool = get_chaos_pool(poolRng)]; pick = pick_weighted(*items, flags, pickRng.RandomFloat() * items->totalWeight); continue; } ItemConfig_Item* bible = collectible_get(COLLECTIBLE_BIBLE); bool isBibleFree = !is_marked(removedCollectibles, COLLECTIBLE_BIBLE) && !is_marked(roomBlacklistedCollectibles, COLLECTIBLE_BIBLE) && !isBanActives; if (isDecrease) mark_set(roomBlacklistedCollectibles, pick->itemId, true); drawn = pick->itemId; if (isBibleFree && bible && bible->IsAvailableEx(AVAILABLE_ALL) && (int)pickRng.RandomInt((uint32_t)items->totalWeight) < items->bibleUpgrade) { if (isDecrease) mark_set(roomBlacklistedCollectibles, COLLECTIBLE_BIBLE, true); drawn = COLLECTIBLE_BIBLE; } } int result = drawn.value_or(defaultItem); if (!drawn && defaultItem == 0) result = fallbackPool == POOL_NONE ? COLLECTIBLE_BREAKFAST : GetCollectible((ItemPoolType)fallbackPool, drawSeed, flags, 0, POOL_NONE); if (!(flags & POOL_FLAG_IGNORE_MODIFIERS)) { int rosaryMultiplier = 0; if (should_force_magic_skin(drawSeed)) result = COLLECTIBLE_MAGIC_SKIN; rosaryMultiplier = players.GetTrinketMultiplier(TRINKET_ROSARY_BEAD); if (rosaryMultiplier > 1 && (int)pickRng.RandomInt((uint32_t)items->totalWeight) < rosaryMultiplier * ROSARY_CHANCE_PER_MULTIPLIER) result = COLLECTIBLE_ROSARY; else if (result == COLLECTIBLE_PYROMANIAC && daily == DAILY_HOST_HAT) result = COLLECTIBLE_HOST_HAT; } int overridden = (int)FUN_00865f10(result, poolType, isDecrease, drawSeed); return overridden ? overridden : result; } // 00737380 A collectible from a fixed list, drawn from the seed. Unavailable entries stand in for random available // ones. Gives the default when none is available, and may blacklist the pick for the room. int ItemPool::GetCollectibleFromList(std::span list, uint32_t drawSeed, int defaultItem, uint32_t pickFlags) { std::vector available; std::vector slots; for (int id : list) { ItemConfig_Item* item = collectible_get(id); bool isFree = item && !is_marked(removedCollectibles, id) && !is_marked(roomBlacklistedCollectibles, id); bool isAllowed = isFree && item->IsAvailableEx(AVAILABLE_ALL) && !((pickFlags & LIST_PICK_BAN_ACTIVES) && item->type == ITEM_ACTIVE); slots.push_back(isAllowed ? id : 0); if (isAllowed) available.push_back(id); } if (!available.empty()) { RNG rng = rng_make(drawSeed, LIST_SHIFT); uint32_t picked = rng.Next() % slots.size(); for (int& slot : slots) if (slot == 0) slot = available[rng.Next() % available.size()]; defaultItem = slots[picked]; } if ((pickFlags & LIST_PICK_BLACKLIST) && defaultItem != 0) mark_set(roomBlacklistedCollectibles, defaultItem, true); return defaultItem; } // 007ec0a0 A room's collectible from the pool its entities pick, or the treasure pool's when they pick none. int ItemPool::GetSeededCollectible(uint32_t drawSeed, uint32_t flags, RoomDescriptor& room) { int pool = get_pool_from_room_entities(drawSeed, room, 0); return GetCollectible(pool == POOL_NONE ? POOL_TREASURE : (ItemPoolType)pool, drawSeed, flags, 0, 0); } // 00732fa0 The pool item a roll lands on among the items' initial weights, kept with the chance of its weight left. // A pass that keeps nothing rolls again from where the last landing fell, up to a budget the bans raise. Out of rolls, // it takes the next item that may be drawn. The pick then loses weight, and is removed below its threshold. // The original's last resort tests the quality of the previous landing and no Devil sacrifice tag, kept here. PoolItem* ItemPool::pick_weighted(ItemPool_Item& pool, uint32_t flags, float roll) { std::vector& list = pool.poolList; ItemConfig_Item* landed = nullptr; PoolItem* pick = nullptr; int repicks = flags & POOL_FLAG_BAN_ACTIVES ? REPICKS_BAN_ACTIVES : REPICKS; float sum = 0; for (int quality = 0; quality < QUALITY_COUNT; quality++) if (flags & (POOL_FLAG_BAN_QUALITY_0 << quality)) repicks += QUALITY_REPICKS[quality]; for (size_t i = 0; i < list.size() && !pick; i++) { PoolItem& item = list[i]; if ((sum += item.initialWeight) <= roll) continue; float landing = (sum - roll) / item.initialWeight; landed = collectible_get(item.itemId); bool isAllowed = landed && is_kind_allowed(landed, flags) && !is_quality_banned(landed, flags) && !((flags & POOL_FLAG_BAN_DEVIL_SACRIFICE) && (landed->tags & TAG_DEVIL_SACRIFICE)); bool isFree = !is_marked(removedCollectibles, item.itemId) && !is_marked(roomBlacklistedCollectibles, item.itemId); if (1 - landing < item.weight / item.initialWeight && isFree && isAllowed) { pick = &item; break; } if (repicks < 1) { log_printf(LOG_INFO, "[warn] item pool ran out of repicks\n"); for (size_t step = 1; step < list.size() && !pick; step++) { PoolItem& next = list[(i + step) % list.size()]; ItemConfig_Item* config = collectible_get(next.itemId); bool isNextFree = !is_marked(removedCollectibles, next.itemId) && !is_marked(roomBlacklistedCollectibles, next.itemId); if (next.weight > 0 && isNextFree && config && is_kind_allowed(config, flags) && !is_quality_banned(landed, flags)) pick = &next; } break; } sum = 0; roll = pool.totalWeight * landing; if (roll == pool.totalWeight) roll = pool.totalWeight / REPICK_EDGE_DIVISOR; repicks--; i = (size_t)-1; } if (!pick || pick->weight <= 0 || (flags & POOL_FLAG_NO_DECREASE)) return pick; pick->weight -= pick->decreaseBy; if (pick->weight >= pick->removeOn) return pick; pick->weight = 0; if (pick->itemId >= 0 && g_game->challenge != CHALLENGE_CANTRIPPED) { if (pick->itemId == COLLECTIBLE_WAIT_WHAT) RemoveCollectible(COLLECTIBLE_BUTTER_BEAN, REMOVE_ANY, REMOVE_APPLY); mark_set(removedCollectibles, pick->itemId, true); } return pick; } // 00732d00 Whether a collectible may still come from the pools: not removed or blacklisted, available (its unlock // checked or not), and no active while someone holds No!. bool ItemPool::is_collectible_available(int collectible, UnlockCheck check) { ItemConfig_Item* item = collectible_get(collectible); uint32_t checks = check == UNLOCK_IGNORED ? AVAILABLE_ALL & ~AVAILABLE_UNLOCKED : AVAILABLE_ALL; if (!item || is_marked(removedCollectibles, collectible) || is_marked(roomBlacklistedCollectibles, collectible)) return false; if (!item->IsAvailableEx(checks)) return false; return !g_game->playerManager.AnyoneHasTrinket(TRINKET_NO) || item->type != ITEM_ACTIVE; } // 00733ff0 Removes a collectible from every pool for the run (Wait What? takes Butter Bean along), or only asks. // Whether it was still in the pools. Nothing is removed in Cantripped!. bool ItemPool::RemoveCollectible(int collectible, RemoveCheck check, RemoveMode mode) { ItemConfig_Item* item = collectible_get(collectible); if (collectible < 0) return true; if (check == REMOVE_AVAILABLE && (!item || !item->IsAvailableEx(AVAILABLE_ALL))) return false; if (g_game->challenge == CHALLENGE_CANTRIPPED) return false; if (collectible == COLLECTIBLE_WAIT_WHAT && mode == REMOVE_APPLY) RemoveCollectible(COLLECTIBLE_BUTTER_BEAN, REMOVE_ANY, REMOVE_APPLY); bool isInPools = !is_marked(removedCollectibles, collectible); if (mode == REMOVE_APPLY) mark_set(removedCollectibles, collectible, true); return isInPools; } // 007340b0 Puts a collectible back in the pools with its full weight. void ItemPool::ResetCollectible(int collectible) { if (collectible < 0) return; mark_set(removedCollectibles, collectible, false); mark_set(roomBlacklistedCollectibles, collectible, false); for (ItemPool_Item& pool : pools) for (PoolItem& item : pool.poolList) if (item.itemId == collectible) item.weight = item.initialWeight; } // 005b14b0 Keeps a collectible out of draws until the room changes. void ItemPool::AddRoomBlacklist(int collectible) { mark_set(roomBlacklistedCollectibles, collectible, true); } // 00736f90 void ItemPool::ResetRoomBlacklist() { roomBlacklistedCollectibles.assign(roomBlacklistedCollectibles.size(), false); } // 00736fd0 Raises the Bible's chance in a pool, or in every pool for a type past the last. A type below 1 is the // treasure pool. void ItemPool::AddBibleUpgrade(int add, int poolType) { if (poolType < POOL_COUNT) pools[std::max(poolType, 0)].bibleUpgrade += add; else for (ItemPool_Item& pool : pools) pool.bibleUpgrade += add; } // Whether a Magic Skin pedestal waits in the current room or a visited one. Room's entity list and the saved // entities of the floor's rooms are not modelled yet. static bool is_magic_skin_waiting() { reconstruction_missing("ItemPool::should_force_magic_skin pedestal scan (Room entity list, saved entities)"); } // 007333f0 Whether Magic Skin replaces a draw: after it has been used, a chance growing with each use, or a fixed // share of draws while no Magic Skin pedestal is waiting. bool ItemPool::should_force_magic_skin(uint32_t drawSeed) { int uses = g_game->magicSkinUses; RNG rng = rng_make(drawSeed, MAGIC_SKIN_SHIFT); if (uses < 1 || g_game->playerManager.AnyoneHasCollectible(COLLECTIBLE_MAGIC_SKIN)) return false; if (rng.RandomFloat() < uses * MAGIC_SKIN_CHANCE_PER_USE) return true; if (is_magic_skin_waiting()) return false; return rng.RandomInt((uint32_t)std::max(MAGIC_SKIN_ROLL_BASE - uses, 1)) == 0; } // (009dcc70) A TMTRAINER glitched collectible, which ProceduralItemManager makes. int ItemPool::CreateGlitchedCollectible(uint32_t, uint32_t) { reconstruction_missing("ItemPool::CreateGlitchedCollectible 009dcc70"); } // Whether a trinket pool slot may be drawn: still in the pool, available, and its trinket may appear. static bool is_trinket_drawable(TrinketPoolItem& slot) { ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(slot.id & TRINKET_ID_MASK); return slot.isInPool && slot.isAvailable && trinket && trinket->IsAvailableEx(AVAILABLE_ALL); } // 00733ca0 Draws a trinket: random slots for half the pool's size (at least one), then the next drawable slot after a // random one. // Taking it removes it from the pool. Once golden trinkets are unlocked, one in 50 is golden. Lua's MC_GET_TRINKET // may override it. // The original crashes on a slot whose trinket is missing. Here such a slot cannot be drawn. uint32_t ItemPool::GetTrinket(TrinketDraw draw) { if (numAvailableTrinkets <= 0) ResetTrinkets(); RNG peekRng = trinketPoolRNG; RNG& rng = draw == TRINKET_DRAW_PEEK ? peekRng : trinketPoolRNG; uint32_t count = (uint32_t)trinketPoolItems.size(); uint32_t index = rng.RandomInt(count); RNG retryRng = rng_make(rng._seed, POOL_SHIFT); std::optional found; int tries = (int)(count / 2); do { if (count && is_trinket_drawable(trinketPoolItems[index])) found = index; else index = count ? retryRng.Next() % count : 0; } while (!found && --tries > 0); if (!found) { log_printf(LOG_INFO, "GetTrinket: no tries left\n"); index = retryRng.RandomInt(count); for (uint32_t scanned = 0; scanned < count && !found; scanned++) if (is_trinket_drawable(trinketPoolItems[index = (index + 1) % count])) found = index; } uint32_t trinket = 0; if (found) { if (draw == TRINKET_DRAW_TAKE) trinketPoolItems[*found].isInPool = false; if (draw == TRINKET_DRAW_TAKE) numAvailableTrinkets--; trinket = trinketPoolItems[*found].id; } if (uint32_t overridden = FUN_008658c0(trinket, &trinketPoolRNG._seed)) return overridden; if (!g_manager->persistentGameData.Unlocked(ACHIEVEMENT_GOLDEN_TRINKETS)) return trinket; bool isGolden = rng_make(rng._seed, GOLDEN_SHIFT).Next() % GOLDEN_TRINKET_ODDS == 0 || (g_game && (g_game->debugFlags & DEBUG_GOLDEN_TRINKETS)); return isGolden ? trinket | TRINKET_GOLDEN : trinket; } // 00734130 Takes a trinket out of the pool. Whether it was there to take. bool ItemPool::RemoveTrinket(int trinketId) { if (trinketId < 1 || trinketId >= (int)trinketPoolItems.size()) return false; TrinketPoolItem& slot = trinketPoolItems[trinketId]; if (!slot.isInPool || !slot.isAvailable) return false; slot.isInPool = false; numAvailableTrinkets--; return true; } // 00736a90 Puts every trinket back in the pool but Perfection, and Butter in Pica Run, then counts the drawable ones. void ItemPool::ResetTrinkets() { for (uint32_t id = 0; id < trinketPoolItems.size(); id++) { TrinketPoolItem& slot = trinketPoolItems[id] = {id}; ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id & TRINKET_ID_MASK); bool isExcluded = !trinket || trinket->id == TRINKET_PERFECTION || (trinket->id == TRINKET_BUTTER && g_game->challenge == CHALLENGE_PICA_RUN); slot.isInPool = !isExcluded; slot.isAvailable = !isExcluded && trinket->IsAvailableEx(AVAILABLE_ALL); } numAvailableTrinkets = (int)std::ranges::count_if(trinketPoolItems, [](TrinketPoolItem& slot) { return slot.isInPool && slot.isAvailable; }); if (numAvailableTrinkets <= 0) log_printf(LOG_ASSERT, "[warn] trinket pool is empty from the start\n"); } // 00734900 A pill color from a seed: one of the 13, gold one in 140 and a horse pill one in 70 once unlocked. Lua's // MC_GET_PILL_COLOR may override it. int ItemPool::GetPill(uint32_t drawSeed) { RNG rng = rng_make(drawSeed, PILL_SHIFT); int color = (int)(rng.Next() % PILL_COLORS) + 1; if (rng.Next() % PILL_GOLD_ODDS == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_GOLD_PILLS)) color = PILL_GOLD; if (rng.Next() % PILL_HORSE_ODDS == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_HORSE_PILLS)) color |= PILL_HORSE; int overridden = (int)FUN_00865c80(PILL_GET_COLOR_CALLBACK, drawSeed); return overridden ? overridden : color; } // The other side of a pill effect from a table, or the effect itself. Every pair is tried in turn, as the original. static int effect_swap(std::span> pairs, int effect) { for (auto [from, to] : pairs) if (effect == from) effect = to; return effect; } // 00734a80 The effect a pill color has for a player: PHD (Virgo, Lucky Foot) turns bad pills good unless False PHD // cancels it, and False PHD alone turns good pills bad. A pill the player cannot use falls back on a safe one. Lua's // MC_GET_PILL_EFFECT may override it. // The original reads past the colors for a color above gold. Here that is no effect. int ItemPool::GetPillEffect(uint32_t pillColor, Entity_Player* player) { int color = (int)(pillColor & PILL_COLOR_MASK); int effect = color < PILL_COLOR_SLOTS ? pillEffects[color] : PILL_EFFECT_NONE; bool isFalsePhd = false; if (g_game->dailyChallenge._specialDailyId == DAILY_EXPLOSIVE_PILLS) return PILLEFFECT_EXPLOSIVE_DIARRHEA; if (player) { bool isPhd = player->HasCollectible(COLLECTIBLE_PHD, 0) || player->HasCollectible(COLLECTIBLE_VIRGO, 0) || player->HasCollectible(COLLECTIBLE_LUCKY_FOOT, 0) || player->GetZodiacEffect() == COLLECTIBLE_VIRGO; bool hasFalsePhd = player->HasCollectible(COLLECTIBLE_FALSE_PHD, 0); isFalsePhd = !isPhd && hasFalsePhd; if (isPhd && !hasFalsePhd) effect = effect_swap(PHD_EFFECTS, effect); if (isFalsePhd) effect = effect_swap(FALSE_PHD_EFFECTS, effect); bool isUsable = player->CanUsePill(effect); if (!isUsable && effect == PILLEFFECT_BAD_TRIP) effect = isFalsePhd ? PILLEFFECT_I_FOUND_PILLS : PILLEFFECT_FULL_HEALTH; else if (!isUsable && effect == PILLEFFECT_HEALTH_DOWN) effect = isFalsePhd ? PILLEFFECT_I_FOUND_PILLS : PILLEFFECT_HEALTH_UP; } int overridden = static_cast(g_luaEngine)->GetPillEffect(effect, color); return overridden != -1 ? overridden : effect; } // 00736ba0 The color with a pill effect, given to a random color first when none has it. int ItemPool::ForceAddPillEffect(int pillEffect) { for (int color = 1; color <= PILL_COLORS; color++) if (pillEffects[color] == pillEffect) return color; int color = (int)(itemPoolRNG.Next() % PILL_COLORS) + 1; pillEffects[color] = pillEffect; return color; } // The identified slot of a pill color, every color past the known ones sharing the last. static int pill_slot_get(uint32_t pillColor) { return std::min((int)(pillColor & PILL_COLOR_MASK), PILL_GOLD); } // 00718ea0 void ItemPool::IdentifyPill(uint32_t pillColor) { identifiedPillEffects[pill_slot_get(pillColor)] = true; } // 0083c490 bool ItemPool::IsPillIdentified(uint32_t pillColor) { return identifiedPillEffects[pill_slot_get(pillColor)]; } // (00736c30) What using a pill does to the pools. int ItemPool::on_pill_used(int, uint32_t, uint32_t&) { reconstruction_missing("ItemPool::on_pill_used 00736c30"); } // (00734cc0) Takes the effects deathmatch bans out of the pill colors. void ItemPool::remove_deathmatch_pill_effects() { reconstruction_missing("ItemPool::remove_deathmatch_pill_effects 00734cc0"); } // (00734870) A card from a seed. int ItemPool::GetCard(uint32_t, bool, bool, bool) { reconstruction_missing("ItemPool::GetCard 00734870"); } // (00734180) A card, rune or special card from a seed, by the chances given. int ItemPool::GetCardEx(int, int, int, int, bool) { reconstruction_missing("ItemPool::GetCardEx 00734180"); }