diff --git a/generated-src/classes.h b/generated-src/classes.h index f6a5ac4..86cf8eb 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -121,6 +121,7 @@ struct AchievementEntry; struct AchievementOverlay; struct AchievementOverlay_Entry; struct ActiveItemDesc; +struct ActiveUse; struct AfterbirthPersistentGameData; struct Ambush; struct AnimationData; @@ -240,6 +241,7 @@ struct Entity_Slot; struct Entity_Tear; struct Entity_Text; struct ErasedEnemy; +struct Explosion; struct FXLayer; struct FXLayers; struct FXParams; @@ -260,6 +262,7 @@ struct FontSettings; struct FormattedText; struct FormattedTextLine; struct FrameQueue; +struct FreeSpotSearch; struct FriendEntry; struct GUID; struct Game; @@ -281,6 +284,7 @@ struct GlowingHourglassState; struct GlyphDraw; struct GlyphQuad; struct GraphicsWindow; +struct GridDestroy; struct GridEntity; struct GridEntityDesc; struct GridEntity_Decoration; @@ -370,6 +374,7 @@ struct Leaderboard; struct Level; struct LevelGenerator; struct LevelGenerator_Room; +struct LightSpawn; struct Lobby; struct LobbyList; struct LobbyLocalhost; @@ -450,6 +455,7 @@ struct OnlineEmotes; struct OnlineStatsScreen; struct OptionsConfig; struct PMD; +struct ParticleSpawn; struct PathFinder; struct PathNode; struct PauseScreen; @@ -564,6 +570,7 @@ struct SpriteShaderParams; struct SpriteTrailData; struct StageNameQuery; struct StageTransition; +struct StageTransitionRequest; struct StageVisit; struct StatHUD; struct StatHUDPlayer; @@ -583,6 +590,7 @@ struct TrinketPoolItem; struct TypeDescriptor; struct UmbilicalBabyData; struct UpdateTally; +struct UseResult; struct UserProfile; struct VariantRange; struct Vector; @@ -3976,19 +3984,6 @@ struct SpriteTrailData { }; LAYOUT32(sizeof(SpriteTrailData) == 0x18); -struct StageTransition { - void Update(); // 0092f1c0 - void Render(); // 0092ffc0 - float get_fade_progress(); // 00930160 - - int _state; - int _frame; - int _duration; -}; -LAYOUT32(offsetof(StageTransition, _state) == 0x0); -LAYOUT32(offsetof(StageTransition, _frame) == 0x4); -LAYOUT32(offsetof(StageTransition, _duration) == 0x8); - struct StatsPanel { static void add_stat_line(); // 0084dc00 void set(Entity_Player *player, uint8_t isGoldenTrinket); // 0084dea0 @@ -6028,7 +6023,6 @@ void FUN_0042a040(int *param_1, int *param_2); // 0042a040 void FUN_0042a210(); // 0042a210 void FUN_0042a230(); // 0042a230 void FUN_0042a350(); // 0042a350 -void FUN_0042a430(uint8_t param_1); // 0042a430 void FUN_0042a490(); // 0042a490 void FUN_0042aca0(); // 0042aca0 bool FUN_0042ae90(); // 0042ae90 @@ -6082,13 +6076,11 @@ long double FUN_0042cf00(); // 0042cf00 void FUN_0042cf10(Entity_Player *param_1, uint32_t param_2); // 0042cf10 int FUN_0042d040(); // 0042d040 void get_netplay_player_color(void *self, ColorMod *outColor, Entity_Player *player); // 0042d060 -void FUN_0042d0f0(uint8_t param_1); // 0042d0f0 uint32_t FUN_0042d1b0(); // 0042d1b0 void FUN_0042d5f0(Entity_Player *param_1, uint32_t param_2); // 0042d5f0 uint32_t FUN_0042d660(); // 0042d660 long double FUN_0042d670(); // 0042d670 void FUN_0042d680(Entity_Player *param_1, uint32_t param_2); // 0042d680 -void FUN_0042d780(uint8_t param_1); // 0042d780 uint32_t FUN_0042d7e0(); // 0042d7e0 uint8_t FUN_0042d7f0(); // 0042d7f0 void FUN_0042d850(); // 0042d850 @@ -6473,7 +6465,6 @@ void FUN_005d2270(); // 005d2270 void FUN_005d2300(); // 005d2300 void FUN_005d2370(uint8_t param_1); // 005d2370 void FUN_005d23a0(uint8_t param_1); // 005d23a0 -void FUN_005d29b0(); // 005d29b0 void FUN_005d4210(); // 005d4210 void FUN_00607540(); // 00607540 void room_perimeter_to_position(float *param_1, float *param_2); // 0060ac70 @@ -6649,7 +6640,6 @@ float normalize_angle_degrees(float angle); // 00682740 float angle_difference(float from, float to); // 006827a0 void FUN_00682a20(); // 00682a20 float approach_angle(float current, float target, float maxStep); // 00682a50 -void FUN_00683010(int param_1, int param_2, int param_3); // 00683010 uint32_t checksum_stream(void *stream, int offset, int trailingSize); // 00683580 void FUN_00683680(); // 00683680 void pop_render_target(); // 006836c0 @@ -6786,12 +6776,10 @@ uint32_t * FUN_006a13b0(uint32_t *param_1); // 006a13b0 uint32_t * FUN_006a1420(uint32_t *param_1); // 006a1420 void FUN_006a14f0(uint32_t param_1, uint32_t *param_2); // 006a14f0 void FUN_006a1e00(uint32_t *param_1); // 006a1e00 -void FUN_006a1e80(); // 006a1e80 void FUN_006a1fc0(); // 006a1fc0 void FUN_006a6910(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4); // 006a6910 void FUN_006a6930(); // 006a6930 void FUN_006a6940(); // 006a6940 -std_string * resolve_resource_path(std_string *outPath, std_string *path, void *suffixes); // 006a69e0 void FUN_006a7ec0(); // 006a7ec0 void FUN_006a80d0(); // 006a80d0 void FUN_006a8180(uint32_t param_1); // 006a8180 @@ -6913,16 +6901,13 @@ Entity_Player * FUN_007103c0(uint32_t *param_1); // 007103c0 uint32_t FUN_00710f70(int param_1); // 00710f70 void FUN_00711530(int param_1); // 00711530 uint32_t FUN_00711740(); // 00711740 -uint32_t FUN_00711fd0(); // 00711fd0 void FUN_007135d0(uint32_t param_1, uint8_t param_2, int *param_3); // 007135d0 void spawn_poop_rewards(uint32_t param_1, int param_2, int param_3, char param_4, uint32_t param_5, int param_6); // 00716db0 void FUN_00718d20(float *param_1); // 00718d20 void FUN_00718ed0(uint32_t param_1); // 00718ed0 uint32_t FUN_00718ee0(); // 00718ee0 -void grid_mark_neighbors_dirty(int gridIndex); // 0071dee0 void FUN_0071df70(uint8_t param_1); // 0071df70 int FUN_0071df80(); // 0071df80 -void FUN_0071f4b0(uint32_t param_1); // 0071f4b0 uint32_t FUN_00721b70(int param_1); // 00721b70 void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6); // 00721e60 void FUN_00721eb0(); // 00721eb0 @@ -7021,7 +7006,6 @@ void FUN_007530c0(); // 007530c0 void std_deque_growmap(void *self, uint32_t count); // 007530f0 void FUN_00753230(uint32_t param_1); // 00753230 void FUN_00753550(); // 00753550 -uint8_t FUN_00753560(); // 00753560 void FUN_00753620(); // 00753620 bool FUN_00753630(); // 00753630 bool FUN_00753640(); // 00753640 @@ -7076,7 +7060,6 @@ Entity_Player * FUN_007a1020(); // 007a1020 uint32_t FUN_007ab0e0(); // 007ab0e0 void FUN_007ad610(); // 007ad610 uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2); // 007ad720 -void FUN_007ae430(short *param_1); // 007ae430 void FUN_007b8c00(int param_1); // 007b8c00 void FUN_007b9a60(); // 007b9a60 void FUN_007b9aa0(); // 007b9aa0 @@ -7203,21 +7186,14 @@ void FUN_007e9170(char param_1); // 007e9170 void FUN_007e92e0(uint32_t param_1, uint32_t param_2); // 007e92e0 void FUN_007e93d0(int param_1); // 007e93d0 void FUN_007ea0c0(); // 007ea0c0 -void FUN_007ea5d0(); // 007ea5d0 void FUN_007ebc40(); // 007ebc40 -uint32_t FUN_007ed240(); // 007ed240 float get_angel_room_chance(); // 007f96f0 -void FUN_007fa2a0(float *param_1); // 007fa2a0 -void FUN_007fa7d0(); // 007fa7d0 -int RoomClear_PickVariant(RNG *rng, uint8_t isForcePickup); // 007fa920 void FUN_00812ea0(float *param_1, int *param_2, int *param_3); // 00812ea0 uint32_t FUN_00813420(int param_1, int param_2); // 00813420 void pickup_roll_random_variant(void *papersOwner, int shopItemId, int *variant, uint32_t *subType, uint32_t seed); // 00814a50 uint32_t FUN_0081e220(); // 0081e220 void FUN_0081fae0(uint32_t *param_1); // 0081fae0 -uint32_t FUN_008207a0(); // 008207a0 void FUN_00821940(); // 00821940 -int FUN_00823ec0(); // 00823ec0 uint32_t FUN_00827180(float *param_1); // 00827180 void FUN_00827f30(); // 00827f30 void FUN_00828010(uint32_t *param_1); // 00828010 @@ -7243,7 +7219,6 @@ void FUN_0082e290(int param_1, int param_2, int param_3); // 0082e290 void Catch_All_0082e7ec(); // 0082e7ec void FUN_0082ea50(uint32_t param_1, uint32_t *param_2, code *param_3); // 0082ea50 void FUN_0082eb20(uint32_t *param_1, code *param_2); // 0082eb20 -void FUN_00831780(int *param_1, uint8_t *param_2, uint8_t *param_3, uint8_t *param_4); // 00831780 void FUN_008332a0(char param_1); // 008332a0 uint64_t * FUN_00834c60(uint64_t *param_1, uint64_t *param_2); // 00834c60 void Catch_All_00834f6f(); // 00834f6f @@ -9529,7 +9504,6 @@ void FUN_00950eb0(); // 00950eb0 void FUN_00951090(); // 00951090 void FUN_009510f0(); // 009510f0 void FUN_00951130(); // 00951130 -uint8_t input_is_action_pressed(int action, int controllerIndex, Entity *entity, int unused); // 00956110 uint8_t is_any_player_restart_held(); // 009563b0 uint32_t FUN_00956750(); // 00956750 uint8_t * FUN_009587e0(StringTable *param_1, uint8_t *param_2, uint8_t *param_3); // 009587e0 @@ -21608,8 +21582,6 @@ void ENTITY_LARRYJR(Entity_NPC *npc); // 0046a0f0 void ENTITY_MONSTRO(Entity_NPC *npc); // 0046c0a0 void ENTITY_DUKE(Entity_NPC *npc); // 0046e290 void ENTITY_WIDOW(Entity_NPC *npc); // 0046fbe0 -void ENTITY_GEMINI(Entity_NPC *npc); // 00471050 -void ENTITY_GEMINI_baby(Entity_NPC *npc); // 00471cc0 void ENTITY_BLASTOCYST_BIG(Entity_NPC *npc); // 00472c40 void ENTITY_SLOTH(Entity_NPC *npc); // 004741f0 void ENTITY_LUST(Entity_NPC *npc); // 00474e00 @@ -21716,10 +21688,7 @@ void ENTITY_STONE_EYE(Entity_NPC *npc); // 00505d00 void ENTITY_CONSTANT_STONE_SHOOTER(Entity_NPC *npc); // 00506320 void ENTITY_EMBRYO(Entity_NPC *npc); // 0050a6b0 void ENTITY_ETERNALFLY(Entity_NPC *npc); // 0050a8a0 -void ENTITY_GUSHER(Entity_NPC *npc); // 0050af90 -void ENTITY_MULLIGAN(Entity_NPC *npc); // 0050bbe0 void ENTITY_HIVE(Entity_NPC *npc); // 0050c370 -void ENTITY_CLOTTY(Entity_NPC *npc); // 0050d370 void ENTITY_GLOBIN(Entity_NPC *npc); // 0050e4d0 uint32_t ENTITY_BOOMFLY(Entity_NPC *npc); // 0050f280 void ENTITY_MAW(Entity_NPC *npc); // 00510ae0 diff --git a/generated-src/kage_filesys_file_manager.cpp b/generated-src/kage_filesys_file_manager.cpp index fb8ad4a..24462b4 100644 --- a/generated-src/kage_filesys_file_manager.cpp +++ b/generated-src/kage_filesys_file_manager.cpp @@ -1,89 +1,5 @@ #include "classes.h" -// 005ca5a0 -bool KAGE_Filesys_FileManager::OpenRead(int param_2, int param_3) -{ - uint8_t isHasFlags; - int iVar1; - int totalCharge; - - if (-1 < param_3) { - iVar1 = Entity_Player::GetActiveMaxCharge(GHIDRA_CAST(this),param_3); - totalCharge = Entity_Player::GetTotalActiveCharge(GHIDRA_CAST(this),param_3); - if (totalCharge < iVar1) { - return false; - } - } - if (0x244 < param_2) { - switch(param_2) { - case 0x248: - if ((*GHIDRA_CAST((this + 0x7ec)) != GHIDRA_CAST(0x0)) && (**GHIDRA_CAST((this + 0x7ec)) == 3)) { - return false; - } - default: - return true; - case 0x26f: - return 0 < *GHIDRA_CAST((this + 0x674)); - case 0x27b: - iVar1 = FUN_005c92f0(); - if (iVar1 != 0) { - iVar1 = Room::GetGridCollisionAtPos(g_game->_room,*GHIDRA_CAST((iVar1 + 0x33c))); - if ((*GHIDRA_CAST((GHIDRA_CAST(&(this[0x725])) + 0x1))) != '\0') { - return iVar1 != 4; - } - if (iVar1 == 0) { - return true; - } - if (iVar1 == 5) { - return true; - } - } - break; - case 0x282: - iVar1 = Entity_Player::GetEffectiveMaxHearts(GHIDRA_CAST(this)); - return 0 < iVar1 + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x66e])) + 0x2)))); - case 0x2c5: - if ((*GHIDRA_CAST((this + 0xa64)) == 0) && - (1.0 < *GHIDRA_CAST((this + 0x120)) * *GHIDRA_CAST((this + 0x120)) + - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x121])) + 0x1)))) * *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x121])) + 0x1)))))) { - return true; - } - break; - case 0x2ca: - isHasFlags = Entity::HasEntityFlags(GHIDRA_CAST(this),0x600000000000000); - if ((isHasFlags == 0) && (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11a])) + 0x2)))) == 0.0)) { - return true; - } - } - return false; - } - if (param_2 == 0x244) { - iVar1 = FUN_00827180(this + 0x114); - return iVar1 != -1; - } - if (0x127 < param_2) { - if (param_2 != 0x1e7) { - if (param_2 == 0x22b) { - return 4 < *GHIDRA_CAST((this + 0x678)); - } - return true; - } -LAB_005ca662: - return 1 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x66a])) + 0x2)))); - } - if (param_2 == 0x127) { - return 0 < *GHIDRA_CAST((this + 0x678)); - } - if (param_2 != 0x82) { - if (param_2 == 0x85) goto LAB_005ca662; - if (param_2 != 0xb5) { - return true; - } - } - return 1.0 < *GHIDRA_CAST((this + 0x120)) * *GHIDRA_CAST((this + 0x120)) + - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x121])) + 0x1)))) * *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x121])) + 0x1)))); -} - // 00a159d0 uint32_t KAGE_Filesys_FileManager::GetPrimaryFilePathHash(uint8_t *filePath) { diff --git a/generated-src/stage_transition.cpp b/generated-src/stage_transition.cpp deleted file mode 100644 index a2b2f49..0000000 --- a/generated-src/stage_transition.cpp +++ /dev/null @@ -1,631 +0,0 @@ -#include "classes.h" - -// 0092f1c0 -void StageTransition::Update() -{ - StageTransition *catchUpPlayer = this; - uint8_t uVar1; - int *piVar2; - uint8_t bVar3; - uint32_t uVar4; - Vector *trapdoorPos; - Entity *spawnedEffect; - uint32_t uVar5; - std_string *animName; - int *playerIt; - RoomDescriptor *startingRoom; - int iVar6; - void *pvVar7; - Game *game; - int gridX; - char cVar8; - uint32_t *playerSlot; - Entity_Player *player; - bool bVar9; - float fVar10; - float fVar11; - double dVar12; - Vector dustVelocity; - float angleSin; - float dustSpeed; - float angle; - Vector spawnPos; - StageTransition *transition; - Entity_Player *waitingPlayer; - GridEntity *trapdoorGrid; - int minExitFrame; - char isExitAnimDone; - Entity_Player *local_38; - Entity_Player *exitingPlayer; - char local_2e; - char isNoPlayerExiting; - void *tmpString [4]; - uint32_t tmpStringSize; - uint32_t tmpStringCapacity; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - void *local_8; - Entity_Player *catchUpPlayer; - uint32_t *flagsHigh; - Manager *manager; - uint64_t savedFlags; - GridEntity *trapdoor; - - game = g_game; - local_8 = (void *)0xffffffff; - puStack_c = &LAB_00b0aced; - local_10 = ExceptionList; - uVar4 = __security_cookie ^ GHIDRA_UINT((tmpString + 10)); - ExceptionList = &local_10; - transition = catchUpPlayer; - local_14 = uVar4; - switch(*GHIDRA_CAST(catchUpPlayer)) { - case 1: - isNoPlayerExiting = '\x01'; - waitingPlayer = GHIDRA_CAST(0x0); - exitingPlayer = GHIDRA_CAST(0x0); - minExitFrame = 1000; - local_2e = '\0'; - EntityList::Update(GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),1); - if (((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) == 4) && - (pvVar7 = (g_game->_playerManager)._stageTransitionPlayer, - *GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0x1b1c)) == g_vectorZero.x)) && - (*GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0x1b20)) == g_vectorZero.y)) { - playerIt = (g_game->_playerManager)._playerList._begin; - if (playerIt != (g_game->_playerManager)._playerList._end) { - do { - piVar2 = GHIDRA_CAST(*playerIt); - if ((piVar2 != GHIDRA_CAST(0x0)) && (piVar2[0xb] == 0)) { - (**(code **)(*piVar2 + 0xc))(); - } - playerIt = playerIt + 1; - } while (playerIt != (g_game->_playerManager)._playerList._end); - } - break; - } - playerSlot = (g_game->_playerManager)._playerList._begin; - player = GHIDRA_CAST(0x0); - if (playerSlot != (g_game->_playerManager)._playerList._end) { - do { - player = GHIDRA_CAST(*playerSlot); - if ((player != GHIDRA_CAST(0x0)) && (player->_variant == 0)) { - if (player->_isPlayingExtraAnimation == 0) { -LAB_0092f31d: - isExitAnimDone = '\0'; - } - else { - if ((player->_sprite)._animState._animData != (void *)0x0) { - local_38 = GHIDRA_CAST((player->_sprite)._animState._animFrame); - dVar12 = floor((double)(float)local_38); - local_38 = GHIDRA_CAST((float)dVar12); - if (GHIDRA_INT(dVar12) != *GHIDRA_CAST((GHIDRA_INT((player->_sprite)._animState._animData) + 0x30)) + -1) - goto LAB_0092f31d; - } - isExitAnimDone = '\x01'; - } - (**(code **)(*GHIDRA_CAST(player) + 0xc))(); - if ((player->_dead == 0) && (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) != 1)) { - if (((player->_isPlayingExtraAnimation == 0) && (player->_isPlayingItemAnimation == 0)) - || ((player->_isCoopGhost != 0 && - (fVar10 = (player->_moveToTarget).x - (player->_pos).x, - fVar11 = (player->_moveToTarget).y - (player->_pos).y, - fVar11 * fVar11 + fVar10 * fVar10 <= 1.0)))) { - if (isExitAnimDone == '\0') { - if ((player->_visible != 0) && (waitingPlayer == GHIDRA_CAST(0x0))) { - waitingPlayer = player; - } - } - else { - player->_visible = 0; - } - } - else { - isNoPlayerExiting = '\0'; - if ((player->_sprite)._animState._animData == (void *)0x0) { - iVar6 = -1; - } - else { - local_38 = GHIDRA_CAST((player->_sprite)._animState._animFrame); - dVar12 = floor((double)(float)local_38); - iVar6 = GHIDRA_INT(dVar12); - } - local_38 = player; - if (minExitFrame <= iVar6) { - iVar6 = minExitFrame; - local_38 = exitingPlayer; - } - minExitFrame = iVar6; - exitingPlayer = local_38; - update_player_trapdoor_scale(catchUpPlayer,player,0); - if (((player->_sprite)._animState._animData != (void *)0x0) && - (bVar3 = AnimationState::IsEventTriggered - (&(player->_sprite)._animState,&DAT_00b1d534), bVar3 != 0)) { - local_2e = '\x01'; - exitingPlayer = local_38; - } - } - } - } - playerSlot = playerSlot + 1; - } while (playerSlot != (g_game->_playerManager)._playerList._end); - player = exitingPlayer; - if (exitingPlayer != GHIDRA_CAST(0x0)) { - fVar10 = (exitingPlayer->_moveToTarget).y; - *GHIDRA_CAST((catchUpPlayer + 2)) = (exitingPlayer->_moveToTarget).x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[2])) + 0x4)))) = fVar10; - } - } - pvVar7 = g_game->_room; - gridX = GHIDRA_INT(((*GHIDRA_CAST((catchUpPlayer + 2)) - 40.0) / 40.0 + 0.5)); - iVar6 = GHIDRA_INT(((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[2])) + 0x4)))) - 120.0) / 40.0 + 0.5)); - if (gridX < 0) { -LAB_0092f849: - cVar8 = isNoPlayerExiting; - } - else { - if (((*GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0xc)) <= gridX) || (iVar6 < 0)) || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0x10)) <= iVar6)) goto LAB_0092f849; - uVar4 = iVar6 * *GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0xc)) + gridX; - if (0x1bf < uVar4) goto LAB_0092f849; - trapdoor = *GHIDRA_CAST((GHIDRA_CAST(pvVar7) + uVar4 * 4 + 0x24)); - trapdoorGrid = trapdoor; - if (((trapdoor == GHIDRA_CAST(0x0)) || (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((trapdoor)) + 0x4)))) != 0x11)) || - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((trapdoor)) + 0x8)))) != 0)) goto LAB_0092f849; - if (local_2e != '\0') { - bVar3 = ANM2::SetAnimation(&trapdoor->_sprite,GHIDRA_CAST("Player Exit"),1); - if (bVar3 != 0) { - AnimationState::Rewind(&(trapdoor->_sprite)._animState); - (trapdoor->_sprite)._animState._isPlaying = 1; - } - if (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x7240)) <= 0.2) { - uVar4 = Random(); - trapdoorPos = GridEntity::Position(trapdoorGrid,&spawnPos); - spawnedEffect = - Game::Spawn(g_game,1000,0xf,trapdoorPos,&g_vectorZero,GHIDRA_CAST(0x0),2,uVar4); - savedFlags = spawnedEffect->_flags; - iVar6 = *GHIDRA_CAST(spawnedEffect); - flagsHigh = GHIDRA_CAST((GHIDRA_INT(&spawnedEffect->_flags) + 4)); - *flagsHigh = *flagsHigh | 0x1000; - *GHIDRA_CAST(&spawnedEffect->_flags) = GHIDRA_INT(savedFlags); - (spawnedEffect->_sprite)._color._tint[3] = 0.5; - (spawnedEffect->_sprite)._playbackSpeed = 2.0; - spawnedEffect->_renderDepthOffset = 4.0; - (**(code **)(iVar6 + 0xc))(); - } - else { - uVar4 = Random(); - trapdoorPos = GridEntity::Position(trapdoorGrid,&spawnPos); - spawnedEffect = - Game::Spawn(g_game,1000,99,trapdoorPos,&g_vectorZero,GHIDRA_CAST(0x0),0,uVar4); - fVar10 = (spawnedEffect->_sprite)._scale.x; - fVar11 = (spawnedEffect->_sprite)._scale.y; - savedFlags = spawnedEffect->_flags; - flagsHigh = GHIDRA_CAST((GHIDRA_INT(&spawnedEffect->_flags) + 4)); - *flagsHigh = *flagsHigh | 0x1000; - *GHIDRA_CAST(&spawnedEffect->_flags) = GHIDRA_INT(savedFlags); - iVar6 = *GHIDRA_CAST(spawnedEffect); - (spawnedEffect->_sprite)._scale.x = fVar10 + fVar10; - (spawnedEffect->_sprite)._scale.y = fVar11 + fVar11; - (spawnedEffect->_sprite)._playbackSpeed = 2.0; - (**(code **)(iVar6 + 0xc))(); - uVar4 = Random(); - trapdoor = trapdoorGrid; - local_38 = GHIDRA_CAST((uVar4 % 5 + 3)); - if (local_38 != GHIDRA_CAST(0x0)) { - do { - uVar4 = Random(); - uVar5 = Random(); - angle = (float)((double)GHIDRA_INT(uVar5) + __uint_to_double_fixup[-(GHIDRA_INT(uVar5) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - angle = angle + angle; - angleSin = sin(angle); - uVar5 = Random(); - dustSpeed = (float)((double)GHIDRA_INT(uVar5) + __uint_to_double_fixup[-(GHIDRA_INT(uVar5) >> 0x1f)] - ) * 2.3283064e-10 * 8.0; - dustVelocity.x = cos(angle); - dustVelocity.x = dustVelocity.x * dustSpeed; - iVar6 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)); - dustVelocity.y = dustSpeed * angleSin; - spawnPos.x = (float)(trapdoor->_gridIndex % iVar6) * 40.0 + 40.0; - spawnPos.y = (float)(trapdoor->_gridIndex / iVar6) * 40.0 + 120.0; - spawnedEffect = - Game::Spawn(g_game,1000,99,&spawnPos,&dustVelocity,GHIDRA_CAST(0x0),1,uVar4); - fVar10 = (spawnedEffect->_sprite)._scale.x; - fVar11 = (spawnedEffect->_sprite)._scale.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(spawnedEffect[1])) + 0x8)))) = 0x3f800000; - (spawnedEffect->_sprite)._scale.x = fVar10 + fVar10; - (spawnedEffect->_sprite)._scale.y = fVar11 + fVar11; - uVar4 = Random(); - flagsHigh = GHIDRA_CAST((GHIDRA_INT(&spawnedEffect->_flags) + 4)); - *flagsHigh = *flagsHigh | 0x1000; - dVar12 = __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]; - *GHIDRA_CAST(&spawnedEffect->_flags) = GHIDRA_INT(spawnedEffect->_flags); - iVar6 = *GHIDRA_CAST(spawnedEffect); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(spawnedEffect[1])) + 0x4)))) = - -8.0 - (float)((double)GHIDRA_INT(uVar4) + dVar12) * 2.3283064e-10 * 4.0; - (**(code **)(iVar6 + 0xc))(); - local_38 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_38[-1])) + 0x2eff)))); - } while (local_38 != GHIDRA_CAST(0x0)); - local_38 = GHIDRA_CAST(0x0); - catchUpPlayer = transition; - player = exitingPlayer; - } - } - } - if (((trapdoorGrid->_sprite)._animState._animData == (void *)0x0) || - ((trapdoorGrid->_sprite)._animState._isPlaying == 0)) goto LAB_0092f849; - ANM2::Update(&trapdoorGrid->_sprite); - cVar8 = '\0'; - } - catchUpPlayer = waitingPlayer; - if (((player == GHIDRA_CAST(0x0)) || (waitingPlayer == GHIDRA_CAST(0x0))) || - (minExitFrame < 6)) { - if (cVar8 == '\0') goto LAB_0092f901; - } - else { - animName = ANM2::GetAnimation(GHIDRA_CAST(&(player->_sprite)._animState),GHIDRA_CAST(tmpString)); - local_8 = (void *)0x0; - if (0xf < animName->_capacity) { - animName = *GHIDRA_CAST(animName->_buf); - } - Entity_Player::PlayExtraAnimation(catchUpPlayer,GHIDRA_CAST(animName)); - local_8 = (void *)0xffffffff; - if (0xf < tmpStringCapacity) { - uVar4 = tmpStringCapacity + 1; - pvVar7 = tmpString[0]; - if (0xfff < uVar4) { - pvVar7 = *(void **)(GHIDRA_INT(tmpString[0]) + -4); - uVar4 = tmpStringCapacity + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(tmpString[0]) + (-4 - GHIDRA_INT(pvVar7))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar7,uVar4); - } - fVar10 = (player->_moveToTarget).y; - tmpStringSize = 0; - tmpStringCapacity = 0xf; - tmpString[0] = (void *)(GHIDRA_UINT(tmpString[0]) & 0xffffff00); - (catchUpPlayer->_moveToTarget).x = (player->_moveToTarget).x; - (catchUpPlayer->_moveToTarget).y = fVar10; -LAB_0092f901: - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) != 1) break; - } - playerIt = (g_game->_playerManager)._playerList._begin; - if (playerIt != (g_game->_playerManager)._playerList._end) { - piVar2 = (g_game->_playerManager)._playerList._end; - do { - iVar6 = *playerIt; - if ((iVar6 != 0) && (*GHIDRA_CAST((iVar6 + 0x2c)) == 0)) { - *GHIDRA_CAST((iVar6 + 0xdc)) = g_vectorZero.x; - *GHIDRA_CAST((iVar6 + 0xe0)) = g_vectorZero.y; - } - playerIt = playerIt + 1; - } while (playerIt != piVar2); - } - if ((0x14 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4))))) || - ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) == 1 && (5 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))))))) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))) = 0; - *GHIDRA_CAST(catchUpPlayer) = 2; - FUN_007ea5d0(); - SFXManager::StopLoopingSounds(&g_manager->_sfxManager); - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) == 4) && (iVar6 = get_stage_ending_id(0), iVar6 != 0)) { - if (iVar6 == 0xff) { - KAGE_LogMessage(1,GHIDRA_CAST("[warn] No ending for big chest!\n")); - Game::FinishChallenge(g_game); - *GHIDRA_CAST(catchUpPlayer) = 4; - } - else { - if (*GHIDRA_CAST(&g_game->_onlineStatsScreen) == '\0') { - Game::End(g_game,iVar6); - } - *GHIDRA_CAST(catchUpPlayer) = 4; - } - } - } - break; - case 2: - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))); - uVar5 = catchUpPlayer->_duration; - if (uVar4 < uVar5) { - if (uVar4 == uVar5 - 2) { - if (*GHIDRA_CAST((catchUpPlayer + 1)) == '\0') { - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))); - if (iVar6 == 2) { - Level::SetStage(GHIDRA_CAST(g_game),0xb,0); - } - else if (iVar6 == 3) { - Level::SetStage(GHIDRA_CAST(g_game),0xc,0); - } - else if (iVar6 == 6) { - Level::SetStage(GHIDRA_CAST(g_game),0xd,0); - } - else { - Level::SetNextStage(GHIDRA_CAST(g_game)); - } - } - else { - bVar3 = Game::IsInTimedSet(g_game,0x10); - if (bVar3 != 0) { - bVar3 = Game::IsGreedMode(game); - if (bVar3 == 0) { - iVar6 = (~g_game->_stageNameNumeral & 1U) + 1; - game = g_game; - } - else { - iVar6 = 1; - } - Level::SetStage(GHIDRA_CAST(game),iVar6,0); - Seeds::ForgetStageSeed(&g_game->_seedEffects,g_game->_stage); - } - } - if (g_manager->_netplayManager != *GHIDRA_CAST((g_manager + 1))) { - NetplayManager::process_pending_joins(GHIDRA_CAST(&g_manager->_netplayManager),0); - } - break; - } - if ((uVar4 != uVar5 - 1) || ((char)catchUpPlayer[1]._duration != '\0')) break; - bVar3 = Level::IsAscent(GHIDRA_CAST(g_game)); - bVar9 = bVar3 == 0; -LAB_0092fe68: - if (!bVar9) break; - } - else { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))) = 0; - *GHIDRA_CAST(catchUpPlayer) = 3; - if (uVar5 == 8) { - catchUpPlayer->_duration = 0xf; - } - game = g_game; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) == 1) { - playerSlot = (g_game->_playerManager)._playerList._begin; - if (playerSlot != (g_game->_playerManager)._playerList._end) { - do { - player = GHIDRA_CAST(*playerSlot); - if ((player != GHIDRA_CAST(0x0)) && (player->_variant == 0)) { - if (player == (game->_playerManager)._stageTransitionPlayer) { - Entity_Player::AnimateCollectible - (player,0x7f,GHIDRA_CAST("Pickup"),GHIDRA_CAST("PlayerPickupSparkle")); - } - else { - Entity_Player::PlayExtraAnimation(player,GHIDRA_CAST("Appear")); - } - game = g_game; - } - playerSlot = playerSlot + 1; - } while (playerSlot != (game->_playerManager)._playerList._end); - } - } - else if (((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) != 5) && - (bVar3 = Level::IsAscent(GHIDRA_CAST(g_game)), bVar3 == 0)) && - (playerSlot = (game->_playerManager)._playerList._begin, - playerSlot != (game->_playerManager)._playerList._end)) { - do { - player = GHIDRA_CAST(*playerSlot); - if ((player != GHIDRA_CAST(0x0)) && (player->_variant == 0)) { - Entity_Player::PlayExtraAnimation(player,GHIDRA_CAST("Appear")); - game = g_game; - } - playerSlot = playerSlot + 1; - } while (playerSlot != (game->_playerManager)._playerList._end); - } - EntityList::Update(GHIDRA_CAST((GHIDRA_INT(game->_room) + 0x1218)),1); - playerIt = (g_game->_playerManager)._playerList._begin; - game = g_game; - if (playerIt != (g_game->_playerManager)._playerList._end) { - do { - piVar2 = GHIDRA_CAST(*playerIt); - if ((piVar2 != GHIDRA_CAST(0x0)) && (piVar2[0xb] == 0)) { - (**(code **)(*piVar2 + 0xc))(); - game = g_game; - *GHIDRA_CAST((GHIDRA_CAST(piVar2) + 0x171)) = 1; - } - playerIt = playerIt + 1; - } while (playerIt != (game->_playerManager)._playerList._end); - } - if ((*GHIDRA_CAST((GHIDRA_CAST((game)) + 0x10))) == '\0') { - game->_stagesWithoutHeartsPicked = game->_stagesWithoutHeartsPicked + 1; - if (1 < game->_stagesWithoutHeartsPicked) { - PersistentGameData::TryUnlock(&g_manager->_persistentGameData,0x2a); - game = g_game; - } - } - else { - game->_stagesWithoutHeartsPicked = 0; - } - if ((game->_levelStateFlags & 0x20) == 0) { - game->_stagesWithoutDamage = game->_stagesWithoutDamage + 1; - if (1 < game->_stagesWithoutDamage) { - PersistentGameData::TryUnlock(&g_manager->_persistentGameData,0x43); - game = g_game; - } - } - else { - game->_stagesWithoutDamage = 0; - } - if ((((game->_difficulty != 2) && (game->_difficulty != 3)) && (game->_stage == 7)) && - ((game->_stageType == 4 || (game->_stageType == 5)))) { - PersistentGameData::TryUnlock(&g_manager->_persistentGameData,0x19b); - game = g_game; - } - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) == 5) { - savedFlags = game->_gameStateFlags; - flagsHigh = GHIDRA_CAST((GHIDRA_INT(&game->_gameStateFlags) + 4)); - *flagsHigh = *flagsHigh | 0x10000; - *GHIDRA_CAST(&game->_gameStateFlags) = GHIDRA_INT(savedFlags); - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(catchUpPlayer[1])) + 0x4)))) != 5) goto LAB_0092fbfd; -LAB_0092fc1b: - manager = g_manager; - local_38 = GHIDRA_CAST(0x267); - seed_fart_sound_override(GHIDRA_CAST(&local_38)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_38),1.0,2,0,1.0,0.0); - game = g_game; - } - else { -LAB_0092fbfd: - if (((0 < game->_stage) && (game->_stage < 7)) && - ((game->_gameStateFlags & 0x1000000000000) != 0)) goto LAB_0092fc1b; - } - Level::Init(GHIDRA_CAST(game),0); - Room::Update(g_game->_room); - Manager::save_game_state(); - PlayerManager::trigger_new_room_effects(&g_game->_playerManager); - game = g_game; - if ((g_game->_challenge == 0x1f) && (g_game->_stage != 0xb)) { - playerIt = (g_game->_playerManager)._playerList._begin; - if (playerIt != (g_game->_playerManager)._playerList._end) { - do { - iVar6 = *playerIt; - if ((iVar6 != 0) && (*GHIDRA_CAST((iVar6 + 0x2c)) == 0)) { - *GHIDRA_CAST((iVar6 + 0x1398)) = 0; - *GHIDRA_CAST((iVar6 + 0x139a)) = 0; - } - playerIt = playerIt + 1; - } while (playerIt != (game->_playerManager)._playerList._end); - } - RoomTransition::start - (&g_game->_roomTransition, - g_game->_roomList[g_game->_lastBossRoomListIdx].GridIndex,-1,0xf, - GHIDRA_CAST(0x0),-1); - RoomTransition::Update(&g_game->_roomTransition); - startingRoom = Level::GetRoomByIdx(GHIDRA_CAST(g_game),g_game->_startingRoomIdx,-1); - game = g_game; - startingRoom->Flags = startingRoom->Flags & 0xfffffffe; - Game::UpdateVisibility(game); - *GHIDRA_CAST(catchUpPlayer) = 0; - } - if ((char)catchUpPlayer[1]._duration == '\0') break; - if ((0 < g_game->_stage) && (g_game->_stage < 7)) { - bVar9 = (g_game->_gameStateFlags & 0x1000000000000) == 0; - goto LAB_0092fe68; - } - } - manager = g_manager; - uVar1 = *GHIDRA_CAST((catchUpPlayer + 1)); - g_manager->_isNightmarePending = 1; - (*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x4b2a5))) = uVar1; - break; - case 3: - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))); - if ((uVar4 == 2) && ((char)catchUpPlayer[1]._duration != '\0')) { - Room::PlayMusic(g_game->_room); - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))); - } - game = g_game; - if (GHIDRA_UINT(catchUpPlayer->_duration) <= uVar4) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))) = 0; - *GHIDRA_CAST(catchUpPlayer) = 4; - Level::ShowName(GHIDRA_CAST(game),0); - } - break; - case 4: - local_2e = '\x01'; - EntityList::Update(GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),1); - playerIt = (g_game->_playerManager)._playerList._begin; - game = g_game; - if (playerIt == (g_game->_playerManager)._playerList._end) { -LAB_0092ff4d: - *GHIDRA_CAST(catchUpPlayer) = 0; - } - else { - cVar8 = local_2e; - do { - piVar2 = GHIDRA_CAST(*playerIt); - if ((piVar2 != GHIDRA_CAST(0x0)) && (piVar2[0xb] == 0)) { - (**(code **)(*piVar2 + 0xc))(uVar4); - if (((char)piVar2[0x4e6] == '\0') && (*GHIDRA_CAST((GHIDRA_CAST(piVar2) + 0x139a)) == '\0')) { - *GHIDRA_CAST((piVar2 + 0x104)) = 1; - } - else { - cVar8 = '\0'; - } - game = g_game; - } - playerIt = playerIt + 1; - } while (playerIt != (game->_playerManager)._playerList._end); - catchUpPlayer = transition; - if (cVar8 != '\0') goto LAB_0092ff4d; - } - (GHIDRA_CAST((&game->_itemOverlay)))->ItemOverlay::Update(0); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((catchUpPlayer)) + 0x4)))) + 1; - game = g_game; - if ((*GHIDRA_CAST(catchUpPlayer) == 3) || (*GHIDRA_CAST(catchUpPlayer) == 2)) { - (g_game->_hud)._hudRefreshType = 2; - (game->_hud)._hudRefreshCountdown = 2; - } - ExceptionList = local_10; - return; -} - -// 0092ffc0 -void StageTransition::Render() -{ - int iVar1; - KColor fadeColor; - uint8_t local_78 [116]; - - iVar1 = *GHIDRA_CAST(this); - if (iVar1 == 3) { - fadeColor._alpha = - 1.0 - (float)((double)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) + - __uint_to_double_fixup[-(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) >> 0x1f)]) / - (float)((double)this->_duration + __uint_to_double_fixup[-(this->_duration >> 0x1f)]) - ; - } - else if (iVar1 == 2) { - fadeColor._alpha = - (float)((double)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) + - __uint_to_double_fixup[-(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) >> 0x1f)]) / - (float)((double)this->_duration + __uint_to_double_fixup[-(this->_duration >> 0x1f)]); - } - else { - fadeColor._alpha = (float)&DAT_bf800000; - } - fadeColor._unk = 0; - fadeColor._red = 0.0; - fadeColor._green = 0.0; - fadeColor._blue = 0.0; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) != 5) { - if ((((g_game->_stage < 1) || (6 < g_game->_stage)) || - ((g_game->_gameStateFlags & 0x1000000000000) == 0)) || (iVar1 == 2)) goto LAB_009300d4; - } - fadeColor._blue = 1.0; - fadeColor._green = 1.0; - fadeColor._red = 1.0; -LAB_009300d4: - g_graphicsManager_blendMode[1] = 1; - if (((uint8_t)g_graphicsManager_flags & 4) == 0) { - g_graphicsManager_blendMode[1] = 6; - } - g_graphicsManager_blendMode[0] = 0; - g_graphicsManager_blendMode[2] = 7; - g_graphicsManager_blendMode[3] = 1; - g_graphicsManager_blendMode[4] = 7; - render_quad_set_uniform_color(local_78,0.0,0.0,g_screenWidth,g_screenHeight,&fadeColor); - if ((*GHIDRA_CAST(this) == 2) || (*GHIDRA_CAST(this) == 3)) { - render_color_shader_pass(local_78); - } - return; -} - -// 00930160 -float StageTransition::get_fade_progress() -{ - float fVar1; - int transitionState; - - transitionState = *GHIDRA_CAST(this); - if ((transitionState != 3) && (transitionState != 2)) { - return -1.0; - } - fVar1 = (float)((double)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) + - __uint_to_double_fixup[-(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) >> 0x1f)]) / - (float)((double)this->_duration + __uint_to_double_fixup[-(this->_duration >> 0x1f)]); - if (transitionState == 3) { - return 1.0 - fVar1; - } - return fVar1; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index adc6b56..9a0c234 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8275,7 +8275,6 @@ void DailyChallenge::Init(uint32_t dailyDate) { generated_stub("DailyChallenge:: DamageInfo::DamageInfo() { generated_stub("DamageInfo::DamageInfo 006a8190"); } void DateTime::set_from_yyyymmdd(void *dateTime, int yyyymmdd) { generated_stub("DateTime::set_from_yyyymmdd 0085af30"); } void DateTime::constructor(uint8_t isNow) { generated_stub("DateTime::constructor 00a24270"); } -DeathmatchTypeBase::~DeathmatchTypeBase() { generated_stub("DeathmatchTypeBase::~DeathmatchTypeBase 0042a430"); } void DeathmatchTypeBase::vfunc_1() { generated_stub("DeathmatchTypeBase::vfunc_1 00af05d3"); } uint8_t DeathmatchTypeBase::Init() { generated_stub("DeathmatchTypeBase::Init 0042a4d0"); } void DeathmatchTypeBase::guard_check_icall() { generated_stub("DeathmatchTypeBase::guard_check_icall 0040c200"); } @@ -8329,7 +8328,6 @@ void DeathmatchTypeKnifeFight::FUN_0042c070(Entity_Player *param_1, uint64_t *pa void DeathmatchTypeKnockout::vfunc_1() { generated_stub("DeathmatchTypeKnockout::vfunc_1 0042cef0"); } long double DeathmatchTypeKnockout::FUN_0042bc10() { generated_stub("DeathmatchTypeKnockout::FUN_0042bc10 0042cf00"); } void DeathmatchTypeKnockout::FUN_0042c070(Entity_Player *param_1, uint64_t *param_2) { generated_stub("DeathmatchTypeKnockout::FUN_0042c070 0042cf10"); } -DeathmatchTypeLudovico::~DeathmatchTypeLudovico() { generated_stub("DeathmatchTypeLudovico::~DeathmatchTypeLudovico 0042d0f0"); } void DeathmatchTypeLudovico::vfunc_1() { generated_stub("DeathmatchTypeLudovico::vfunc_1 0042d1b0"); } void DeathmatchTypeLudovico::vfunc_20() { generated_stub("DeathmatchTypeLudovico::vfunc_20 0042cb80"); } void DeathmatchTypeLudovico::FUN_0042bc90() { generated_stub("DeathmatchTypeLudovico::FUN_0042bc90 0042d1c0"); } @@ -8337,7 +8335,6 @@ void DeathmatchTypeLudovico::FUN_0042c070(Entity_Player *param_1, uint64_t *para void DeathmatchTypeMachineGun::vfunc_1() { generated_stub("DeathmatchTypeMachineGun::vfunc_1 0042d660"); } long double DeathmatchTypeMachineGun::FUN_0042bc10() { generated_stub("DeathmatchTypeMachineGun::FUN_0042bc10 0042d670"); } void DeathmatchTypeMachineGun::FUN_0042c070(Entity_Player *param_1, uint64_t *param_2) { generated_stub("DeathmatchTypeMachineGun::FUN_0042c070 0042d680"); } -DeathmatchTypeNormal::~DeathmatchTypeNormal() { generated_stub("DeathmatchTypeNormal::~DeathmatchTypeNormal 0042d780"); } void DeathmatchTypeNormal::vfunc_1() { generated_stub("DeathmatchTypeNormal::vfunc_1 0042d7e0"); } uint8_t DeathmatchTypeNormal::Init() { generated_stub("DeathmatchTypeNormal::Init 0042d7f0"); } void DeathmatchTypeNormal::Update() { generated_stub("DeathmatchTypeNormal::Update 0042d850"); } @@ -9153,7 +9150,6 @@ void KAGE::Thread::vfunc_1() { generated_stub("KAGE::Thread::vfunc_1 00a5a570"); void KAGE::Thread::FUN_00a62830(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4) { generated_stub("KAGE::Thread::FUN_00a62830 00a5a530"); } void KAGE::Thread::vfunc_3() { generated_stub("KAGE::Thread::vfunc_3 00a5a700"); } uint32_t KAGE::Util::String::CharacterIteratorUTF8::FUN_00a55aa0() { generated_stub("KAGE::Util::String::CharacterIteratorUTF8::FUN_00a55aa0 00a55aa0"); } -bool KAGE_Filesys_FileManager::OpenRead(int param_2, int param_3) { generated_stub("KAGE_Filesys_FileManager::OpenRead 005ca5a0"); } uint32_t KAGE_Filesys_FileManager::GetPrimaryFilePathHash(uint8_t *filePath) { generated_stub("KAGE_Filesys_FileManager::GetPrimaryFilePathHash 00a159d0"); } uint32_t KAGE_Filesys_FileManager::GetSecondaryFilePathHash() { generated_stub("KAGE_Filesys_FileManager::GetSecondaryFilePathHash 00a15ab0"); } void KAGE_Filesys_FileManager::LoadArchiveFile(uint8_t *param_1, uint32_t *param_2, uint16_t param_3) { generated_stub("KAGE_Filesys_FileManager::LoadArchiveFile 00a179c0"); } @@ -9435,9 +9431,6 @@ void Sprite::set_offset(Vector *offset) { generated_stub("Sprite::set_offset 004 long double Sprite::PlaybackSpeed() { generated_stub("Sprite::PlaybackSpeed 00456360"); } Vector * Sprite::Offset() { generated_stub("Sprite::Offset 0049cb40"); } SpriteTrailData::~SpriteTrailData() { generated_stub("SpriteTrailData::~SpriteTrailData 005d2370"); } -void StageTransition::Update() { generated_stub("StageTransition::Update 0092f1c0"); } -void StageTransition::Render() { generated_stub("StageTransition::Render 0092ffc0"); } -float StageTransition::get_fade_progress() { generated_stub("StageTransition::get_fade_progress 00930160"); } void StatsPanel::add_stat_line() { generated_stub("StatsPanel::add_stat_line 0084dc00"); } void StatsPanel::set(Entity_Player *player, uint8_t isGoldenTrinket) { generated_stub("StatsPanel::set 0084dea0"); } void StatsPanel::snapshot_stats(uint32_t param_1) { generated_stub("StatsPanel::snapshot_stats 0084e9d0"); } @@ -10042,7 +10035,6 @@ void FUN_0042a040(int *param_1, int *param_2) { generated_stub("FUN_0042a040 004 void FUN_0042a210() { generated_stub("FUN_0042a210 0042a210"); } void FUN_0042a230() { generated_stub("FUN_0042a230 0042a230"); } void FUN_0042a350() { generated_stub("FUN_0042a350 0042a350"); } -void FUN_0042a430(uint8_t param_1) { generated_stub("FUN_0042a430 0042a430"); } void FUN_0042a490() { generated_stub("FUN_0042a490 0042a490"); } void FUN_0042aca0() { generated_stub("FUN_0042aca0 0042aca0"); } bool FUN_0042ae90() { generated_stub("FUN_0042ae90 0042ae90"); } @@ -10097,13 +10089,11 @@ long double FUN_0042cf00() { generated_stub("FUN_0042cf00 0042cf00"); } void FUN_0042cf10(Entity_Player *param_1, uint32_t param_2) { generated_stub("FUN_0042cf10 0042cf10"); } int FUN_0042d040() { generated_stub("FUN_0042d040 0042d040"); } void get_netplay_player_color(void *self, ColorMod *outColor, Entity_Player *player) { generated_stub("get_netplay_player_color 0042d060"); } -void FUN_0042d0f0(uint8_t param_1) { generated_stub("FUN_0042d0f0 0042d0f0"); } uint32_t FUN_0042d1b0() { generated_stub("FUN_0042d1b0 0042d1b0"); } void FUN_0042d5f0(Entity_Player *param_1, uint32_t param_2) { generated_stub("FUN_0042d5f0 0042d5f0"); } uint32_t FUN_0042d660() { generated_stub("FUN_0042d660 0042d660"); } long double FUN_0042d670() { generated_stub("FUN_0042d670 0042d670"); } void FUN_0042d680(Entity_Player *param_1, uint32_t param_2) { generated_stub("FUN_0042d680 0042d680"); } -void FUN_0042d780(uint8_t param_1) { generated_stub("FUN_0042d780 0042d780"); } uint32_t FUN_0042d7e0() { generated_stub("FUN_0042d7e0 0042d7e0"); } uint8_t FUN_0042d7f0() { generated_stub("FUN_0042d7f0 0042d7f0"); } void FUN_0042d850() { generated_stub("FUN_0042d850 0042d850"); } @@ -10259,8 +10249,6 @@ void NpcAI::ENTITY_LARRYJR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LARR void NpcAI::ENTITY_MONSTRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MONSTRO 0046c0a0"); } void NpcAI::ENTITY_DUKE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DUKE 0046e290"); } void NpcAI::ENTITY_WIDOW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WIDOW 0046fbe0"); } -void NpcAI::ENTITY_GEMINI(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GEMINI 00471050"); } -void NpcAI::ENTITY_GEMINI_baby(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GEMINI_baby 00471cc0"); } void NpcAI::ENTITY_BLASTOCYST_BIG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLASTOCYST_BIG 00472c40"); } void NpcAI::ENTITY_SLOTH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SLOTH 004741f0"); } void NpcAI::ENTITY_LUST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LUST 00474e00"); } @@ -10462,10 +10450,7 @@ void NpcAI::ENTITY_STONE_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ST void NpcAI::ENTITY_CONSTANT_STONE_SHOOTER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CONSTANT_STONE_SHOOTER 00506320"); } void NpcAI::ENTITY_EMBRYO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EMBRYO 0050a6b0"); } void NpcAI::ENTITY_ETERNALFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ETERNALFLY 0050a8a0"); } -void NpcAI::ENTITY_GUSHER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUSHER 0050af90"); } -void NpcAI::ENTITY_MULLIGAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MULLIGAN 0050bbe0"); } void NpcAI::ENTITY_HIVE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HIVE 0050c370"); } -void NpcAI::ENTITY_CLOTTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLOTTY 0050d370"); } void NpcAI::ENTITY_GLOBIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GLOBIN 0050e4d0"); } uint32_t NpcAI::ENTITY_BOOMFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOOMFLY 0050f280"); } void NpcAI::ENTITY_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAW 00510ae0"); } @@ -10785,7 +10770,6 @@ void FUN_005d2270() { generated_stub("FUN_005d2270 005d2270"); } void FUN_005d2300() { generated_stub("FUN_005d2300 005d2300"); } void FUN_005d2370(uint8_t param_1) { generated_stub("FUN_005d2370 005d2370"); } void FUN_005d23a0(uint8_t param_1) { generated_stub("FUN_005d23a0 005d23a0"); } -void FUN_005d29b0() { generated_stub("FUN_005d29b0 005d29b0"); } void FUN_005d4210() { generated_stub("FUN_005d4210 005d4210"); } void FUN_00607540() { generated_stub("FUN_00607540 00607540"); } void room_perimeter_to_position(float *param_1, float *param_2) { generated_stub("room_perimeter_to_position 0060ac70"); } @@ -10989,7 +10973,6 @@ float normalize_angle_degrees(float angle) { generated_stub("normalize_angle_deg float angle_difference(float from, float to) { generated_stub("angle_difference 006827a0"); } void FUN_00682a20() { generated_stub("FUN_00682a20 00682a20"); } float approach_angle(float current, float target, float maxStep) { generated_stub("approach_angle 00682a50"); } -void FUN_00683010(int param_1, int param_2, int param_3) { generated_stub("FUN_00683010 00683010"); } uint32_t checksum_stream(void *stream, int offset, int trailingSize) { generated_stub("checksum_stream 00683580"); } void FUN_00683680() { generated_stub("FUN_00683680 00683680"); } void pop_render_target() { generated_stub("pop_render_target 006836c0"); } @@ -11127,12 +11110,10 @@ uint32_t * FUN_006a13b0(uint32_t *param_1) { generated_stub("FUN_006a13b0 006a13 uint32_t * FUN_006a1420(uint32_t *param_1) { generated_stub("FUN_006a1420 006a1420"); } void FUN_006a14f0(uint32_t param_1, uint32_t *param_2) { generated_stub("FUN_006a14f0 006a14f0"); } void FUN_006a1e00(uint32_t *param_1) { generated_stub("FUN_006a1e00 006a1e00"); } -void FUN_006a1e80() { generated_stub("FUN_006a1e80 006a1e80"); } void FUN_006a1fc0() { generated_stub("FUN_006a1fc0 006a1fc0"); } void FUN_006a6910(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4) { generated_stub("FUN_006a6910 006a6910"); } void FUN_006a6930() { generated_stub("FUN_006a6930 006a6930"); } void FUN_006a6940() { generated_stub("FUN_006a6940 006a6940"); } -std_string * resolve_resource_path(std_string *outPath, std_string *path, void *suffixes) { generated_stub("resolve_resource_path 006a69e0"); } void FUN_006a7ec0() { generated_stub("FUN_006a7ec0 006a7ec0"); } void FUN_006a80d0() { generated_stub("FUN_006a80d0 006a80d0"); } void FUN_006a8180(uint32_t param_1) { generated_stub("FUN_006a8180 006a8180"); } @@ -11260,16 +11241,13 @@ Entity_Player * FUN_007103c0(uint32_t *param_1) { generated_stub("FUN_007103c0 0 uint32_t FUN_00710f70(int param_1) { generated_stub("FUN_00710f70 00710f70"); } void FUN_00711530(int param_1) { generated_stub("FUN_00711530 00711530"); } uint32_t FUN_00711740() { generated_stub("FUN_00711740 00711740"); } -uint32_t FUN_00711fd0() { generated_stub("FUN_00711fd0 00711fd0"); } void FUN_007135d0(uint32_t param_1, uint8_t param_2, int *param_3) { generated_stub("FUN_007135d0 007135d0"); } void spawn_poop_rewards(uint32_t param_1, int param_2, int param_3, char param_4, uint32_t param_5, int param_6) { generated_stub("spawn_poop_rewards 00716db0"); } void FUN_00718d20(float *param_1) { generated_stub("FUN_00718d20 00718d20"); } void FUN_00718ed0(uint32_t param_1) { generated_stub("FUN_00718ed0 00718ed0"); } uint32_t FUN_00718ee0() { generated_stub("FUN_00718ee0 00718ee0"); } -void grid_mark_neighbors_dirty(int gridIndex) { generated_stub("grid_mark_neighbors_dirty 0071dee0"); } void FUN_0071df70(uint8_t param_1) { generated_stub("FUN_0071df70 0071df70"); } int FUN_0071df80() { generated_stub("FUN_0071df80 0071df80"); } -void FUN_0071f4b0(uint32_t param_1) { generated_stub("FUN_0071f4b0 0071f4b0"); } uint32_t FUN_00721b70(int param_1) { generated_stub("FUN_00721b70 00721b70"); } void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6) { generated_stub("FUN_00721e60 00721e60"); } void FUN_00721eb0() { generated_stub("FUN_00721eb0 00721eb0"); } @@ -11368,7 +11346,6 @@ void FUN_007530c0() { generated_stub("FUN_007530c0 007530c0"); } void std_deque_growmap(void *self, uint32_t count) { generated_stub("std_deque_growmap 007530f0"); } void FUN_00753230(uint32_t param_1) { generated_stub("FUN_00753230 00753230"); } void FUN_00753550() { generated_stub("FUN_00753550 00753550"); } -uint8_t FUN_00753560() { generated_stub("FUN_00753560 00753560"); } void FUN_00753620() { generated_stub("FUN_00753620 00753620"); } bool FUN_00753630() { generated_stub("FUN_00753630 00753630"); } bool FUN_00753640() { generated_stub("FUN_00753640 00753640"); } @@ -11423,7 +11400,6 @@ Entity_Player * FUN_007a1020() { generated_stub("FUN_007a1020 007a1020"); } uint32_t FUN_007ab0e0() { generated_stub("FUN_007ab0e0 007ab0e0"); } void FUN_007ad610() { generated_stub("FUN_007ad610 007ad610"); } uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_007ad720 007ad720"); } -void FUN_007ae430(short *param_1) { generated_stub("FUN_007ae430 007ae430"); } void FUN_007b8c00(int param_1) { generated_stub("FUN_007b8c00 007b8c00"); } void FUN_007b9a60() { generated_stub("FUN_007b9a60 007b9a60"); } void FUN_007b9aa0() { generated_stub("FUN_007b9aa0 007b9aa0"); } @@ -11551,22 +11527,15 @@ void FUN_007e9170(char param_1) { generated_stub("FUN_007e9170 007e9170"); } void FUN_007e92e0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_007e92e0 007e92e0"); } void FUN_007e93d0(int param_1) { generated_stub("FUN_007e93d0 007e93d0"); } void FUN_007ea0c0() { generated_stub("FUN_007ea0c0 007ea0c0"); } -void FUN_007ea5d0() { generated_stub("FUN_007ea5d0 007ea5d0"); } void FUN_007ebc40() { generated_stub("FUN_007ebc40 007ebc40"); } -uint32_t FUN_007ed240() { generated_stub("FUN_007ed240 007ed240"); } float get_angel_room_chance() { generated_stub("get_angel_room_chance 007f96f0"); } -void FUN_007fa2a0(float *param_1) { generated_stub("FUN_007fa2a0 007fa2a0"); } -void FUN_007fa7d0() { generated_stub("FUN_007fa7d0 007fa7d0"); } -int RoomClear_PickVariant(RNG *rng, uint8_t isForcePickup) { generated_stub("RoomClear_PickVariant 007fa920"); } void FUN_00812ea0(float *param_1, int *param_2, int *param_3) { generated_stub("FUN_00812ea0 00812ea0"); } uint32_t FUN_00813420(int param_1, int param_2) { generated_stub("FUN_00813420 00813420"); } void pickup_roll_random_variant(void *papersOwner, int shopItemId, int *variant, uint32_t *subType, uint32_t seed) { generated_stub("pickup_roll_random_variant 00814a50"); } int _Room::ResolveHeartSubType(uint32_t param_1, int param_2, Entity_Player *param_3) { generated_stub("_Room::ResolveHeartSubType 00816250"); } uint32_t FUN_0081e220() { generated_stub("FUN_0081e220 0081e220"); } void FUN_0081fae0(uint32_t *param_1) { generated_stub("FUN_0081fae0 0081fae0"); } -uint32_t FUN_008207a0() { generated_stub("FUN_008207a0 008207a0"); } void FUN_00821940() { generated_stub("FUN_00821940 00821940"); } -int FUN_00823ec0() { generated_stub("FUN_00823ec0 00823ec0"); } uint32_t FUN_00827180(float *param_1) { generated_stub("FUN_00827180 00827180"); } void FUN_00827f30() { generated_stub("FUN_00827f30 00827f30"); } void FUN_00828010(uint32_t *param_1) { generated_stub("FUN_00828010 00828010"); } @@ -11592,7 +11561,6 @@ void FUN_0082e290(int param_1, int param_2, int param_3) { generated_stub("FUN_0 void Catch_All_0082e7ec() { generated_stub("Catch_All_0082e7ec 0082e7ec"); } void FUN_0082ea50(uint32_t param_1, uint32_t *param_2, code *param_3) { generated_stub("FUN_0082ea50 0082ea50"); } void FUN_0082eb20(uint32_t *param_1, code *param_2) { generated_stub("FUN_0082eb20 0082eb20"); } -void FUN_00831780(int *param_1, uint8_t *param_2, uint8_t *param_3, uint8_t *param_4) { generated_stub("FUN_00831780 00831780"); } void FUN_008332a0(char param_1) { generated_stub("FUN_008332a0 008332a0"); } uint64_t * FUN_00834c60(uint64_t *param_1, uint64_t *param_2) { generated_stub("FUN_00834c60 00834c60"); } void Catch_All_00834f6f() { generated_stub("Catch_All_00834f6f 00834f6f"); } @@ -13972,7 +13940,6 @@ void FUN_00950eb0() { generated_stub("FUN_00950eb0 00950eb0"); } void FUN_00951090() { generated_stub("FUN_00951090 00951090"); } void FUN_009510f0() { generated_stub("FUN_009510f0 009510f0"); } void FUN_00951130() { generated_stub("FUN_00951130 00951130"); } -uint8_t input_is_action_pressed(int action, int controllerIndex, Entity *entity, int unused) { generated_stub("input_is_action_pressed 00956110"); } uint8_t is_any_player_restart_held() { generated_stub("is_any_player_restart_held 009563b0"); } uint32_t FUN_00956750() { generated_stub("FUN_00956750 00956750"); } uint8_t * FUN_009587e0(StringTable *param_1, uint8_t *param_2, uint8_t *param_3) { generated_stub("FUN_009587e0 009587e0"); } diff --git a/src/active_items.h b/src/active_items.h new file mode 100644 index 0000000..9c1ef1b --- /dev/null +++ b/src/active_items.h @@ -0,0 +1,55 @@ +#pragma once + +#include "classes.h" +#include + +enum ButtonAction : int; +enum ChargeType : int; + +// The active item slots (Lua's ActiveSlot), or none for a use that comes from no slot. +enum ActiveSlot : int +{ + ACTIVE_SLOT_NONE = -1, + ACTIVE_SLOT_PRIMARY, + ACTIVE_SLOT_SECONDARY, + ACTIVE_SLOT_POCKET, + ACTIVE_SLOT_POCKET2 +}; + +// How an active item's effect was triggered (Lua's UseFlag). +enum UseFlag : uint32_t +{ + USE_NOANIM = 1 << 0, + USE_NOCOSTUME = 1 << 1, + USE_OWNED = 1 << 2, + USE_ALLOWNONMAIN = 1 << 3, + USE_REMOVEACTIVE = 1 << 4, + USE_CARBATTERY = 1 << 5, + USE_VOID = 1 << 6, + USE_MIMIC = 1 << 7, + USE_NOANNOUNCER = 1 << 8, + USE_ALLOWWISPSPAWN = 1 << 9, + USE_CUSTOMVARDATA = 1 << 10, + USE_NOHUD = 1 << 11 +}; + +// One use of an active item: the item, how it was triggered, the slot it came from and the data its slot keeps. +struct ActiveUse +{ + int item = 0; + uint32_t flags = 0; + int slot = ACTIVE_SLOT_NONE; + int varData = 0; +}; + +// What a use asks of its slot afterwards: whether its charge is spent and whether the item goes. +struct UseResult +{ + bool isDischarge = true; + bool isRemove = false; +}; + +bool input_is_action_pressed(ButtonAction action, int controllerIndex, Entity* entity); +bool input_is_action_triggered(ButtonAction action, int controllerIndex, Entity* entity); +bool is_active_usable(Entity_Player& player, int item, int slot); +ChargeType active_charge_type(Entity_Player& player, int slot); diff --git a/src/anm2.cpp b/src/anm2.cpp index 94218af..c1728fa 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -121,7 +121,7 @@ ColorMod color_lerp(const ColorMod& from, const ColorMod& to, float t) } // Tints a colour by another, as Color's *= does: tints multiply, offsets add and colorizes average. -static void color_multiply(ColorMod& color, const ColorMod& other) +void color_multiply(ColorMod& color, const ColorMod& other) { for (int i = 0; i < 4; i++) color._tint[i] = other._tint[i] * color._tint[i]; diff --git a/src/anm2.h b/src/anm2.h index 67ad657..e722a51 100644 --- a/src/anm2.h +++ b/src/anm2.h @@ -370,3 +370,4 @@ struct AnmCache float angle_lerp(float from, float to, float t); ColorMod color_lerp(const ColorMod& from, const ColorMod& to, float t); +void color_multiply(ColorMod& color, const ColorMod& other); diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp new file mode 100644 index 0000000..f3623f3 --- /dev/null +++ b/src/bomb_explosion.cpp @@ -0,0 +1,358 @@ +#include "entity_bomb.h" +#include "boss_ai.h" +#include "entity_combat.h" +#include "entity_player.h" +#include "entity_save_state.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include "npc_ai.h" +#include "room.h" +#include "room_descriptor.h" +#include "room_grid.h" +#include +#include +#include +#include +#include + +// An explosion's reach by its damage, a giga bomb's, and the crater's size at the smallest reach. +constexpr float RADIUS_SMALL = 75; +constexpr float RADIUS_MEDIUM = 90; +constexpr float RADIUS_LARGE = 105; +constexpr float DAMAGE_MEDIUM = 140; +constexpr float DAMAGE_LARGE = 175; + +// Safety Scissors shrink the explosions no player set off: by a quarter for two, by half for more. +constexpr int TRINKET_SAFETY_SCISSORS = 63; +constexpr float SCISSORS_DOUBLE_SCALE = 0.75f; +constexpr float SCISSORS_MORE_SCALE = 0.5f; + +// The shake of a strong explosion, the push it gives (less for heavy entities, a player's capped), and the damage a +// player or familiar takes: half a heart, a whole one from a strong explosion, a fifth of it in a versus match. +constexpr float SHAKE_DAMAGE = 166; +constexpr float SHAKE_DAMAGE_CROSS = 125; +constexpr int SHAKE_BASE = 7; +constexpr int SHAKE_EXTRA = 7; +constexpr float PUSH_MAX = 15; +constexpr float PUSH_HEAVY_MASS = 20; +constexpr float PUSH_HEAVY_SCALE = 0.5f; +constexpr float PUSH_VELOCITY_KEPT = 0.5f; +constexpr float PUSH_PLAYER_MAX = 10; +constexpr float PLAYER_DAMAGE_STRONG = 85; +constexpr float DEATHMATCH_DAMAGE_SCALE = 0.2f; +constexpr float IMMOVABLE_MASS = 1000; +constexpr int HIT_COUNTDOWN = 30; +constexpr float TEAR_EFFECT_DAMAGE = 3.5f; +constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; + +// The grid an explosion breaks: rays cast every so far around its reach, stepping so far, and a line walked in steps. +constexpr float RAY_DENSITY = 8; +constexpr float RAY_STEP = 20; +constexpr float LINE_STEP = 10; + +// The entities and effects an explosion treats apart. +constexpr int ENTITY_MEGA_SATAN = 274; +constexpr int CHALLENGE_BLUE_BOMBER = 23; +constexpr int EFFECT_ISAACS_CARPET = 74; +constexpr int CARPET_BLOWN = 1000; +constexpr std::array EFFECTS_BLOWN_AWAY = {21, 33, 63, 64, 158, 159}; +constexpr int BOMB_EXPLOSION_EFFECT = 1; +constexpr int BOMB_CRATER_EFFECT = 18; +constexpr int FIREWORKS_EFFECT = 104; +constexpr int SPECIAL_DAILY_FIREWORKS = 12; +constexpr int TRINKET_BROKEN_PADLOCK = 136; +constexpr size_t SAVED_EFFECTS_MAX = 128; + +// The colors poison, butt and brimstone bombs tint the explosion with. +constexpr ColorMod POISON_COLOR = {{0.4f, 0.97f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod BUTT_COLOR = {{0.4431373f, 0.2901961f, 0.06666667f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod BRIMSTONE_COLOR = {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The Mom's Shovel quest: a bomb in the first floor's start room while the quest is on digs the shovel up. +constexpr uint32_t LEVEL_STATE_SHOVEL_QUEST = 1u << 16; +constexpr int COLLECTIBLE_BROKEN_SHOVEL = 550; + +// Whether Safety Scissors shrink an explosion: one no player or player's entity set off. +static bool is_scissored(Entity* source) +{ + return !source || (source->type != ENTITY_PLAYER && !source->GetPlayerAncestor()); +} + +// Room::CheckLine's explosion mode (2): the line walked in steps, cell by cell. A metal block stops it, and so does a +// wall, unless it is a door, a wall the check ignores, or a lock Broken Padlock lets the blast through. +static bool explosion_line_clear(const Vector& start, const Vector& end, bool isIgnoreWalls) +{ + Room& room = *g_game->room; + Vector step = vector_sub(start, end); + float length = vector_length(step); + if (length <= 0) return true; + + step = vector_scale(step, LINE_STEP / length); + Vector at = start; + for (float walked = 0; walked < length; walked += LINE_STEP) + { + at = vector_sub(at, step); + int gridIndex = room.GetGridIndex(at); + uint32_t collision = room.GetGridCollision(gridIndex); + GridEntity* grid = gridIndex >= 0 ? room.GetGridEntity((uint32_t)gridIndex) : nullptr; + if (grid && collision != COLLISION_NONE && grid->type == GRID_ROCKB) return false; + if (collision != COLLISION_WALL) continue; + + bool isPadlock = grid && grid->type == GRID_LOCK && g_game->playerManager.AnyoneHasTrinket(TRINKET_BROKEN_PADLOCK); + bool isOpening = grid && (grid->type == GRID_DOOR || (grid->type == GRID_WALL && isIgnoreWalls)); + if (!isPadlock && !isOpening) return false; + } + return true; +} + +// Pushes an entity away from an explosion, harder the deeper inside it is, a heavy one half as far and with Knockback +// twice as far. A player keeps its push and half its speed, at most so fast. +// Past a mass of 20 the original's further tiers (30, 50, 150) are never reached. They are left out. +static void explosion_push(const Explosion& explosion, Entity& entity, const TearFlags& flags, Vector away, float distance) +{ + float force = std::min(explosion.radius + entity.size - distance, PUSH_MAX); + if (entity.mass > PUSH_HEAVY_MASS) force *= PUSH_HEAVY_SCALE; + bool isPlayer = entity.type == ENTITY_PLAYER; + if (flags[TEAR_KNOCKBACK] && !isPlayer) force += force; + + Vector pushed = vector_add(vector_scale(away, force / distance), vector_scale(entity.velocity, PUSH_VELOCITY_KEPT)); + if (isPlayer) pushed = vector_resized(pushed, std::min(vector_length(pushed), PUSH_PLAYER_MAX)); + entity.velocity = pushed; +} + +// Hurts a player or familiar caught in an explosion: half a heart, a whole one for a strong explosion. +static void explosion_player_hurt(const Explosion& explosion, Entity& entity, bool isPlayerSource) +{ + if (explosion.damage <= 0) return; + + EntityRef source(explosion.source); + if (isPlayerSource) source.flags |= ENTITY_REF_FRIENDLY; + float damage = explosion.damage < PLAYER_DAMAGE_STRONG ? 1.0f : 2.0f; + if (explosion.damageFlags & DAMAGE_NO_PENALTIES) damage = 1; + if (g_game->deathmatchManager.is_active()) damage = explosion.damage * DEATHMATCH_DAMAGE_SCALE; + if (entity.type == ENTITY_PLAYER && entity.ToPlayer()->is_evil_charm_immune(source)) return; + entity.TakeDamage(damage, explosion.damageFlags, source, HIT_COUNTDOWN); +} + +// Hurts an entity caught in an explosion (not a player or familiar): its damage, the blue flies and other flags the +// source's tear effects add, then those effects on a vulnerable enemy. Ambient effects are blown away. +static void explosion_entity_hurt(Explosion& explosion, Entity& entity, const TearFlags& flags) +{ + if (entity.type == ENTITY_EFFECT) + { + if (std::ranges::count(EFFECTS_BLOWN_AWAY, entity.variant)) + { + entity.isDead = true; + return; + } + if (entity.variant == EFFECT_ISAACS_CARPET) + { + if (entity.subtype != 0) return; + reconstruction_missing("Game::BombDamage 006ff2a0: the hole under Isaac's carpet (stairs or a trapdoor)"); + entity.subtype = CARPET_BLOWN; + return; + } + } + if (flags[TEAR_CROSS_BOMB]) reconstruction_missing("Game::BombDamage 006ff2a0: Bomber Boy's shared damage"); + + TearFlags effects = flags; + effects.reset(TEAR_EXPLOSIVE); + explosion.damageFlags |= tear_damage_flags_get(effects, explosion.source); + entity.TakeDamage(explosion.damage, explosion.damageFlags, EntityRef(explosion.source), HIT_COUNTDOWN); + + Entity* source = explosion.source; + bool isTearEffecting = flags.any() && source && !Entity::is_enemy_type(source->spawnerType); + if (isTearEffecting && entity.IsVulnerableEnemy(nullptr)) + Entity_Tear::ApplyTearFlagEffects(&entity, explosion.position, effects, source, TEAR_EFFECT_DAMAGE); +} + +// 00711fd0 Blows a lock block open: Broken Padlock opens a closed one, otherwise it is hurt as by any explosion. +static bool lock_blast(GridEntity& lock) +{ + if (lock.state == 0 && g_game->playerManager.AnyoneHasTrinket(TRINKET_BROKEN_PADLOCK)) + reconstruction_missing("GridEntity_Lock::break_open 00711bb0: a lock Broken Padlock opens for no player"); + return lock.Hurt(4, EntityRef()); +} + +// The cells an explosion reaches: its own, and every grid entity along rays cast around it, stopping at metal blocks. +static std::set explosion_cells_get(const Explosion& explosion) +{ + Room& room = *g_game->room; + std::set cells; + int rays = (int)std::ceil(explosion.radius * RAY_DENSITY / GRID_CELL_SIZE); + float rayAngle = 2 * PI_F / (float)rays; + int center = room.GetGridIndex(explosion.position); + if (center >= 0) cells.insert(center); + + float angle = 0; + for (int ray = 0; ray < rays; ray++, angle += rayAngle) + { + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + for (float walked = 0; walked < explosion.radius;) + { + walked = std::min(walked + RAY_STEP, explosion.radius); + GridEntity* grid = room_grid_entity_at(vector_add(explosion.position, vector_scale(direction, walked))); + if (!grid) continue; + + cells.insert(grid->gridIndex); + if (grid->type == GRID_ROCKB) break; + } + } + return cells; +} + +// Breaks the grid entities an explosion reaches in a clear line. A solid one that breaks fills the pit behind it. +static void explosion_grid_break(const Explosion& explosion) +{ + Room& room = *g_game->room; + for (int gridIndex : explosion_cells_get(explosion)) + { + Vector cell = room.GetGridPosition(gridIndex); + if (!explosion_line_clear(explosion.position, cell, false)) continue; + + uint32_t collision = room.GetGridCollision(gridIndex); + GridEntity* grid = room.GetGridEntity((uint32_t)gridIndex); + bool isBroken = grid && grid->type == GRID_LOCK && lock_blast(*grid); + if (!isBroken) isBroken = room_grid_destroy({.source = EntityRef(explosion.source), .gridIndex = gridIndex}); + if (!isBroken || collision != COLLISION_SOLID) continue; + + Vector beyond = vector_add(cell, vector_scale(vector_cardinal(vector_sub(cell, explosion.position)), GRID_CELL_SIZE)); + int beyondIndex = room.GetGridIndex(beyond); + if (beyondIndex >= 0) room_bridge_make(room.GetGridEntity((uint32_t)beyondIndex), grid); + } +} + +// 006ff2a0 An explosion's damage: a strong one shakes the screen, everything in its reach and in a clear line is +// pushed away and hurt (players and familiars as by any explosion), and the grid it reaches breaks. Safety Scissors +// shrink one no player set off. +void explosion_damage(Explosion explosion) +{ + if (is_scissored(explosion.source)) + { + int scissors = g_game->playerManager.GetTrinketMultiplier(TRINKET_SAFETY_SCISSORS); + if (scissors == 2) explosion.radius *= SCISSORS_DOUBLE_SCALE; + else if (scissors > 2) explosion.radius *= SCISSORS_MORE_SCALE; + } + bool isCross = explosion.tearFlags[TEAR_CROSS_BOMB]; + if (explosion.damage >= SHAKE_DAMAGE || (isCross && explosion.damage >= SHAKE_DAMAGE_CROSS)) + game_shake_screen((int)(Random() % SHAKE_EXTRA) + SHAKE_BASE); + + Entity* source = explosion.source; + bool isPlayerSource = source && source->type == ENTITY_PLAYER && !explosion.isDamageSource; + TearFlags flags = explosion.tearFlags; + for (Entity* entity : entity_query_radius(explosion.position, explosion.radius, QUERY_ALL)) + { + int type = entity->type; + bool isSkipped = (entity == source && !explosion.isDamageSource) || entity->isDead || + entity->entityCollisionClass == ENTCOLL_NONE || entity->entityGridCollisionClass == GRIDCOLL_BULLET || + entity->mass == 0 || type == ENTITY_TEAR || type == ENTITY_PROJECTILE; + bool isMegaSatanSpared = source && type == ENTITY_MEGA_SATAN && source->type == ENTITY_MEGA_SATAN && + g_game->challenge != CHALLENGE_BLUE_BOMBER; + if (isSkipped || isMegaSatanSpared) continue; + + Vector away = vector_sub(entity->pos, explosion.position); + float distance = vector_length(away); + if (explosion.isLineCheck && !explosion_line_clear(explosion.position, entity->pos, true)) continue; + if (source && source->type == ENTITY_BOMB) flags |= static_cast(source)->tearFlags; + + bool isPlayerSpared = type == ENTITY_PLAYER && (entity->mass == IMMOVABLE_MASS || (source && source->IsFriendly()) || + isPlayerSource); + if (distance > 0 && type != ENTITY_EFFECT && !entity->HasEntityFlags(FLAG_NO_KNOCKBACK) && !isPlayerSpared) + explosion_push(explosion, *entity, flags, away, distance); + + if (type == ENTITY_PLAYER || type == ENTITY_FAMILIAR) explosion_player_hurt(explosion, *entity, isPlayerSource); + else explosion_entity_hurt(explosion, *entity, flags); + } + explosion_grid_break(explosion); +} + +// 007009a0 The tear effects an explosion spreads (Butt, Sad, Hot, Glitter, Sticky Bombs' eggs, Bob's Curse, Blood, +// Brimstone and Giga Bombs, the Mysterious Liquid). A plain explosion has none. +void explosion_tear_flag_effects(const Explosion& explosion) +{ + constexpr std::array SPREAD_FLAGS = {TEAR_BUTT_BOMB, TEAR_SAD_BOMB, TEAR_MYSTERIOUS_LIQUID_CREEP, TEAR_BURN, + TEAR_GLITTER_BOMB, TEAR_EGG_FLAG, TEAR_POISON, TEAR_BLOOD_BOMB, + TEAR_BRIMSTONE_BOMB, TEAR_GIGA_BOMB}; + Entity* source = explosion.source; + bool isBrimstoneBomb = source && source->type == ENTITY_BOMB && source->variant == BOMB_BRIMSTONE; + bool isSpread = std::ranges::any_of(SPREAD_FLAGS, [&](int bit) { return explosion.tearFlags[bit]; }); + if (isSpread || isBrimstoneBomb) reconstruction_missing("Game::BombTearflagEffects 007009a0: the bombs' tear effects"); +} + +// 008207a0 Digs Mom's Shovel up when a bomb goes off in the first floor's start room while its quest is on. +static void shovel_quest_dig() +{ + Game& game = *g_game; + bool isQuestRoom = game.stage == 1 && (game.levelStateFlags & LEVEL_STATE_SHOVEL_QUEST) && + game.currentRoomIdx == game.startingRoomIdx; + if (isQuestRoom && !game.itemPool.removedCollectibles[COLLECTIBLE_BROKEN_SHOVEL]) + reconstruction_missing("Room 008207a0: Mom's Shovel dug up by a bomb"); +} + +// 00700060, 00700061 An explosion as a bomb makes it: its damage and reach (larger for a stronger one), a crater (smaller +// under Safety Scissors), the blast itself in the bomb's color (or the poison, butt or brimstone bomb's), and the tear +// effects it spreads. +void explosion_effects(const Explosion& explosion) +{ + Entity* source = explosion.source; + if (source && explosion.tearFlags[TEAR_GIGA_BOMB]) + reconstruction_missing("Game::BombExplosionEffects 00700061: the giga explosion's wave"); + if (explosion.tearFlags[TEAR_CROSS_BOMB]) + reconstruction_missing("Game::BombExplosionEffects 00700061: Bomber Boy's cross of explosions"); + + float radius = explosion.damage >= DAMAGE_LARGE ? RADIUS_LARGE : explosion.damage > DAMAGE_MEDIUM ? RADIUS_MEDIUM : RADIUS_SMALL; + float craterScale = radius / RADIUS_SMALL * explosion.radiusMultiplier; + if (is_scissored(source)) + { + int scissors = g_game->playerManager.GetTrinketMultiplier(TRINKET_SAFETY_SCISSORS); + if (scissors == 2) craterScale *= SCISSORS_DOUBLE_SCALE; + else if (scissors > 2) craterScale *= SCISSORS_MORE_SCALE; + } + Explosion damaged = explosion; + damaged.radius = radius * explosion.radiusMultiplier; + explosion_damage(damaged); + bomb_crater_spawn(explosion.position, nullptr, craterScale); + + Entity* blast = g_game->Spawn({.position = explosion.position, .spawner = source, .type = ENTITY_EFFECT, + .variant = BOMB_EXPLOSION_EFFECT, .seed = Random()}); + blast->SetColor(explosion.color, -1, 255, false, true); + const float* tint = explosion.color._tint; + bool isWhite = tint[0] == 1 && tint[1] == 1 && tint[2] == 1 && tint[3] == 1; + if (explosion.tearFlags[TEAR_POISON] && isWhite) blast->SetColor(POISON_COLOR, -1, 255, false, true); + if (explosion.tearFlags[TEAR_BUTT_BOMB]) blast->SetColor(BUTT_COLOR, -1, 255, false, true); + blast->sprite.scale = vector_make(craterScale, craterScale); + if (source && source->type == ENTITY_BOMB && source->variant == BOMB_BRIMSTONE) + blast->SetColor(BRIMSTONE_COLOR, -1, 255, false, true); + + bool isFetusBomb = source && source->type == ENTITY_BOMB && static_cast(source)->isFetus; + if (g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_FIREWORKS && isFetusBomb) + { + Entity* fireworks = g_game->Spawn({.position = explosion.position, .subType = 1, .type = ENTITY_EFFECT, + .variant = FIREWORKS_EFFECT, .seed = Random()}); + fireworks->isDead = true; + fireworks->Update(); + } + explosion_tear_flag_effects(damaged); + shovel_quest_dig(); +} + +// 00703190 Leaves a crater at a size, kept in the room's saved effects (the oldest go past 128). +Entity* bomb_crater_spawn(const Vector& position, Entity* spawner, float scale) +{ + uint32_t seed = Random(); + Entity* crater = g_game->Spawn({.position = position, .spawner = spawner, .type = ENTITY_EFFECT, + .variant = BOMB_CRATER_EFFECT, .seed = seed}); + crater->sprite.scale = vector_make(scale, scale); + crater->Update(); + + std::vector& saved = g_game->room->descriptor->savedEffects; + while (saved.size() + 1 > SAVED_EFFECTS_MAX) saved.erase(saved.begin()); + EntitySaveState& state = saved.emplace_back(); + state.type = ENTITY_EFFECT; + state.variant = BOMB_CRATER_EFFECT; + state.targetPosition = position; + state.initSeed = crater->initSeed; + state.intStorage1 = std::bit_cast(scale); + return crater; +} diff --git a/src/boss_ai.h b/src/boss_ai.h new file mode 100644 index 0000000..3c52d38 --- /dev/null +++ b/src/boss_ai.h @@ -0,0 +1,62 @@ +#pragma once + +#include "game.h" +#include "npc_ai.h" +#include "room.h" +#include + +// The flags the boss AIs test that entity.h leaves unnamed: a Delirium form keeps its health and its calm. +constexpr uint64_t FLAG_DELIRIUM_FORM = 1ull << 60; + +// The effects and projectile looks the bosses leave. +constexpr int EFFECT_BLOOD_EXPLOSION = 2; +constexpr int EFFECT_CREEP_RED = 22; +constexpr int PROJECTILE_FCUK = 12; +constexpr uint64_t PROJECTILE_SMART = 1ull << 0; +constexpr uint64_t PROJECTILE_NO_WALL_COLLIDE = 1ull << 13; + +constexpr int COLOR_PRIORITY_DEFAULT = 255; +constexpr float BOSS_BLOOD_DEPTH = 10; + +// EntityList::QuerySublist uncached: the updated entities of a type (and variant unless -1) a query may see. +inline std::vector entity_query(int type, int variant) +{ + std::vector found; + + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == type && (variant < 0 || entity->variant == variant) && + !entity->HasEntityFlags(FLAG_NO_QUERY)) + found.push_back(entity); + return found; +} + +// spawn_blood_explosion: a tinted blood explosion with its sprite offset, drawn in front. +inline Entity* blood_explosion_spawn(int subType, const Vector& position, const Vector& spriteOffset, + const ColorMod& color, const Vector& velocity) +{ + Entity* explosion = g_game->Spawn({.position = position, + .velocity = velocity, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + explosion->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + explosion->sprite.offset = spriteOffset; + explosion->renderDepthOffset = BOSS_BLOOD_DEPTH; + return explosion; +} + +// Vector::ToCardinal: the axis a vector leans along most, as a unit step (vertical on a tie). +inline Vector vector_cardinal(Vector v) +{ + if (std::abs(v.x) <= std::abs(v.y)) return vector_make(0, v.y < 0 ? -1 : 1); + return vector_make(v.x < 0 ? -1 : 1, 0); +} + +// Whether the room is cleared, which calms a Delirium form. +inline bool room_is_clear() +{ + return g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; +} + +void boss_gemini_update(Entity_NPC& npc); diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp new file mode 100644 index 0000000..3423ba7 --- /dev/null +++ b/src/boss_gemini.cpp @@ -0,0 +1,485 @@ +#include "boss_ai.h" +#include "camera.h" +#include "entity_laser.h" +#include "room_descriptor.h" +#include + +// Gemini's parts, by variant: the big twins below 10 (Gemini, Steven, Blighted Ovum), their babies ten above, and the +// umbilical cord's segments. +constexpr int GEMINI_STEVEN = 1; +constexpr int GEMINI_BLIGHTED_OVUM = 2; +constexpr int GEMINI_BABY = 10; +constexpr int GEMINI_STEVEN_BABY = 11; +constexpr int GEMINI_BLIGHTED_OVUM_BABY = 12; +constexpr int GEMINI_CORD = 20; +constexpr int GEMINI_NO_CORD = 1; + +constexpr int CORD_SEGMENTS = 18; +constexpr int CORD_SEGMENT_KEEPS_APPEAR = 9; +constexpr float CORD_LENGTH = 196; +constexpr float CORD_SAG = 1.5f; +constexpr float CORD_SAG_CENTER = 9; +constexpr float CORD_SPAN = 18; +constexpr float CORD_SPAN_START = 16; +constexpr float CORD_STEP_DROP = 0.8f; +constexpr float CORD_OFFSET_X = -6; +constexpr float CORD_OFFSET_Y = -20; +constexpr float CORD_LAYER_OFFSET_Y = -8; +constexpr float BABY_SPAWN_OFFSET_Y = -8; + +constexpr float TWIN_FRICTION = 0.8f; +constexpr float NO_CORD_FRICTION = 0.92f; +constexpr int CREEP_FRAMES = 7; +constexpr float WALK_THRESHOLD = 0.1f; +constexpr float SPEED = 1.4f; +constexpr float OVUM_SPEED = 1.6f; +constexpr float PATH_SPEED_SCALE = 0.83f; +constexpr int PATH_MARKER = 900; +constexpr int RAGE_ODDS = 60; +constexpr int OVUM_RAGE_MASK = 3; +constexpr float RAGE_ACCELERATION = 0.04f; +constexpr float RAGE_DAMPING = 0.98f; +constexpr float OVUM_RAGE_BONUS = 0.2f; +constexpr int RAGE_FRAMES = 100; +constexpr int PANT_FRAMES = 100; +constexpr float LEASH = 76; +constexpr float LEASH_PULL = 0.01f; +constexpr float STEVEN_LEASH = 26; +constexpr float STEVEN_LEASH_PULL = 0.1f; + +constexpr float BABY_CLAMP_TOP = 30; +constexpr float BABY_CLAMP_BOTTOM = 10; +constexpr float BABY_PULL = 0.25f; +constexpr float BABY_SHOT_RANGE = 300; +constexpr int BABY_RANGE_FRAMES = 7; +constexpr int BABY_COOLDOWN = 35; +constexpr float BABY_SHOT_SPEED = 7; +constexpr float BABY_HARD_SHOT_SPEED = 10; +constexpr float BABY_SHOT_FALLING_SPEED = 3; +constexpr float BABY_SHOT_HEIGHT = -15; +constexpr float BABY_SHOT_VELOCITY_MULTI = 1.2f; +constexpr float BABY_BLOOD_SPEED = 0.4f; +constexpr float BABY_BLOOD_OFFSET_X = 7; +constexpr float BABY_BLOOD_OFFSET_Y = -25; +constexpr float ORPHAN_SPEED_BASE = 1.1764705f; +constexpr float ORPHAN_PULL = 0.5f; +constexpr float ORPHAN_MASS = 8; +constexpr float STEVEN_RAGE_HEALTH = 60; + +constexpr float OVUM_BABY_RANGE = 300; +constexpr float OVUM_BABY_CHASE = 0.65f; +constexpr float OVUM_BABY_CHASE_Y = 0.9f; +constexpr float OVUM_BABY_DRIFT = 0.01f; +constexpr float OVUM_BABY_DRIFT_LIMIT = 0.2f; +constexpr int OVUM_BABY_CHASE_FRAMES = 160; +constexpr int OVUM_BABY_BURST_ODDS = 30; +constexpr int OVUM_BABY_BURST_FIRST = 61; +constexpr int OVUM_BABY_BURST_SPAN = 99; +constexpr int OVUM_BABY_RESET_ODDS = 40; +constexpr int OVUM_BABY_RESET_FRAMES = 240; +constexpr int OVUM_BABY_AIM_FRAMES = 40; +constexpr float OVUM_BABY_LINE = 20; + +constexpr int STEVEN_DEATH_SHOTS_SPEED = 8; +constexpr int STEVEN_DEATH_BURST_SPEED = 4; +constexpr int WALLACE_DEATH_SHOTS_SPEED = 10; +constexpr float STEVEN_DEATH_FALL = -0.08f; +constexpr float WALLACE_DEATH_FALL = -0.06f; +constexpr float STEVEN_DEATH_SCALE = 2; + +constexpr int SOUND_CUTE_GRUNT = 25; +constexpr int SOUND_MONSTER_YELL_B = 122; +constexpr int SOUND_BLOODSHOOT = 178; +constexpr int SOUND_WORM_SPIT = 318; +constexpr int SOUND_STEVEN_DEATH_BIG = 961; +constexpr int SOUND_STEVEN_DEATH_SMALL = 962; +constexpr int SOUND_STEVEN_RAGE = 963; + +constexpr ColorMod STEVEN_SPLAT_COLOR = {{0.1f, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod OVUM_BABY_SPLAT_COLOR = {{0, 0, 0, 0.3f}, {0, 0, 0, 0}, {0.8f, 0.8f, 0.8f}}; +constexpr ColorMod STEVEN_BABY_BLOOD_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod PSY_BLOOD_COLOR = {{1, 1, 1, 0.6f}, {0.8f, 0.15f, 1, 1}, {0.26f, 0.05f, 0.4f}}; + +// The cord segments a Gemini spawned, which it hides when it loses its baby. +static std::vector cord_segments_get(Entity_NPC& npc) +{ + std::vector segments; + + for (Entity* entity : entity_query(ENTITY_GEMINI, -1)) + if (entity->variant == GEMINI_CORD && entity->parent == &npc) + segments.push_back(static_cast(entity)); + return segments; +} + +// The first frame: the baby spawns tied to its twin (with Gemini's cord unless subtype 1), sharing a Delirium form's +// health, and Steven bleeds dark. +static void twin_init(Entity_NPC& npc) +{ + bool isDelirium = npc.HasEntityFlags(FLAG_DELIRIUM_FORM); + auto* baby = + static_cast(g_game->Spawn({.position = vector_make(npc.pos.x, npc.pos.y + BABY_SPAWN_OFFSET_Y), + .spawner = &npc, + .type = npc.type, + .variant = npc.variant + GEMINI_BABY, + .seed = Random()})); + baby->parent = &npc; + if (isDelirium) + { + baby->maxHitPoints = npc.maxHitPoints; + baby->health = npc.maxHitPoints; + } + npc.child = baby; + baby->Update(); + + if (npc.variant == 0 && npc.subtype != GEMINI_NO_CORD) + { + for (int i = 0; i < CORD_SEGMENTS; i++) + { + auto* segment = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = npc.type, .variant = GEMINI_CORD, .seed = Random()})); + if (i != CORD_SEGMENT_KEEPS_APPEAR) segment->ClearEntityFlags(FLAG_APPEAR); + segment->SetBossColorIdx(npc.bosscoloridx, 0); + segment->parent = &npc; + segment->entityCollisionClass = ENTCOLL_NONE; + segment->isVisible = false; + if (!isDelirium) continue; + + segment->maxHitPoints = npc.maxHitPoints; + segment->health = npc.maxHitPoints; + } + } + + npc.state = NPC_STATE_MOVE; + if (npc.variant == GEMINI_STEVEN) npc.splatColor = STEVEN_SPLAT_COLOR; +} + +// Walks after its target along the grid at a speed. +static void twin_walk(Entity_NPC& npc, float speed) +{ + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), speed * PATH_SPEED_SCALE, PATH_MARKER, DIRECT_PATH_FAR); +} + +// Shows the idle head over the walk from its first frame. +static void twin_head_idle(Entity_NPC& npc) +{ + if (npc.sprite.SetOverlayAnimation("IdleHead") && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); +} + +// The twin's states: walking after its target until it rages at random (an Ovum rarely), raging faster for 100 frames, +// then panting 100 frames (an Ovum skips the pant). +static void twin_state_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + return twin_init(npc); + case NPC_STATE_IDLE: + npc.sprite.overlayAnimState.SetAnimationData(nullptr); + npc.sprite.Play("Pant"); + npc.stateFrame++; + npc.aiFloat = 0; + if (npc.stateFrame <= PANT_FRAMES) return; + + npc.state = NPC_STATE_MOVE; + npc.sprite.SetFrame("WalkVert", 0); + return twin_head_idle(npc); + case NPC_STATE_MOVE: + { + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.aiFloat = npc.variant == GEMINI_BLIGHTED_OVUM ? OVUM_SPEED : SPEED; + twin_walk(npc, npc.aiFloat); + twin_head_idle(npc); + + bool isCalm = npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear(); + if (isCalm || Random() % RAGE_ODDS != 0) return; + if (npc.variant == GEMINI_BLIGHTED_OVUM && (Random() & OVUM_RAGE_MASK) != 0) return; + + npc.PlaySound(SOUND_MONSTER_YELL_B, 1, 2, false, 1); + npc.stateFrame = 0; + npc.state = NPC_STATE_ATTACK; + return; + } + case NPC_STATE_ATTACK: + npc.aiFloat = (npc.aiFloat + RAGE_ACCELERATION) * RAGE_DAMPING; + twin_walk(npc, npc.variant == GEMINI_BLIGHTED_OVUM ? npc.aiFloat + OVUM_RAGE_BONUS : npc.aiFloat); + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.sprite.PlayOverlay("RageBody"); + if (++npc.stateFrame <= RAGE_FRAMES) return; + + npc.stateFrame = 0; + npc.state = npc.variant == GEMINI_BLIGHTED_OVUM ? NPC_STATE_MOVE : NPC_STATE_IDLE; + return; + } +} + +// Pulls the baby back toward its twin past the leash: Steven's always, the rest past 76. +static void baby_leash_update(Entity_NPC& npc, Entity& baby, Vector offset, float distance) +{ + if (npc.variant == GEMINI_STEVEN) + { + if (distance > 0 && baby.parent == &npc) + baby.AddVelocity_divided(vector_scale(offset, (distance - STEVEN_LEASH) * STEVEN_LEASH_PULL / distance), + false); + return; + } + if (distance > LEASH) + baby.AddVelocity_divided(vector_scale(offset, (distance - LEASH) * LEASH_PULL / distance), false); +} + +// Hangs Gemini's cord from its belly to the baby, sagging the more the slacker it is. +static void cord_update(Entity_NPC& npc, const std::vector& segments, Vector offset, float distance) +{ + float slack = std::max(CORD_LENGTH - distance, 0.0f); + float index = 0; + + for (Entity_NPC* segment : segments) + { + float span = (CORD_SPAN_START - index) / CORD_SPAN; + float fromCenter = std::abs(index - CORD_SAG_CENTER) * 0.5f; + float sag = (CORD_SPAN_START - fromCenter * fromCenter) * (slack / CORD_LENGTH) * CORD_SAG; + + segment->pos.x = npc.pos.x - span * offset.x + CORD_OFFSET_X; + segment->pos.y = npc.pos.y - span * offset.y + CORD_OFFSET_Y + sag + index * CORD_STEP_DROP; + segment->sprite.GetLayer(0)->pos = vector_make(0, CORD_LAYER_OFFSET_Y); + segment->isVisible = true; + index++; + } +} + +// 00471050 A big twin: Gemini, Steven or Blighted Ovum walking and raging at its target, an Ovum leaving red creep, +// with its baby leashed to it. Gemini hangs the cord between them and removes it once the baby is gone. +static void twin_update(Entity_NPC& npc) +{ + if (npc.variant == GEMINI_BLIGHTED_OVUM && npc.IsFrame(CREEP_FRAMES, 0)) + g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, + .seed = Random()}); + twin_state_update(npc); + + if (npc.child && !npc.child->parent) npc.child = nullptr; + if (npc.subtype == GEMINI_NO_CORD) return; + + std::vector segments; + if (npc.variant == 0) segments = cord_segments_get(npc); + if (!npc.child || npc.isDead) + { + for (Entity_NPC* segment : segments) segment->Remove(); + return; + } + + Entity& baby = *npc.child; + Vector offset = vector_sub(npc.pos, baby.pos); + float distance = vector_length(offset); + baby_leash_update(npc, baby, offset, distance); + if (npc.variant == 0) cord_update(npc, segments, offset, distance); +} + +// The first frame of a baby: an Ovum's baby is an invincible part of no boss that lets go of its twin and bleeds pale, +// Steven's bleeds dark. +static void baby_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + if (npc.variant == GEMINI_STEVEN_BABY) npc.splatColor = STEVEN_SPLAT_COLOR; + if (npc.variant != GEMINI_BLIGHTED_OVUM_BABY) return; + + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.isInvincible = true; + npc.isBoss = false; + if (npc.parent) npc.parent->child = nullptr; + npc.splatColor = OVUM_BABY_SPLAT_COLOR; +} + +// The Ovum's baby: dies with its twin, chases its target within 300 or drifts toward its row, and fires a short laser +// at a target in line with it. +static void ovum_baby_update(Entity_NPC& npc, Vector toAim, Vector toTarget) +{ + if (!npc.parent || npc.parent->isDead) npc.Kill(EntityRef()); + npc.pos = g_game->room->GetClampedPositionImpl(npc.pos, BABY_CLAMP_TOP, 0, BABY_CLAMP_BOTTOM, 0); + + if (npc.state == NPC_STATE_MOVE) + { + if (npc.stateFrame < OVUM_BABY_CHASE_FRAMES) + { + Vector chase = vector_normalized(toAim); + if (vector_length(toAim) < OVUM_BABY_RANGE) + npc.AddVelocity_divided( + vector_make(chase.x * OVUM_BABY_CHASE, chase.y * OVUM_BABY_CHASE * OVUM_BABY_CHASE_Y), false); + } + else + { + float drift = std::clamp(toAim.y * OVUM_BABY_DRIFT, -OVUM_BABY_DRIFT_LIMIT, OVUM_BABY_DRIFT_LIMIT); + npc.velocity.y = drift * npc.speedMultiplier / npc.friction + npc.velocity.y; + } + + if (Random() % OVUM_BABY_BURST_ODDS == 0 && + (unsigned)(npc.stateFrame - OVUM_BABY_BURST_FIRST) < (unsigned)OVUM_BABY_BURST_SPAN) + npc.stateFrame = OVUM_BABY_CHASE_FRAMES; + else if (Random() % OVUM_BABY_RESET_ODDS == 0 && npc.stateFrame > OVUM_BABY_RESET_FRAMES) npc.stateFrame = 0; + + npc.sprite.Play("Walk01"); + npc.sprite.isFlipX = npc.velocity.x < 0; + bool isCalm = npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear(); + bool isInLine = std::abs(toTarget.x) < OVUM_BABY_LINE || std::abs(toTarget.y) < OVUM_BABY_LINE; + if (!isCalm && npc.stateFrame > OVUM_BABY_AIM_FRAMES && isInLine && vector_length(toTarget) < OVUM_BABY_RANGE && + g_game->room->camera->IsPosVisible(npc.pos)) + { + npc.v1 = vector_cardinal(toTarget); + if (std::abs(npc.v1.x) <= 0) + { + npc.v1 = {}; + npc.stateFrame++; + return; + } + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + npc.sprite.Play("Attack01", PLAY_FORCED); + npc.sprite.isFlipX = npc.v1.x < 0; + reconstruction_missing("ENTITY_GEMINI_baby 00471cc0: Entity::SpawnFollowingEffect198 " + "0060b890's warning"); + npc.stateFrame++; + return; + } + } + else if (npc.state == NPC_STATE_ATTACK) + { + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + return reconstruction_missing("ENTITY_GEMINI_baby 00471cc0: Entity_Laser::ShootAngle 0096f310"); + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + } + } + npc.stateFrame++; +} + +// An orphaned baby (Steven's once Steven drops to 60 health): it lets go, rages and runs faster straight at its target. +static void orphan_update(Entity_NPC& npc, Vector toAim) +{ + if (npc.sprite.IsFinished("Rage")) npc.sprite.Play("Walk02"); + else if (!npc.sprite.IsPlaying("Walk02") && !npc.sprite.IsPlaying("Rage")) + { + npc.PlaySound(npc.variant == GEMINI_STEVEN_BABY ? SOUND_STEVEN_RAGE : SOUND_CUTE_GRUNT, 1, 2, false, 1); + npc.sprite.Play("Rage", PLAY_FORCED); + } + + npc.pos = g_game->room->GetClampedPositionImpl(npc.pos, BABY_CLAMP_TOP, 0, BABY_CLAMP_BOTTOM, 0); + npc.parent = nullptr; + + float boost = ORPHAN_SPEED_BASE; + if (npc.speedMultiplier != 1) + boost = ORPHAN_SPEED_BASE / (npc.speedMultiplier + ORPHAN_SPEED_BASE - npc.speedMultiplier * ORPHAN_SPEED_BASE); + npc.velocity = vector_scale(npc.velocity, boost); + npc.AddVelocity_divided(vector_scale(vector_normalized(toAim), ORPHAN_PULL), false); + npc.mass = ORPHAN_MASS; +} + +// The baby's spit: a shot at its target (a fcuk shot for Steven's, a homing one for a pink champion's baby) with a +// blood burst at its mouth. +static void baby_shoot(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + + ProjectileParams params; + params.fallingSpeedModifier = BABY_SHOT_FALLING_SPEED; + params.heightModifier = BABY_SHOT_HEIGHT; + params.velocityMulti = BABY_SHOT_VELOCITY_MULTI; + bool isPink = npc.variant == GEMINI_BABY && npc.bosscoloridx == 1; + if (npc.variant == GEMINI_STEVEN_BABY) params.variant = PROJECTILE_FCUK; + else if (isPink) params.bulletFlags = PROJECTILE_SMART; + + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + aim = vector_resized(aim, game_is_hard_mode() ? BABY_HARD_SHOT_SPEED : BABY_SHOT_SPEED); + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); + + ColorMod color = COLOR_DEFAULT; + if (npc.variant == GEMINI_STEVEN_BABY) color = STEVEN_BABY_BLOOD_COLOR; + else if (isPink) color = PSY_BLOOD_COLOR; + Vector offset = vector_make(npc.sprite.isFlipX ? -BABY_BLOOD_OFFSET_X : BABY_BLOOD_OFFSET_X, BABY_BLOOD_OFFSET_Y); + blood_explosion_spawn(EFFECT_BLOOD_EXPLOSION, npc.pos, offset, color, vector_scale(npc.velocity, BABY_BLOOD_SPEED)); +} + +// A leashed baby drifts after its target and spits at it in range, then rests 35 frames. +static void leashed_update(Entity_NPC& npc, Vector toAim) +{ + npc.AddVelocity_divided(vector_scale(vector_normalized(toAim), BABY_PULL), false); + + if (npc.state == NPC_STATE_MOVE) + { + if (npc.projectileCooldown < 1 && npc.IsTargetInAttackRange(BABY_SHOT_RANGE, BABY_RANGE_FRAMES, false)) + { + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack01", PLAY_FORCED); + } + return; + } + if (npc.state != NPC_STATE_ATTACK) return; + + if (npc.sprite.IsEventTriggered("Shoot")) baby_shoot(npc); + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + + npc.sprite.Play("Walk01"); + npc.state = NPC_STATE_MOVE; + npc.projectileCooldown = BABY_COOLDOWN; +} + +// 00471cc0 A baby twin: the Ovum's baby on its own, the others leashed until orphaned, facing the way they aim most. +static void baby_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return baby_init(npc); + + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + Vector toAim = vector_sub(npc.CalcTargetPosition(0), npc.pos); + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + + if (npc.variant == GEMINI_BLIGHTED_OVUM_BABY) ovum_baby_update(npc, toAim, toTarget); + else + { + bool isOrphan = + !npc.parent || (npc.variant == GEMINI_STEVEN_BABY && npc.ParentNPC()->health < STEVEN_RAGE_HEALTH); + if (isOrphan) orphan_update(npc, toAim); + else leashed_update(npc, toAim); + if (std::abs(toAim.y) < std::abs(toAim.x)) npc.sprite.isFlipX = toAim.x < 0; + } + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); +} + +// Steven's and its baby's death: a ring of eight fcuk shots, Steven's big and through walls with a slower ring inside. +static void steven_death_shots(Entity_NPC& npc) +{ + ProjectileParams params; + params.variant = PROJECTILE_FCUK; + float speed = WALLACE_DEATH_SHOTS_SPEED; + if (npc.variant == GEMINI_STEVEN) + { + npc_sound_play(SOUND_STEVEN_DEATH_BIG, 1, 2, 1); + params.fallingAccelModifier = STEVEN_DEATH_FALL; + params.scale = STEVEN_DEATH_SCALE; + params.bulletFlags = PROJECTILE_NO_WALL_COLLIDE; + npc.FireProjectiles(npc.pos, vector_make(STEVEN_DEATH_SHOTS_SPEED, 0), PROJECTILES_EIGHT, params); + speed = STEVEN_DEATH_BURST_SPEED; + } + else + { + npc_sound_play(SOUND_STEVEN_DEATH_SMALL, 1, 2, 1); + params.fallingAccelModifier = WALLACE_DEATH_FALL; + } + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_EIGHT, params); +} + +// Gemini's parts, the case npc_ai_update inlined at 006c2a45: they slide on low friction (less still for a twin without +// a cord), Steven and its baby shoot as they die, and a cord segment only follows, without dying with the boss. +void boss_gemini_update(Entity_NPC& npc) +{ + npc.friction *= TWIN_FRICTION; + if (npc.variant < GEMINI_BABY && npc.subtype != 0) npc.friction *= NO_CORD_FRICTION; + if (npc.isDead && (npc.variant == GEMINI_STEVEN_BABY || npc.variant == GEMINI_STEVEN)) steven_death_shots(npc); + + if (npc.variant < GEMINI_BABY) return twin_update(npc); + if (npc.variant < GEMINI_CORD) return baby_update(npc); + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_NO_DEATH_TRIGGER; +} diff --git a/src/boss_intro.cpp b/src/boss_intro.cpp new file mode 100644 index 0000000..82824fe --- /dev/null +++ b/src/boss_intro.cpp @@ -0,0 +1,269 @@ +#include "data.h" +#include "entity_config.h" +#include "entity_player.h" +#include "game.h" +#include "level.h" +#include "log.h" +#include "manager.h" +#include "room.h" +#include "room_transition.h" +#include "stage_transition.h" +#include "stb_image.h" +#include + +constexpr std::string_view VERSUS_ANM2 = "gfx/ui/boss/versusscreen.anm2"; +constexpr std::string_view VERSUS_DOGMA_ANM2 = "gfx/ui/boss/versusscreen_dogma.anm2"; +constexpr std::string_view VERSUS_MOTHER_ANM2 = "gfx/ui/boss/versusscreen_mother.anm2"; +constexpr std::string_view DOUBLE_TROUBLE_PNG = "gfx/ui/boss/doubletrouble.png"; +constexpr std::string_view G_FUEL_PORTRAIT = "gfx/promo/gfuel/ui/boss/g fuel bluebaby portrait.png"; + +// The versus screen's layers: the backdrop, the spots the portraits stand on, the boss's portraits and name, the +// player's, the overlay multiplied over it, and the co-op players' portraits with their alternates and spots. +constexpr int LAYER_BACKGROUND = 0; +constexpr int LAYER_BOSS_SPOT = 2; +constexpr int LAYER_PLAYER_SPOT = 3; +constexpr int LAYER_BOSS_PORTRAIT = 4; +constexpr int LAYER_PLAYER_PORTRAIT = 5; +constexpr int LAYER_PLAYER_NAME = 6; +constexpr int LAYER_BOSS_NAME = 7; +constexpr int LAYER_SECOND_BOSS_PORTRAIT = 9; +constexpr int LAYER_DOUBLE_TROUBLE = 10; +constexpr int LAYER_OVERLAY = 11; +constexpr int LAYER_PLAYER_PORTRAIT_ALT = 12; +constexpr int LAYER_BOSS_SHADOW = 13; +constexpr int LAYER_SECOND_BOSS_SHADOW = 14; +constexpr unsigned int DOGMA_OVERLAY_FLAGS = 0x60; +constexpr std::array PLAYER_LAYERS_HIDDEN = {5, 12, 15, 18, 21, 16, 19, 22, 17, 20, 23}; + +// A co-op player's layers: its portrait, the alternate the floating characters use, and its spot. +struct PlayerLayers +{ + int portrait; + int portraitAlt; + int spot; +}; + +constexpr PlayerLayers MAIN_PLAYER_LAYERS = {LAYER_PLAYER_PORTRAIT, LAYER_PLAYER_PORTRAIT_ALT, LAYER_PLAYER_SPOT}; +constexpr std::array COOP_PLAYER_LAYERS = {{{18, 21, 15}, {19, 22, 16}, {20, 23, 17}}}; + +// The characters whose portrait goes on the alternate layer: ???, Keeper, The Forgotten and The Soul, and the tainted +// ???, Keeper and Forgotten. +constexpr std::array ALT_PORTRAIT_PLAYERS = {4, 16, 17, 14, 25, 35, 33}; + +constexpr int MUSIC_JINGLE_BOSS = 81; +constexpr uint32_t BOSS_BLUE_BABY = 40; +constexpr uint32_t BOSS_MEGA_SATAN = 55; +constexpr uint32_t BOSS_MOTHER = 88; +constexpr uint32_t BOSS_DOGMA = 99; +constexpr int BOSS_ROOM_DELIRIUM = 90; +constexpr int DELIRIUM_STAGE = 8; +constexpr int DOUBLE_TROUBLE_FIRST = 3700; +constexpr int DOUBLE_TROUBLE_SPAN = 150; +constexpr float BYTE_TO_UNIT = 0.003921569f; +constexpr float UNKNOWN_SHADOW_GREEN = 0.5568628f; +constexpr float UNKNOWN_SHADOW_BLUE = 0.4666667f; + +// The blend that multiplies the overlay layer into what it covers. +constexpr std::array MULTIPLY_BLEND = {0, 4, 7, 4, 7}; + +// A boss's portrait for the floor, its alternate for the stage if it has one. +static const std::string& boss_portrait_get(const EntityConfig_Boss& boss) +{ + int stageId = g_game->GetStageID(); + for (const EntityConfig_BossAlt& alt : boss.alts) + if (alt.stageId == stageId) return alt.portraitPath; + return boss.portraitPath; +} + +// A boss's portrait config by id (an out of range id logs and uses the first). +static const EntityConfig_Boss& boss_config_get(uint32_t bossId) +{ + std::vector& bosses = g_manager->entityConfig.bosses; + if (bossId >= bosses.size()) + { + log_printf(LOG_ERROR, "BossID out of bounds\n"); + return bosses.front(); + } + return bosses[bossId]; +} + +// 00831780 Puts a character's portrait on its layers: the spot shows, the portrait (or the floating characters' +// alternate) takes the character's picture, and a character with an animated portrait plays it on that layer. +static void player_portrait_set(RoomTransition& transition, const EntityConfig_Player& config, + const PlayerLayers& layers) +{ + ANM2& versus = transition.versusScreenANM2; + bool isAlt = std::ranges::find(ALT_PORTRAIT_PLAYERS, config.id) != ALT_PORTRAIT_PLAYERS.end(); + int layer = isAlt ? layers.portraitAlt : layers.portrait; + + versus.GetLayer(layers.spot)->isVisible = true; + versus.ReplaceSpritesheet(layer, config.portraitPath); + versus.GetLayer(layer)->isVisible = true; + if (config.extraPortraitPath.empty()) return; + + ANM2& extra = transition.extraLayerANM2s[layer]; + extra.Load(config.extraPortraitPath, GRAPHICS_LOAD); + extra.Play(extra.GetDefaultAnimationName()); +} + +// The players' side: the portrait and name of the player who entered, then each other main player's portrait in the +// next co-op slot (its twin apart). +static void players_set(RoomTransition& transition) +{ + Game& game = *g_game; + ANM2& versus = transition.versusScreenANM2; + PlayerManager& players = game.playerManager; + Entity_Player* entering = players.roomTransitionPlayer ? players.roomTransitionPlayer : game.GetPlayer(0); + EntityConfig_Player* config = g_manager->entityConfig.GetPlayer(entering->playerType); + if (!config) + return log_printf(LOG_INFO, "[warn] could not load player config for type %d.\n", entering->playerType); + + for (int layer : PLAYER_LAYERS_HIDDEN) versus.GetLayer(layer)->isVisible = false; + player_portrait_set(transition, *config, MAIN_PLAYER_LAYERS); + versus.ReplaceSpritesheet(LAYER_PLAYER_NAME, config->nameImagePath); + + size_t slot = 0; + for (int i = 0; i < players.count_main_players(); i++) + { + Entity_Player* coop = players.get_main_player(i); + if (!coop || coop == entering || coop == entering->twinPlayer.get()) continue; + + // The original read a missing character's config through a null pointer. This skips it. + EntityConfig_Player* coopConfig = g_manager->entityConfig.GetPlayer(coop->playerType); + if (slot >= COOP_PLAYER_LAYERS.size()) log_printf(LOG_ERROR, "Ran out of slots for players"); + else if (coopConfig) player_portrait_set(transition, *coopConfig, COOP_PLAYER_LAYERS[slot]); + slot++; + } +} + +// The stage whose spots the screen stands on: the boss room's own (an extra boss room's adjusted), Delirium's always +// the Womb's. +static int spot_stage_id_get() +{ + Game& game = *g_game; + int stage = (int)game.stage; + int stageType = game.GetRoomStageType(game.currentRoomIdx); + RoomConfig_Room* config = game.room->descriptor->data; + + if (game.currentRoomIdx == ROOM_EXTRA_BOSS_IDX) Level::boss_count_adjust(stage, stageType); + if (game.room->roomType == ROOM_BOSS && config->subtype == BOSS_ROOM_DELIRIUM) + { + stage = DELIRIUM_STAGE; + stageType = STAGETYPE_ORIGINAL; + } + return RoomConfig::GetStageID(stage, stageType, ROOM_MODE_CURRENT); +} + +// The bosses' side: their portraits (the second boss's, or the first's again), with the first's pivot and name, and +// Blue Baby's G FUEL portrait with its seed. +static void bosses_set(ANM2& versus, uint32_t bossId1, uint32_t bossId2) +{ + const EntityConfig_Boss& boss = boss_config_get(bossId1); + const std::string& second = boss_portrait_get(bossId2 == 0 ? boss : boss_config_get(bossId2)); + + versus.ReplaceSpritesheet(LAYER_BOSS_PORTRAIT, boss_portrait_get(boss)); + versus.ReplaceSpritesheet(LAYER_BOSS_SHADOW, boss_portrait_get(boss)); + versus.ReplaceSpritesheet(LAYER_SECOND_BOSS_PORTRAIT, second); + versus.ReplaceSpritesheet(LAYER_SECOND_BOSS_SHADOW, second); + if (bossId1 == BOSS_BLUE_BABY && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) + { + versus.ReplaceSpritesheet(LAYER_BOSS_PORTRAIT, G_FUEL_PORTRAIT); + versus.ReplaceSpritesheet(LAYER_BOSS_SHADOW, G_FUEL_PORTRAIT); + } + versus.ReplaceSpritesheet(LAYER_BOSS_NAME, boss.namePath); + for (int layer : {LAYER_BOSS_PORTRAIT, LAYER_BOSS_SHADOW, LAYER_SECOND_BOSS_PORTRAIT, LAYER_SECOND_BOSS_SHADOW}) + versus.GetLayer(layer)->pos = boss.pivot; +} + +// Sets a layer's tint, opaque. +static void layer_tint(ANM2& versus, int layer, float red, float green, float blue) +{ + float* tint = versus.GetLayer(layer)->color._tint; + + tint[0] = red; + tint[1] = green; + tint[2] = blue; + tint[3] = 1; +} + +// Tints the backdrop by the boss spot's first texel and the portraits' shadows by its second, doubled. A spot that did +// not load leaves the backdrop black and the shadows a default red. Mega Satan's backdrop is black. +static void backdrop_tint(ANM2& versus, uint32_t bossId1) +{ + const KAGE::Graphics::ImagePtr& sheet = versus.GetLayer(LAYER_BOSS_SPOT)->spriteSheet; + int width = 0; + int height = 0; + int channels = 0; + stbi_uc* texels = nullptr; + + if (sheet && sheet->isLoaded) + texels = stbi_load(resource_path(sheet->path).c_str(), &width, &height, &channels, STBI_rgb_alpha); + if (!texels || width < 2) + { + layer_tint(versus, LAYER_BACKGROUND, 0, 0, 0); + layer_tint(versus, LAYER_BOSS_SHADOW, 1, UNKNOWN_SHADOW_GREEN, UNKNOWN_SHADOW_BLUE); + layer_tint(versus, LAYER_SECOND_BOSS_SHADOW, 1, UNKNOWN_SHADOW_GREEN, UNKNOWN_SHADOW_BLUE); + } + else + { + auto unit = [&](int index, int scale) { + return (float)(texels[index] * scale) * BYTE_TO_UNIT; + }; + layer_tint(versus, LAYER_BACKGROUND, unit(0, 1), unit(1, 1), unit(2, 1)); + layer_tint(versus, LAYER_BOSS_SHADOW, unit(4, 2), unit(5, 2), unit(6, 2)); + layer_tint(versus, LAYER_SECOND_BOSS_SHADOW, unit(4, 2), unit(5, 2), unit(6, 2)); + } + stbi_image_free(texels); + if (bossId1 == BOSS_MEGA_SATAN) layer_tint(versus, LAYER_BACKGROUND, 0, 0, 0); +} + +// 0082f1c0 Starts a boss room's versus screen as the transition goes out: the boss jingle (when a transition runs), the +// room's ambient loops and the HUD off, Dogma's and Mother's own screens, the players' and the bosses' portraits, names +// and spots for the floor, the backdrop tinted by the spot, and the Double Trouble banner for two bosses. Online +// co-op's animations are left out, as the game is offline. +void RoomTransition::StartBossIntro(uint32_t bossId1, uint32_t bossId2) +{ + Game& game = *g_game; + ANM2& versus = versusScreenANM2; + bool isDogma = bossId1 == BOSS_DOGMA; + std::string_view path = isDogma ? VERSUS_DOGMA_ANM2 : bossId1 == BOSS_MOTHER ? VERSUS_MOTHER_ANM2 : VERSUS_ANM2; + + bossIntroBossId = bossId1; + if (mode != TRANSITION_NONE) g_manager->musicManager.Play(MUSIC_JINGLE_BOSS, g_manager->optionsConfig.musicVolume); + room_ambient_sounds_stop(); + game.hud.isVisible = false; + if (!versus.isLoaded || versus.filename != path) versus.Load(path, GRAPHICS_LOAD); + if (isDogma) versus.GetLayer(LAYER_OVERLAY)->bitflags |= DOGMA_OVERLAY_FLAGS; + versus.GetLayer(LAYER_OVERLAY)->blendMode = MULTIPLY_BLEND; + extraLayerANM2s.clear(); + + players_set(*this); + bosses_set(versus, bossId1, bossId2); + if (!isDogma) + { + RoomConfig_Stage& stage = game.roomConfig.stages[spot_stage_id_get()]; + for (int layer : {LAYER_PLAYER_SPOT, 15, 16, 17}) versus.ReplaceSpritesheet(layer, stage.playerSpot); + versus.ReplaceSpritesheet(LAYER_BOSS_SPOT, stage.bossSpot); + versus.GetLayer(LAYER_BOSS_SPOT)->isVisible = bossId1 != BOSS_MEGA_SATAN; + } + if (bossId1 == BOSS_MOTHER) + reconstruction_missing("RoomTransition::StartBossIntro 0082f1c0: Mother's " + "layer 24 (FUN_0069d250)"); + versus.LoadGraphics(); + if (isDogma) + for (int layer : {LAYER_BACKGROUND, LAYER_BOSS_SHADOW, LAYER_SECOND_BOSS_SHADOW}) + layer_tint(versus, layer, 1, 1, 1); + else backdrop_tint(versus, bossId1); + + RoomConfig_Room* data = game.GetRoomByIdx(roomIndex)->data; + if (!data) log_printf(LOG_ERROR, "Room Data is NULL in RoomTransition::change_room.\n"); + bool isDoubleTrouble = data && data->type == ROOM_BOSS && + (unsigned)(data->variant - DOUBLE_TROUBLE_FIRST) < (unsigned)DOUBLE_TROUBLE_SPAN; + if (isDoubleTrouble) + { + versus.ReplaceSpritesheet(LAYER_DOUBLE_TROUBLE, DOUBLE_TROUBLE_PNG); + versus.LoadGraphics(); + } + versus.Play(isDoubleTrouble ? "DoubleTrouble" : "Scene", PLAY_FORCED); + mode = TRANSITION_OUT; +} diff --git a/src/deathmatch_manager.cpp b/src/deathmatch_manager.cpp index b36c06a..bd4896f 100644 --- a/src/deathmatch_manager.cpp +++ b/src/deathmatch_manager.cpp @@ -26,6 +26,12 @@ void DeathmatchManager::enter_arena() reconstruction_missing("DeathmatchManager::enter_arena 00429570: the versus arena of an online match"); } +// The match types' destruction (0042a430, 0042d0f0, 0042d780) frees what their construction filled, which the curated +// code leaves empty, so it does nothing more. Ludovico's image waits for DeathmatchTypeLudovico's takeover. +DeathmatchTypeBase::~DeathmatchTypeBase() {} +DeathmatchTypeLudovico::~DeathmatchTypeLudovico() {} +DeathmatchTypeNormal::~DeathmatchTypeNormal() {} + // 00429be0 Replaces the match's rules with those of a type, logging an unknown type and leaving none. // The Ludovico rules also load the Ludovico Technique's image, which waits for DeathmatchTypeLudovico's takeover. void DeathmatchManager::set_type(DeathmatchRules rules) diff --git a/src/entity.cpp b/src/entity.cpp index 6b45bad..071081a 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -1230,12 +1230,6 @@ void Entity::SetSpriteOverlayFrame(std::string_view animation, int frame) // The rest of Entity is not reconstructed yet. -// 0060af70 -Entity* Entity::AddFear(int, int, int) -{ - reconstruction_missing("Entity::AddFear 0060af70"); -} - // 0064bb70 void Entity::convert_shot_for_enemy_owner(Entity*) { diff --git a/src/entity.h b/src/entity.h index 1d1c06e..01c6444 100644 --- a/src/entity.h +++ b/src/entity.h @@ -512,7 +512,6 @@ struct Entity void AddConfusion(const EntityRef& source, int duration, bool isIgnoreBossCooldown); void AddMidasFreeze(const EntityRef& source, int duration, bool isIgnoreBossCooldown); void AddFear(const EntityRef& source, int duration, bool isIgnoreBossCooldown); - Entity* AddFear(int duration, int unknown1, int unknown2); void AddBurn(const EntityRef& source, int duration, float damage, bool isIgnoreBossCooldown); void AddBleeding(const EntityRef& source, int duration); void AddShrink(const EntityRef& source, int duration, bool isIgnoreBossCooldown); diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index 6a6a89d..3179110 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -1,8 +1,137 @@ #include "entity_bomb.h" +#include "data.h" +#include "entity_config.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "grid_entity_rock.h" +#include "item_config.h" #include "log.h" +#include "lua_callbacks.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "sfx_manager.h" +#include +#include +#include -constexpr int BOMB_ROCKET = 19; -constexpr int BOMB_ROCKET_GIGA = 20; +constexpr uint64_t DAMAGE_IGNORE_ARMOR = 1ull << 30; + +// A bomb's fuse and damage, and the brimstone and giga bombs' own. Troll bombs light a random part of a second longer. +constexpr int FUSE_FRAMES = 45; +constexpr int FUSE_TROLL_EXTRA = 30; +constexpr int FUSE_BRIMSTONE = 94; +constexpr int FUSE_GIGA = 87; +constexpr float DAMAGE_DEFAULT = 100; +constexpr float DAMAGE_BRIMSTONE = 20; +constexpr float DAMAGE_GIGA = 300; +constexpr int COLLISION_COOLDOWN = 4; +constexpr float ROCKET_HEIGHT = -14; + +// The fall: gravity, Hydrobounce's, the heights the grid collision changes at, and a bounce's loss and limit. +constexpr float FALL_GRAVITY = 0.8f; +constexpr float FALL_GRAVITY_BOUNCY = 2.5f; +constexpr float FALL_GRAVITY_ROCKET_BOUNCY = 1.6f; +constexpr float FALL_HIGH = -26; +constexpr float FALL_LOW = -3; +constexpr float BOUNCE_SPEED_MIN = 2; +constexpr int BOUNCE_MAX = 3; +constexpr float BOUNCE_START_SPEED = -8; + +// The pulse loops so many frames before the fuse runs out. The Remote Detonator holds it in its first ones. +constexpr int PULSE_LOOP = 15; +constexpr int PULSE_REMOTE_LAST = 14; + +// The slide a bomb loses each frame, and the troll bombs' chase of the nearest player. +constexpr float SLIDE_FRICTION = 0.95f; +constexpr float SLIDE_STOP = 0.5f; +constexpr float CHASE_LOOKAHEAD = 5; +constexpr float CHASE_RANGE = 270; +constexpr float CHASE_ACCELERATION = 1.5f; +constexpr float CHASE_FRICTION = 0.8f; +constexpr int CHASE_START_FRAMES = 20; +constexpr float PITFALL_FRICTION = 0.6f; +constexpr float BRIMSTONE_FRICTION = 0.8f; +constexpr float CRAWLSPACE_GRAVITY = 0.9f; +constexpr int SOLID_AFTER_FRAMES = 15; + +// The golden troll bomb lights again after exploding, sliding off in a random direction. +constexpr int GOLDEN_FUSE_EXTRA = 30; +constexpr int GOLDEN_FUSE = 60; +constexpr float GOLDEN_APPEAR_FRAME = 8; +constexpr float GOLDEN_SPEED_EXTRA = 5; +constexpr float GOLDEN_SPEED = 5; +constexpr int GOLDEN_SCATTER_FRAMES = 90; +constexpr int GIGA_UPDATE_DELAY = 5; + +// Safety Scissors turn a troll bomb into a pickup bomb of its kind, shown on its last frames. +constexpr int SCISSORS_BOMB_FRAMES_LEFT = 8; +constexpr int BOMB_PICKUP_TROLL = 1; +constexpr int BOMB_PICKUP_DOUBLE = 2; +constexpr int BOMB_PICKUP_GOLDEN = 4; +constexpr int BOMB_PICKUP_GIGA = 7; +constexpr int BLASTING_CAP_CHANCE = 10; + +// The sounds a bomb makes, and the size its costume sprites are picked by. +constexpr int SOUND_FETUS_LAND = 40; +constexpr int SOUND_BEEP = 171; +constexpr int SOUND_GOLD_HEART_DROP = 466; +constexpr int SOUND_SAFETY_SCISSORS = 900; +constexpr float GOLDEN_VOLUME = 0.8f; +constexpr float GIGA_DROP_PITCH = 0.8f; +constexpr float BEEP_PITCH = 1.5f; +constexpr int DROP_SOUND_DELAY = 4; +constexpr int GIGA_DROP_SHAKE = 6; +constexpr float BIG_BOMB_SCALE = 1.5f; +constexpr size_t EXTENSION_SIZE = 4; +constexpr size_t ANM2_EXTENSION_SIZE = 5; + +// The items and entities a bomb asks about (Lua's names). +constexpr int COLLECTIBLE_REMOTE_DETONATOR = 137; +constexpr int TRINKET_SAFETY_SCISSORS = 63; +constexpr int TRINKET_BLASTING_CAP = 73; +constexpr int PICKUP_BOMB = 40; +constexpr int PICKUP_BOMBCHEST = 51; +constexpr int POOF01_EFFECT = 15; +constexpr int ENTITY_VISAGE = 903; +constexpr int ENTITY_HORNFEL = 906; +constexpr int ENTITY_COLOSTOMIA = 917; +constexpr int ENTITY_LITTLE_HORN = 404; +constexpr int ENTITY_BIG_HORN = 411; +constexpr int ENTITY_PITFALL = 291; +constexpr int VISAGE_MASK_VARIANT = 10; + +// Pushes and slowdowns of a bomb that collides with something low. +constexpr float LOW_COLLIDER_SLOW = 0.2f; +constexpr float LOW_BOMB_SLOW = 0.5f; +constexpr float PLAYER_PUSH = 0.4f; +constexpr float PUSH_MIN_DISTANCE = 0.0001f; +constexpr int HIT_COUNTDOWN = 30; + +// The running number each player bomb takes on its first frame (the original's 00c7ec64). +static int g_bombIndexCounter = 0; + +// Stops where a bomb's tear effect is not reconstructed yet. +static void flag_check(const Entity_Bomb& bomb, int bit, const char* what) +{ + if (bomb.tearFlags[bit]) reconstruction_missing(what); +} + +// The sound a bomb lands with. +struct LandSound +{ + float volume; + int id; +}; + +// The sound a bomb lands with: louder up to a normal size, a golden troll bomb's own and quieter. +static LandSound land_sound_get(const Entity_Bomb& bomb) +{ + bool isGolden = bomb.variant == BOMB_GOLDENTROLL; + return {std::min(bomb.scale, 1.0f) * (isGolden ? GOLDEN_VOLUME : 1), isGolden ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_LAND}; +} // 00452c40 Lights the fuse for the given frames. void Entity_Bomb::SetExplosionCountdown(int countdown) @@ -17,34 +146,593 @@ bool Entity_Bomb::IsRocket() return variant == BOMB_ROCKET || variant == BOMB_ROCKET_GIGA; } -// The rest of Entity_Bomb is not reconstructed yet. - -// 006a2050 -void Entity_Bomb::Init(int, int, int, uint32_t) +// 006a2050 Starts the bomb: its fuse (longer and random for troll and hot bombs, the brimstone and giga bombs' own), +// its damage, its sprite and first animation, and a rocket's flight height. +void Entity_Bomb::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { - reconstruction_missing("Entity_Bomb::Init 006a2050"); + Entity::Init(entityType, entityVariant, entitySubType, seed); + explosionDamage = DAMAGE_DEFAULT; + explosionCountdown = FUSE_FRAMES; + updateDelay = 0; + scatterTimer = 0; + bool isTroll = variant == BOMB_TROLL || variant == BOMB_SUPERTROLL || variant == BOMB_HOT || variant == BOMB_GOLDENTROLL; + if (isTroll) explosionCountdown += (int)(dropRNG.Next() % FUSE_TROLL_EXTRA); + if (variant == BOMB_BRIMSTONE) + { + explosionCountdown = FUSE_BRIMSTONE; + explosionDamage = DAMAGE_BRIMSTONE; + } + else if (variant == BOMB_GIGA || variant == BOMB_ROCKET_GIGA) + { + explosionCountdown = FUSE_GIGA; + explosionDamage = DAMAGE_GIGA; + } + + scale = 1; + rocketSpeed = 0; + fallAcceleration = 0; + entityGridCollisionClass = GRIDCOLL_GROUND; + collisionCooldown = COLLISION_COOLDOWN; + parentCollisionCooldown = COLLISION_COOLDOWN; + isFetus = false; + tearFlags.reset(); + isPrismTouched = false; + bounceCount = 0; + fallSpeed = 0; + radiusMultiplier = 1; + stickyTarget = nullptr; + if (config) sprite.Load(config->anm2Path, GRAPHICS_LOAD); + hitList.clear(); + isHasCostumes = false; + isLoadCostumes = false; + + if (variant == BOMB_DECOY) sprite.Play("Idle"); + else if (isTroll || variant == BOMB_GIGA) + { + if (subtype == 1) reconstruction_missing("Entity_Bomb::Init 006a2050: a returned bomb in the floor's color"); + sprite.Play("Appear", PLAY_FORCED); + } + else sprite.Play("Pulse", PLAY_FORCED); + + rocketAngle = 0; + isSkipNextUpdate = false; + if (IsRocket()) + { + AddEntityFlags(FLAG_NO_KNOCKBACK); + posOffset.y = ROCKET_HEIGHT; + } + lua_callback_check(MC_POST_BOMB_INIT, "LuaEngine::PostBombInit 00861ea0"); } -// 006a24d0 +// Falls back to the floor, colliding with less of the grid the higher it flies, and lands with a sound. Hydrobounce +// bounces it. +void Entity_Bomb::fall_update(bool isBouncy) +{ + float height = posOffset.y + fallSpeed; + posOffset.y = height; + float gravity = fallAcceleration == 0 ? FALL_GRAVITY : fallAcceleration; + if (IsRocket()) gravity = isBouncy ? FALL_GRAVITY_ROCKET_BOUNCY : fallAcceleration; + else if (isBouncy) gravity = FALL_GRAVITY_BOUNCY; + fallSpeed += gravity; + + if (height < FALL_HIGH) entityGridCollisionClass = GRIDCOLL_WALLS; + else if (height >= FALL_LOW && !isFetus && !IsRocket()) entityGridCollisionClass = GRIDCOLL_GROUND; + else entityGridCollisionClass = GRIDCOLL_NOPITS; + if (height < 0) return; + + if (isBouncy && fallSpeed > BOUNCE_SPEED_MIN && bounceCount <= BOUNCE_MAX) + reconstruction_missing("Entity_Bomb::Update 006a24d0: Hydrobounce's bounce (tear_flags_area_apply)"); + posOffset.y = 0; + fallSpeed = 0; + collisionDamage = 0; + if (IsRocket()) explosionCountdown = 0; + else + { + LandSound land = land_sound_get(*this); + grid_sound_play(land.id, {.volume = land.volume}); + } +} + +// Keeps the pulse in step with the fuse, so its last loop ends as it blows. The Remote Detonator's bomb loops its +// first frames until it is set off. +void Entity_Bomb::pulse_update(Entity_Player* spawner) +{ + if (!sprite.IsPlaying("Pulse") || IsRocket()) return; + + bool isRemote = !isFetus && spawnerType == ENTITY_PLAYER && spawner && + spawner->HasCollectible(COLLECTIBLE_REMOTE_DETONATOR); + if (isRemote) + { + if (sprite.GetFrame() > PULSE_REMOTE_LAST) sprite.SetFrame(0.0f); + return; + } + int frame = sprite.animState.GetAnimationLength() - explosionCountdown - 1; + if (frame < 0) frame = frame % PULSE_LOOP + PULSE_LOOP; + if (frame != sprite.GetFrame()) sprite.SetFrame((float)frame); +} + +// 006a24d0 A bomb's frame: an exploded one finishes its animation and goes, a held or frozen one waits. Otherwise it +// falls, pulses and slides to a stop, its fuse burns down and it explodes, troll bombs chase the players and the drop +// sound plays. void Entity_Bomb::Update() { - reconstruction_missing("Entity_Bomb::Update 006a24d0"); + if (isSkipNextUpdate) + { + isSkipNextUpdate = false; + return; + } + if (isLoadCostumes) update_sparks(); + if (isFetus || IsRocket()) reconstruction_missing("Entity_Bomb::Update 006a24d0: Dr. Fetus bombs and rockets"); + + bool isBouncy = tearFlags[TEAR_HYDROBOUNCE]; + if (g_game->frameCount - spawnFrame == 1) + { + if (spawnerType == ENTITY_PLAYER) bombIndex = g_bombIndexCounter++; + if (isBouncy) + { + fallSpeed = BOUNCE_START_SPEED; + posOffset.y = FALL_LOW; + } + } + if (isDead) + { + velocity = {}; + Entity::Update(); + if (updateDelay > 0) updateDelay--; + else if (!sprite.animState.animData || !sprite.animState.isPlaying || variant == BOMB_DECOY) Remove(); + return; + } + if (pitfallState != 0) + { + friction *= PITFALL_FRICTION; + if (explosionCountdown > 0) explosionCountdown++; + if ((!sprite.animState.animData || !sprite.animState.isPlaying) && pitfallState == 1) + { + pitfallState = 2; + if (!parent) Remove(); + } + } + if (HasEntityFlags(FLAG_FREEZE)) + { + sprite.SetFrame("Idle", 0); + if (isHasCostumes) + for (ANM2& costume : bombCostumesSprites) costume.Update(); + Entity::Update(); + return; + } + + if (isVisible && pitfallState == 0 && (posOffset.y < 0 || fallSpeed < 0)) fall_update(isBouncy); + Entity_Player* spawner = spawnerEntity && spawnerEntity->is_player() ? spawnerEntity->ToPlayer() : nullptr; + bool isOneShotPlaying = sprite.animState.animData && sprite.animState.isPlaying && !sprite.animState.IsLoopingAnimation(); + if (!isOneShotPlaying && variant != BOMB_DECOY && pitfallState == 0) sprite.Play("Pulse"); + pulse_update(spawner); + + flag_check(*this, TEAR_BURN, "Entity_Bomb::Update 006a24d0: Hot Bombs' burn"); + flag_check(*this, TEAR_OCCULT, "Entity_Bomb::Update 006a24d0: the Occult's steering"); + Entity::Update(); + if (spawnerType == ENTITY_PLAYER) + { + flag_check(*this, TEAR_HOMING, "Entity_Bomb::Update 006a24d0: Bobby-Bomb's homing"); + flag_check(*this, TEAR_CREEP_TRAIL, "Entity_Bomb::Update 006a24d0: Bob's Bladder's creep"); + } + velocity = vector_scale(velocity, SLIDE_FRICTION); + if (vector_length_squared(velocity) < 1) velocity = vector_scale(velocity, SLIDE_STOP); + flag_check(*this, TEAR_STICKY, "Entity_Bomb::Update 006a24d0: Sticky Bombs' hold"); + if (fuse_update(spawner)) late_update(); } -// 006a5a60 -void Entity_Bomb::Render(const Vector&) +// Burns the fuse down, or keeps it at its end while the Remote Detonator waits, and explodes. Safety Scissors defuse a +// troll bomb as its fuse ends, which ends the bomb's frame (false). +bool Entity_Bomb::fuse_update(Entity_Player* spawner) { - reconstruction_missing("Entity_Bomb::Render 006a5a60"); + bool isRemoteSet = spawner && spawner->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_REMOTE_DETONATOR); + if (explosionCountdown >= 1 && !(spawnerType == ENTITY_PLAYER && isRemoteSet)) + { + explosionCountdown--; + flag_check(*this, TEAR_ATTRACTOR, "Entity_Bomb::Update 006a24d0: Strange Attractor (Game::AttractEntities)"); + + bool isTroll = variant == BOMB_TROLL || variant == BOMB_SUPERTROLL || variant == BOMB_HOT || + variant == BOMB_GOLDENTROLL; + bool isGigaTroll = variant == BOMB_GIGA && spawnerType != ENTITY_PLAYER && !IsFriendly(); + if (!g_game->playerManager.AnyoneHasTrinket(TRINKET_SAFETY_SCISSORS) || explosionCountdown != 0 || + !(isTroll || isGigaTroll)) + return true; + + Remove(); + grid_sound_play(SOUND_SAFETY_SCISSORS); + int kind = variant == BOMB_SUPERTROLL ? BOMB_PICKUP_DOUBLE + : variant == BOMB_GOLDENTROLL ? BOMB_PICKUP_GOLDEN + : variant == BOMB_GIGA ? BOMB_PICKUP_GIGA + : BOMB_PICKUP_TROLL; + Entity* pickup = g_game->Spawn({.position = pos, .velocity = velocity, .subType = kind, .type = ENTITY_PICKUP, + .variant = PICKUP_BOMB, .seed = Random()}); + if (const AnimationData* data = pickup->sprite.animState.animData) + pickup->sprite.animState.SetFrameFloat((float)(data->length - SCISSORS_BOMB_FRAMES_LEFT)); + g_game->Spawn({.position = pos, .subType = 1, .type = ENTITY_EFFECT, .variant = POOF01_EFFECT, .seed = Random()}); + return false; + } + + bool isRemoteHeld = !isFetus && spawner && spawner->HasCollectible(COLLECTIBLE_REMOTE_DETONATOR) && !isRemoteSet && + spawnerType == ENTITY_PLAYER; + if (!isRemoteHeld) explode(spawner); + return true; } -// 006a5f00 -bool Entity_Bomb::HandleCollision(Entity*, bool) +// Blows the bomb up: the explosion, its tear effects, the explode animation, and Blasting Cap's chance of a bomb. A +// golden troll bomb lights again. +void Entity_Bomb::explode(Entity_Player* spawner) { - reconstruction_missing("Entity_Bomb::HandleCollision 006a5f00"); + TearFlags flags = tearFlags; + if (variant == BOMB_GIGA || variant == BOMB_ROCKET_GIGA) + { + flags.set(TEAR_GIGA_BOMB); + updateDelay = GIGA_UPDATE_DELAY; + } + explosion_effects({.tearFlags = flags, .color = sprite.color, .position = pos, .source = this, + .damageFlags = DAMAGE_EXPLOSION | DAMAGE_IGNORE_ARMOR, .damage = explosionDamage, + .radiusMultiplier = radiusMultiplier}); + flag_check(*this, TEAR_SCATTER_BOMB, "Entity_Bomb::Update 006a24d0: Scatter Bombs' bomblets"); + flag_check(*this, TEAR_GHOST_BOMB, "Entity_Bomb::Update 006a24d0: Ghost Bombs' ghost"); + + isDead = true; + if (pitfallState == 0) sprite.Play("Explode"); + flag_check(*this, TEAR_STICKY, "Entity_Bomb::Update 006a24d0: Sticky Bombs' spiders"); + if (variant != BOMB_THROWABLE && spawner && spawner->HasTrinket(TRINKET_BLASTING_CAP)) + { + RNG& rng = spawner->GetTrinketRNG(TRINKET_BLASTING_CAP); + if (rng.RandomInt(BLASTING_CAP_CHANCE / spawner->GetTrinketMultiplier(TRINKET_BLASTING_CAP)) == 0) + g_game->Spawn({.position = pos, .subType = 1, .type = ENTITY_PICKUP, .variant = PICKUP_BOMB, .seed = Random()}); + } + + if (variant == BOMB_GOLDENTROLL) + { + isDead = false; + explosionCountdown = (int)dropRNG.RandomInt(GOLDEN_FUSE_EXTRA) + GOLDEN_FUSE; + sprite.Play("Appear", PLAY_FORCED); + if (sprite.animState.animData) sprite.animState.SetFrameFloat(GOLDEN_APPEAR_FRAME); + RNG directionRng = {dropRNG.Next(), 3, 1, 14}; + float angle = directionRng.RandomFloat() * RANDOM_HALF_TURN; + angle += angle; + float speed = dropRNG.RandomFloat() * GOLDEN_SPEED_EXTRA + GOLDEN_SPEED; + velocity = vector_make(speed * std::cos(angle), speed * std::sin(angle)); + scatterTimer = GOLDEN_SCATTER_FRAMES; + } + bool isVirtuesWisp = !HasEntityFlags(FLAG_NO_REWARD) && spawner && spawnerEntity.get() == spawner && + spawner->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_REMOTE_DETONATOR) && + spawner->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES); + if (isVirtuesWisp) reconstruction_missing("Entity_Bomb::Update 006a24d0: the Remote Detonator's wisp"); } -// 006a6f10 +// The rest of the frame: a super troll bomb chases the nearest player, the cooldowns run, the bomb turns solid, falls +// in a crawlspace, the brimstone bomb beeps, the drop sound plays and the costumes animate. +void Entity_Bomb::late_update() +{ + if (variant == BOMB_SUPERTROLL) + { + Entity_Player* nearest = game_nearest_player(pos); + Vector toward = vector_sub(vector_add(nearest->pos, vector_scale(nearest->velocity, CHASE_LOOKAHEAD)), pos); + if (vector_length_squared(toward) < CHASE_RANGE * CHASE_RANGE) + velocity = vector_add(velocity, vector_scale(vector_normalized(toward), CHASE_ACCELERATION)); + velocity = vector_scale(velocity, CHASE_FRICTION); + if (g_game->frameCount - spawnFrame < CHASE_START_FRAMES) friction *= CHASE_FRICTION; + } + if (collisionCooldown > 0) collisionCooldown--; + if (parentCollisionCooldown > 0) parentCollisionCooldown--; + if (scatterTimer > 0) scatterTimer--; + + int age = g_game->frameCount - spawnFrame; + if (age > SOLID_AFTER_FRAMES && entityCollisionClass == ENTCOLL_PLAYERONLY) entityCollisionClass = ENTCOLL_ALL; + if (explosionCountdown < age && entityCollisionClass == ENTCOLL_NONE) entityCollisionClass = ENTCOLL_ALL; + if (g_game->room->roomType == ROOM_DUNGEON) velocity.y += CRAWLSPACE_GRAVITY; + if (variant == BOMB_BRIMSTONE) + { + if (posOffset.y >= 0 && fallSpeed >= 0) friction *= BRIMSTONE_FRICTION; + if (sprite.animState.animData && sprite.animState.IsEventTriggered("Beep")) + grid_sound_play(SOUND_BEEP, {.pitch = BEEP_PITCH}); + } + if (!stickyTarget && entityGridCollisionClass == GRIDCOLL_NONE) entityGridCollisionClass = GRIDCOLL_GROUND; + if (!isVisible) + { + entityCollisionClass = ENTCOLL_NONE; + entityGridCollisionClass = GRIDCOLL_NONE; + collisionCooldown = COLLISION_COOLDOWN; + } + if (sprite.animState.animData && sprite.animState.IsEventTriggered("DropSound")) + { + if (variant == BOMB_GIGA) + { + g_manager->sfxManager.Play(SOUND_FETUS_LAND, {.frameDelay = DROP_SOUND_DELAY, .pitch = GIGA_DROP_PITCH}); + game_shake_screen(GIGA_DROP_SHAKE); + } + else + { + LandSound land = land_sound_get(*this); + g_manager->sfxManager.Play(land.id, {.volume = land.volume, .frameDelay = DROP_SOUND_DELAY}); + } + } + if (isHasCostumes) + for (ANM2& costume : bombCostumesSprites) costume.Update(); + lua_callback_check(MC_POST_BOMB_UPDATE, "LuaEngine::PostBombUpdate 00861f80"); +} + +// 006a5a60 Draws the bomb at its place: with costumes, the back costume, the bomb, then the others, each following the +// bomb's first layer. +// The original reads the first layer's frame without checking for one. Without one, the costumes are left out. +void Entity_Bomb::Render(const Vector& offset) +{ + if (!isExists || !isVisible) return; + if (isLoadCostumes) update_sparks(); + + renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset); + SpriteDraw draw = {renderPosition, {}, {}}; + const AnimationFrame* frame = isHasCostumes ? sprite.animState.GetLayerFrame(0) : nullptr; + if (!frame) + { + sprite.Render(draw); + lua_callback_check(MC_POST_BOMB_RENDER, "LuaEngine::PostBombRender 00862060"); + return; + } + + Vector local = vector_make((frame->pos.x + sprite.offset.x) * sprite.scale.x, + (sprite.offset.y + frame->pos.y) * sprite.scale.y); + float angle = sprite.rotation * DEGREES_TO_RADIANS; + Vector turned = vector_make(std::cos(angle) * local.x - std::sin(angle) * local.y, + std::cos(angle) * local.y + std::sin(angle) * local.x); + if (sprite.isFlipX) turned.x = -turned.x; + if (sprite.isFlipY) turned.y = -turned.y; + ColorMod color = sprite.color; + color_multiply(color, frame->color); + SpriteDraw costumeDraw = {vector_add(renderPosition, turned), {}, {}}; + + for (int i = 0; i < BOMB_COSTUME_LAYERS; i++) + { + ANM2& costume = bombCostumesSprites[i]; + if (costume.isLoaded && frame->isVisible) + { + costume.rotation = sprite.rotation + frame->rotation; + costume.scale = vector_make(sprite.scale.x * frame->scale.x, sprite.scale.y * frame->scale.y); + costume.color = color; + costume.Render(costumeDraw); + } + if (i == 0) sprite.Render(draw); + } + lua_callback_check(MC_POST_BOMB_RENDER, "LuaEngine::PostBombRender 00862060"); +} + +// Whether a rocket flies past what it meets: anything but enemies, or a friendly enemy. +static bool is_passed_by_rocket(Entity& collider) +{ + switch (collider.type) + { + case ENTITY_PLAYER: + case ENTITY_FAMILIAR: + case ENTITY_KNIFE: + return true; + default: + return collider.IsFriendly(); + } +} + +// Pushes an enemy the bomb hit and did not kill off it, reflecting a head-on hit, by their masses. +static void enemy_push(Entity_Bomb& bomb, Entity& collider) +{ + if (collider.HasEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK)) return; + + Vector away = vector_sub(collider.pos, bomb.pos); + float distance = vector_length(away); + if (distance < PUSH_MIN_DISTANCE) return; + + Vector relative = vector_sub(bomb.velocity, collider.velocity); + if (vector_length(relative) > (collider.size + bomb.size) * 0.5f && vector_dot(relative, away) < 0) + { + float along = vector_dot(vector_normalized(relative), vector_normalized(away)); + away = vector_add(away, vector_scale(away, along + along)); + distance = vector_length(away); + } + float share = bomb.collision_mass_get(&collider) / (collider.collision_mass_get(&bomb) + bomb.collision_mass_get(&collider)); + float speed = vector_length(vector_sub(collider.velocity, bomb.velocity)); + collider.velocity = vector_add(collider.velocity, vector_scale(away, speed * share / distance)); +} + +// 006a5f00 Meets another entity: falling bombs and rockets pass tears and bombs, bombs pass pickups and slots, players +// nudge it, its hit damages enemies once, and something low slows both down. +bool Entity_Bomb::HandleCollision(Entity* collider, bool isLow) +{ + LuaResult result = lua_engine_get().PreBombCollision(this, collider, isLow); + if (result != LUA_RESULT_NIL) return result == LUA_RESULT_TRUE; + if (pitfallState != 0) return true; + + int type = collider->type; + if ((type == ENTITY_TEAR || type == ENTITY_BOMB) && (posOffset.y <= FALL_LOW || fallSpeed < 0 || IsRocket())) + return true; + if (isFetus && type == ENTITY_TEAR && static_cast(collider)->tearFlags[TEAR_FETUS_FLAG]) return true; + if (IsRocket() && g_game->frameCount - spawnFrame < 2) return true; + + if (type == ENTITY_PICKUP || type == ENTITY_SLOT) + { + if (!IsRocket()) return true; + if (type == ENTITY_PICKUP && (collider->variant != PICKUP_BOMBCHEST || collider->subtype != 1)) return true; + if (type == ENTITY_SLOT && collider->isDead) return true; + } + if (type == ENTITY_HORNFEL || type == ENTITY_DARK_ESAU) return true; + if (type == ENTITY_VISAGE && collider->variant == VISAGE_MASK_VARIANT) return true; + if (type == ENTITY_COLOSTOMIA && spawnerType == ENTITY_COLOSTOMIA) return true; + if (IsRocket() && is_passed_by_rocket(*collider)) return true; + + bool isDeathmatch = g_game->deathmatchManager.is_active(); + if (type == ENTITY_PLAYER && (!isDeathmatch || IsDescendantOf(collider))) + { + if (parent && parent->type == ENTITY_FAMILIAR) return true; + if (collisionCooldown > 0) + { + collisionCooldown = COLLISION_COOLDOWN; + return true; + } + velocity = vector_add(velocity, vector_scale(collider->velocity, PLAYER_PUSH)); + } + + bool isHitter = (type != ENTITY_PLAYER && type != ENTITY_PROJECTILE) || + (isDeathmatch && type == ENTITY_PLAYER && !IsDescendantOf(collider)); + if (isHitter) + { + if (IsRocket() || tearFlags[TEAR_PIERCING]) + { + if (EntityList::HitListContains(hitList, *collider)) return true; + uint32_t hitIndex = collider->GetHitListIndex(); + auto at = std::ranges::lower_bound(hitList, hitIndex); + if (at == hitList.end() || *at != hitIndex) hitList.insert(at, hitIndex); + } + if (collider == parent.get() && parentCollisionCooldown > 0) + { + parentCollisionCooldown = COLLISION_COOLDOWN; + return true; + } + bool isUnfiredBomb = type == ENTITY_BOMB && !static_cast(collider)->isFetus && isFetus; + bool isTrigger = collider->IsVulnerableEnemy(nullptr) || type == ENTITY_SLOT || isUnfiredBomb; + bool isBlownOnTouch = tearFlags[TEAR_EXPLOSIVE] || (g_game->room->roomType == ROOM_DUNGEON && scatterTimer < 1); + if (IsRocket() || (isTrigger && isBlownOnTouch)) explosionCountdown = 0; + + bool isStickyEnemy = tearFlags[TEAR_STICKY] && collider->IsEnemy(); + if (isStickyEnemy && !collider->isDead && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && !stickyTarget) + { + stickyTarget = collider; + targetPosition = vector_sub(pos, collider->pos); + } + bool isPlainHit = !tearFlags[TEAR_STICKY] && !tearFlags[TEAR_EXPLOSIVE]; + if (isPlainHit && collider->IsVulnerableEnemy(nullptr) && !collider->isDead && collisionDamage > 0) + { + collider->TakeDamage(collisionDamage, 0, EntityRef(this), HIT_COUNTDOWN); + if (collider->HasMortalDamage() || tearFlags[TEAR_PIERCING]) + { + enemy_push(*this, *collider); + return true; + } + collisionDamage = 0; + } + } + + if (type == ENTITY_LITTLE_HORN && collider->spawnerType == ENTITY_BIG_HORN) return true; + if (collider->HasEntityFlags(FLAG_FRIENDLY) || type == ENTITY_PITFALL) return true; + if (isLow && type == ENTITY_PROJECTILE) return true; + if (isLow && type == ENTITY_BOMB && isFetus) return true; + if (type == ENTITY_TEAR && collider->spawnerType != ENTITY_PLAYER && isFetus) return true; + if (type == ENTITY_KNIFE) return true; + if (!isLow || type == ENTITY_PIN) return false; + if (type == ENTITY_BOMB && static_cast(collider)->IsRocket()) return false; + + collider->velocity = vector_scale(collider->velocity, LOW_COLLIDER_SLOW); + velocity = vector_scale(velocity, LOW_BOMB_SLOW); + return false; +} + +// A bomb sprite's file at its size: its name with the size's digit before the extension. +// The original throws on a path shorter than the extension. Here it is kept as it is. +static std::string sized_path(const std::string& path, char size) +{ + if (path.size() < ANM2_EXTENSION_SIZE) return path; + size_t stem = path.size() - ANM2_EXTENSION_SIZE; + return path.substr(0, stem) + size + path.substr(stem); +} + +// 006a69e0 A spritesheet as the first suffix that has a file of its own changes it (before the extension, as mods +// redirect it), or the sheet itself. +// The original throws on a path shorter than the extension. Here it is kept as it is. +static std::string suffixed_sheet_get(const std::string& path, const std::vector& suffixes) +{ + if (suffixes.empty() || path.size() < EXTENSION_SIZE) return path; + + size_t stem = path.size() - EXTENSION_SIZE; + for (const std::string& suffix : suffixes) + { + std::string candidate = g_manager->modManager.TryRedirectPath(path.substr(0, stem) + suffix + path.substr(stem)); + std::error_code error; + if (std::filesystem::exists(resource_path(candidate), error)) return candidate; + } + return path; +} + +// Loads a sprite with its spritesheets swapped for the suffixed ones. +static void costume_sprite_load(ANM2& sprite, const std::string& path, const std::vector& suffixes) +{ + sprite.Load(path, GRAPHICS_DEFER); + for (int i = 0; i < (int)sprite.layerStates.size(); i++) + { + const LayerData* layer = sprite.layerStates[i].layerData; + sprite.ReplaceSpritesheet(i, suffixed_sheet_get(layer ? layer->spriteSheetPath : std::string(), suffixes)); + } + sprite.LoadGraphics(); +} + +// 006a6f10 Dresses the bomb as bombcostumes.xml's rules for its variant and tear effects say: the body sprite and the +// costume layers at the bomb's size, their sheets swapped by the rules' suffixes, keeping the animation it showed. A +// variant without rules only scales the sprite, big bombs a third less. void Entity_Bomb::update_sparks() { - reconstruction_missing("Entity_Bomb::update_sparks 006a6f10"); + isHasCostumes = false; + isLoadCostumes = false; + for (ANM2& costume : bombCostumesSprites) + if (costume.isLoaded) costume.Reset(); + + auto rules = g_manager->itemConfig.bombCostumes.find(variant); + if (rules == g_manager->itemConfig.bombCostumes.end()) + { + bool isBig = variant == BOMB_MR_MEGA || variant == BOMB_POISON_BIG || variant == BOMB_BIG || variant == BOMB_DECOY; + float spriteScale = isBig ? scale / BIG_BOMB_SCALE : scale; + sprite.scale = vector_make(spriteScale, spriteScale); + return; + } + + std::string animation = sprite.animState.animData ? sprite.animState.animData->name : std::string(); + float frame = sprite.animState.animFrame; + bool isPlaying = sprite.animState.animData && sprite.animState.isPlaying; + char size = scale <= 0.5f ? '0' : scale <= 0.75f ? '1' : scale <= 1.1f ? '2' : '3'; + sprite.scale = vector_make(1, 1); + + std::string bodyPath; + std::array costumePaths; + std::string suffix; + std::string suffix2; + for (const BombCostumeRule& rule : rules->second) + { + if ((tearFlags & rule.includeFlags) != rule.includeFlags || (tearFlags & rule.excludeFlags).any()) continue; + + if (!rule.body.empty()) bodyPath = sized_path(rule.body, size); + const std::string* layers[] = {&rule.back, &rule.body2, &rule.front, &rule.front2, &rule.overlay}; + for (int i = 0; i < BOMB_COSTUME_LAYERS; i++) + if (!layers[i]->empty()) costumePaths[i] = sized_path(*layers[i], size); + if (!rule.suffix.empty()) suffix = rule.suffix; + if (!rule.suffix2.empty()) suffix2 = rule.suffix2; + } + + std::vector suffixes; + if (!suffix.empty() && !suffix2.empty()) suffixes.push_back(suffix + suffix2); + if (!suffix2.empty()) suffixes.push_back(suffix2); + if (!suffix.empty()) suffixes.push_back(suffix); + + if (!bodyPath.empty()) + { + costume_sprite_load(sprite, bodyPath, suffixes); + if (LayerState* sparks = sprite.GetLayer("sparks")) sparks->bitflags |= ANIM_RENDER_UNTINTED; + } + for (int i = 0; i < BOMB_COSTUME_LAYERS; i++) + { + if (costumePaths[i].empty()) continue; + + ANM2& costume = bombCostumesSprites[i]; + costume_sprite_load(costume, costumePaths[i], suffixes); + costume.Play(costume.GetDefaultAnimationName(), PLAY_FORCED); + isHasCostumes = true; + } + + if (animation.empty()) return; + if (isPlaying) + { + sprite.Play(animation, PLAY_FORCED); + if (sprite.animState.animData) sprite.animState.SetFrameFloat(frame); + } + else if (sprite.SetAnimation(animation) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(frame); + sprite.animState.isPlaying = false; + } } diff --git a/src/entity_bomb.h b/src/entity_bomb.h index 1e30214..f8dbdc6 100644 --- a/src/entity_bomb.h +++ b/src/entity_bomb.h @@ -2,13 +2,57 @@ #include "entity.h" #include "anm2.h" +#include "entity_tear.h" #include #include -// The costume layers a bomb draws its holder's item looks with. +// The costume layers a bomb draws its holder's item looks with: behind the body, then four over it. constexpr int BOMB_COSTUME_LAYERS = 5; -// Construction and destruction (006a1f30) are the defaults. +// The bombs (Lua's BombVariant). +enum BombVariant : int +{ + BOMB_NORMAL, + BOMB_BIG, + BOMB_DECOY, + BOMB_TROLL, + BOMB_SUPERTROLL, + BOMB_POISON, + BOMB_POISON_BIG, + BOMB_SAD, + BOMB_HOT, + BOMB_BUTT, + BOMB_MR_MEGA, + BOMB_BOBBY, + BOMB_GLITTER, + BOMB_THROWABLE, + BOMB_SMALL, + BOMB_BRIMSTONE, + BOMB_SAD_BLOOD, + BOMB_GIGA, + BOMB_GOLDENTROLL, + BOMB_ROCKET, + BOMB_ROCKET_GIGA +}; + +// An explosion (the arguments of Game::BombExplosionEffects and Game::BombDamage): where, from what, the tear effects +// it carries, the damage it deals and its flags, and how far it reaches. BombDamage takes the radius itself, +// BombExplosionEffects works it out from the damage and the multiplier. A damage source hurts the source too. +struct Explosion +{ + TearFlags tearFlags{}; + ColorMod color = COLOR_DEFAULT; + Vector position{}; + Entity* source = nullptr; + uint64_t damageFlags = DAMAGE_EXPLOSION; + float damage = 0; + float radius = 0; + float radiusMultiplier = 1; + bool isDamageSource = false; + bool isLineCheck = true; +}; + +// Construction and destruction (006a1e80, 006a1f30) are the defaults. // Field accessors (004316a0, 005cd560, 0060cdc0) are the public fields. // A bomb (Lua's EntityBomb): its fuse, the explosion it deals, the tear effects it carries, its fall and bounce, and // the costume layers its holder's items add. @@ -16,7 +60,7 @@ struct Entity_Bomb : Entity { std::array bombCostumesSprites; std::vector hitList; - TearFlags tearFlags; + TearFlags tearFlags{}; EntityPtr stickyTarget; float explosionDamage = 0; float fallAcceleration = 0; @@ -47,4 +91,16 @@ struct Entity_Bomb : Entity void SetExplosionCountdown(int countdown); bool IsRocket(); void update_sparks(); + +private: + void fall_update(bool isBouncy); + void pulse_update(Entity_Player* spawner); + bool fuse_update(Entity_Player* spawner); + void explode(Entity_Player* spawner); + void late_update(); }; + +void explosion_damage(Explosion explosion); +void explosion_effects(const Explosion& explosion); +void explosion_tear_flag_effects(const Explosion& explosion); +Entity* bomb_crater_spawn(const Vector& position, Entity* spawner, float scale); diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 83645e9..480ffb4 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -245,18 +245,6 @@ static Entity_Effect* effect_spawn(int variant, int subType, Vector position, Ve return static_cast(effect); } -// Color::__mul: tints multiply, colorizes average (or one takes the other's while it has none), offsets add. -static ColorMod color_multiply(ColorMod color, const ColorMod& other) -{ - for (int i = 0; i < 4; i++) color._tint[i] *= other._tint[i]; - bool isOtherColorized = other._colorize[0] + other._colorize[1] + other._colorize[2] != 0; - bool isColorized = color._colorize[0] + color._colorize[1] + color._colorize[2] != 0; - for (int i = 0; isOtherColorized && i < 4; i++) - color._colorize[i] = isColorized ? (color._colorize[i] + other._colorize[i]) * HALF_F : other._colorize[i]; - for (int i = 0; i < 3; i++) color._offset[i] += other._offset[i]; - return color; -} - // A random angle of a full turn, as the bursts draw it. static float random_angle() { @@ -597,7 +585,8 @@ static Entity_Effect* gib_blood_spawn(const GibSpawn& gibs, int kind, uint32_t s } else { - ColorMod tinted = color_multiply(gibs.color, POISON_GIB_TINT); + ColorMod tinted = gibs.color; + color_multiply(tinted, POISON_GIB_TINT); gib->SetColor(kind == 0 ? tinted : gibs.color, -1, COLOR_PRIORITY_TOP, false, true); gib->splatColor = tinted; } diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 8e29ba9..a1ae2d9 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -1,106 +1,46 @@ #include "entity_effect.h" +#include "entity_effect_ambient.h" +#include "entity_effect_combat.h" #include "entity_list.h" -#include "entity_player.h" -#include "entity_tear.h" #include "game.h" #include "log.h" #include "lua_engine.h" #include "manager.h" #include "room.h" -#include "room_config.h" #include "sfx_manager.h" #include #include -#include // The creep variants the players leave (holy water trail, black, red, white, holy water, green, Lemon Mishap, Lemon // Party, 204, Black Powder, milk, Black Powder's pentagram). constexpr std::array PLAYER_CREEPS = {54, 45, 46, 44, 37, 53, 32, 78, 204, 92, 90, 93}; -constexpr int EFFECT_BLOOD_SPLAT = 7; -constexpr int EFFECT_BULLET_POOF = 11; -constexpr int EFFECT_TEAR_POOF_A = 12; -constexpr int EFFECT_TEAR_POOF_B = 13; -constexpr int EFFECT_RIPPLE_POOF = 14; -constexpr int EFFECT_TEAR_POOF_SMALL = 79; -constexpr int EFFECT_TEAR_POOF_VERYSMALL = 80; -constexpr int EFFECT_IMPACT = 97; +// The floor stains a crawlspace never shows: blood, craters, creep of every kind, footprints and puddles. +constexpr std::array CRAWLSPACE_HIDDEN_EFFECTS = {7, 18, 22, 23, 24, 25, 26, 32, 37, 44, 45, 46, 53, + 54, 56, 77, 78, 89, 90, 92, 93, 94, 100, 169, 195, 204}; + +// The creep a familiar's wave of creep (familiar variant 125) leaves, which keeps its chain going. +constexpr std::array WAVE_CHAIN_CREEPS = {53, 44, 46, 45, 32, 204}; +constexpr int FAMILIAR_CREEP_WAVE = 125; + +constexpr int EFFECT_BLOOD_PARTICLE = 5; +constexpr int EFFECT_HUSH_LASER = 96; +constexpr int EFFECT_HUSH_LASER_UP = 101; +constexpr int EFFECT_BLACK_POWDER = 92; constexpr int EFFECT_BOOMERANG = 60; constexpr int EFFECT_PORTAL_TELEPORT = 161; constexpr int EFFECT_TIMER = 119; constexpr int EFFECT_ENEMY_SOUL = 179; constexpr int EFFECT_ANIMA_CHAIN = 193; constexpr int EFFECT_REDEMPTION = 185; -constexpr int EFFECT_BLOOD_EXPLOSION = 2; -constexpr int EFFECT_POOF01 = 15; -constexpr int EFFECT_POOF02 = 16; -constexpr int EFFECT_TINY_FLY = 33; +constexpr int EFFECT_LIGHT = 121; -// The variants whose Init, Update and Render are reconstructed: the tear poofs, the blood stains, the poofs and the -// ambient tiny fly. -constexpr std::array EFFECT_RECONSTRUCTED_VARIANTS = { - EFFECT_BLOOD_SPLAT, EFFECT_BULLET_POOF, EFFECT_TEAR_POOF_A, EFFECT_TEAR_POOF_B, - EFFECT_RIPPLE_POOF, EFFECT_TEAR_POOF_SMALL, EFFECT_TEAR_POOF_VERYSMALL, EFFECT_IMPACT, - EFFECT_POOF01, EFFECT_POOF02, EFFECT_TINY_FLY}; - -// The animations a poof plays by its subtype: POOF01 from 1 to 3, POOF02's lava splash at random. -constexpr std::array POOF01_ANIMATIONS = {"Poof2", "Poof_Small", "Poof", "Poof_Large"}; -constexpr std::array LAVA_SPLASH_ANIMATIONS = {"Poof0", "Poof1", "Poof2"}; -constexpr int POOF01_SUBTYPE_LAST = 3; -constexpr int POOF02_LAVA_SPLASH = 66; -constexpr int POOF02_LAVA_SPLASH_LARGE = 67; -constexpr int POOF_RENDER_Z = 8000; -constexpr uint32_t LAVA_SPLASH_SHIFT = 4; - -// The tiny fly: white in the Cathedral, its own color in Dross, how it wanders, flees the nearest player within -// range, dies to tears, knives and fires, and drops down in circles when dead. -constexpr int STAGE_ID_CATHEDRAL = 15; -constexpr int BACKDROP_DROSS = 45; -constexpr int ENTITY_KNIFE_TYPE = 8; -constexpr int FLY_WANDER_ODDS = 5; -constexpr int FLY_JITTER_FRAMES = 5; -constexpr float FLY_MASS = 1; -constexpr float FLY_FRICTION = 0.98f; -constexpr float FLY_DEAD_FRICTION = 0.8f; -constexpr float FLY_PULL = 0.5f; -constexpr float FLY_JITTER = 0.9f; -constexpr float FLY_FLEE_RANGE = 60; -constexpr float FLY_FLEE_PUSH = -0.2f; -constexpr float FLY_HIT_RADIUS = 0.5f; -constexpr float FLY_KNIFE_REACH = 1.5f; -constexpr float FLY_FIRE_REACH = 2; -constexpr float FLY_FALL_STEP = 0.25f; -constexpr float FLY_FALL_HEIGHT = 16; -constexpr float FLY_CIRCLE_SPEED = 15; -constexpr float FLY_CIRCLE_RADIUS = 3; -constexpr float FLY_CLAMP_MARGIN = 2; -constexpr float FLY_SPLAT_SCALE = 0.1f; -constexpr float FLY_BURST_SCALE = 0.3f; -constexpr float FLY_BURST_RISE = -16; -constexpr float MIN_DISTANCE = 0.01f; -constexpr float RANDOM_UNIT = 2.3283064e-10f; -constexpr float RANDOM_HALF_TURN = 3.14f; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; -// The poofs that turn with their rotation. -constexpr std::array EFFECT_TURNED_POOFS = {EFFECT_TEAR_POOF_A, EFFECT_TEAR_POOF_B, EFFECT_TEAR_POOF_SMALL, - EFFECT_TEAR_POOF_VERYSMALL, EFFECT_IMPACT}; - -// The blood stain animations by the scale it was spawned at: the first whose limit is above it, the last past all. -constexpr std::array STAIN_SCALE_LIMITS = {0.4f, 0.6f, 0.8f, 1.2f, 2.0f}; -constexpr std::array STAIN_ANIMATIONS = {"Size1BloodStains", "Size2BloodStains", "Size3BloodStains", - "Size4BloodStains", "Size5BloodStains", "Size6BloodStains"}; -constexpr float STAIN_ALPHA_MIN = 0.5f; -constexpr float STAIN_ALPHA_STEP = 0.1f; -constexpr int STAIN_ALPHA_STEPS = 6; - -// The ripple poof's animations for small spawn scales, which it draws larger. -constexpr float RIPPLE_TINY_SCALE = 0.5f; -constexpr float RIPPLE_SMALL_SCALE = 0.75f; -constexpr float RIPPLE_TINY_GROWTH = 2; -constexpr float RIPPLE_SMALL_GROWTH = 1.33333f; +// The Hourglass slows Hush's lasers from full speed to half as its effect's cooldown runs from 0 to 30. +constexpr int COLLECTIBLE_HOURGLASS = 66; +constexpr float HOURGLASS_COOLDOWN_SPAN = 30; +constexpr float HOURGLASS_SLOWEST = 0.5f; constexpr float PAUSE_VELOCITY_DECAY = 0.6f; -constexpr float RIGHT_ANGLE = 90; constexpr int SOUND_BOOMERANG_LOOP = 837; constexpr int SOUND_PORTAL_ENTITY_LOOP = 846; constexpr int SOUND_CHAIN_LOOP = 503; @@ -149,9 +89,9 @@ bool Entity_Effect::IsPlayerCreep(int effectVariant) return std::find(PLAYER_CREEPS.begin(), PLAYER_CREEPS.end(), effectVariant) != PLAYER_CREEPS.end(); } -// 005cdb20 Starts the effect from its config's sprite with no timeout, rotation or extra data. A crawlspace removes -// its blood stains at once. The tear poofs face a random quarter turn and the ripple a random side. -// Only the tear poofs and the blood stains are reconstructed yet. +// 005cdb20 Starts the effect from its config's sprite with no timeout, rotation or extra data, then hands it to its +// variant. A crawlspace removes its floor stains at once, and a variant that removes itself skips its graphics and +// Lua's callback. void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { extraData.reset(); @@ -175,30 +115,18 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u maxRadius = 0; damageSource = 0; varData = {}; - if (!is_listed(EFFECT_RECONSTRUCTED_VARIANTS, variant)) - reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); - if (g_game->room->roomType == ROOM_DUNGEON && variant == EFFECT_BLOOD_SPLAT) + if (g_game->room->roomType == ROOM_DUNGEON && is_listed(CRAWLSPACE_HIDDEN_EFFECTS, variant)) { isVisible = false; return Remove(); } - if (variant == EFFECT_BLOOD_SPLAT) sortingLayer = SORTING_BACKGROUND; - if (variant == EFFECT_RIPPLE_POOF) - { - sortingLayer = SORTING_BACKGROUND; - sprite.isFlipX = Random() & 1; - } - entityGridCollisionClass = GRIDCOLL_NONE; + entityGridCollisionClass = variant == EFFECT_BLOOD_PARTICLE ? GRIDCOLL_WALLS : GRIDCOLL_NONE; entityCollisionClass = ENTCOLL_NONE; - if (is_listed(EFFECT_TURNED_POOFS, variant)) - { - rotation = (float)(Random() & 3) * RIGHT_ANGLE; - isUnknown176 = true; - } - if (variant == EFFECT_IMPACT) sprite.isFlipX = !(Random() & 1); - if (variant == EFFECT_POOF01 || variant == EFFECT_POOF02) poof_init(); - if (variant == EFFECT_TINY_FLY) tiny_fly_init(); + if (is_ambient_effect(variant)) ambient_effect_init(*this); + else if (is_combat_effect(variant)) combat_effect_init(*this); + else reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); + if (!isExists) return; sprite.LoadGraphics(); if (g_game->deathmatchManager.is_active()) @@ -207,10 +135,19 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u } // 005d4380 Runs the effect for a frame at the room's time scale, held in place while paused and kept on its parent -// while following it, then counts its timeout down to its death. +// while following it, then runs its variant and counts its timeout down to its death. void Entity_Effect::Update() { speedMultiplier = g_game->room->GetTimeScale(this); + if (variant == EFFECT_HUSH_LASER || variant == EFFECT_HUSH_LASER_UP) + { + if (TemporaryEffect* hourglass = g_game->room->temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOURGLASS)) + { + float t = std::clamp((float)hourglass->cooldown / HOURGLASS_COOLDOWN_SPAN, 0.0f, 1.0f); + speedMultiplier *= (HOURGLASS_SLOWEST - 1) * t + 1; + } + } + if (variant == EFFECT_BLACK_POWDER) pauseTimer = 0; if (pauseTimer != 0) { uint64_t savedFlags = flags; @@ -237,246 +174,22 @@ void Entity_Effect::Update() { velocity = {}; isFollowing = false; + if (variant == EFFECT_LIGHT && timeout < 0) SetTimeout(state); } - if (variant == EFFECT_BLOOD_SPLAT) stain_update(); - else if (variant == EFFECT_TINY_FLY) tiny_fly_update(); - else poof_update(); + EffectUpdateEnd end = EFFECT_UPDATE_FINISH; + if (is_ambient_effect(variant)) end = ambient_effect_update(*this); + else if (is_combat_effect(variant)) end = combat_effect_update(*this); + else reconstruction_missing("Entity_Effect::Update 005d4380: this effect variant"); + if (end == EFFECT_UPDATE_RETURN) return; + if (timeout > 0 && --timeout < 1) isDead = true; pausePosition = pos; + if (spawnerType == ENTITY_FAMILIAR && spawnerVariant == FAMILIAR_CREEP_WAVE && is_listed(WAVE_CHAIN_CREEPS, variant)) + update_wave_chain(); lua_engine_get().PostEffectUpdate(this); } -// A poof's animation by its subtype. POOF01 and POOF02's large kinds draw over everything, POOF02's small kinds lie -// on the floor outside the crawl space, and its lava splashes face a seeded side. -void Entity_Effect::poof_init() -{ - if (variant == EFFECT_POOF01) - { - if (subtype >= 1 && subtype <= POOF01_SUBTYPE_LAST) sprite.Play(POOF01_ANIMATIONS[subtype]); - renderZOffset = POOF_RENDER_Z; - return; - } - - if (subtype == 1 || subtype == 3) - { - if (g_game->room->roomType != ROOM_DUNGEON) sortingLayer = SORTING_BACKGROUND; - sprite.Play("Poof"); - } - else if (subtype == 2 || subtype == 4 || subtype == 5) - { - renderZOffset = POOF_RENDER_Z; - sprite.Play("Poof"); - } - else if (subtype == POOF02_LAVA_SPLASH || subtype == POOF02_LAVA_SPLASH_LARGE) - { - RNG rng = rng_make(initSeed, LAVA_SPLASH_SHIFT); - uint32_t roll = subtype == POOF02_LAVA_SPLASH ? rng.Next() % LAVA_SPLASH_ANIMATIONS.size() : 0; - sprite.Play(subtype == POOF02_LAVA_SPLASH ? LAVA_SPLASH_ANIMATIONS[roll] : "PoofLarge"); - sprite.isFlipX = !(initSeed & 1); - } -} - -// A tiny fly: white in the Cathedral, uncolored in Dross, light and colliding with everything. -void Entity_Effect::tiny_fly_init() -{ - if (RoomConfig::GetStageID((int)g_game->stage, (int)g_game->stageType, (RoomMode)-1) == STAGE_ID_CATHEDRAL) - sprite.Play("White"); - mass = FLY_MASS; - entityCollisionClass = ENTCOLL_ALL; - isUnknown176 = true; - if (g_game->room->backdropType == BACKDROP_DROSS) sprite.color = COLOR_DEFAULT; -} - -// The player nearest a position, the first one on a tie (Game::GetNearestPlayer 00703950, which Game does not -// declare yet). -static Entity_Player* nearest_player_get(const Vector& position) -{ - Entity_Player* nearest = nullptr; - float nearestDistance = 0; - - for (Entity_Player* player : g_game->playerManager.playerList) - { - float dx = position.x - player->pos.x; - float dy = position.y - player->pos.y; - float distance = dy * dy + dx * dx; - if (nearest && distance >= nearestDistance) continue; - nearest = player; - nearestDistance = distance; - } - return nearest; -} - -static float random_unit() -{ - return (float)Random() * RANDOM_UNIT; -} - -static Vector vector_scaled(Vector v, float scale) -{ - return vector_make(v.x * scale, v.y * scale); -} - -static float vector_length(Vector v) -{ - return std::sqrt(v.x * v.x + v.y * v.y); -} - -// Whether an entity of the list stands within reach of a position, reach scaled from its size. -static bool is_within_reach(Entity& entity, const Vector& position, float reach) -{ - float dx = entity.pos.x - position.x; - float dy = entity.pos.y - position.y; - return dx * dx + dy * dy < reach * reach; -} - -// Bursts the fly into a small splash of its blood color. -void Entity_Effect::tiny_fly_burst() -{ - isDead = true; - Entity* burst = g_game->Spawn({vector_make(pos.x, pos.y + FLY_BURST_RISE), {}, nullptr, 0, ENTITY_EFFECT, - EFFECT_BLOOD_EXPLOSION, Random()}); - burst->SetColor(splatColor, -1, 255, false, true); - burst->sprite.scale = vector_make(FLY_BURST_SCALE, FLY_BURST_SCALE); - burst->Update(); - sprite.Stop(); -} - -// A tiny fly's frame: alive it drifts at random, now and then toward its parent or the nearest player, and away -// from a player close by, and bursts on a tear, knife or fire. Dead, it spirals down and splats. It faces its motion -// and stays in the room. -void Entity_Effect::tiny_fly_update() -{ - Entity_Player* player = nearest_player_get(pos); - Vector toPlayer = vector_make(player->pos.x - pos.x, player->pos.y - pos.y); - float distance = vector_length(toPlayer); - Vector direction = vector_scaled(toPlayer, 1 / (distance == 0 ? MIN_DISTANCE : distance)); - EntityList& entities = g_game->room->entityList; - - friction *= FLY_FRICTION; - if (isDead) - { - LayerState& layer = *sprite.GetLayer(0); - if (layer.pos.y <= FLY_FALL_HEIGHT) - { - layer.pos.y += FLY_FALL_STEP; - float side = (float)(index % 2) * 2 - 1; - float angle = (float)g_game->frameCount * FLY_CIRCLE_SPEED * side * DEGREES_TO_RADIANS; - Vector circle = vector_make(std::cos(angle), std::sin(angle)); - circle = vector_scaled(vector_scaled(circle, std::abs(layer.pos.y) / FLY_FALL_HEIGHT), FLY_CIRCLE_RADIUS); - pos = vector_make(pos.x + circle.x, pos.y + circle.y); - friction *= FLY_DEAD_FRICTION; - } - else - { - Entity* splat = g_game->Spawn({pos, {}, nullptr, 0, ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, Random()}); - splat->SetColor(splatColor, -1, 255, false, true); - splat->sprite.scale = vector_make(FLY_SPLAT_SCALE, FLY_SPLAT_SCALE); - splat->Update(); - Remove(); - } - } - - if (!isDead) - { - if (Random() % FLY_WANDER_ODDS == 0) - { - Vector pull = direction; - if (parent) - { - Vector toParent = vector_make(parent->pos.x - pos.x, parent->pos.y - pos.y); - float length = vector_length(toParent); - if (length > 0) toParent = vector_scaled(toParent, (length - parent->size) / length); - float resized = vector_length(toParent); - pull = resized > 0 ? vector_scaled(toParent, 1 / resized) : toParent; - } - AddVelocity_divided(vector_scaled(pull, random_unit() * FLY_PULL), false); - } - if (IsFrame(FLY_JITTER_FRAMES, (int)index)) - { - float angle = random_unit() * RANDOM_HALF_TURN * 2; - Vector jitter = vector_make(std::cos(angle), std::sin(angle)); - AddVelocity_divided(vector_scaled(jitter, random_unit() * FLY_JITTER), false); - } - if (distance < FLY_FLEE_RANGE) - { - float push = (1 - distance * distance / (FLY_FLEE_RANGE * FLY_FLEE_RANGE)) * FLY_FLEE_PUSH; - AddVelocity_divided(vector_scaled(direction, push), false); - } - - EntityList_EL shots; - entities.partitions[PARTITION_SHOTS].query_box(shots, pos, vector_make(FLY_HIT_RADIUS, FLY_HIT_RADIUS)); - bool isShot = std::any_of(shots.begin(), shots.end(), [this](Entity* shot) { - return !shot->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && shot->type == ENTITY_TEAR && - is_within_reach(*shot, pos, FLY_HIT_RADIUS + shot->size); - }); - if (isShot) tiny_fly_burst(); - - std::vector hazards(entities.updateEL); - for (Entity* hazard : hazards) - { - bool isKnife = - hazard->type == ENTITY_KNIFE_TYPE && is_within_reach(*hazard, pos, hazard->size * FLY_KNIFE_REACH); - bool isFire = - hazard->type == ENTITY_FIREPLACE && is_within_reach(*hazard, pos, hazard->size + FLY_FIRE_REACH); - if (isKnife || isFire) tiny_fly_burst(); - } - } - - sprite.isFlipX = pos.x - targetPosition.x < 0; - pos = g_game->room->GetClampedPosition(pos, FLY_CLAMP_MARGIN); - targetPosition = pos; -} - -// Turns a poof by its rotation, mirrored unless flipped, and removes it once its animation ends. A ripple first -// draws its small sizes larger with their own animations. -void Entity_Effect::poof_update() -{ - if (variant == EFFECT_RIPPLE_POOF && state == 0) - { - float spawnScale = sprite.scale.x; - if (spawnScale <= RIPPLE_TINY_SCALE) - { - sprite.scale = vector_make(sprite.scale.x * RIPPLE_TINY_GROWTH, sprite.scale.y * RIPPLE_TINY_GROWTH); - sprite.Play("Poof_Tiny"); - } - else if (spawnScale <= RIPPLE_SMALL_SCALE) - { - sprite.scale = vector_make(sprite.scale.x * RIPPLE_SMALL_GROWTH, sprite.scale.y * RIPPLE_SMALL_GROWTH); - sprite.Play("Poof_Small"); - } - state = 1; - } - sprite.rotation = sprite.isFlipX ? rotation : -rotation; - if (sprite.IsFinished()) Remove(); -} - -// Settles a blood stain on its first update: the stain animation for the scale it was spawned at on a random frame, -// its own scale, random flips, a random strength for an opaque color, and the floor to be drawn into. -// A glowing stain, whose color is brighter than white, fades with a light instead, which is not reconstructed yet. -void Entity_Effect::stain_update() -{ - if (state != 0) reconstruction_missing("Entity_Effect::Update 005d4380: a glowing blood stain's fade"); - float spawnScale = sprite.scale.x; - sprite.scale = vector_make(scale, scale); - - auto limit = std::find_if(STAIN_SCALE_LIMITS.begin(), STAIN_SCALE_LIMITS.end(), - [spawnScale](float scaleLimit) { return spawnScale < scaleLimit; }); - const char* animation = STAIN_ANIMATIONS[limit - STAIN_SCALE_LIMITS.begin()]; - if (const AnimationData* data = sprite.GetAnimationData(animation)) - sprite.SetFrame(animation, (int)(data->length == 0 ? 0 : Random() % (uint32_t)data->length)); - sprite.isFlipX = Random() % 2 == 0; - sprite.isFlipY = Random() % 2 == 0; - - ColorMod stainColor = sprite.color; - bool isGlowing = color._tint[3] > 1; - if (stainColor._tint[3] >= 1) - stainColor._tint[3] = (float)(Random() % STAIN_ALPHA_STEPS) * STAIN_ALPHA_STEP + STAIN_ALPHA_MIN; - sprite.color = stainColor; - if (isGlowing) reconstruction_missing("Entity_Effect::Update 005d4380: a glowing blood stain"); - AddEntityFlags(FLAG_RENDER_FLOOR); -} - // 005d2520 Moves the effect half a step between updates, keeping a following effect on its parent. void Entity_Effect::Interpolate() { @@ -488,14 +201,15 @@ void Entity_Effect::Interpolate() posOffset = parent->posOffset; } -// 00607620 Draws the effect's sprite at its place on screen. +// 00607620 Draws the effect at its place on screen through its variant, or its sprite. A light only lights the room. void Entity_Effect::Render(const Vector& offset) { - if (!isVisible) return; + if (variant == EFFECT_LIGHT || !isVisible) return; Vector screen = render_position_get(vector_make(pos.x + posOffset.x, pos.y + posOffset.y), RENDER_SNAPPED); renderPosition = vector_make(screen.x + offset.x, screen.y + offset.y); - sprite.Render(SpriteDraw{renderPosition, {}, {}}); + if (is_ambient_effect(variant)) ambient_effect_render(*this, offset); + else sprite.Render(SpriteDraw{renderPosition, {}, {}}); lua_engine_get().PostEffectRender(this, offset); } diff --git a/src/entity_effect.h b/src/entity_effect.h index 533b197..40dc5fe 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -8,12 +8,21 @@ // The effect variant that spawns a boss, which counts as the boss until it does. constexpr int EFFECT_SPAWN_PENTAGRAM = 203; +// Whether Update goes on to its shared end (the timeout, the pause position and the Lua callback) after a variant's +// frame, or returns at once as the original does when a shrinking rock particle vanishes. +enum EffectUpdateEnd +{ + EFFECT_UPDATE_FINISH, + EFFECT_UPDATE_RETURN +}; + // Construction and destruction (005cd9f0, 005cd960) are the defaults, the extra data shared with its other holders. // Field accessors (00435e60, 00435eb0, 004d7770, 005784c0, 0060ce20) are the public fields. // An effect (Lua's EntityEffect): a visual or a hazard such as creep, a poof or a light beam, with its timeout, its // fall, the per-variant data it keeps and the extra data some variants share. -// Only the tear poofs, the blood stains, the poofs and the tiny fly are reconstructed yet: Init stops at any other -// variant. +// Init, Update and Render run the shared parts here and hand each variant to entity_effect_ambient.h (ambient and +// environment effects, creep) or entity_effect_combat.h (blood, gibs, poofs, explosions). Any other variant stops. + struct Entity_Effect : Entity { // The base of the extra data some variants keep (MrMeData, PickupGhostData, SpriteTrailData). @@ -65,12 +74,4 @@ struct Entity_Effect : Entity void update_variant178_shooter(bool isPositionOnly); static Entity_Effect* CreateLootPreview(void* lootlist, const Vector& pos, Entity* owner, Entity_Effect* effect); void setup_loot_preview(void* lootQueue); - -private: - void poof_init(); - void tiny_fly_init(); - void poof_update(); - void stain_update(); - void tiny_fly_update(); - void tiny_fly_burst(); }; diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp new file mode 100644 index 0000000..6f96e3e --- /dev/null +++ b/src/entity_effect_ambient.cpp @@ -0,0 +1,2182 @@ +#include "entity_effect_ambient.h" +#include "data.h" +#include "deathmatch_manager.h" +#include "entity_tear.h" +#include "entity_list.h" +#include "entity_player.h" +#include "fx_layers.h" +#include "game.h" +#include "grid_entity.h" +#include "grid_entity_door.h" +#include "kage_graphics.h" +#include "npc_ai.h" +#include "room.h" +#include "room_config.h" +#include "room_descriptor.h" +#include +#include +#include +#include +#include +#include +#include "stb_image.h" + +// The ambient and environment variants (Lua's EffectVariant). +enum AmbientVariant : int +{ + EFFECT_BLOOD_EXPLOSION = 2, + EFFECT_BLOOD_SPLAT = 7, + EFFECT_TINY_BUG = 21, + EFFECT_TINY_FLY = 33, + EFFECT_WATER_DROPLET = 41, + EFFECT_BEETLE = 64, + EFFECT_EMBER_PARTICLE = 66, + EFFECT_WALL_BUG = 68, + EFFECT_ISAACS_CARPET = 74, + EFFECT_DICE_FLOOR = 76, + EFFECT_FALLING_EMBER = 87, + EFFECT_BROKEN_SHOVEL_SHADOW = 115, + EFFECT_SPAWNER = 120, + EFFECT_LIGHT = 121, + EFFECT_WATER_RIPPLE = 133, + EFFECT_RAIN_DROP = 135, + EFFECT_BACKDROP_DECORATION = 140, + EFFECT_DOOR_OUTLINE = 154, + EFFECT_TALL_LADDER = 156, + EFFECT_WISP = 65, + EFFECT_HEAVEN_LIGHT_DOOR = 39, + EFFECT_TADPOLE = 158, + EFFECT_LIL_GHOST = 159, + EFFECT_CREEP_RED = 22, + EFFECT_CREEP_GREEN = 23, + EFFECT_CREEP_YELLOW = 24, + EFFECT_CREEP_WHITE = 25, + EFFECT_CREEP_BLACK = 26, + EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, + EFFECT_PLAYER_CREEP_HOLYWATER = 37, + EFFECT_PLAYER_CREEP_WHITE = 44, + EFFECT_PLAYER_CREEP_BLACK = 45, + EFFECT_PLAYER_CREEP_RED = 46, + EFFECT_PLAYER_CREEP_GREEN = 53, + EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL = 54, + EFFECT_CREEP_BROWN = 56, + EFFECT_PLAYER_CREEP_LEMON_PARTY = 78, + EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90, + EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, + EFFECT_PENTAGRAM_BLACKPOWDER = 93, + EFFECT_CREEP_SLIPPERY_BROWN = 94, + EFFECT_CREEP_STATIC = 169, + EFFECT_PLAYER_CREEP_YELLOW = 204 +}; + +// What an ambient variant runs: its part of Init, its frame and its draw. A missing one keeps the shared default. +struct AmbientBehaviour +{ + int variant = -1; + void (*init)(Entity_Effect&) = nullptr; + EffectUpdateEnd (*update)(Entity_Effect&) = nullptr; + void (*render)(Entity_Effect&, const Vector&) = nullptr; +}; + +// An update that always goes on to Update's shared end. +template EffectUpdateEnd finishing(Entity_Effect& effect) +{ + UPDATE(effect); + return EFFECT_UPDATE_FINISH; +} + +constexpr int STAGE_ID_CATHEDRAL = 15; +constexpr int BACKDROP_DROSS = 45; +constexpr int ROOM_BARREN_TYPE = 19; +constexpr int SOUND_DROPLET_SPLASH = 397; +constexpr int SOUND_SPAWNER_SUMMON = 265; +constexpr int DOOR_STATE_KEEPS_DECORATIONS = 7; +constexpr int RENDER_Z_DECORATION_LIMIT = 0x40000000; +constexpr float NEAR_PLAYER_RANGE_SQUARED = 10000; +constexpr float FULL_TURN = 360; +constexpr float HALF_TURN = 180; +constexpr float RIGHT_ANGLE = 90; + +// The tiny fly: white in the Cathedral, how it wanders, flees the nearest player within range, dies to tears, +// knives and fires, and drops down in circles when dead. +constexpr int FLY_WANDER_ODDS = 5; +constexpr int FLY_JITTER_FRAMES = 5; +constexpr float FLY_FRICTION = 0.98f; +constexpr float FLY_DEAD_FRICTION = 0.8f; +constexpr float FLY_PULL = 0.5f; +constexpr float FLY_JITTER = 0.9f; +constexpr float FLY_FLEE_RANGE = 60; +constexpr float FLY_FLEE_PUSH = -0.2f; +constexpr float FLY_HIT_RADIUS = 0.5f; +constexpr float FLY_KNIFE_REACH = 1.5f; +constexpr float FLY_FIRE_REACH = 2; +constexpr float FLY_FALL_STEP = 0.25f; +constexpr float FLY_FALL_HEIGHT = 16; +constexpr float FLY_CIRCLE_SPEED = 15; +constexpr float FLY_CIRCLE_RADIUS = 3; +constexpr float FLY_CLAMP_MARGIN = 2; +constexpr float FLY_SPLAT_SCALE = 0.1f; +constexpr float FLY_BURST_SCALE = 0.3f; +constexpr float FLY_BURST_RISE = -16; +constexpr float MIN_DISTANCE = 0.01f; + +// The crawling bugs: how they idle, run in bursts and turn, flee a player close by, stay off the walls and grid, and +// splat when stepped on or hit by a tear's splash. +constexpr int BUG_BURST_ODDS = 30; +constexpr int BUG_BURST_MIN = 15; +constexpr int BUG_BURST_SPAN = 120; +constexpr int BUG_STEP_ODDS = 5; +constexpr int BUG_FLEE_ODDS = 3; +constexpr int BUG_FLEE_MIN = 30; +constexpr int BUG_FLEE_SPAN = 100; +constexpr float BUG_FRICTION = 0.8f; +constexpr float BUG_STEP = 0.5f; +constexpr float BUG_FLEE_PUSH = 2; +constexpr float BUG_TURN_SPAN = 50; +constexpr float BUG_TURN_BACK = 25; +constexpr float BUG_ROOM_MARGIN = -2; +constexpr float BUG_CELL_EDGE = 20; +constexpr float BUG_STOPPED_SPEED = 0.1f; +constexpr float BUG_SQUASH_RANGE_SQUARED = 100; +constexpr float BUG_SPLASH_RANGE_SQUARED = 400; +constexpr float BUG_SPLAT_SCALE = 0.3f; +constexpr int WALL_BUG_RENDER_Z = 5000; +constexpr float WALL_BUG_START_SPAN = 10000; +constexpr float WALL_BUG_INSET_SPAN = 40; +constexpr float WALL_BUG_TURN_RATE = 0.2f; +constexpr float WALL_BUG_DOOR_STEP = 2; + +// The walls a wall bug walks: its depth into them, clamped, and the outer and inner edges it lies between. +constexpr float WALL_DEPTH = 40; +constexpr float WALL_INSET_MIN = -10; + +// The wisps' drift, their pull toward a moving player and back into the room, and their float. +constexpr float WISP_DRIFT_SPEED = 8; +constexpr float WISP_DRIFT_RATE_MIN = 0.01f; +constexpr float WISP_DRIFT_RATE_SPAN = 0.03f; +constexpr float WISP_WALL_MARGIN = 40; +constexpr float WISP_CENTER_PULL = 0.08f; +constexpr float WISP_FLOAT_HEIGHT = -50; +constexpr float WISP_FLOAT_RATE = 0.01f; +constexpr float WISP_SCALE_MIN = 0.5f; +constexpr float WISP_SCALE_SPAN = 0.5f; + +// The stages whose wisps glow yellow (the Womb, Utero, Scarred Womb, the Dross' rooms, Mausoleum, Corpse and the +// Scarred Womb's alternate) and red (Sheol and Gehenna). +constexpr std::array WISP_YELLOW_STAGES = {10, 11, 12, 28, 30, 33, 34}; +constexpr std::array WISP_RED_STAGES = {16, 31}; +constexpr int WISP_ORANGE_STAGE = 32; + +// The water droplets that fall from the ceiling and splash or stain where they land. +constexpr int DROPLET_KINDS = 3; +constexpr int STAGE_DEPTHS_2 = 6; +constexpr int STAGE_DEPTHS = 5; +constexpr int STAGE_WOMB = 7; +constexpr int STAGE_TYPE_AFTERBIRTH = 2; +constexpr float DROPLET_HEIGHT = -10; +constexpr float DROPLET_LANDED_HEIGHT = 10; +constexpr float DROPLET_GRAVITY = 1; +constexpr float DROPLET_FRICTION = 0.98f; +constexpr float DROPLET_FLOOR_OFFSET = 12; + +// The embers: the particles fires shed, fading as they rise, and the ones falling from the Burning Basement's +// ceiling. +constexpr int EMBER_GLOWING_SUBTYPE = 10; +constexpr int EMBER_GLOW_MIN = 30; +constexpr int EMBER_GLOW_SPAN = 60; +constexpr int EMBER_MIN = 2; +constexpr int EMBER_SPAN = 30; +constexpr float EMBER_DRIFT_X = 0.4f; +constexpr float EMBER_DRIFT_Y = 0.1f; +constexpr float EMBER_FRICTION_X = 0.98f; +constexpr float EMBER_FRICTION_Y = 0.97f; +constexpr float FALLING_EMBER_FRICTION = 0.97f; +constexpr float FALLING_EMBER_FRICTION_SCALE = 0.03f; +constexpr float FALLING_EMBER_FALL = 0.15f; +constexpr float FALLING_EMBER_FALL_SPAN = 0.05f; + +// The rain drops: the frame they splash on, and the ripple it leaves. +constexpr int RAIN_DROP_SPLASH_FRAME = 13; +constexpr int RAIN_DROP_KINDS = 4; +constexpr int RIPPLE_FROM_RAIN = 1; + +// The lights: those of subtype 1 flicker. +constexpr int LIGHT_FLICKER = 1; +constexpr int LIGHT_TOGGLE_ODDS = 24; +constexpr int LIGHT_DIM_ODDS = 100; +constexpr float LIGHT_ALPHA_MIN = 0.6f; +constexpr float LIGHT_ALPHA_SPAN = 0.6f; + +// The pieces of the floor rooms place: the broken carpet, the dice floor's faces and the ladder's step distance. +constexpr int CARPET_BROKEN = 1000; +constexpr int DICE_FACE_LAST = 5; +constexpr int DICE_ARM_FRAMES = 15; +constexpr float DICE_REACH = 75; +constexpr int SHOVEL_SHADOW_RENDER_Z = 10000; +constexpr int LADDER_ARM_FRAMES = 5; +constexpr float LADDER_NEAR = 50; +constexpr float LADDER_CLIMB = 21; + +template +static bool is_listed(const std::array& list, int value) +{ + return std::find(list.begin(), list.end(), value) != list.end(); +} + +// normalize_angle_degrees 00682740: an angle brought into -180 to 180. +static float angle_normalized(float angle) +{ + if (std::abs(angle) > FULL_TURN) angle = std::fmod(angle, FULL_TURN); + if (angle > HALF_TURN) return angle - FULL_TURN; + if (angle < -HALF_TURN) angle += FULL_TURN; + return angle; +} + +// Vector::Lerp a10210: moves a vector t of the way to a target. +static void vector_lerp(Vector& v, Vector target, float t) +{ + v.x = (target.x - v.x) * t + v.x; + v.y = (target.y - v.y) * t + v.y; +} + +static float distance_squared(Vector a, Vector b) +{ + return vector_length_squared(vector_sub(a, b)); +} + +// Game::GetNearestPlayer 00703950: the player nearest a position, the first one on a tie. +static Entity_Player* nearest_player_get(Vector position) +{ + Entity_Player* nearest = nullptr; + float nearestDistance = 0; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = distance_squared(position, player->pos); + if (nearest && distance >= nearestDistance) continue; + nearest = player; + nearestDistance = distance; + } + return nearest; +} + +// Room::GetGridCollisionAtPos 007f0780 and Room::GetGridEntityFromPos 00456620. +static int grid_collision_at(Vector position) +{ + Room& room = *g_game->room; + return (int)room.GetGridCollision(room.GetGridIndex(position)); +} + +static GridEntity* grid_entity_at(Vector position) +{ + Room& room = *g_game->room; + return room.GetGridEntity((uint32_t)room.GetGridIndex(position)); +} + +// What EntityList::QueryRadius 0041a790 looks through: Lua's EntityPartition bits. +enum QueryMask : uint32_t +{ + QUERY_FAMILIARS = 1 << 0, + QUERY_PROJECTILES = 1 << 1, + QUERY_TEARS = 1 << 2, + QUERY_ENEMIES = 1 << 3, + QUERY_PICKUPS = 1 << 4, + QUERY_PLAYERS = 1 << 5 +}; + +// The entities of the masked partitions (and the players) touching a position within a radius, in the original's +// partition order, those in their interpolation update left out. +static EntityList_EL entities_near(Vector position, float radius, uint32_t mask) +{ + constexpr std::array, 5> PARTITIONS = {{{QUERY_FAMILIARS, PARTITION_FAMILIARS}, + {QUERY_TEARS, PARTITION_SHOTS}, + {QUERY_ENEMIES, PARTITION_ENEMIES}, + {QUERY_PROJECTILES, PARTITION_PROJECTILES}, + {QUERY_PICKUPS, PARTITION_PICKUPS}}}; + EntityList& entities = g_game->room->entityList; + EntityList_EL found; + + for (auto [bit, partition] : PARTITIONS) + if (mask & bit) entities.partitions[partition].query_box(found, position, vector_make(radius, radius)); + if (mask & QUERY_PLAYERS) + for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player); + std::erase_if(found, [&](Entity* entity) { + float reach = radius + entity->size; + return entity->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || + distance_squared(entity->pos, position) >= reach * reach; + }); + return found; +} + +// Sets a layer to draw additively (BlendMode::SetMode 2). +static void layer_additive_set(LayerState& layer) +{ + KAGE::Graphics::BlendMode mode; + mode.SetMode(KAGE::Graphics::BLEND_ADDITIVE); + layer.blendMode = {mode.equation, mode.rgbSource, mode.rgbDest, mode.alphaSource, mode.alphaDest}; +} + +// A color tinted, with no colorize or offset (Color::Reset and SetTint). +static ColorMod tint_make(float red, float green, float blue, float alpha) +{ + return {{red, green, blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; +} + +// Spawns a blood splat of a bug's blood color where it died, at a scale, onto the floor or the wall. +static void bug_splat(Entity_Effect& bug, uint64_t addedFlags) +{ + Entity* splat = g_game->Spawn({.position = bug.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, + .seed = Random()}); + splat->SetColor(bug.splatColor, -1, 255, false, true); + static_cast(splat)->scale = BUG_SPLAT_SCALE; + splat->AddEntityFlags(addedFlags); + splat->Update(); + bug.Remove(); +} + +// Pushes a crawler back to the edge of the grid cell at a point, along the side it entered from, stopping it there. +static void cell_push_out(Entity_Effect& crawler, Vector point) +{ + Room& room = *g_game->room; + Vector cell = room.GetGridPosition(room.GetGridIndex(point)); + Vector toCell = vector_sub(cell, crawler.pos); + + if (std::abs(toCell.x) <= std::abs(toCell.y)) + { + crawler.pos.y = toCell.y <= 0 ? cell.y + BUG_CELL_EDGE : cell.y - BUG_CELL_EDGE; + crawler.velocity.y *= BUG_STOPPED_SPEED; + } + else + { + crawler.pos.x = toCell.x <= 0 ? cell.x + BUG_CELL_EDGE : cell.x - BUG_CELL_EDGE; + crawler.velocity.x *= BUG_STOPPED_SPEED; + } +} + +// The crawlers and flies: light, colliding with everything, uncolored in the Dross. +static void critter_init(Entity_Effect& effect) +{ + effect.mass = 1; + effect.entityCollisionClass = ENTCOLL_ALL; + effect.isUnknown176 = true; + if (g_game->room->backdropType == BACKDROP_DROSS) effect.sprite.color = COLOR_DEFAULT; +} + +// A tiny bug crawls on the floor among the door layer's sprites. +static void tiny_bug_init(Entity_Effect& effect) +{ + effect.sortingLayer = SORTING_DOOR; + critter_init(effect); +} + +// A tiny fly is white in the Cathedral. +static void tiny_fly_init(Entity_Effect& effect) +{ + if (RoomConfig::GetStageID((int)g_game->stage, (int)g_game->stageType, (RoomMode)-1) == STAGE_ID_CATHEDRAL) + effect.sprite.Play("White"); + critter_init(effect); +} + +// A wall bug starts somewhere along the walls (its target position holds its depth and its distance along them) and +// draws over the floor. +static void wall_bug_init(Entity_Effect& effect) +{ + effect.sortingLayer = SORTING_BACKGROUND; + effect.renderZOffset = WALL_BUG_RENDER_Z; + float along = random_unit() * WALL_BUG_START_SPAN; + effect.targetPosition = vector_make(random_unit() * WALL_BUG_INSET_SPAN, along); + critter_init(effect); +} + +// A tiny bug's frame: it idles or runs in bursts along its heading, which wobbles, flees a player close by, and is +// pushed out of the grid cells it walks into. It splats when a player walks over it or a tear splashes on it. +static void tiny_bug_update(Entity_Effect& bug) +{ + Room& room = *g_game->room; + + bug.friction *= BUG_FRICTION; + if (bug.state < 1) + { + if (random_below(BUG_BURST_ODDS) == 0) bug.state = random_below(BUG_BURST_SPAN) + BUG_BURST_MIN; + else if (random_below(BUG_STEP_ODDS) == 0) + bug.AddVelocity_divided(vector_scale(vector_from_angle(bug.rotation), random_unit() * BUG_STEP), false); + } + else + { + Vector heading = vector_from_angle(bug.rotation); + bug.AddVelocity_divided(vector_scale(heading, random_unit() * BUG_STEP + BUG_STEP), false); + bug.state--; + } + + Entity_Player* player = nearest_player_get(bug.pos); + float playerDistance = distance_squared(bug.pos, player->pos); + if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && random_below(BUG_FLEE_ODDS) == 0) + { + float push = (1 - playerDistance / NEAR_PLAYER_RANGE_SQUARED) * BUG_FLEE_PUSH; + bug.AddVelocity_divided(vector_scale(vector_normalized(vector_sub(bug.pos, player->pos)), push), false); + bug.state = random_below(BUG_FLEE_SPAN) + BUG_FLEE_MIN; + } + bug.rotation = angle_normalized(random_unit() * BUG_TURN_SPAN + bug.rotation - BUG_TURN_BACK); + bug.pos = room.GetClampedPosition(bug.pos, BUG_ROOM_MARGIN); + + if (grid_collision_at(bug.pos) != COLLISION_NONE) + { + GridEntity* grid = grid_entity_at(bug.pos); + cell_push_out(bug, bug.pos); + if (grid && grid->type == GRID_PIT && grid_collision_at(bug.pos) != COLLISION_NONE) + { + bug.pos = bug.targetPosition; + bug.rotation = angle_normalized(random_unit() * FULL_TURN); + if (grid_collision_at(bug.pos) == COLLISION_PIT) bug.pos = vector_add(bug.pos, random_direction()); + } + } + bug.targetPosition = bug.pos; + + if (bug.isDead) bug_splat(bug, 0); + if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying()) + bug.isDead = true; + for (Entity* tear : entities_near(bug.pos, 1, QUERY_TEARS)) + if (tear->type == ENTITY_TEAR && tear->isDead && distance_squared(tear->pos, bug.pos) < BUG_SPLASH_RANGE_SQUARED) + bug.isDead = true; +} + +// room_perimeter_to_position 0060ac70: the point a wall bug stands on from its depth into the walls (clamped) and +// its distance along them (wrapped), both written back. The walk runs up the left wall, along the top, down the +// right and back along the bottom. +static Vector wall_position_get(Vector& walk) +{ + Room& room = *g_game->room; + Vector topLeft = room.topLeftPos; + Vector bottomRight = room.bottomRightPos; + + walk.x = std::min(std::max(walk.x, WALL_INSET_MIN), WALL_DEPTH); + float width = bottomRight.x - topLeft.x; + float height = bottomRight.y - topLeft.y; + float perimeter = width + width + height + height; + walk.y = std::fmod(walk.y, perimeter); + if (walk.y < 0) walk.y += perimeter; + + // The corners of the walk at its depth, each between the outer edge of the walls and the floor's. + float depth = walk.x / WALL_DEPTH; + auto inset = [depth](float outer, float inner) { return (inner - outer) * depth + outer; }; + float left = inset(topLeft.x - WALL_DEPTH, topLeft.x); + float right = inset(bottomRight.x + WALL_DEPTH, bottomRight.x); + float top = inset(topLeft.y - WALL_DEPTH, topLeft.y); + float bottom = inset(bottomRight.y + WALL_DEPTH, bottomRight.y); + + Vector from = vector_make(left, bottom); + Vector to = vector_make(left, top); + float along = walk.y / height; + if (walk.y >= width + height + height) + { + from = vector_make(right, bottom); + to = vector_make(left, bottom); + along = (walk.y - (height + height + width)) / width; + } + else if (walk.y >= width + height) + { + from = vector_make(right, top); + to = vector_make(right, bottom); + along = (walk.y - (width + height)) / height; + } + else if (walk.y >= height) + { + from = vector_make(left, top); + to = vector_make(right, top); + along = (walk.y - height) / width; + } + return vector_make((to.x - from.x) * along + from.x, (to.y - from.y) * along + from.y); +} + +// A wall bug's frame: it idles or runs in bursts along the walls with a wobbling heading, turns back from the floor's +// edge and from doors, and splats onto the wall when a tear splashes on it. +static void wall_bug_update(Entity_Effect& bug) +{ + bug.velocity = {}; + Vector previous = bug.targetPosition; + bug.rotation = angle_normalized(random_unit() * BUG_TURN_SPAN + bug.rotation - BUG_TURN_BACK); + if (bug.state < 1) + { + if (random_below(BUG_BURST_ODDS) == 0) bug.state = random_below(BUG_BURST_SPAN) + BUG_BURST_MIN; + else if (random_below(BUG_STEP_ODDS) == 0) + bug.targetPosition = vector_add(bug.targetPosition, vector_scale(vector_from_angle(bug.rotation), random_unit())); + } + else + { + Vector heading = vector_from_angle(bug.rotation); + bug.targetPosition = vector_add(bug.targetPosition, vector_scale(heading, random_unit() + 1)); + bug.state--; + } + + float depth = bug.targetPosition.x; + bug.pos = wall_position_get(bug.targetPosition); + if (depth != bug.targetPosition.x) + { + float turn = (depth <= 0) == (bug.rotation <= 0) ? RIGHT_ANGLE : -RIGHT_ANGLE; + bug.rotation = angle_lerp(bug.rotation, bug.rotation + turn, WALL_BUG_TURN_RATE); + } + if (grid_collision_at(bug.pos) == COLLISION_WALL_EXCEPT_PLAYER) + { + bool isTurnLeft = bug.targetPosition.y <= previous.y ? bug.rotation >= -RIGHT_ANGLE : bug.rotation <= RIGHT_ANGLE; + float turn = isTurnLeft ? -RIGHT_ANGLE : RIGHT_ANGLE; + bug.rotation = angle_lerp(bug.rotation, bug.rotation + turn, WALL_BUG_TURN_RATE); + bug.targetPosition = previous; + bug.pos = wall_position_get(bug.targetPosition); + } + if (grid_collision_at(bug.pos) == COLLISION_WALL_EXCEPT_PLAYER) bug.targetPosition.y += WALL_BUG_DOOR_STEP; + + if (bug.isDead) bug_splat(bug, FLAG_RENDER_WALL); + for (Entity* tear : entities_near(bug.pos, 1, QUERY_TEARS)) + { + if (tear->type != ENTITY_TEAR || !tear->isDead) continue; + bug.isDead = true; + break; + } +} + +// Bursts the fly into a small splash of its blood color. +static void tiny_fly_burst(Entity_Effect& fly) +{ + fly.isDead = true; + Entity* burst = g_game->Spawn({.position = vector_make(fly.pos.x, fly.pos.y + FLY_BURST_RISE), + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + burst->SetColor(fly.splatColor, -1, 255, false, true); + burst->sprite.scale = vector_make(FLY_BURST_SCALE, FLY_BURST_SCALE); + burst->Update(); + fly.sprite.Stop(); +} + +// Whether an entity stands within reach of a position. +static bool is_within_reach(Entity& entity, Vector position, float reach) +{ + return distance_squared(entity.pos, position) < reach * reach; +} + +// A tiny fly's frame: alive it drifts at random, now and then toward its parent or the nearest player, and away +// from a player close by, and bursts on a tear, knife or fire. Dead, it spirals down and splats. It faces its motion +// and stays in the room. +static void tiny_fly_update(Entity_Effect& fly) +{ + Entity_Player* player = nearest_player_get(fly.pos); + Vector toPlayer = vector_sub(player->pos, fly.pos); + float distance = vector_length(toPlayer); + Vector direction = vector_scale(toPlayer, 1 / (distance == 0 ? MIN_DISTANCE : distance)); + EntityList& entities = g_game->room->entityList; + + fly.friction *= FLY_FRICTION; + if (fly.isDead) + { + LayerState& layer = *fly.sprite.GetLayer(0); + if (layer.pos.y <= FLY_FALL_HEIGHT) + { + layer.pos.y += FLY_FALL_STEP; + float side = (float)(fly.index % 2) * 2 - 1; + float angle = (float)g_game->frameCount * FLY_CIRCLE_SPEED * side * DEGREES_TO_RADIANS; + Vector circle = vector_make(std::cos(angle), std::sin(angle)); + circle = vector_scale(vector_scale(circle, std::abs(layer.pos.y) / FLY_FALL_HEIGHT), FLY_CIRCLE_RADIUS); + fly.pos = vector_add(fly.pos, circle); + fly.friction *= FLY_DEAD_FRICTION; + } + else + { + Entity* splat = g_game->Spawn({.position = fly.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, + .seed = Random()}); + splat->SetColor(fly.splatColor, -1, 255, false, true); + splat->sprite.scale = vector_make(FLY_SPLAT_SCALE, FLY_SPLAT_SCALE); + splat->Update(); + fly.Remove(); + } + } + + if (!fly.isDead) + { + if (Random() % FLY_WANDER_ODDS == 0) + { + Vector pull = direction; + if (fly.parent) + { + Vector toParent = vector_sub(fly.parent->pos, fly.pos); + float length = vector_length(toParent); + if (length > 0) toParent = vector_scale(toParent, (length - fly.parent->size) / length); + float resized = vector_length(toParent); + pull = resized > 0 ? vector_scale(toParent, 1 / resized) : toParent; + } + fly.AddVelocity_divided(vector_scale(pull, random_unit() * FLY_PULL), false); + } + if (fly.IsFrame(FLY_JITTER_FRAMES, (int)fly.index)) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector jitter = vector_make(std::cos(angle), std::sin(angle)); + fly.AddVelocity_divided(vector_scale(jitter, random_unit() * FLY_JITTER), false); + } + if (distance < FLY_FLEE_RANGE) + { + float push = (1 - distance * distance / (FLY_FLEE_RANGE * FLY_FLEE_RANGE)) * FLY_FLEE_PUSH; + fly.AddVelocity_divided(vector_scale(direction, push), false); + } + + EntityList_EL shots; + entities.partitions[PARTITION_SHOTS].query_box(shots, fly.pos, vector_make(FLY_HIT_RADIUS, FLY_HIT_RADIUS)); + bool isShot = std::any_of(shots.begin(), shots.end(), [&fly](Entity* shot) { + return !shot->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && shot->type == ENTITY_TEAR && + is_within_reach(*shot, fly.pos, FLY_HIT_RADIUS + shot->size); + }); + if (isShot) tiny_fly_burst(fly); + + std::vector hazards(entities.updateEL); + for (Entity* hazard : hazards) + { + bool isKnife = hazard->type == ENTITY_KNIFE && is_within_reach(*hazard, fly.pos, hazard->size * FLY_KNIFE_REACH); + bool isFire = hazard->type == ENTITY_FIREPLACE && is_within_reach(*hazard, fly.pos, hazard->size + FLY_FIRE_REACH); + if (isKnife || isFire) tiny_fly_burst(fly); + } + } + + fly.sprite.isFlipX = fly.pos.x - fly.targetPosition.x < 0; + fly.pos = g_game->room->GetClampedPosition(fly.pos, FLY_CLAMP_MARGIN); + fly.targetPosition = fly.pos; +} + +// A wisp's glow by the stage: yellow in the wombs, red in Sheol and Gehenna, orange in the Mines and blue elsewhere, +// at a random height and size, drawn additively. Its blood color matches. +static void wisp_init(Entity_Effect& wisp) +{ + int stageId = g_game->GetStageID(); + ColorMod splat = COLOR_DEFAULT; + + if (is_listed(WISP_YELLOW_STAGES, stageId)) + { + wisp.sprite.Play("White"); + wisp.sprite.color = tint_make(1, 0.8f, 0, 1); + splat = tint_make(1, 1, 0.5f, 1); + } + else if (is_listed(WISP_RED_STAGES, stageId)) + { + wisp.sprite.Play("Red"); + splat = tint_make(1, 0.5f, 0.5f, 1); + } + else if (stageId == WISP_ORANGE_STAGE) + { + wisp.sprite.Play("White"); + wisp.sprite.color = tint_make(1, 0.02f, 0, 1); + } + else wisp.sprite.Play("Blue"); + wisp.splatColor = splat; + + wisp.posOffset.y = random_unit() * WISP_FLOAT_HEIGHT; + float size = random_unit() * WISP_SCALE_SPAN + WISP_SCALE_MIN; + wisp.sprite.scale = vector_make(size, size); + layer_additive_set(*wisp.sprite.GetLayer(0)); +} + +// A wisp's frame: it drifts at random, follows a moving player close by, keeps away from the walls and floats at a +// wandering height. +static void wisp_update(Entity_Effect& wisp) +{ + Room& room = *g_game->room; + + wisp.pos = room.GetClampedPosition(wisp.pos, 0); + float driftRate = random_unit() * WISP_DRIFT_RATE_SPAN + WISP_DRIFT_RATE_MIN; + Vector drift = random_direction(); + vector_lerp(wisp.velocity, vector_scale(drift, random_unit() * WISP_DRIFT_SPEED), driftRate); + + Entity_Player* player = nearest_player_get(wisp.pos); + float playerDistance = distance_squared(player->pos, wisp.pos); + if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && vector_length_squared(player->velocity) > 1) + { + float closeness = 1 - playerDistance / NEAR_PLAYER_RANGE_SQUARED; + vector_lerp(wisp.velocity, player->velocity, (random_unit() * WISP_DRIFT_RATE_SPAN + WISP_DRIFT_RATE_MIN) * closeness); + } + Vector inside = room.GetClampedPosition(wisp.pos, WISP_WALL_MARGIN); + if (wisp.pos.x != inside.x || wisp.pos.y != inside.y) + vector_lerp(wisp.velocity, vector_normalized(vector_sub(Room::GetCenterPos(), wisp.pos)), WISP_CENTER_PULL); + + float height = random_unit() * WISP_FLOAT_HEIGHT; + wisp.posOffset.y = (height - wisp.posOffset.y) * WISP_FLOAT_RATE + wisp.posOffset.y; +} + +// A water droplet: dank in the Dank Depths, bloody from the Womb on, large and sized at random or small. +static void water_droplet_init(Entity_Effect& drop) +{ + int stage = (int)g_game->stage; + + if ((stage == STAGE_DEPTHS || stage == STAGE_DEPTHS_2) && (int)g_game->stageType == STAGE_TYPE_AFTERBIRTH) + drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_DankDroplets.png"); + else if (stage >= STAGE_WOMB) drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_BloodDroplets.png"); + + drop.state = (int)(Random() % DROPLET_KINDS); + if (drop.state == 0) + { + drop.sprite.Play("LargeDrop"); + float size = random_unit() * 0.5f + 0.5f; + drop.sprite.scale = vector_make(size, size); + } + else drop.sprite.Play("SmallDrop"); + drop.height = DROPLET_HEIGHT; + drop.sprite.isFlipX = !(Random() & 1); +} + +// The floor under a droplet falling in a crawlspace: the cell above the first solid one below the first open cell of +// its column. It is gone when the column has none. +static bool droplet_floor_find(Entity_Effect& drop) +{ + Room& room = *g_game->room; + int column = room.GetGridIndex(drop.targetPosition) % room.gridWidth; + int row = 0; + + while (row < room.gridHeight && room.GetGridCollision(room.GetGridIndexByTile(column, row)) != COLLISION_NONE) row++; + if (row >= room.gridHeight) return false; + while (row < room.gridHeight && room.GetGridCollision(room.GetGridIndexByTile(column, row)) == COLLISION_NONE) row++; + drop.targetPosition.y = room.GetGridPosition(room.GetGridIndexByTile(column, row - 1)).y + DROPLET_FLOOR_OFFSET; + return true; +} + +// A droplet's frame: it picks a random floor height under it, falls there, then splashes in water or stains the +// floor, and goes once that plays out. +static EffectUpdateEnd water_droplet_update(Entity_Effect& drop) +{ + Room& room = *g_game->room; + + if (drop.FrameCount() == 0) + { + float floor = random_unit() * (room.bottomRightPos.y - room.topLeftPos.y) + room.topLeftPos.y; + drop.targetPosition = vector_make(drop.pos.x, floor); + if (room.roomType == ROOM_DUNGEON && !droplet_floor_find(drop)) + { + drop.Remove(); + return EFFECT_UPDATE_RETURN; + } + } + + if (drop.height >= 0) + { + drop.pos = drop.targetPosition; + drop.velocity = {}; + if (drop.sprite.IsFinished()) drop.Remove(); + return EFFECT_UPDATE_FINISH; + } + + drop.velocity.y += DROPLET_GRAVITY; + drop.velocity.x = 0; + drop.friction *= DROPLET_FRICTION; + if (drop.pos.y + drop.velocity.y <= drop.targetPosition.y) return EFFECT_UPDATE_FINISH; + + drop.pos = drop.targetPosition; + drop.height = DROPLET_LANDED_HEIGHT; + if (!room.HasWater()) drop.sprite.Play(drop.state == 0 ? "Spot1" : "Spot2"); + else + { + drop.sprite.Play("Splash"); + drop.sprite.isFlipY = false; + float pitch = random_unit() * 0.5f + 1; + float volume = random_unit() * 0.5f + 0.5f; + npc_sound_play(SOUND_DROPLET_SPLASH, volume, 2, pitch); + } + drop.velocity = {}; + drop.sortingLayer = SORTING_BACKGROUND; + drop.sprite.isFlipX = random_below(2) == 0; + drop.sprite.isFlipY = random_below(2) == 0; + return EFFECT_UPDATE_FINISH; +} + +// An ember's frame: it picks its life on the first (glowing embers live longer and draw additively), drifts up and +// sideways, slows, and plays its animation through as it burns out. +static void ember_particle_update(Entity_Effect& ember) +{ + if (ember.state == 0) + { + if (ember.subtype == EMBER_GLOWING_SUBTYPE) + { + ember.state = random_below(EMBER_GLOW_SPAN) + EMBER_GLOW_MIN; + layer_additive_set(*ember.sprite.GetLayer(0)); + } + else ember.state = random_below(EMBER_SPAN) + EMBER_MIN; + ember.timeout = ember.state - 1; + } + + float driftY = random_unit() * EMBER_DRIFT_Y - EMBER_DRIFT_Y / 2; + float driftX = random_unit() * EMBER_DRIFT_X - EMBER_DRIFT_X / 2; + ember.velocity = vector_add(ember.velocity, vector_make(driftX, driftY)); + ember.velocity = vector_make(ember.velocity.x * EMBER_FRICTION_X, ember.velocity.y * EMBER_FRICTION_Y); + float burnt = (float)ember.timeout / (float)ember.state; + ember.sprite.SetFrame((float)(int)((float)ember.sprite.animState.GetAnimationLength() * burnt)); + if (ember.isDead) ember.Remove(); +} + +// A falling ember glows additively at a random size. +static void falling_ember_init(Entity_Effect& ember) +{ + layer_additive_set(*ember.sprite.GetLayer(0)); + float size = ember.dropRNG.RandomFloat() * 0.5f + 0.5f; + ember.sprite.scale = vector_make(size, size); +} + +// A falling ember's frame: it picks a floor height on its first, then flutters down to it, the larger ones slower. +static void falling_ember_update(Entity_Effect& ember) +{ + Room& room = *g_game->room; + + if (ember.FrameCount() == 0) + { + float floor = random_unit() * (room.bottomRightPos.y - room.topLeftPos.y) + room.topLeftPos.y; + ember.targetPosition = vector_make(ember.pos.x, floor); + } + ember.velocity.x += random_unit() - 0.5f; + ember.friction *= FALLING_EMBER_FRICTION - ember.sprite.scale.x * FALLING_EMBER_FRICTION_SCALE; + ember.velocity.y += FALLING_EMBER_FALL - random_unit() * FALLING_EMBER_FALL_SPAN; + if (ember.pos.y > ember.targetPosition.y) ember.Remove(); +} + +// A rain drop: one of four, partway through when the room has just loaded, tinted like the room's water. +static void rain_drop_init(Entity_Effect& drop) +{ + drop.sprite.Play("Drop0" + std::to_string(random_below(RAIN_DROP_KINDS) + 1)); + if (g_game->room->GetFrameCount() == 0) drop.sprite.SetFrame((float)random_below(drop.sprite.animState.GetAnimationLength())); + drop.sprite.color = g_game->room->fxLayers.fxParams.waterEffectColor; +} + +// A rain drop's frame: it leaves a ripple of its color when it lands and goes when its animation ends. +static void rain_drop_update(Entity_Effect& drop) +{ + if (drop.sprite.IsFinished()) drop.Remove(); + if (drop.sprite.GetFrame() != RAIN_DROP_SPLASH_FRAME) return; + + Entity* ripple = g_game->Spawn({.position = drop.pos, .subType = RIPPLE_FROM_RAIN, .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_RIPPLE, .seed = Random()}); + ripple->sprite.color = drop.sprite.color; +} + +// A ripple turns with its rotation and goes once its animation ends, as the poofs Update shares its case with do. +static void water_ripple_update(Entity_Effect& ripple) +{ + ripple.sprite.rotation = ripple.sprite.isFlipX ? ripple.rotation : -ripple.rotation; + if (ripple.sprite.IsFinished()) ripple.Remove(); +} + +// Isaac's carpet lies on the floor touching only the players, torn in a barren room. +static void carpet_init(Entity_Effect& carpet) +{ + carpet.sortingLayer = SORTING_BACKGROUND; + carpet.entityGridCollisionClass = GRIDCOLL_WALLS; + carpet.entityCollisionClass = ENTCOLL_PLAYERONLY; + if (g_game->room->roomType == ROOM_BARREN_TYPE) carpet.sprite.ReplaceSpritesheet(0, "gfx/Effects/IsaacCarpet_Barren.png"); +} + +// A carpet of subtype 1000 shows torn. +static void carpet_update(Entity_Effect& carpet) +{ + if (carpet.subtype == CARPET_BROKEN) carpet.sprite.Play("Broken"); +} + +// The dice room's floor shows its face, 1 to 6 by subtype, on the floor. +static void dice_floor_init(Entity_Effect& floor) +{ + floor.sprite.Play(std::to_string(std::min(floor.subtype, DICE_FACE_LAST) + 1)); + floor.sortingLayer = SORTING_BACKGROUND; +} + +// The dice floor's frame: once armed, the first player standing on it rolls its face's dice, once per room. +static void dice_floor_update(Entity_Effect& floor) +{ + if (g_game->room->IsSacrificeDone() || floor.FrameCount() <= DICE_ARM_FRAMES) return; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0 || player->isCoopGhost || player->entityCollisionClass == ENTCOLL_NONE) continue; + Vector offset = vector_sub(player->pos, floor.pos); + if (std::abs(offset.x) >= DICE_REACH || std::abs(offset.y) >= DICE_REACH) continue; + reconstruction_missing("Entity_Effect::Update 005d4380: the dice floor's roll (Game::Darken, ShakeScreen, " + "the D4, D6, D20 and D100)"); + } +} + +// The Broken Shovel's shadow draws over everything, until it falls. +static void shovel_shadow_init(Entity_Effect& shadow) +{ + shadow.sprite.Play("Idle"); + shadow.renderZOffset = SHOVEL_SHADOW_RENDER_Z; + shadow.state = 0; + shadow.AddEntityFlags(FLAG_DONT_OVERWRITE); +} + +static void shovel_shadow_update(Entity_Effect& shadow) +{ + if (shadow.state != 0) shadow.sprite.Play("Fall"); +} + +// A spawner holds an entity back (its type the subtype, its variant and subtype the extra data) unseen until it is +// killed. +static void spawner_init(Entity_Effect& spawner) +{ + spawner.isVisible = false; + spawner.varData[0] = 0; + spawner.varData[1] = 0; + spawner.state = -1; + spawner.AddEntityFlags(FLAG_DONT_OVERWRITE); +} + +// A killed spawner lets its entity out, an enemy as an ambush with the summon sound. When it brings enemies into a +// room that had none, the doors close and the room is no longer clear, losing its reward if it was. +static void spawner_update(Entity_Effect& spawner) +{ + if (!spawner.isDead) return; + + Room& room = *g_game->room; + int enemiesBefore = room.GetAliveEnemiesCount(); + Entity* entity = g_game->Spawn({.position = spawner.pos, .subType = (int)spawner.varData[1], .type = spawner.subtype, + .variant = (int)spawner.varData[0], .seed = spawner.initSeed}); + if (entity->IsEnemy()) + { + npc_sound_play(SOUND_SPAWNER_SUMMON, 1, 2, 1); + entity->AddEntityFlags(FLAG_AMBUSH); + } + entity->Update(); + spawner.Remove(); + if (enemiesBefore != 0 || room.GetAliveEnemiesCount() <= 0) return; + + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + if (GridEntity_Door* door = room.GetDoor(slot)) door->Close(false); + uint32_t& flags = room.descriptor->flags; + if (flags & ROOM_DESCRIPTOR_FLAG_CLEAR) flags |= ROOM_DESCRIPTOR_FLAG_NO_REWARD; + flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; +} + +// The pieces the room keeps through overwrites: lights, decorations, door outlines and ladders. +static void kept_init(Entity_Effect& effect) +{ + effect.AddEntityFlags(FLAG_DONT_OVERWRITE); +} + +// A light starts dark on its default frame. Lighting draws it, never its own Render. +static void light_init(Entity_Effect& light) +{ + light.AddEntityFlags(FLAG_DONT_OVERWRITE); + light.scale = 0; + light.sprite.SetFrame("Default", 0); +} + +// A backdrop detail on the wall in front of a door is gone (the door's state 7 keeps it). +static bool backdrop_detail_cleared(Entity_Effect& effect) +{ + if (!effect.HasEntityFlags(FLAG_BACKDROP_DETAIL) || effect.renderZOffset >= RENDER_Z_DECORATION_LIMIT) return false; + + GridEntity* grid = grid_entity_at(effect.pos); + if (!grid || grid->type != GRID_DOOR || grid->state == DOOR_STATE_KEEPS_DECORATIONS) return false; + effect.Remove(); + return true; +} + +// A light's frame: off a door's wall, flickering for subtype 1 while lit, fading out over its timeout's last +// stretch, gone when dead. A light that lost the parent it followed starts fading in Update's shared part. +static EffectUpdateEnd light_update(Entity_Effect& light) +{ + if (backdrop_detail_cleared(light)) return EFFECT_UPDATE_RETURN; + + if (light.timeout < 0 || light.state <= light.timeout) + { + if (light.subtype == LIGHT_FLICKER) + { + if (random_below(LIGHT_TOGGLE_ODDS) == 0) light.isVisible = !light.isVisible; + if (random_below(LIGHT_DIM_ODDS) == 0) + { + float dim = random_unit() * LIGHT_ALPHA_SPAN; + light.sprite.color._tint[3] = dim * random_unit() + LIGHT_ALPHA_MIN; + } + } + } + else light.sprite.color._tint[3] = light.color._tint[3] * ((float)light.timeout / (float)light.state); + if (light.isDead) light.Remove(); + return EFFECT_UPDATE_FINISH; +} + +static EffectUpdateEnd backdrop_decoration_update(Entity_Effect& decoration) +{ + return backdrop_detail_cleared(decoration) ? EFFECT_UPDATE_RETURN : EFFECT_UPDATE_FINISH; +} + +// Game::GetNearestPlayerEx 00703ab0 for the main players: the nearest one that is no coop ghost, hologram or held +// body and still collides. +static Entity_Player* nearest_main_player_get(Vector position) +{ + Entity_Player* nearest = nullptr; + float nearestDistance = 1e10f; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = distance_squared(position, player->pos); + if (distance >= nearestDistance || player->variant != 0 || player->isCoopGhost || player->parent) continue; + if (player->IsHologram() || player->entityCollisionClass == ENTCOLL_NONE) continue; + nearest = player; + nearestDistance = distance; + } + return nearest; +} + +// A ladder's frame: it counts the frames no player stands close, and a player climbing it once it is ready leaves. +static void tall_ladder_update(Entity_Effect& ladder) +{ + Entity_Player* player = nearest_main_player_get(ladder.pos); + float distance = player ? vector_length(vector_sub(ladder.pos, player->pos)) : 1e9f; + + ladder.state = distance < LADDER_NEAR && ladder.state <= LADDER_ARM_FRAMES ? 0 : ladder.state + 1; + if (player && distance < LADDER_CLIMB && ladder.state > LADDER_ARM_FRAMES) + reconstruction_missing("Entity_Effect::Update 005d4380: climbing a ladder out of the room"); +} + +// The creep: how long it lasts, where it lies, and how it fades when it dies. +constexpr std::array LASTING_CREEPS = {EFFECT_PLAYER_CREEP_LEMON_MISHAP, EFFECT_PLAYER_CREEP_HOLYWATER, + EFFECT_PLAYER_CREEP_LEMON_PARTY, EFFECT_PLAYER_CREEP_PUDDLE_MILK}; +constexpr int CREEP_RENDER_Z = 2000; +constexpr int CREEP_FRAMES = 125; +constexpr int LASTING_CREEP_FRAMES = 290; +constexpr int GREEN_CREEP_FRAMES = 25; +constexpr int BACKDROP_WOMB = 10; +constexpr unsigned int CREEP_STATIC_RENDER_FLAG = 0x20; +constexpr float LEMON_MISHAP_PLAYER_SCALE = 1.3f; +constexpr float CREEP_RADIUS_PER_SCALE = 20; +constexpr float CREEP_FADE_SHRINK = 0.98f; +constexpr int CREEP_FADE_FRAMES = 40; +constexpr int CREEP_BLOOD_KINDS = 6; +constexpr int CREEP_DAMAGE_COUNTDOWN = 30; +constexpr int CREEP_RANDOM_TIMEOUT = 30; +constexpr int CREEP_DAMAGE_PERIOD = 3; +constexpr float CREEP_ELLIPSE_SQUASH = 1.75f; +constexpr float CREEP_TEXEL_OPAQUE = 0.5f; +constexpr float SCREEN_SCALE = 0.65f; + +// The creep sizes: the spawn scale picks the art, smaller than 0.99, 1.3 and 2.1. +constexpr float CREEP_SMALL = 0.99f; +constexpr float CREEP_BIG = 1.3f; +constexpr float CREEP_BIGGEST = 2.1f; + +// Lost Cork grows the players' creep by its multiplier: small creep gains size, larger creep multiplies it. +constexpr uint32_t TRINKET_LOST_CORK = 106; +constexpr std::array CORK_SMALL_GROWTH = {1, 1.25f, 1.5f}; +constexpr std::array CORK_GROWTH = {1.65f, 1.9f, 2.15f}; + +// What spares a player creep: Callus, and the collectible 571 (Evil Charm's immunity is the player's). +constexpr uint32_t TRINKET_CALLUS = 14; +constexpr int COLLECTIBLE_CREEP_IMMUNE = 571; +constexpr uint64_t DAMAGE_ACID = 1 << 4; +constexpr uint64_t DAMAGE_COUNTDOWN = 1 << 6; + +// The slowing creep: white slows more than the black and brown, for ten frames past touching it, tinted grey-blue. +constexpr int PLAYER_SLOW_FRAMES = -10; +constexpr int ENEMY_SLOW_FRAMES = -1; +constexpr float WHITE_CREEP_SLOW = 0.75f; +constexpr float CREEP_SLOW = 0.85f; +constexpr float PLAYER_CREEP_SLOW = 0.9f; +constexpr ColorMod CREEP_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}}; + +// The holy water trail's homing: how far ahead it looks, how far it searches, and how fast it follows. +constexpr float HOMING_LOOKAHEAD = 5; +constexpr float HOMING_RANGE = 128; +constexpr float HOMING_NONE = 1e9f; +constexpr float HOMING_HIT_PENALTY = 1000; +constexpr float HOMING_MAX_PULL = 4; +constexpr float HOMING_PULL_DIVISOR = 10; +constexpr int TEAR_FLAG_HOMING = 2; + +// The players' lasting creep grows in over its first 15 frames and shrinks away over its last 65. Holy water freezes +// what it burns, now and then. +constexpr float LASTING_GROW_FRAMES = 15; +constexpr float LASTING_SHRINK_FRAMES = 65; +constexpr int PLAYER_CREEP_COUNTDOWN = 10; +constexpr int HOLY_WATER_FREEZE_PERIOD = 10; +constexpr int HOLY_WATER_VERSUS_FREEZE_PERIOD = 60; +constexpr int HOLY_WATER_FREEZE = 10; +constexpr int HOLY_WATER_BOSS_FREEZE = 90; + +// Black Powder's pentagram: its reach from its spawn scale, its tiny start, its burn and its fade. +constexpr float PENTAGRAM_REACH = 0.7f; +constexpr float PENTAGRAM_START_SCALE = 0.00390625f; +constexpr float PENTAGRAM_DAMAGE = 10; +constexpr float PENTAGRAM_VERSUS_DAMAGE = 5; +constexpr float PENTAGRAM_FADE = 0.8f; +constexpr int PENTAGRAM_FADE_FRAMES = 10; + +// A color with its tint and offset, as the Color constructors build it. +static ColorMod color_make(std::array tint, std::array offset) +{ + return {{tint[0], tint[1], tint[2], tint[3]}, {0, 0, 0, 0}, {offset[0], offset[1], offset[2]}}; +} + +// A spritesheet's texels, read once from its file. +struct Texels +{ + std::vector rgba; + int height = 0; + int width = 0; +}; + +static const Texels& texels_get(const KAGE::Graphics::ImageBase& image) +{ + static std::unordered_map cache; + auto [entry, isNew] = cache.try_emplace(image.path); + if (!isNew) return entry->second; + + int channels = 0; + Texels& texels = entry->second; + stbi_uc* data = stbi_load(resource_path(image.path).c_str(), &texels.width, &texels.height, &channels, STBI_rgb_alpha); + if (data) texels.rgba.assign(data, data + (size_t)texels.width * texels.height * 4); + stbi_image_free(data); + return texels; +} + +// The texel at a spritesheet position, white off the image. +static KColor texel_read(const KAGE::Graphics::ImageBase& image, int x, int y) +{ + const Texels& texels = texels_get(image); + if ((uint32_t)x >= (uint32_t)texels.width || (uint32_t)y >= (uint32_t)texels.height || texels.rgba.empty()) + return kcolor_rgba(1, 1, 1, 1); + + const uint8_t* texel = &texels.rgba[((size_t)y * texels.width + x) * 4]; + return kcolor_rgba(texel[0] / 255.0f, texel[1] / 255.0f, texel[2] / 255.0f, texel[3] / 255.0f); +} + +// ANM2::GetTexel 0040b600: the color a sprite drawn at a place shows at a point, from the first layer (by track) +// whose texel there is at least half opaque, tinted and offset by the sprite's, layer's and keyframe's colors. None is +// clear. The original reads the texel back from the texture, this from the spritesheet's file. +static KColor sprite_texel_get(ANM2& sprite, Vector point, Vector place) +{ + const AnimationState& state = sprite.animState; + if (!state.animData) return kcolor_rgba(0, 0, 0, 0); + + for (size_t track = 0; track < state.animData->animLayers.size(); track++) + { + const AnimationLayer& animLayer = state.animData->animLayers[track]; + int frameIndex = state.layerFrames[track]; + LayerState* layer = sprite.GetLayer(animLayer.layerId); + if (animLayer.frames.empty() || !layer || frameIndex < 0 || frameIndex >= (int)animLayer.frames.size()) continue; + + const AnimationFrame& frame = animLayer.frames[frameIndex]; + if (!frame.isVisible || !layer->isVisible || !layer->spriteSheet) continue; + + SourceQuad source = AnimationLayer::GetSourceQuad(frame, *layer, SpriteDraw{}, sprite); + DestinationQuad screen = AnimationLayer::GetDestQuad(frame, *layer, SpriteDraw{place, {}, {}}, sprite); + float layerTurn = frame.rotation + layer->rotation; + float spriteTurn = sprite.rotation; + if (spriteTurn != 0 || layerTurn != 0) + { + float scaleX = frame.scale.x * layer->size.x; + float scaleY = frame.scale.y * layer->size.y; + float spriteScaleY = sprite.isFlipY ? -sprite.scale.y : sprite.scale.y; + if ((sprite.scale.x < 0) != (scaleX < 0)) + { + if (sprite.scale.x < 0) + { + layerTurn = -layerTurn; + spriteTurn = -spriteTurn; + } + if (scaleX < 0) layerTurn = -layerTurn; + } + if (layer->isFlipY) scaleY = -scaleY; + if ((spriteScaleY < 0) != (scaleY < 0)) + { + if (spriteScaleY < 0) + { + layerTurn = -layerTurn; + spriteTurn = -spriteTurn; + } + if (scaleY < 0) layerTurn = -layerTurn; + } + + float angle = -(layerTurn + spriteTurn) * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + for (Vector* corner : {&screen._topLeft, &screen._topRight, &screen._bottomLeft, &screen._bottomRight}) + *corner = vector_make(corner->x * cosine - corner->y * sine, corner->y * cosine + corner->x * sine); + point = vector_make(cosine * point.x - sine * point.y, cosine * point.y + sine * point.x); + } + + Vector topLeft = screen._topLeft; + Vector bottomRight = screen._bottomRight; + if (point.x <= topLeft.x || point.x >= bottomRight.x || point.y <= topLeft.y || point.y >= bottomRight.y) continue; + + float u = std::clamp((point.x - topLeft.x) / (bottomRight.x - topLeft.x), 0.0f, 1.0f); + float v = std::clamp((point.y - topLeft.y) / (bottomRight.y - topLeft.y), 0.0f, 1.0f); + float x = (source._bottomRight.x - source._topLeft.x) * u + source._topLeft.x; + float y = (source._bottomRight.y - source._topLeft.y) * v + source._topLeft.y; + KColor texel = texel_read(*layer->spriteSheet, (int)x, (int)y); + if (texel._alpha < CREEP_TEXEL_OPAQUE) continue; + + std::array tint{}; + std::array offset{}; + for (int i = 0; i < 4; i++) tint[i] = frame.color._tint[i] * (layer->color._tint[i] * sprite.color._tint[i]); + for (int i = 0; i < 3; i++) offset[i] = frame.color._offset[i] + (layer->color._offset[i] + sprite.color._offset[i]); + return kcolor_rgba(tint[0] * texel._red + offset[0], tint[1] * texel._green + offset[1], + tint[2] * texel._blue + offset[2], tint[3] * texel._alpha); + } + return kcolor_rgba(0, 0, 0, 0); +} + +// Lost Cork's multiplier for a creep's owner, 1 to 3, or 0 for none. +static int lost_cork_get(Entity* owner) +{ + if (!owner || !owner->is_player()) return 0; + + Entity_Player& player = *static_cast(owner); + if (!player.HasTrinket(TRINKET_LOST_CORK)) return 0; + int multiplier = player.GetTrinketMultiplier(TRINKET_LOST_CORK); + return multiplier >= 1 && multiplier <= (int)CORK_GROWTH.size() ? multiplier : 0; +} + +// Creep lies on the floor among the floor stains and lasts 125 frames (green 25), the players' lemon, holy water and +// milk 290. Red creep is grey in the Womb, a player's Lemon Mishap larger. +static void creep_init(Entity_Effect& creep) +{ + creep.sortingLayer = SORTING_BACKGROUND; + creep.renderZOffset = CREEP_RENDER_Z; + bool isLasting = is_listed(LASTING_CREEPS, creep.variant); + if (isLasting) creep.lifespan = LASTING_CREEP_FRAMES; + creep.timeout = isLasting ? LASTING_CREEP_FRAMES : CREEP_FRAMES; + creep.isUnknown176 = true; + if (creep.variant == EFFECT_CREEP_RED && g_game->room->backdropType == BACKDROP_WOMB) + creep.sprite.color = tint_make(0.5f, 0.5f, 0.5f, 1); + if (creep.variant == EFFECT_CREEP_STATIC) creep.sprite.bitflags |= CREEP_STATIC_RENDER_FLAG; + if (creep.variant == EFFECT_PLAYER_CREEP_GREEN) creep.timeout = GREEN_CREEP_FRAMES; + if (creep.variant == EFFECT_PLAYER_CREEP_LEMON_MISHAP && creep.spawnerEntity && creep.spawnerEntity->is_player()) + creep.scale = LEMON_MISHAP_PLAYER_SCALE; +} + +// Settles creep on its first frame: its art and radius by the scale it was spawned at (Lost Cork's growth added), +// drawn at its own scale on the game's frame of a random puddle. The players' white, red, green and holy water creep +// and the yellow hold their first frame, the black and Black Powder their third, and the holy water, brown, yellow and +// slippery creep take their colors. Its alpha now is what it fades from. +// The original divides by zero for an animation without frames. This takes the first frame. +static void creep_settle(Entity_Effect& creep) +{ + creep.state++; + float spawnScale = creep.sprite.scale.x; + if (int cork = creep.spawnerEntity ? lost_cork_get(creep.spawnerEntity->GetLastSpawner()) : 0) + { + if (spawnScale >= CREEP_BIGGEST) creep.scale *= CORK_GROWTH[cork - 1]; + else if (spawnScale >= CREEP_SMALL) spawnScale *= CORK_GROWTH[cork - 1]; + else spawnScale += CORK_SMALL_GROWTH[cork - 1]; + } + + const char* kind = "SmallBlood"; + if (spawnScale >= CREEP_SMALL && creep.variant != EFFECT_PLAYER_CREEP_BLACKPOWDER) + kind = spawnScale >= CREEP_BIGGEST ? "BiggestBlood" : spawnScale >= CREEP_BIG ? "BigBlood" : "Blood"; + char animation[32]; + std::snprintf(animation, sizeof(animation), "%s%02d", kind, random_below(CREEP_BLOOD_KINDS) + 1); + creep.size = spawnScale * CREEP_RADIUS_PER_SCALE * creep.scale; + creep.sprite.scale = vector_make(creep.scale, creep.scale); + creep.sprite.Play(animation); + int length = creep.sprite.animState.GetAnimationLength(); + creep.sprite.SetFrame(length > 0 ? (float)(g_game->frameCount % length) : 0.0f); + + switch (creep.variant) + { + case EFFECT_PLAYER_CREEP_WHITE: + case EFFECT_PLAYER_CREEP_RED: + case EFFECT_PLAYER_CREEP_GREEN: + case EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL: + case EFFECT_CREEP_BROWN: + case EFFECT_PLAYER_CREEP_YELLOW: + creep.sprite.SetFrame(0.0f); + creep.sprite.Stop(); + if (creep.variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL) + { + ColorMod& color = creep.sprite.color; + KColor water = kcolor_rgba(135 / 255.0f, 165 / 255.0f, 201 / 255.0f, 1); + creep.sprite.color = color_make({0, 0, 0, 1}, {color._tint[0] * water._red + color._offset[0], + color._tint[1] * water._green + color._offset[1], + color._tint[2] * water._blue + color._offset[2]}); + creep.timeout /= 2; + } + else if (creep.variant == EFFECT_CREEP_BROWN) + creep.sprite.color = color_make({0, 0, 0, 1}, {166 / 255.0f, 104 / 255.0f, 41 / 255.0f}); + else if (creep.variant == EFFECT_PLAYER_CREEP_YELLOW) + creep.sprite.color = color_make({0, 0, 0, 1}, {146 / 255.0f, 146 / 255.0f, 10 / 255.0f}); + break; + case EFFECT_PLAYER_CREEP_BLACK: + case EFFECT_PLAYER_CREEP_BLACKPOWDER: + creep.sprite.SetFrame(2.0f); + creep.sprite.Stop(); + break; + case EFFECT_CREEP_SLIPPERY_BROWN: + creep.sprite.color = color_make({0, 0, 0, 1}, {0.6f, 0.4f, 0}); + break; + } + creep.minRadius = creep.sprite.color._tint[3]; +} + +// Runs touch for each player on the ground the creep's opaque part lies under, and leaves its color on their feet +// unless it is Dogma's. +static void creep_players_touch(Entity_Effect& creep, void (*touch)(Entity_Effect&, Entity_Player&)) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->isDead || player->entityCollisionClass == ENTCOLL_NONE) continue; + if (player->entityGridCollisionClass != GRIDCOLL_GROUND || player->HasTrinket(TRINKET_CALLUS)) continue; + if (player->HasCollectible(COLLECTIBLE_CREEP_IMMUNE)) continue; + float distance = vector_length(vector_sub(player->pos, creep.pos)); + if (distance >= creep.size * creep.sprite.scale.x + player->size) continue; + + Vector point = vector_scale(player->pos, SCREEN_SCALE); + KColor texel = sprite_texel_get(creep.sprite, point, vector_scale(creep.pos, SCREEN_SCALE)); + if (texel._alpha <= CREEP_TEXEL_OPAQUE) continue; + touch(creep, *player); + if (creep.variant != EFFECT_CREEP_STATIC) player->SetFootprintColor(texel, false); + } +} + +// Whether a player shrugs creep off: Evil Charm against its kind, or the collectible 571. +static bool is_creep_immune(Entity_Effect& creep, Entity_Player& player) +{ + return player.is_evil_charm_immune(EntityRef(&creep)) || player.HasCollectible(COLLECTIBLE_CREEP_IMMUNE); +} + +// Red, green and yellow creep burn a player for a heart, as their parent's. +static void creep_burn(Entity_Effect& creep, Entity_Player& player) +{ + if (is_creep_immune(creep, player)) return; + Entity* source = creep.parent ? creep.parent.get() : &creep; + player.TakeDamage(1, DAMAGE_ACID, EntityRef(source), CREEP_DAMAGE_COUNTDOWN); +} + +// White, black and brown creep slow a player. +static void creep_slow(Entity_Effect& creep, Entity_Player& player) +{ + if (is_creep_immune(creep, player)) return; + float slow = creep.variant == EFFECT_CREEP_WHITE ? WHITE_CREEP_SLOW : CREEP_SLOW; + player.AddSlowing(EntityRef(&creep), PLAYER_SLOW_FRAMES, slow, CREEP_SLOW_COLOR, false); +} + +// Slippery creep makes a player slide. +static void creep_slip(Entity_Effect&, Entity_Player& player) +{ + player.AddEntityFlags(FLAG_SLIPPERY_PHYSICS); +} + +// Whether the players' creep reaches an entity: a vulnerable enemy on the ground that did not spawn it, within the +// creep's radius squashed into a floor ellipse. A player counts unless creep cannot touch them. +static bool is_creep_victim(Entity_Effect& creep, Entity& entity, float radius) +{ + if (entity.is_player() && is_creep_immune(creep, *static_cast(&entity))) return false; + if (!entity.IsVulnerableEnemy(nullptr) || entity.IsFlying()) return false; + if (creep.spawnerEntity && creep.spawnerEntity->IsDescendantOf(&entity)) return false; + + Vector offset = vector_sub(entity.pos, creep.pos); + offset.y *= CREEP_ELLIPSE_SQUASH; + float reach = radius + entity.size; + return vector_length_squared(offset) < reach * reach; +} + +// Burns an enemy with the creep's damage as acid, or raises the acid hit it already takes this frame to it. +static void creep_acid_burn(Entity_Effect& creep, Entity& enemy) +{ + if (!(enemy.pendingDamageFlags & DAMAGE_ACID)) + { + enemy.TakeDamage(creep.collisionDamage, DAMAGE_ACID, EntityRef(&creep), CREEP_DAMAGE_COUNTDOWN); + return; + } + for (DamageEvent& event : enemy.damageEvents) + { + if (!(event.damageFlags & DAMAGE_ACID)) continue; + event.damage = std::max(event.damage, creep.collisionDamage); + break; + } +} + +// The tear flags a holy water trail carries in its extra data. +static TearFlags creep_tear_flags(const Entity_Effect& creep) +{ + TearFlags flags; + for (size_t bit = 0; bit < flags.size(); bit++) flags[bit] = (creep.varData[bit / 32] >> (bit % 32)) & 1; + return flags; +} + +// A homing holy water trail picks the nearest enemy on the ground ahead of it (with some chance, and ones it hit +// last), and drifts toward its target. +static void holy_water_trail_home(Entity_Effect& trail) +{ + if (!trail.target) + { + Entity* best = nullptr; + float bestScore = HOMING_NONE; + Vector ahead = vector_add(trail.pos, vector_scale(trail.velocity, HOMING_LOOKAHEAD)); + for (Entity* enemy : entities_near(ahead, HOMING_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + if (trail.spawnerEntity && trail.spawnerEntity->IsDescendantOf(enemy)) continue; + if (enemy->HasEntityFlags(FLAG_FRIENDLY) || enemy->entityGridCollisionClass != GRIDCOLL_GROUND) continue; + float score = vector_length(vector_sub(ahead, enemy->pos)) + random_unit() * HOMING_RANGE; + if (EntityList::HitListContains(trail.hitList, *enemy)) score += HOMING_HIT_PENALTY; + if (score >= bestScore) continue; + bestScore = score; + best = enemy; + } + trail.target = best; + } + if (!trail.target) return; + + Vector pull = vector_sub(trail.target->pos, trail.pos); + if (vector_length(pull) > HOMING_MAX_PULL) pull = vector_resized(pull, HOMING_MAX_PULL); + trail.velocity = vector_add(trail.velocity, vector_scale(pull, 1 / HOMING_PULL_DIVISOR)); +} + +// Every third frame the players' red, holy water and yellow creep burn the enemies over them they have not hit, and +// the holy water trail brings its tears' effects and drifts after enemies when it homes. +static void creep_enemies_burn(Entity_Effect& creep) +{ + if (g_game->frameCount % CREEP_DAMAGE_PERIOD != 0) return; + + float radius = creep.size * creep.sprite.scale.x; + bool isTrail = creep.variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL; + TearFlags flags = creep_tear_flags(creep); + for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + { + if (EntityList::HitListContains(creep.hitList, *enemy) || !is_creep_victim(creep, *enemy, radius)) continue; + creep_acid_burn(creep, *enemy); + if (isTrail) Entity_Tear::ApplyTearFlagEffects(enemy, creep.pos, flags, &creep, creep.collisionDamage); + } + if (!isTrail) return; + if (flags[TEAR_FLAG_HOMING]) holy_water_trail_home(creep); + else creep.velocity = {}; +} + +// The creep's frame: settled on its first, it dies with its room's enemies (or in a flooded stage's water) unless it +// is the players'. Alive and not just decoration, enemies' creep burns, slows or trips the players over it, the +// players' slows or burns enemies. Dead, it shrinks and fades out over 40 frames. +static void creep_update(Entity_Effect& creep) +{ + Room& room = *g_game->room; + int variant = creep.variant; + + if (creep.state == 0) creep_settle(creep); + int stageId = room.waterAmount > 0.1f ? g_game->GetStageID() : 0; + bool isFlooded = stageId == 12 || stageId == 33; + bool isFriendly = creep.HasEntityFlags(FLAG_FRIENDLY); + if (!isFriendly && !Entity_Effect::IsPlayerCreep(variant) && ((room.IsClear() && room.GetAliveEnemiesCount() <= 0) || isFlooded)) + creep.isDead = true; + + bool isStaticBurning = variant == EFFECT_CREEP_STATIC && !isFriendly; + if (!creep.isDead && !creep.HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) + { + bool isSticky = variant == EFFECT_CREEP_WHITE || variant == EFFECT_CREEP_BLACK || variant == EFFECT_CREEP_BROWN; + if ((isSticky || variant == EFFECT_CREEP_SLIPPERY_BROWN) && creep.timeout == 0 && !creep.parent) + creep.timeout = random_below(CREEP_RANDOM_TIMEOUT); + + if (variant == EFFECT_CREEP_RED || variant == EFFECT_CREEP_GREEN || variant == EFFECT_CREEP_YELLOW || isStaticBurning) + creep_players_touch(creep, creep_burn); + else if (isSticky) creep_players_touch(creep, creep_slow); + else if (variant == EFFECT_CREEP_SLIPPERY_BROWN) creep_players_touch(creep, creep_slip); + else if (variant == EFFECT_PLAYER_CREEP_WHITE || variant == EFFECT_PLAYER_CREEP_BLACK) + { + float radius = creep.size * creep.sprite.scale.x; + for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + if (is_creep_victim(creep, *enemy, radius)) + enemy->AddSlowing(EntityRef(&creep), ENEMY_SLOW_FRAMES, PLAYER_CREEP_SLOW, CREEP_SLOW_COLOR, false); + } + else if (variant == EFFECT_PLAYER_CREEP_RED || variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL || + variant == EFFECT_PLAYER_CREEP_YELLOW) + creep_enemies_burn(creep); + else if (variant == EFFECT_PLAYER_CREEP_GREEN) + { + float radius = creep.size * creep.sprite.scale.x; + for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + if (is_creep_victim(creep, *enemy, radius)) + enemy->TakeDamage(creep.collisionDamage, 0, EntityRef(&creep), CREEP_DAMAGE_COUNTDOWN); + } + } + + if (!creep.isDead) return; + creep.sprite.scale = vector_scale(creep.sprite.scale, CREEP_FADE_SHRINK); + float fade = std::clamp((float)(CREEP_FADE_FRAMES - creep.state) / CREEP_FADE_FRAMES, 0.0f, 1.0f); + creep.sprite.color._tint[3] = fade * creep.minRadius; + if (++creep.state > CREEP_FADE_FRAMES) creep.Remove(); +} + +// The players' lasting creep (Lemon Mishap, holy water, Lemon Party, milk): Lost Cork grows it on its first frame. It +// grows in and shrinks out with its timeout (a player's Lemon Mishap holds full size), and all but the milk burn the +// enemies over it, holy water freezing them now and then. +static void lasting_creep_update(Entity_Effect& creep) +{ + if (creep.state == 0) + { + Entity* owner = creep.GetLastSpawner(); + if (int cork = owner ? lost_cork_get(owner->ToPlayer()) : 0) creep.scale *= CORK_GROWTH[cork - 1]; + creep.state++; + } + + float growth = 1; + if (creep.timeout > creep.lifespan - (int)LASTING_GROW_FRAMES) + growth = (float)(creep.lifespan - creep.timeout) / LASTING_GROW_FRAMES; + else if (creep.variant == EFFECT_PLAYER_CREEP_LEMON_MISHAP && creep.spawnerEntity && creep.spawnerEntity->is_player()) + creep.timeout++; + else if (creep.timeout < (int)LASTING_SHRINK_FRAMES) growth = (float)creep.timeout / LASTING_SHRINK_FRAMES; + creep.sprite.scale = vector_make(growth * creep.scale, growth * creep.scale); + + if (creep.variant != EFFECT_PLAYER_CREEP_PUDDLE_MILK) + { + float radius = creep.size * growth * creep.scale; + int freezePeriod = g_game->deathmatchManager.is_active() ? HOLY_WATER_VERSUS_FREEZE_PERIOD : HOLY_WATER_FREEZE_PERIOD; + for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + { + if (!is_creep_victim(creep, *enemy, radius)) continue; + enemy->TakeDamage(creep.collisionDamage, DAMAGE_COUNTDOWN, EntityRef(&creep), PLAYER_CREEP_COUNTDOWN); + if (creep.variant != EFFECT_PLAYER_CREEP_HOLYWATER || !creep.IsFrame(freezePeriod, 0)) continue; + enemy->AddFreeze(EntityRef(&creep), enemy->IsBoss() ? HOLY_WATER_BOSS_FREEZE : HOLY_WATER_FREEZE, false); + } + } + if (creep.isDead) creep.Remove(); +} + +// Black Powder's pentagram: it starts as a speck with its reach from its spawn scale and burns the enemies inside it +// until it dies, then fades out over 10 frames. +static void pentagram_update(Entity_Effect& pentagram) +{ + if (pentagram.state == 0) + { + pentagram.state++; + pentagram.size = pentagram.sprite.scale.x * pentagram.scale * PENTAGRAM_REACH; + float start = pentagram.scale * PENTAGRAM_START_SCALE; + pentagram.sprite.scale = vector_make(start, start); + pentagram.sprite.Play("Pentagram"); + } + + if (!pentagram.isDead) + { + float damage = g_game->deathmatchManager.is_active() ? PENTAGRAM_VERSUS_DAMAGE : PENTAGRAM_DAMAGE; + for (Entity* enemy : entities_near(pentagram.pos, pentagram.size, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || pentagram.IsDescendantOf(enemy)) continue; + float reach = enemy->size + pentagram.size; + if (distance_squared(enemy->pos, pentagram.pos) >= reach * reach) continue; + enemy->TakeDamage(damage, DAMAGE_ACID | DAMAGE_COUNTDOWN, EntityRef(&pentagram), PLAYER_CREEP_COUNTDOWN); + } + return; + } + pentagram.sprite.color._tint[3] *= PENTAGRAM_FADE; + if (++pentagram.state > PENTAGRAM_FADE_FRAMES) pentagram.Remove(); +} + +// The Downpour's tadpoles: their swim and its pull by the current, their darts away from the walls and from a player +// close by. +constexpr float TADPOLE_FRICTION = 0.93f; +constexpr float TADPOLE_STROKE = 0.2f; +constexpr float TADPOLE_CURRENT_PULL = 0.3f; +constexpr float TADPOLE_SPEED_ANIMATION = 0.5f; +constexpr float TADPOLE_FASTEST_ANIMATION = 2.5f; +constexpr float TADPOLE_WALL_MARGIN = 40; +constexpr float TADPOLE_WALL_TURN = 0.05f; +constexpr float TADPOLE_WOBBLE = 10; +constexpr float TADPOLE_TIRE_MIN = 0.9f; +constexpr float TADPOLE_TIRE_SPAN = 0.1f; +constexpr float TADPOLE_RESTING = 0.05f; +constexpr int TADPOLE_REST_KICK_ODDS = 15; +constexpr int TADPOLE_KICK_ODDS = 30; +constexpr int TADPOLE_CURRENT_KICK_ODDS = 3; +constexpr float TADPOLE_KICK_JITTER = 0.4f; +constexpr float TADPOLE_CURRENT_KICK = 1.35f; +constexpr float TADPOLE_SLOW = 0.6f; +constexpr float TADPOLE_FLEE_RANGE_SQUARED = 4900; +constexpr int TADPOLE_FLEE_ODDS = 3; +constexpr int TADPOLE_STILL_FLEE_ODDS = 40; +constexpr float TADPOLE_STILL_SPEED_SQUARED = 0.1f; +constexpr float TADPOLE_FLEE_SPREAD = 40; +constexpr float TADPOLE_FLEE_SPEED = 2; +constexpr float TADPOLE_SPLASH_RANGE = 10; + +// The lil ghosts: where they appear (away from shots, enemies and players), how long they stay gone, and their drift. +constexpr int GHOST_GONE_MIN = 30; +constexpr int GHOST_GONE_SPAN = 600; +constexpr int GHOST_FIRST_TRIES = 5; +constexpr float GHOST_ROOM_MARGIN = 20; +constexpr float GHOST_SPOT_CLEARANCE = 200; +constexpr float GHOST_SHY_RANGE = 80; +constexpr float GHOST_DRIFT = 0.005f; +constexpr float GHOST_TURN = 10; +constexpr float GHOST_SCALE_SPAN = 0.2f; +constexpr float GHOST_SPEED_SPAN = 0.3f; +constexpr float GHOST_ALPHA_MIN = 0.3f; +constexpr float GHOST_ALPHA_SPAN = 0.3f; +constexpr uint32_t GHOST_SHY_OF = QUERY_PROJECTILES | QUERY_TEARS | QUERY_ENEMIES | QUERY_PLAYERS; + +// The backdrops whose lil ghosts are pale violet: the Mausoleum's. +constexpr std::array GHOST_PALE_BACKDROPS = {33, 38, 40, 41, 42}; + +// The heaven door (subtype 0), Luna's moonlight (1) and the light beam up (2): how close a player steps in, when the +// door is ready, and the sounds. +constexpr int HEAVEN_DOOR_MOONLIGHT = 1; +constexpr int HEAVEN_DOOR_BEAM = 2; +constexpr int ROOM_INDEX_GENESIS = -2; +constexpr float HEAVEN_DOOR_RANGE_SQUARED = 625; +constexpr float MOONLIGHT_RANGE_SQUARED = 900; +constexpr int MOONLIGHT_READY = 60; +constexpr int HEAVEN_DOOR_READY = 41; +constexpr int HEAVEN_DOOR_EARLY = 8; +constexpr int HEAVEN_DOOR_RESET = -10; +constexpr int HEAVEN_DOOR_REOPEN = 25; +constexpr int BEAM_READY = 32; +constexpr int BEAM_FADE = 82; +constexpr int SOUND_POWER_UP = 128; +constexpr int SOUND_HEAVEN_DOOR = 1051; +constexpr int MOONLIGHT_GROUND_LAYER = 2; +constexpr float MOONLIGHT_DEPTH = 10; + +// A tadpole swims on the floor, facing a random way. +static void tadpole_init(Entity_Effect& tadpole) +{ + tadpole.sprite.Play("Idle"); + tadpole.rotation = angle_normalized(random_unit() * FULL_TURN); + tadpole.sprite.GetLayer(0)->rotation = tadpole.rotation + HALF_TURN; + tadpole.height = 0; + tadpole.isUnknown176 = true; +} + +// A tadpole's stroke: a new heading from its old one against the current with a jitter, and a burst of speed. +static void tadpole_kick(Entity_Effect& tadpole, Vector current) +{ + Vector heading = vector_sub(vector_from_angle(tadpole.rotation), current); + tadpole.rotation = vector_angle(vector_add(heading, vector_scale(random_direction(), TADPOLE_KICK_JITTER))); + tadpole.minRadius = random_unit() + 1; + if (!vector_is_zero(current)) tadpole.minRadius *= TADPOLE_CURRENT_KICK; +} + +// A tadpole's frame (its speed is its minimum radius): it swims along its wobbling heading with the current, turns +// from the walls, tires, and kicks off again now and then, more often in a current. Slow, it darts from a player +// close by. It is pushed out of the grid, and splats when stepped on or splashed. +static void tadpole_update(Entity_Effect& tadpole) +{ + Room& room = *g_game->room; + Vector current = room.waterCurrent; + + tadpole.sortingLayer = SORTING_DOOR; + tadpole.friction *= TADPOLE_FRICTION; + Vector stroke = vector_scale(vector_scale(vector_from_angle(tadpole.rotation), tadpole.minRadius), TADPOLE_STROKE); + tadpole.velocity = vector_add(tadpole.velocity, vector_add(stroke, vector_scale(current, TADPOLE_CURRENT_PULL))); + tadpole.sprite.playbackSpeed = std::min(tadpole.minRadius + TADPOLE_SPEED_ANIMATION, TADPOLE_FASTEST_ANIMATION); + Vector inside = room.GetClampedPosition(tadpole.pos, TADPOLE_WALL_MARGIN); + if (inside.x != tadpole.pos.x || inside.y != tadpole.pos.y) + tadpole.rotation = angle_lerp(tadpole.rotation, vector_angle(vector_sub(inside, tadpole.pos)), TADPOLE_WALL_TURN); + tadpole.rotation = angle_normalized(random_unit() * TADPOLE_WOBBLE + tadpole.rotation - TADPOLE_WOBBLE / 2); + tadpole.minRadius *= random_unit() * TADPOLE_TIRE_SPAN + TADPOLE_TIRE_MIN; + + bool isKick = tadpole.minRadius <= TADPOLE_RESTING && random_below(TADPOLE_REST_KICK_ODDS) == 0; + if (!isKick) isKick = random_below(TADPOLE_KICK_ODDS) == 0; + if (!isKick) isKick = !vector_is_zero(current) && random_below(TADPOLE_CURRENT_KICK_ODDS) == 0; + if (isKick) tadpole_kick(tadpole, current); + + Entity_Player* player = nearest_player_get(tadpole.pos); + float playerDistance = distance_squared(tadpole.pos, player->pos); + if (tadpole.minRadius <= TADPOLE_SLOW && playerDistance < TADPOLE_FLEE_RANGE_SQUARED && + random_below(TADPOLE_FLEE_ODDS) == 0) + { + bool isStill = vector_length_squared(player->velocity) <= TADPOLE_STILL_SPEED_SQUARED; + if (!isStill || random_below(TADPOLE_STILL_FLEE_ODDS) == 0) + { + float away = vector_angle(vector_sub(tadpole.pos, player->pos)); + tadpole.rotation = away + random_unit() * TADPOLE_FLEE_SPREAD - TADPOLE_FLEE_SPREAD / 2; + tadpole.minRadius = random_unit() + TADPOLE_FLEE_SPEED; + } + } + + tadpole.pos = room.GetClampedPosition(tadpole.pos, BUG_ROOM_MARGIN); + Vector next = vector_add(tadpole.pos, tadpole.velocity); + if (grid_collision_at(next) > COLLISION_PIT) cell_push_out(tadpole, next); + tadpole.targetPosition = tadpole.pos; + + if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying()) + tadpole.isDead = true; + for (Entity* tear : entities_near(tadpole.pos, TADPOLE_SPLASH_RANGE, QUERY_TEARS)) + { + if (tear->type != ENTITY_TEAR || !tear->isDead) continue; + tadpole.isDead = true; + break; + } + if (tadpole.isDead) bug_splat(tadpole, 0); + tadpole.sprite.GetLayer(0)->rotation = tadpole.rotation + HALF_TURN; +} + +// A lil ghost starts where it was spawned with a random heading, size, speed and faintness, pale violet in the dark +// backdrops. +static void lil_ghost_init(Entity_Effect& ghost) +{ + ghost.targetPosition = ghost.pos; + ghost.rotation = angle_normalized(random_unit() * FULL_TURN); + ghost.sprite.Play("Idle"); + float size = ghost.dropRNG.RandomFloat() * GHOST_SCALE_SPAN + 1; + ghost.sprite.scale = vector_make(size, size); + ghost.sprite.isFlipX = ghost.dropRNG.RandomInt(2) != 0; + ghost.sprite.playbackSpeed = ghost.dropRNG.RandomFloat() * GHOST_SPEED_SPAN + 1; + if (is_listed(GHOST_PALE_BACKDROPS, g_game->room->backdropType)) ghost.sprite.color = tint_make(0.96f, 0.9f, 1, 1); + ghost.sprite.color._tint[3] = ghost.dropRNG.RandomFloat() * GHOST_ALPHA_SPAN + GHOST_ALPHA_MIN; + ghost.isUnknown176 = true; +} + +// Picks a quiet spot for a lil ghost, with five tries on its first frames and one after: open floor with nothing +// that shoots or walks within 200. It appears there, or stays gone a frame longer. +static void lil_ghost_spot_find(Entity_Effect& ghost) +{ + Room& room = *g_game->room; + int tries = ghost.FrameCount() < 2 ? GHOST_FIRST_TRIES : 1; + + for (int i = 0; i < tries; i++) + { + Vector spot = room.GetRandomPosition(GHOST_ROOM_MARGIN); + if (grid_collision_at(spot) != COLLISION_NONE || !entities_near(spot, GHOST_SPOT_CLEARANCE, GHOST_SHY_OF).empty()) + continue; + ghost.targetPosition = spot; + ghost.pos = spot; + break; + } + if (vector_is_zero(ghost.targetPosition)) + { + ghost.sprite.Play("Disappear"); + ghost.sprite.SetLastFrame(); + ghost.state = 1; + } + else if (ghost.FrameCount() > 1) ghost.sprite.Play("Appear"); +} + +// A lil ghost's frame: dead, it vanishes for a while instead. Visible, it drifts around its spot and vanishes when +// anything comes within 80. Gone, it waits out its time, then appears at a new spot. +static void lil_ghost_update(Entity_Effect& ghost) +{ + if (ghost.isDead) + { + ghost.isDead = false; + ghost.sprite.Play("Disappear"); + ghost.velocity = {}; + ghost.state = random_below(GHOST_GONE_SPAN) + GHOST_GONE_MIN; + } + if (ghost.state < 1 && vector_is_zero(ghost.targetPosition)) lil_ghost_spot_find(ghost); + if (ghost.state >= 1) + { + ghost.targetPosition = {}; + ghost.state--; + return; + } + + if (ghost.sprite.IsFinished()) ghost.sprite.Play("Idle"); + Vector wander = vector_scale(vector_from_angle(ghost.rotation), random_unit() * GHOST_DRIFT); + Vector home = vector_scale(vector_sub(ghost.targetPosition, ghost.pos), GHOST_DRIFT); + ghost.velocity = vector_add(ghost.velocity, vector_add(wander, home)); + ghost.rotation += GHOST_TURN - random_unit() * GHOST_TURN * 2; + if (ghost.sprite.animState.IsLoopingAnimation() && !entities_near(ghost.pos, GHOST_SHY_RANGE, GHOST_SHY_OF).empty()) + ghost.isDead = true; +} + +// FUN_007ab0e0: whether a player is free to step into a light: no extra or item animation playing, unless carrying +// their twin. +static bool is_player_free(Entity_Player& player) +{ + bool isAnimating = player.isPlayingExtraAnimation || player.isPlayingItemAnimation; + return !isAnimating || (player.heldEntity && player.heldEntity == player.twinPlayer.get()); +} + +// The heaven door keeps through overwrites. Luna's moonlight glows additively with its ground layer hidden, and +// spawns a copy of itself on the floor that shows that ground layer under everything. +static void heaven_door_init(Entity_Effect& door) +{ + door.AddEntityFlags(FLAG_DONT_OVERWRITE); + if (door.subtype != HEAVEN_DOOR_MOONLIGHT) return; + if (door.spawnerType != 0) + { + door.sortingLayer = SORTING_BACKGROUND; + return; + } + + for (int layerId : {0, MOONLIGHT_GROUND_LAYER}) + { + LayerState& layer = *door.sprite.GetLayer(layerId); + layer.minFilterMode = 1; + layer.magFilterMode = 1; + layer_additive_set(layer); + } + door.sprite.GetLayer(MOONLIGHT_GROUND_LAYER)->isVisible = false; + Entity* ground = g_game->Spawn({.position = door.pos, .spawner = &door, .subType = door.subtype, .type = door.type, + .variant = door.variant, .seed = door.initSeed}); + door.child = ground; + ground->parent = &door; + door.renderDepthOffset = MOONLIGHT_DEPTH; +} + +// Luna's moonlight: it shines until a player stands in it once it is ready, then fades out with its ground copy. The +// copy stays on it. +static void moonlight_update(Entity_Effect& light) +{ + if (light.spawnerType != 0) + { + if (!light.parent) light.Remove(); + else light.pos = light.parent->pos; + return; + } + if (light.state < 0) + { + light.sprite.Play("Disappear"); + if (!light.sprite.IsFinished()) return; + light.Remove(); + if (light.child) light.child->Remove(); + return; + } + + light.state++; + light.sprite.Play("Appear"); + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0 || player->parent || player->entityCollisionClass == ENTCOLL_NONE) continue; + if (distance_squared(player->pos, light.pos) >= MOONLIGHT_RANGE_SQUARED || light.state <= MOONLIGHT_READY) continue; + light.state = -1; + npc_sound_play(SOUND_POWER_UP, 1, 2, 1); + reconstruction_missing("Entity_Effect::Update 005d4380: Luna's moonlight blessing (Entity_Effect::CreateTimer)"); + } +} + +// The light beam up: it appears, waits, and once a player free to move stands in it, carries them up. +static void light_beam_update(Entity_Effect& beam) +{ + if (beam.state == 0) + { + beam.sprite.Play("Appear"); + beam.state++; + } + else if (beam.state < BEAM_READY || (beam.state > BEAM_READY && beam.state < BEAM_FADE)) beam.state++; + else if (beam.state == BEAM_FADE) + { + beam.sprite.Play("Disappear"); + beam.state++; + } + else if (beam.state == BEAM_READY) + { + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0 || player->isCoopGhost || player->entityCollisionClass == ENTCOLL_NONE) continue; + if (distance_squared(player->pos, beam.pos) < HEAVEN_DOOR_RANGE_SQUARED && is_player_free(*player)) + reconstruction_missing("Entity_Effect::Update 005d4380: the light beam's travel (AnimateLightTravel)"); + } + } +} + +// The heaven door: open while the room is clear (in Backasswards only in the starting room or Genesis's), it takes a +// player standing in it once ready up to the next floor. A player stepping in too early closes it again. +static void heaven_door_update(Entity_Effect& door) +{ + if (door.subtype == HEAVEN_DOOR_MOONLIGHT) return moonlight_update(door); + if (door.subtype == HEAVEN_DOOR_BEAM) return light_beam_update(door); + + int roomIndex = g_game->currentRoomIdx; + bool isBackasswardsAway = (int)g_game->challenge == CHALLENGE_BACKASSWARDS && roomIndex != g_game->startingRoomIdx && + roomIndex != ROOM_INDEX_GENESIS; + if (!g_game->room->IsClear() || isBackasswardsAway) + { + door.sprite.Play("Disappear"); + door.state = 0; + return; + } + + door.state++; + door.sprite.Play("Appear"); + bool isEntered = false; + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0 || player->entityCollisionClass == ENTCOLL_NONE) continue; + if (distance_squared(player->pos, door.pos) >= HEAVEN_DOOR_RANGE_SQUARED || !is_player_free(*player)) continue; + if (door.state >= HEAVEN_DOOR_READY) + reconstruction_missing("Entity_Effect::Update 005d4380: the heaven door's travel (StartStageTransition)"); + if (door.state < HEAVEN_DOOR_EARLY) door.state = HEAVEN_DOOR_RESET; + npc_sound_play(SOUND_HEAVEN_DOOR, 1, 2, 1); + isEntered = true; + break; + } + if (!isEntered && door.state < 0) door.state = HEAVEN_DOOR_REOPEN; +} + +// Luna's moonlight copy draws its parent's ground layer under everything, the rest their own sprite. +static void heaven_door_render(Entity_Effect& door, const Vector&) +{ + Entity* parent = door.parent; + if (door.subtype != HEAVEN_DOOR_MOONLIGHT || !parent) + return door.sprite.Render(SpriteDraw{door.renderPosition, {}, {}}); + if (parent->sprite.layerStates.size() <= MOONLIGHT_GROUND_LAYER) return; + + LayerState& ground = *parent->sprite.GetLayer(MOONLIGHT_GROUND_LAYER); + ground.isVisible = true; + parent->sprite.RenderLayer(MOONLIGHT_GROUND_LAYER, SpriteDraw{door.renderPosition, {}, {}}); + ground.isVisible = false; +} + +// The beetles: how they crawl in bursts, take off from a player close by and fly about until they land, and what +// knocks them down. +constexpr int BEETLE_FLYING = 1; +constexpr int BEETLE_BURST_ODDS = 40; +constexpr int BEETLE_STEP_ODDS = 10; +constexpr int BEETLE_TAKEOFF_ODDS = 3; +constexpr int BEETLE_STILL_TAKEOFF_ODDS = 40; +constexpr int BEETLE_FLEE_ODDS = 2; +constexpr int BEETLE_LAND_ODDS = 100; +constexpr float BEETLE_STEP = 0.05f; +constexpr float BEETLE_RUN = 0.2f; +constexpr float BEETLE_RUN_MIN = 0.1f; +constexpr float BEETLE_WALK_WOBBLE = 10; +constexpr float BEETLE_RUN_WOBBLE = 30; +constexpr float BEETLE_FLIGHT_WOBBLE = 50; +constexpr float BEETLE_FLIGHT_TURN = 0.4f; +constexpr float BEETLE_FLEE_TURN = 0.2f; +constexpr float BEETLE_FLIGHT_SPEED = 0.4f; +constexpr float BEETLE_FLEE_PUSH = 1.5f; +constexpr float BEETLE_TAKEOFF_RANGE_SQUARED = 4900; +constexpr float BEETLE_FLIGHT_HEIGHT = -20; +constexpr float BEETLE_SHADOW_MIN = 0.5f; +constexpr float BEETLE_SHADOW_FADE = 0.8f; +constexpr float BEETLE_SHADOW_ALPHA_MIN = 0.1f; +constexpr float BEETLE_HIT_RANGE = 5; +constexpr float BEETLE_FIRE_REACH = 3; +constexpr float BEETLE_BURST_SCALE = 0.4f; +constexpr int BEETLE_SHADOW_LAYER = 1; + +// A beetle crawls on the floor, facing a random way. +static void beetle_init(Entity_Effect& beetle) +{ + beetle.sprite.Play("WalkHori"); + beetle.rotation = angle_normalized(random_unit() * FULL_TURN); + beetle.sprite.GetLayer(0)->rotation = beetle.rotation; + beetle.height = 0; + beetle.isUnknown176 = true; + if (g_game->room->backdropType == BACKDROP_DROSS) beetle.sprite.color = COLOR_DEFAULT; +} + +// A flying beetle's shadow shrinks and fades with its height. +static void beetle_shadow_set(Entity_Effect& beetle) +{ + float lift = beetle.height / BEETLE_FLIGHT_HEIGHT; + LayerState& shadow = *beetle.sprite.GetLayer(BEETLE_SHADOW_LAYER); + shadow.size = vector_make(lift + BEETLE_SHADOW_MIN, lift + BEETLE_SHADOW_MIN); + shadow.color._tint[3] = (1 - lift) * BEETLE_SHADOW_FADE + BEETLE_SHADOW_ALPHA_MIN; +} + +// Turns a beetle back from the walls. +static void beetle_wall_turn(Entity_Effect& beetle) +{ + Vector inside = g_game->room->GetClampedPosition(beetle.pos, TADPOLE_WALL_MARGIN); + if (inside.x != beetle.pos.x || inside.y != beetle.pos.y) + beetle.rotation = angle_lerp(beetle.rotation, vector_angle(vector_sub(inside, beetle.pos)), TADPOLE_WALL_TURN); +} + +// A crawling beetle lands if it was flying, takes off from a player close by (rarely from one standing still), idles +// or runs in bursts with a wobbling heading, turns from the walls, is pushed out of the grid, and splats when stepped +// on or splashed. +static void beetle_crawl(Entity_Effect& beetle) +{ + Room& room = *g_game->room; + + if (beetle.height >= 0) + { + beetle.sortingLayer = SORTING_DOOR; + beetle.sprite.Play("WalkHori"); + } + else + { + beetle.sprite.Play("FlyHori"); + beetle.height += 1; + if (beetle.height < 0) beetle_shadow_set(beetle); + else + { + beetle.height = 0; + beetle.state = 0; + } + } + beetle.friction *= BUG_FRICTION; + + Entity_Player* player = nearest_player_get(beetle.pos); + float playerDistance = distance_squared(beetle.pos, player->pos); + if (playerDistance < BEETLE_TAKEOFF_RANGE_SQUARED && random_below(BEETLE_TAKEOFF_ODDS) == 0) + { + bool isStill = vector_length_squared(player->velocity) <= TADPOLE_STILL_SPEED_SQUARED; + if (!isStill || random_below(BEETLE_STILL_TAKEOFF_ODDS) == 0) beetle.subtype = BEETLE_FLYING; + } + float wobble = beetle.state < 1 ? BEETLE_WALK_WOBBLE : BEETLE_RUN_WOBBLE; + beetle.rotation = angle_normalized(random_unit() * wobble + beetle.rotation - wobble / 2); + beetle.pos = room.GetClampedPosition(beetle.pos, BUG_ROOM_MARGIN); + + if (beetle.state < 1) + { + if (random_below(BEETLE_BURST_ODDS) == 0) beetle.state = random_below(BUG_BURST_SPAN) + BUG_BURST_MIN; + else if (random_below(BEETLE_STEP_ODDS) == 0) + beetle.AddVelocity_divided(vector_scale(vector_from_angle(beetle.rotation), random_unit() * BEETLE_STEP), false); + } + else + { + Vector heading = vector_from_angle(beetle.rotation); + beetle.AddVelocity_divided(vector_scale(heading, random_unit() * BEETLE_RUN + BEETLE_RUN_MIN), false); + beetle.state--; + } + beetle_wall_turn(beetle); + + if (grid_collision_at(beetle.pos) != COLLISION_NONE) + { + GridEntity* grid = grid_entity_at(beetle.pos); + cell_push_out(beetle, beetle.pos); + if (grid && grid->type == GRID_PIT && grid_collision_at(beetle.pos) != COLLISION_NONE) + { + beetle.pos = beetle.targetPosition; + beetle.rotation = angle_normalized(random_unit() * FULL_TURN); + if (grid_collision_at(beetle.pos) == COLLISION_PIT) beetle.pos = vector_add(beetle.pos, random_direction()); + } + } + beetle.targetPosition = beetle.pos; + + if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying()) + beetle.isDead = true; + for (Entity* tear : entities_near(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS)) + { + if (tear->type != ENTITY_TEAR || !tear->isDead) continue; + beetle.isDead = true; + break; + } +} + +// A flying beetle climbs to its height, flutters about away from the walls, flees a player close by now and then, +// and lands on open floor at random. A tear, knife or fire knocks it out of the air. +static void beetle_fly(Entity_Effect& beetle) +{ + Room& room = *g_game->room; + + beetle.sortingLayer = SORTING_NORMAL; + if (beetle.height > BEETLE_FLIGHT_HEIGHT) + { + beetle.height -= 1; + beetle_shadow_set(beetle); + } + beetle.friction *= BUG_FRICTION; + float wobble = random_unit() * BEETLE_FLIGHT_WOBBLE + beetle.rotation - BEETLE_FLIGHT_WOBBLE / 2; + beetle.rotation = angle_lerp(beetle.rotation, wobble, BEETLE_FLIGHT_TURN); + beetle.pos = room.GetClampedPosition(beetle.pos, BUG_ROOM_MARGIN); + beetle_wall_turn(beetle); + Vector heading = vector_from_angle(beetle.rotation); + beetle.AddVelocity_divided(vector_scale(heading, random_unit() * BEETLE_FLIGHT_SPEED + BEETLE_FLIGHT_SPEED), false); + + Entity_Player* player = nearest_player_get(beetle.pos); + float playerDistance = distance_squared(beetle.pos, player->pos); + if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && random_below(BEETLE_FLEE_ODDS) == 0) + { + float closeness = 1 - playerDistance / NEAR_PLAYER_RANGE_SQUARED; + beetle.rotation = angle_lerp(beetle.rotation, vector_angle(vector_sub(beetle.pos, player->pos)), BEETLE_FLEE_TURN); + beetle.AddVelocity_divided(vector_scale(vector_from_angle(beetle.rotation), closeness * BEETLE_FLEE_PUSH), false); + } + else if (random_below(BEETLE_LAND_ODDS) == 0 && grid_collision_at(beetle.pos) == COLLISION_NONE) beetle.subtype = 0; + beetle.sprite.Play("FlyHori"); + + EntityList_EL tears = entities_near(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS); + bool isHit = std::any_of(tears.begin(), tears.end(), [](Entity* tear) { return tear->type == ENTITY_TEAR; }); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (isHit) break; + if (entity->type == ENTITY_KNIFE) isHit = is_within_reach(*entity, beetle.pos, entity->size * FLY_KNIFE_REACH); + } + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (isHit) break; + if (entity->type == ENTITY_FIREPLACE) isHit = is_within_reach(*entity, beetle.pos, entity->size + BEETLE_FIRE_REACH); + } + if (!isHit) return; + beetle.isDead = true; + beetle.sprite.Stop(); +} + +// A beetle's frame: it crawls or flies by its subtype. Dead, it splats on the floor or bursts in the air. +static void beetle_update(Entity_Effect& beetle) +{ + if (beetle.subtype == 0) beetle_crawl(beetle); + else beetle_fly(beetle); + + if (beetle.isDead) + { + if (beetle.sortingLayer == SORTING_DOOR) bug_splat(beetle, 0); + else + { + Entity* burst = g_game->Spawn({.position = vector_make(beetle.pos.x, beetle.pos.y + beetle.height), + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + burst->sprite.scale = vector_make(BEETLE_BURST_SCALE, BEETLE_BURST_SCALE); + burst->SetColor(beetle.splatColor, -1, 255, false, true); + burst->Update(); + beetle.Remove(); + } + } + beetle.sprite.GetLayer(0)->rotation = beetle.rotation; + beetle.sprite.GetLayer(0)->pos.y = beetle.height; +} + +// The ambient variants by their Init, Update and Render. +constexpr auto AMBIENT_BEHAVIOURS = std::to_array({ + {EFFECT_TINY_BUG, tiny_bug_init, finishing, nullptr}, + {EFFECT_TINY_FLY, tiny_fly_init, finishing, nullptr}, + {EFFECT_WATER_DROPLET, water_droplet_init, water_droplet_update, nullptr}, + {EFFECT_WISP, wisp_init, finishing, nullptr}, + {EFFECT_EMBER_PARTICLE, nullptr, finishing, nullptr}, + {EFFECT_WALL_BUG, wall_bug_init, finishing, nullptr}, + {EFFECT_ISAACS_CARPET, carpet_init, finishing, nullptr}, + {EFFECT_DICE_FLOOR, dice_floor_init, finishing, nullptr}, + {EFFECT_FALLING_EMBER, falling_ember_init, finishing, nullptr}, + {EFFECT_BROKEN_SHOVEL_SHADOW, shovel_shadow_init, finishing, nullptr}, + {EFFECT_SPAWNER, spawner_init, finishing, nullptr}, + {EFFECT_LIGHT, light_init, light_update, nullptr}, + {EFFECT_WATER_RIPPLE, nullptr, finishing, nullptr}, + {EFFECT_RAIN_DROP, rain_drop_init, finishing, nullptr}, + {EFFECT_BACKDROP_DECORATION, kept_init, backdrop_decoration_update, nullptr}, + {EFFECT_DOOR_OUTLINE, kept_init, nullptr, nullptr}, + {EFFECT_TALL_LADDER, kept_init, finishing, nullptr}, + {EFFECT_HEAVEN_LIGHT_DOOR, heaven_door_init, finishing, heaven_door_render}, + {EFFECT_TADPOLE, tadpole_init, finishing, nullptr}, + {EFFECT_BEETLE, beetle_init, finishing, nullptr}, + {EFFECT_LIL_GHOST, lil_ghost_init, finishing, nullptr}, + {EFFECT_CREEP_RED, creep_init, finishing, nullptr}, + {EFFECT_CREEP_GREEN, creep_init, finishing, nullptr}, + {EFFECT_CREEP_YELLOW, creep_init, finishing, nullptr}, + {EFFECT_CREEP_WHITE, creep_init, finishing, nullptr}, + {EFFECT_CREEP_BLACK, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_WHITE, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_BLACK, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_RED, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_GREEN, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL, creep_init, finishing, nullptr}, + {EFFECT_CREEP_BROWN, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_BLACKPOWDER, creep_init, finishing, nullptr}, + {EFFECT_CREEP_SLIPPERY_BROWN, creep_init, finishing, nullptr}, + {EFFECT_CREEP_STATIC, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_YELLOW, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_LEMON_MISHAP, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_HOLYWATER, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_LEMON_PARTY, creep_init, finishing, nullptr}, + {EFFECT_PLAYER_CREEP_PUDDLE_MILK, creep_init, finishing, nullptr}, + {EFFECT_PENTAGRAM_BLACKPOWDER, creep_init, finishing, nullptr}, +}); + +// The behaviours indexed by variant, for the variants up to the last vanilla one. +constexpr int AMBIENT_VARIANT_LIMIT = 256; +constexpr std::array AMBIENT_TABLE = [] { + std::array table{}; + for (const AmbientBehaviour& behaviour : AMBIENT_BEHAVIOURS) + if (behaviour.variant >= 0) table[behaviour.variant] = behaviour; + return table; +}(); + +static const AmbientBehaviour& behaviour_get(int variant) +{ + return AMBIENT_TABLE[variant]; +} + +bool is_ambient_effect(int variant) +{ + return variant >= 0 && variant < AMBIENT_VARIANT_LIMIT && AMBIENT_TABLE[variant].variant == variant; +} + +void ambient_effect_init(Entity_Effect& effect) +{ + if (auto init = behaviour_get(effect.variant).init) init(effect); +} + +EffectUpdateEnd ambient_effect_update(Entity_Effect& effect) +{ + auto update = behaviour_get(effect.variant).update; + return update ? update(effect) : EFFECT_UPDATE_FINISH; +} + +void ambient_effect_render(Entity_Effect& effect, const Vector& offset) +{ + if (auto render = behaviour_get(effect.variant).render) return render(effect, offset); + effect.sprite.Render(SpriteDraw{effect.renderPosition, {}, {}}); +} diff --git a/src/entity_effect_ambient.h b/src/entity_effect_ambient.h new file mode 100644 index 0000000..90c6444 --- /dev/null +++ b/src/entity_effect_ambient.h @@ -0,0 +1,19 @@ +#pragma once + +#include "entity_effect.h" + +// The ambient and environment effects: the bugs, flies, wisps, drops and embers rooms scatter, the floor pieces +// rooms place (carpets, the dice floor, lights, decorations, ladders) and the creep and puddles enemies and players +// leave. Entity_Effect's Init, Update and Render hand these variants here. + +// Whether the variant is one of the ambient effects. +bool is_ambient_effect(int variant); + +// Starts an ambient effect after Init's shared start and before its LoadGraphics. +void ambient_effect_init(Entity_Effect& effect); + +// Runs an ambient effect's own frame, between Update's shared start (time scale, pause, parent) and its shared end. +[[nodiscard]] EffectUpdateEnd ambient_effect_update(Entity_Effect& effect); + +// Draws an ambient effect at its place on screen. +void ambient_effect_render(Entity_Effect& effect, const Vector& offset); diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp new file mode 100644 index 0000000..d583347 --- /dev/null +++ b/src/entity_effect_combat.cpp @@ -0,0 +1,1329 @@ +#include "entity_effect_combat.h" +#include "entity_bomb.h" +#include "entity_player.h" +#include "fx_layers.h" +#include "game.h" +#include "grid_entity_rock.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "sfx_manager.h" +#include +#include +#include + +// The effect variants this file runs (Lua's EffectVariant). +enum class CombatEffect : int +{ + BOMB_EXPLOSION = 1, + BLOOD_EXPLOSION = 2, + FLY_EXPLOSION = 3, + ROCK_PARTICLE = 4, + BLOOD_PARTICLE = 5, + BLOOD_SPLAT = 7, + BULLET_POOF = 11, + TEAR_POOF_A = 12, + TEAR_POOF_B = 13, + RIPPLE_POOF = 14, + POOF01 = 15, + POOF02 = 16, + POOF04 = 17, + BOMB_CRATER = 18, + WOOD_PARTICLE = 27, + TOOTH_PARTICLE = 35, + SPIDER_EXPLOSION = 38, + BLOOD_GUSH = 42, + POOP_EXPLOSION = 43, + BATTERY = 48, + HEART = 49, + POOP_PARTICLE = 58, + DUST_CLOUD = 59, + ROCK_EXPLOSION = 62, + WORM = 63, + BLOOD_DROP = 70, + LARGE_BLOOD_EXPLOSION = 77, + TEAR_POOF_SMALL = 79, + TEAR_POOF_VERYSMALL = 80, + DIAMOND_PARTICLE = 85, + NAIL_PARTICLE = 86, + GOLD_PARTICLE = 95, + IMPACT = 97, + COIN_PARTICLE = 98, + CHAIN_GIB = 163 +}; + +constexpr std::array COMBAT_EFFECTS = { + CombatEffect::BOMB_EXPLOSION, CombatEffect::BLOOD_EXPLOSION, CombatEffect::FLY_EXPLOSION, + CombatEffect::ROCK_PARTICLE, CombatEffect::BLOOD_PARTICLE, CombatEffect::BLOOD_SPLAT, + CombatEffect::BULLET_POOF, CombatEffect::TEAR_POOF_A, CombatEffect::TEAR_POOF_B, + CombatEffect::RIPPLE_POOF, CombatEffect::POOF01, CombatEffect::POOF02, + CombatEffect::POOF04, CombatEffect::BOMB_CRATER, CombatEffect::WOOD_PARTICLE, + CombatEffect::TOOTH_PARTICLE, CombatEffect::SPIDER_EXPLOSION, CombatEffect::BLOOD_GUSH, + CombatEffect::POOP_EXPLOSION, CombatEffect::BATTERY, CombatEffect::HEART, + CombatEffect::POOP_PARTICLE, CombatEffect::DUST_CLOUD, CombatEffect::ROCK_EXPLOSION, + CombatEffect::WORM, CombatEffect::BLOOD_DROP, CombatEffect::LARGE_BLOOD_EXPLOSION, + CombatEffect::TEAR_POOF_SMALL, CombatEffect::TEAR_POOF_VERYSMALL, CombatEffect::DIAMOND_PARTICLE, + CombatEffect::NAIL_PARTICLE, CombatEffect::GOLD_PARTICLE, CombatEffect::IMPACT, + CombatEffect::COIN_PARTICLE, CombatEffect::CHAIN_GIB}; + +// The particles that play a gib animation and go once it ends. +constexpr std::array ANIMATED_PARTICLES = { + CombatEffect::TOOTH_PARTICLE, CombatEffect::DIAMOND_PARTICLE, CombatEffect::NAIL_PARTICLE, + CombatEffect::GOLD_PARTICLE, CombatEffect::COIN_PARTICLE}; + +constexpr int EFFECT_LIGHT = 121; + +// The animations by subtype or at random. +constexpr std::array BLOOD_EXPLOSION_ANIMATIONS = {"Poof_Large", "Poof_Small", "Poof", + "Poof_Large1", "Poof_Large2", "Poof_Alt"}; +constexpr std::array POOF01_ANIMATIONS = {"Poof2", "Poof_Small", "Poof", "Poof_Large"}; +constexpr std::array LAVA_SPLASH_ANIMATIONS = {"Poof0", "Poof1", "Poof2"}; +constexpr std::array NOTIFY_ANIMATIONS = {"Heart", "Battery", "Betrayal", + "BatteryDown", "SoulHeart", "BlackHeart"}; +constexpr std::array GIB_FRAMES = {"Gib1", "Gib2", "Gib3", "Gib4"}; +constexpr std::array GIB_ANIMATIONS = {"Gib01", "Gib02", "Gib03", "Gib04", "Gib05"}; +constexpr std::array BLOOD_GIBS = {"BloodGib01", "BloodGib02", "BloodGib03"}; +constexpr std::array BONES = {"Bone02", "Bone01"}; +constexpr std::array GUTS = {"Guts01", "Guts02", "Liver"}; +constexpr std::array FLESH_BREAKS = {"WombBreak1", "WombBreak2", "WombBreak3"}; +constexpr std::array WORM_ANIMATIONS = {"WormHori", "MaggotHori", "LeechHori"}; +constexpr std::array STAIN_ANIMATIONS = {"Size1BloodStains", "Size2BloodStains", "Size3BloodStains", + "Size4BloodStains", "Size5BloodStains", "Size6BloodStains"}; + +// The blood stain animation by the scale it was spawned at: the first whose limit is above it, the last past all. +constexpr std::array STAIN_SCALE_LIMITS = {0.4f, 0.6f, 0.8f, 1.2f, 2.0f}; + +// The blood particle's kinds by subtype. +enum BloodParticle : int +{ + BLOOD_PARTICLE_BLOOD, + BLOOD_PARTICLE_BONE, + BLOOD_PARTICLE_GUTS, + BLOOD_PARTICLE_EYE, + BLOOD_PARTICLE_GIB = 5 +}; + +// The states the falling particles pass: falling to stay, falling to bounce, bounced, sinking into a pit, glowing. +enum ParticleState : int +{ + PARTICLE_FALLING = 1, + PARTICLE_BOUNCING = 2, + PARTICLE_BOUNCED = 3, + PARTICLE_SINKING = 10, + PARTICLE_GLOWING = 1000 +}; + +// A rock particle's subtype: the backdrop whose rocks it shows in its low bits (none for the rock under it), and +// whether it shows the alternate rubble and bounces. Subtype 1 makes the other particles bounce, mostly. +constexpr int ROCK_PARTICLE_BACKDROP_MASK = 0xffff; +constexpr int ROCK_PARTICLE_ALT = 0x10000; +constexpr int ROCK_PARTICLE_BOUNCY = 0x20000; +constexpr int PARTICLE_BOUNCY = 1; +constexpr int PARTICLE_STILL_ODDS = 40; + +// How the falling particles start and fall: their height, rise, gravity, the time scale's drag, and the bounce. +constexpr float PARTICLE_START_HEIGHT = -23; +constexpr float PARTICLE_RISE = -5; +constexpr float PARTICLE_RISE_RANGE = 10; +constexpr float GIB_FALL = 5; +constexpr float GIB_RISE_RANGE = 30; +constexpr float PARTICLE_GRAVITY = 1.3f; +constexpr float PARTICLE_GROUND_HEIGHT = -5; +constexpr float PARTICLE_FALL_DRAG = 0.9f; +constexpr float PARTICLE_FALL_PULL = 0.1f; +constexpr float PARTICLE_BOUNCE = -0.4f; +constexpr float PARTICLE_BOUNCE_SLOWDOWN = 0.6f; +constexpr float PARTICLE_ROOM_MARGIN = 5; +constexpr float PARTICLE_ROOM_PULL_SQUARED = 100; +constexpr int PARTICLE_FLOOR_Z = 90; +constexpr int PARTICLE_SHRINK_DELAY = 10; +constexpr float PARTICLE_SHRINK = 0.05f; +constexpr float PARTICLE_SINK_SHRINK = 0.15f; +constexpr float PARTICLE_SINK_FADE = 0.8f; + +// A crawlspace's side view: the particles drop past the room's bottom. +constexpr float CRAWLSPACE_HEIGHT = -100; +constexpr float CRAWLSPACE_GRAVITY = 0.7f; +constexpr float CRAWLSPACE_FLOOR_MARGIN = 80; + +// The blood particle: its drops, the splats and drops it leaves in the air, and the gore it trails in a crawlspace. +constexpr int BLOOD_DROP_FRAMES = 13; +constexpr int BLOOD_DROP_GONE_FIRST = 4; +constexpr int BLOOD_DROP_GONE_LAST = 10; +constexpr float BLOOD_DROP_RISE_RANGE = 20; +constexpr int BLOOD_SPLAT_ODDS = 3; +constexpr float BLOOD_SPLAT_SCALE_MIN = 0.1f; +constexpr float BLOOD_SPLAT_SCALE_RANGE = 0.3f; +constexpr int BLOOD_DRIP_FIRST_STATE = 2; +constexpr int BLOOD_DRIP_LAST_STATE = 4; +constexpr float BLOOD_DRIP_SPEED = 5; +constexpr int PARTICLE_GLOW_FRAMES = 15; +constexpr uint32_t GORE_SPIN_SHIFT = 35; +constexpr float GORE_SPIN_MIN = 10; +constexpr float GORE_SPIN_RANGE = 40; +constexpr int GORE_TRAIL_FRAMES = 4; +constexpr int GORE_TRAIL_ODDS = 3; +constexpr int GORE_TRAIL_SUBTYPE = 4; +constexpr float GORE_TRAIL_SPEED = 0.4f; + +// How a glowing stain fades: toward these colors, its alpha from full to half. +constexpr ColorMod PARTICLE_GLOW_FADE = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 1}, {0.08f, 0.08f, 0.08f}}; +constexpr ColorMod STAIN_GLOW_FADE = {{0.2f, 1, 1, 1}, {0, 0, 0, 0}, {0.08f, 0.08f, 0.08f}}; +constexpr float GLOW_ALPHA_MIN = 0.5f; + +// The blood stain: its alpha steps, and a glowing one's time and the light it gives. +constexpr float STAIN_ALPHA_MIN = 0.5f; +constexpr float STAIN_ALPHA_STEP = 0.1f; +constexpr int STAIN_ALPHA_STEPS = 6; +constexpr int STAIN_GLOW_FRAMES = 30; +constexpr int STAIN_LIGHT_LEAD = 10; +constexpr float STAIN_LIGHT_SCALE = 0.6f; +constexpr float STAIN_LIGHT_BOOST = 1.1f; +constexpr float STAIN_LIGHT_RED = 103; +constexpr float STAIN_LIGHT_GREEN = 10; +constexpr float STAIN_LIGHT_BLUE = 11; +constexpr float COLOR_CHANNEL_MAX = 255; + +// One world unit is 0.65 screen pixels. A glowing stain sits on whole pixels. +constexpr float WORLD_PER_PIXEL = 1.5384616f; +constexpr float HALF = 0.5f; + +// The tear poofs' quarter turns, the ripple's small sizes and the poofs' layers. +constexpr float RIGHT_ANGLE = 90; +constexpr float RIPPLE_TINY_SCALE = 0.5f; +constexpr float RIPPLE_SMALL_SCALE = 0.75f; +constexpr float RIPPLE_TINY_GROWTH = 2; +constexpr float RIPPLE_SMALL_GROWTH = 1.33333f; +constexpr int POOF_RENDER_Z = 8000; +constexpr int POOF01_GFUEL = 11; +constexpr int POOF01_REPEATING = 100; +constexpr int POOF02_LAVA_SPLASH = 66; +constexpr int POOF02_LAVA_SPLASH_LARGE = 67; +constexpr uint32_t LAVA_SPLASH_SHIFT = 4; +constexpr int GFUEL_SHAKE = 40; +constexpr float GFUEL_PITCH_MIN = 0.9f; +constexpr float GFUEL_PITCH_RANGE = 0.2f; + +// The blood explosion's floor frame, from 6 to 8, from which it stays on the floor. +constexpr int BLOOD_EXPLOSION_FLOOR_FRAME = 6; +constexpr int BLOOD_EXPLOSION_FLOOR_RANGE = 3; + +// The bomb explosion's sound by the size it was spawned at, and the spawners that play their own. +constexpr float EXPLOSION_SMALL_SCALE = 0.7f; +constexpr float EXPLOSION_LARGE_SCALE = 1.4f; +constexpr float EXPLOSION_SMALL_VOLUME = 0.95f; +constexpr float EXPLOSION_LARGE_VOLUME = 1.1f; +constexpr int ENTITY_DUKE_OF_FLIES = 67; +constexpr int ENTITY_RAG_MEGA = 409; +constexpr const char* GFUEL_EXPLOSION_ANM2 = "gfx/promo/gfuel/effects/explosion3.anm2"; +constexpr int TRINKET_SAFETY_SCISSORS = 63; +constexpr float SCISSORS_SCALE_DOUBLE = 0.75f; +constexpr float SCISSORS_SCALE_TRIPLE = 0.5f; + +// The bomb crater: its small kind, the darker one in the Dark Room, and a temporary one's fade. +constexpr float CRATER_SMALL_SCALE = 0.5f; +constexpr float CRATER_SMALL_GROWTH = 2; +constexpr uint32_t CRATER_FRAME_SHIFT = 35; +constexpr float CRATER_ALPHA_MIN = 0.8f; +constexpr float CRATER_ALPHA_RANGE = 0.2f; +constexpr int BACKDROP_DARK_ROOM = 16; +constexpr float CRATER_DARK_TINT = 0.5f; +constexpr int CRATER_TEMPORARY = 1; +constexpr int CRATER_TEMPORARY_FRAMES = 150; +constexpr int CRATER_FADE_FRAMES = 60; + +// The dust cloud's start and spread. +constexpr float DUST_SCALE = 0.5f; +constexpr float DUST_DARKEN = -0.5f; +constexpr int DUST_DARK = 1; +constexpr int DUST_PULSE = 2; +constexpr float DUST_FRICTION = 0.9f; +constexpr float DUST_GROWTH = 0.9f; +constexpr float DUST_PULSE_PEAK = 0.5f; +constexpr float DUST_PULSE_SHARPNESS = 4; + +// The blood drop's fall and splat. +constexpr int DROPLET_KINDS = 3; +constexpr float DROPLET_SHADOW = 0.04f; +constexpr float DROPLET_FALL = 1; +constexpr float DROPLET_RISE_RANGE = 15; +constexpr float DROPLET_DRAG = 0.9f; +constexpr float DROPLET_FRICTION = 0.95f; + +// A backdrop's ground break sheet, and whether it breaks like flesh with its own animations. +struct GroundBreak +{ + const char* sheet; + int backdrop; + bool isFleshy; +}; + +constexpr const char* GROUND_BREAK_CAVES = "gfx/Effects/Effect_062_GroundBreakCaves.png"; +constexpr const char* GROUND_BREAK_DEPTHS = "gfx/Effects/Effect_062_GroundBreakDepths.png"; +constexpr const char* GROUND_BREAK_WOMB = "gfx/Effects/Effect_062_GroundBreakWomb.png"; +constexpr const char* GROUND_BREAK_BLUE_WOMB = "gfx/Effects/Effect_062_GroundBreakBlueWomb.png"; +constexpr const char* GROUND_BREAK_MINES = "gfx/Effects/Effect_062_GroundBreakMines.png"; +constexpr const char* GROUND_BREAK_MINES_LAVA = "gfx/Effects/Effect_062_GroundBreakMinesLava.png"; +constexpr const char* GROUND_BREAK_MAUSOLEUM = "gfx/Effects/Effect_062_GroundBreakMausoleum.png"; +constexpr const char* GROUND_BREAK_CORPSE = "gfx/Effects/Effect_062_GroundBreakCorpse.png"; +constexpr const char* GROUND_BREAK_CORPSE2 = "gfx/Effects/Effect_062_GroundBreakCorpse2.png"; +constexpr int BACKDROP_MINES = 32; +constexpr std::array GROUND_BREAKS = {{ + {GROUND_BREAK_CAVES, 4, false}, {GROUND_BREAK_CAVES, 5, false}, {GROUND_BREAK_DEPTHS, 7, false}, + {GROUND_BREAK_DEPTHS, 8, false}, {GROUND_BREAK_DEPTHS, 9, false}, {GROUND_BREAK_WOMB, 10, true}, + {GROUND_BREAK_WOMB, 11, true}, {GROUND_BREAK_WOMB, 12, true}, {GROUND_BREAK_BLUE_WOMB, 13, true}, + {GROUND_BREAK_MAUSOLEUM, 33, false}, {GROUND_BREAK_CORPSE, 34, true}, {GROUND_BREAK_MAUSOLEUM, 40, false}, + {GROUND_BREAK_MAUSOLEUM, 41, false}, {GROUND_BREAK_MAUSOLEUM, 42, false}, {GROUND_BREAK_CORPSE2, 43, true}, + {GROUND_BREAK_WOMB, 44, true}, {GROUND_BREAK_MINES_LAVA, 46, false}}}; + +// The rock explosion's sparks, and its glow over lava. +constexpr int ROCK_EXPLOSION_SPARK_FRAME = 1; +constexpr int ROCK_EXPLOSION_SPARK_ODDS = 5; +constexpr float ROCK_EXPLOSION_SPARK_SPEED = 5; +constexpr ColorMod LAVA_GLOW_COLOR = {{1, 0.6f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int LAVA_GLOW_FRAMES = 22; +constexpr float LAVA_GLOW_SCALE = 0.5f; + +constexpr int LIGHT_FADE_DEFAULT = 6; + +// The worm: how it wanders, crawls, turns from walls and the nearest player, and dies under feet or tears. +constexpr float WORM_IDLE_WOBBLE = 5; +constexpr float WORM_CRAWL_WOBBLE = 20; +constexpr float WORM_FALL_DRAG = 0.9f; +constexpr float WORM_FRICTION = 0.9f; +constexpr float WORM_GROUND_FRICTION = 0.5f; +constexpr float WORM_SHADOW_HEIGHT = -20; +constexpr float WORM_SHADOW = 0.07f; +constexpr float WORM_INNER_MARGIN = -2; +constexpr float WORM_WALL_MARGIN = 40; +constexpr float WORM_WALL_TURN = 0.05f; +constexpr std::array WORM_PUSHES = {0.2f, 0.1f, 0.05f}; +constexpr int WORM_CRAWL_ODDS = 30; +constexpr int WORM_CRAWL_RANGE = 120; +constexpr int WORM_CRAWL_MIN = 15; +constexpr int WORM_NUDGE_ODDS = 10; +constexpr float WORM_FLEE_RANGE_SQUARED = 10000; +constexpr int WORM_FLEE_ODDS = 3; +constexpr float WORM_FLEE_TURN = 0.2f; +constexpr float WORM_FLEE_PUSH = 4; +constexpr int WORM_FLEE_RANGE = 100; +constexpr int WORM_FLEE_MIN = 30; +constexpr float WORM_CELL_EDGE = 20; +constexpr float WORM_EDGE_SLOWDOWN = 0.1f; +constexpr float WORM_SPLAT_SCALE = 0.3f; +constexpr float WORM_STEP_RANGE_SQUARED = 100; +constexpr float WORM_STEP_SPEED_SQUARED = 1; +constexpr float WORM_TEAR_RANGE = 5; +constexpr float WORM_STILL_SPEED_SQUARED = 1; + +constexpr float HALF_TURN = 180; +constexpr float FULL_TURN = 360; +constexpr float SPRITE_UP = 90; + +// The sounds the explosions play (Lua's SoundEffect). +enum CombatSound : int +{ + SOUND_BOSS_EXPLOSION = 182, + SOUND_EXPLOSION_WEAK = 183, + SOUND_EXPLOSION_STRONG = 184, + SOUND_ROCKET_EXPLOSION = 587, + SOUND_GFUEL_EXPLOSION = 822, + SOUND_GFUEL_EXPLOSION_BIG = 823, + SOUND_GLITTER_BOMB = 866 +}; + +static CombatEffect variant_get(const Entity_Effect& effect) +{ + return static_cast(effect.variant); +} + +template +static bool is_listed(const std::array& list, CombatEffect variant) +{ + return std::find(list.begin(), list.end(), variant) != list.end(); +} + +bool is_combat_effect(int variant) +{ + return is_listed(COMBAT_EFFECTS, static_cast(variant)); +} + +// normalize_angle_degrees 00682740: an angle wrapped into -180 to 180. +static float angle_wrap(float angle) +{ + if (std::fabs(angle) > FULL_TURN) angle = std::fmod(angle, FULL_TURN); + if (angle > HALF_TURN) return angle - FULL_TURN; + if (angle < -HALF_TURN) return angle + FULL_TURN; + return angle; +} + +// Math::timescale_factor 00684cb0: a per-frame factor stretched to the time scale. +static float timescale_factor(float factor, float timeScale) +{ + return timeScale == 1 ? factor : factor / (factor + timeScale - factor * timeScale); +} + +// Plays a sound through the fart seeds. +static void sound_play(int sound, float volume, float pitch) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = volume, .pitch = pitch}); +} + +// Spawns a still effect with no spawner or subtype on a fresh seed. +static Entity_Effect* effect_spawn(const Vector& position, int variant) +{ + uint32_t seed = Random(); + return static_cast(g_game->Spawn({position, {}, nullptr, 0, ENTITY_EFFECT, variant, seed})); +} + +// Spawns a blood stain of a color under an effect. +static Entity_Effect* stain_spawn(const Entity_Effect& effect) +{ + Entity_Effect* stain = effect_spawn(effect.pos, static_cast(CombatEffect::BLOOD_SPLAT)); + stain->SetColor(effect.splatColor, -1, 255, false, true); + return stain; +} + +// Snaps a position onto whole screen pixels. +static Vector pixel_snap(Vector position) +{ + return vector_make(std::floor(position.x / WORLD_PER_PIXEL + HALF) * WORLD_PER_PIXEL, + std::floor(position.y / WORLD_PER_PIXEL + HALF) * WORLD_PER_PIXEL); +} + +// 00703330 Game::SpawnParticles: throws effects out at a speed in random directions, flattened to the floor's +// perspective, tinted, from a height unless it is PARTICLE_HEIGHT_KEPT. +void game_particles_spawn(const ParticleSpawn& spawn) +{ + for (int i = 0; i < spawn.count; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector velocity = vector_make(std::cos(angle) * spawn.speed, std::sin(angle) * HALF * spawn.speed); + auto* particle = static_cast( + g_game->Spawn({spawn.position, velocity, nullptr, spawn.subType, ENTITY_EFFECT, spawn.variant, seed})); + + particle->SetColor(spawn.color, -1, 255, false, true); + if (spawn.height != PARTICLE_HEIGHT_KEPT) particle->height = spawn.height; + if (g_game->roomTransition.is_active()) particle->AddEntityFlags(FLAG_TRANSITION_UPDATE); + particle->Update(); + } +} + +// 0060af70 Entity_Effect::CreateLight: a light of a color and size that lasts its timeout and fades over its fade +// frames, following its parent if it has one. +Entity_Effect* effect_light_create(const LightSpawn& light) +{ + Entity_Effect* effect = effect_spawn(light.position, EFFECT_LIGHT); + ColorMod color = {{light.color._red, light.color._green, light.color._blue, light.color._alpha}, {}, {}}; + + effect->SetColor(color, -1, 255, false, true); + effect->SetTimeout(light.timeout > 0 ? light.timeout : -1); + effect->sprite.scale = vector_make(light.scale, light.scale); + effect->state = light.fadeFrames > 0 ? light.fadeFrames : LIGHT_FADE_DEFAULT; + if (light.parent) effect->FollowParent(light.parent); + return effect; +} + +// Safety Scissors shrink an explosion no player set off: to three quarters with two, to half with three or more. +static void explosion_shrink(Entity_Effect& effect) +{ + Entity* spawner = effect.spawnerEntity; + if (spawner && (spawner->type == ENTITY_PLAYER || spawner->GetPlayerAncestor())) return; + + int multiplier = g_game->playerManager.GetTrinketMultiplier(TRINKET_SAFETY_SCISSORS); + if (multiplier < 2) return; + float shrink = multiplier == 2 ? SCISSORS_SCALE_DOUBLE : SCISSORS_SCALE_TRIPLE; + effect.sprite.scale = vector_scale(effect.sprite.scale, shrink); +} + +// A falling particle 23 high and rising, on a random gib frame or animation by its kind. +static void particle_init(Entity_Effect& effect) +{ + CombatEffect variant = variant_get(effect); + + effect.fallingAcceleration = PARTICLE_GRAVITY; + effect.height = PARTICLE_START_HEIGHT; + effect.posOffset.y = PARTICLE_START_HEIGHT; + effect.fallingSpeed = PARTICLE_RISE - random_unit() * PARTICLE_RISE_RANGE; + if (variant == CombatEffect::WOOD_PARTICLE || variant == CombatEffect::CHAIN_GIB) + effect.sprite.SetFrame(GIB_FRAMES[Random() & 3], 0); + if (!is_listed(ANIMATED_PARTICLES, variant)) return; + + const char* animation = GIB_ANIMATIONS[Random() & 3]; + bool isStill = Random() % 3 == 0 && variant != CombatEffect::DIAMOND_PARTICLE; + if (isStill) effect.sprite.SetFrame(animation, 0); + else effect.sprite.Play(animation); +} + +// A poop particle 23 high and rising, turned and on a random gib animation. +static void poop_particle_init(Entity_Effect& effect) +{ + effect.fallingAcceleration = PARTICLE_GRAVITY; + effect.height = PARTICLE_START_HEIGHT; + effect.sprite.GetLayer(0)->rotation = random_unit() * FULL_TURN; + effect.sprite.Play(GIB_ANIMATIONS[Random() % GIB_ANIMATIONS.size()]); + effect.fallingSpeed = GIB_FALL - random_unit() * GIB_RISE_RANGE; +} + +// A poof's animation by its subtype. POOF01 and POOF02's large kinds draw over everything, POOF02's small kinds lie +// on the floor outside a crawlspace, and its lava splashes face a seeded side. +static void poof_init(Entity_Effect& effect) +{ + int subtype = effect.subtype; + + if (variant_get(effect) == CombatEffect::POOF01) + { + if (subtype >= 1 && subtype < (int)POOF01_ANIMATIONS.size()) effect.sprite.Play(POOF01_ANIMATIONS[subtype]); + effect.renderZOffset = POOF_RENDER_Z; + return; + } + + if (subtype == 1 || subtype == 3) + { + if (g_game->room->roomType != ROOM_DUNGEON) effect.sortingLayer = SORTING_BACKGROUND; + effect.sprite.Play("Poof"); + } + else if (subtype == 2 || subtype == 4 || subtype == 5) + { + effect.renderZOffset = POOF_RENDER_Z; + effect.sprite.Play("Poof"); + } + else if (subtype == POOF02_LAVA_SPLASH || subtype == POOF02_LAVA_SPLASH_LARGE) + { + RNG rng = rng_make(effect.initSeed, LAVA_SPLASH_SHIFT); + uint32_t roll = rng.Next() % LAVA_SPLASH_ANIMATIONS.size(); + effect.sprite.Play(subtype == POOF02_LAVA_SPLASH ? LAVA_SPLASH_ANIMATIONS[roll] : "PoofLarge"); + effect.sprite.isFlipX = !(effect.initSeed & 1); + } +} + +// A dust cloud on a random frame, side and turn at half size over everything, darkened as subtype 1. +static void dust_cloud_init(Entity_Effect& effect) +{ + const AnimationData* clouds = effect.sprite.GetAnimationData("Clouds"); + if (!clouds) return; + + int frame = clouds->length == 0 ? 0 : (int)(Random() % (uint32_t)clouds->length); + effect.sprite.SetFrame(clouds->name, frame); + effect.sprite.isFlipX = !(Random() & 1); + effect.sprite.rotation = random_unit() * FULL_TURN - HALF_TURN; + effect.sprite.scale = vector_make(DUST_SCALE, DUST_SCALE); + effect.renderZOffset = POOF_RENDER_Z; + if (effect.subtype == DUST_DARK) effect.sprite.color = {{1, 1, 1, 1}, {}, {DUST_DARKEN, DUST_DARKEN, DUST_DARKEN}}; +} + +// A rock explosion's ground break on a random side, in the sheet of its backdrop. Fleshy floors break with their +// own animations. +static void rock_explosion_init(Entity_Effect& effect) +{ + Room& room = *g_game->room; + + effect.sprite.isFlipX = !(Random() & 1); + if (room.backdropType == BACKDROP_MINES) + { + bool isLava = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER; + effect.sprite.ReplaceSpritesheet(0, isLava ? GROUND_BREAK_MINES_LAVA : GROUND_BREAK_MINES); + return; + } + + auto found = std::find_if(GROUND_BREAKS.begin(), GROUND_BREAKS.end(), + [&room](const GroundBreak& entry) { return entry.backdrop == room.backdropType; }); + if (found == GROUND_BREAKS.end()) return; + effect.sprite.ReplaceSpritesheet(0, found->sheet); + if (found->isFleshy) effect.sprite.Play(FLESH_BREAKS[effect.dropRNG.Next() % FLESH_BREAKS.size()]); +} + +// A worm, maggot or leech facing a random way and rising. A crawlspace has none. +static void worm_init(Entity_Effect& effect) +{ + if (g_game->room->roomType == ROOM_DUNGEON) return effect.Remove(); + + if (effect.subtype >= 0 && effect.subtype < (int)WORM_ANIMATIONS.size()) + effect.sprite.Play(WORM_ANIMATIONS[effect.subtype]); + effect.rotation = angle_wrap(random_unit() * FULL_TURN); + effect.sprite.rotation = effect.rotation; + effect.sortingLayer = SORTING_DOOR; + effect.fallingAcceleration = PARTICLE_GRAVITY; + effect.fallingSpeed = GIB_FALL - random_unit() * GIB_RISE_RANGE; +} + +void combat_effect_init(Entity_Effect& effect) +{ + ANM2& sprite = effect.sprite; + int subtype = effect.subtype; + + switch (variant_get(effect)) + { + case CombatEffect::BOMB_EXPLOSION: + explosion_shrink(effect); + sprite.isFlipX = !(Random() & 1); + break; + case CombatEffect::BOMB_CRATER: + effect.sortingLayer = SORTING_BACKGROUND; + explosion_shrink(effect); + break; + case CombatEffect::BLOOD_SPLAT: + effect.sortingLayer = SORTING_BACKGROUND; + break; + case CombatEffect::RIPPLE_POOF: + effect.sortingLayer = SORTING_BACKGROUND; + sprite.isFlipX = Random() & 1; + break; + case CombatEffect::TEAR_POOF_A: + case CombatEffect::TEAR_POOF_B: + case CombatEffect::TEAR_POOF_SMALL: + case CombatEffect::TEAR_POOF_VERYSMALL: + effect.rotation = (float)(Random() & 3) * RIGHT_ANGLE; + effect.isUnknown176 = true; + break; + case CombatEffect::IMPACT: + effect.rotation = (float)(Random() & 3) * RIGHT_ANGLE; + effect.isUnknown176 = true; + sprite.isFlipX = !(Random() & 1); + break; + case CombatEffect::BLOOD_EXPLOSION: + if (subtype >= 1 && subtype < (int)BLOOD_EXPLOSION_ANIMATIONS.size()) + sprite.Play(BLOOD_EXPLOSION_ANIMATIONS[subtype]); + effect.isUnknown176 = true; + break; + case CombatEffect::HEART: + if (subtype >= 0 && subtype < (int)NOTIFY_ANIMATIONS.size()) sprite.Play(NOTIFY_ANIMATIONS[subtype]); + break; + case CombatEffect::BLOOD_DROP: + sprite.SetFrame("Droplets", random_below(DROPLET_KINDS)); + effect.fallingAcceleration = PARTICLE_GRAVITY; + effect.fallingSpeed = DROPLET_FALL - random_unit() * DROPLET_RISE_RANGE; + effect.shadowSize = DROPLET_SHADOW; + break; + case CombatEffect::ROCK_PARTICLE: + case CombatEffect::WOOD_PARTICLE: + case CombatEffect::TOOTH_PARTICLE: + case CombatEffect::DIAMOND_PARTICLE: + case CombatEffect::NAIL_PARTICLE: + case CombatEffect::GOLD_PARTICLE: + case CombatEffect::COIN_PARTICLE: + case CombatEffect::CHAIN_GIB: + particle_init(effect); + break; + case CombatEffect::POOP_PARTICLE: poop_particle_init(effect); break; + case CombatEffect::POOF01: + case CombatEffect::POOF02: + poof_init(effect); + break; + case CombatEffect::DUST_CLOUD: dust_cloud_init(effect); break; + case CombatEffect::ROCK_EXPLOSION: rock_explosion_init(effect); break; + case CombatEffect::WORM: worm_init(effect); break; + default: break; + } +} + +// Turns a poof by its rotation, mirrored unless flipped, and removes it once its animation ends. G FUEL's poof +// booms on its event, and POOF01's subtype 100 leaves a plain poof behind. +static void poof_update(Entity_Effect& effect) +{ + bool isPoof01 = variant_get(effect) == CombatEffect::POOF01; + + effect.sprite.rotation = effect.sprite.isFlipX ? effect.rotation : -effect.rotation; + if (isPoof01 && effect.subtype == POOF01_GFUEL && effect.sprite.IsEventTriggered("GFuelExplosion")) + { + sound_play(SOUND_GFUEL_EXPLOSION_BIG, 1, random_unit() * GFUEL_PITCH_RANGE + GFUEL_PITCH_MIN); + game_shake_screen(GFUEL_SHAKE); + } + if (!effect.sprite.IsFinished()) return; + + if (isPoof01 && effect.subtype == POOF01_REPEATING) effect_spawn(effect.pos, effect.variant)->Update(); + effect.Remove(); +} + +// A bomb explosion's sound on its first frame, by what set it off and its size. With G FUEL!, an unturned one turns +// into its promo explosion. +static void explosion_sound_play(Entity_Effect& effect) +{ + if (effect.spawnerType == ENTITY_DUKE_OF_FLIES || effect.spawnerType == ENTITY_RAG_MEGA || effect.state != 0) + return; + effect.state++; + + if (effect.rotation == 0 && g_game->playerManager.GetGFuelCount() >= 1) + { + effect.sprite.Load(GFUEL_EXPLOSION_ANM2, GRAPHICS_LOAD); + effect.sprite.Play("Idle"); + bool isLarge = effect.sprite.scale.x >= EXPLOSION_LARGE_SCALE; + return sound_play(isLarge ? SOUND_EXPLOSION_STRONG : SOUND_GFUEL_EXPLOSION, 1, 1); + } + + Entity* spawner = effect.spawnerEntity; + auto* bomb = spawner && spawner->is_bomb() ? static_cast(spawner) : nullptr; + float size = effect.sprite.scale.x; + if (bomb && bomb->tearFlags.test(TEAR_GLITTER_BOMB)) sound_play(SOUND_GLITTER_BOMB, 1, 1); + else if (size < EXPLOSION_SMALL_SCALE) sound_play(SOUND_EXPLOSION_WEAK, EXPLOSION_SMALL_VOLUME, 1); + else if (size > EXPLOSION_LARGE_SCALE) sound_play(SOUND_EXPLOSION_STRONG, EXPLOSION_LARGE_VOLUME, 1); + else if (bomb && bomb->IsRocket()) sound_play(SOUND_ROCKET_EXPLOSION, 1, 1); + else sound_play(SOUND_BOSS_EXPLOSION, 1, 1); +} + +// A blood or poop explosion and POOF04: random flips and a floor frame at first, then laid on the floor from that +// frame on (its subtype 0 only), and removed when done. +static void blood_explosion_update(Entity_Effect& effect) +{ + bool isBlood = variant_get(effect) == CombatEffect::BLOOD_EXPLOSION; + ANM2& sprite = effect.sprite; + + if (effect.state == 0) + { + bool isFlipX = random_below(2) == 0; + bool isFlipY = random_below(2) == 0; + + // The original sets layer 0's flips once for each layer. + if (!sprite.layerStates.empty()) + { + sprite.GetLayer(0)->isFlipX = isFlipX; + sprite.GetLayer(0)->isFlipY = isFlipY; + } + effect.state = random_below(BLOOD_EXPLOSION_FLOOR_RANGE) + BLOOD_EXPLOSION_FLOOR_FRAME; + } + + if (sprite.GetFrame() == effect.state && effect.subtype == 0) + { + effect.AddEntityFlags(FLAG_RENDER_FLOOR); + if (isBlood) effect.AddEntityFlags(FLAG_NO_REMOVE_ON_TEX_RENDER); + } + else if (isBlood) effect.ClearEntityFlags(FLAG_RENDER_FLOOR | FLAG_NO_REMOVE_ON_TEX_RENDER); + if (sprite.IsFinished()) effect.Remove(); +} + +// Falls a particle by its speed and gravity at the room's time scale, its height shown as its offset. +static void particle_fall(Entity_Effect& effect) +{ + float timeScale = effect.speedMultiplier; + + effect.fallingSpeed *= timescale_factor(PARTICLE_FALL_DRAG, timeScale); + effect.fallingSpeed += timeScale * PARTICLE_FALL_PULL; + effect.fallingSpeed += effect.fallingAcceleration * timeScale; + effect.height += effect.fallingSpeed * timeScale; + effect.posOffset.y = effect.height; +} + +// A crawlspace's side view: the particle drops flat until it is past the room's bottom, where it goes. +static void particle_drop(Entity_Effect& effect) +{ + effect.height = CRAWLSPACE_HEIGHT; + effect.friction = 1; + effect.entityGridCollisionClass = GRIDCOLL_NONE; + effect.entityCollisionClass = ENTCOLL_NONE; + effect.posOffset = {}; + effect.velocity.y += effect.speedMultiplier * CRAWLSPACE_GRAVITY; + if (effect.velocity.y > 0 && effect.pos.y > g_game->room->bottomRightPos.y + CRAWLSPACE_FLOOR_MARGIN) + effect.Remove(); +} + +// Lays a particle still on the floor, drawn into it. +static void particle_land(Entity_Effect& effect) +{ + effect.velocity = {}; + effect.sortingLayer = SORTING_BACKGROUND; + effect.renderZOffset = PARTICLE_FLOOR_Z; + effect.AddEntityFlags(FLAG_RENDER_FLOOR); +} + +// 005d29b0 Pulls a falling particle back inside the walls, by under 10 a frame, while it falls. +static void particle_room_pull(Entity_Effect& effect) +{ + float margin = effect.height + PARTICLE_ROOM_MARGIN; + Vector inside = g_game->room->GetClampedPositionImpl(effect.pos, margin, margin, margin, margin); + Vector pull = vector_sub(inside, effect.pos); + float distance = vector_length_squared(pull); + + if (distance <= 0 || distance >= PARTICLE_ROOM_PULL_SQUARED || effect.fallingSpeed <= 0) return; + effect.velocity = pull; + effect.pos = inside; +} + +// A rock particle's first frame: the sheet and rubble of the rock under it, or of its backdrop's rocks, on a random +// rubble frame, set to bounce by its subtype. +// The original reads past the backdrops for a subtype's backdrop over the last. It takes the room's own. +static void rock_particle_start(Entity_Effect& effect) +{ + Room& room = *g_game->room; + Backdrop& backdrop = room.backdrop; + int subtype = effect.subtype; + uint32_t backdropId = subtype & ROCK_PARTICLE_BACKDROP_MASK; + std::string_view rubble = "rubble"; + GridEntity* under = backdropId == 0 ? room.GetGridEntity((uint32_t)room.GetGridIndex(effect.pos)) : nullptr; + + if (auto* rock = dynamic_cast(under)) + { + effect.sprite = rock->sprite; + rubble = rock->rubbleAnim; + } + else + { + uint32_t id = backdropId == 0 || backdropId >= BACKDROP_COUNT ? backdrop.backdropId : backdropId; + effect.sprite.ReplaceSpritesheet(0, backdrop.configs[id].rocks); + effect.sprite.LoadGraphics(); + if (backdropId != 0 && (subtype & ROCK_PARTICLE_ALT)) rubble = "rubble_alt"; + } + + if (const AnimationData* data = effect.sprite.GetAnimationData(rubble)) + effect.sprite.SetFrame(rubble, random_below(data->length)); + effect.state = (subtype & ROCK_PARTICLE_BOUNCY) ? PARTICLE_BOUNCING : PARTICLE_FALLING; +} + +// A falling particle's frame: it falls, lands on the floor or bounces off it while pulled inside the walls, and an +// animated one goes when its animation ends. A rock particle shrinks away after bouncing, faster in a pit. +static EffectUpdateEnd particle_update(Entity_Effect& effect) +{ + CombatEffect variant = variant_get(effect); + bool isRock = variant == CombatEffect::ROCK_PARTICLE; + bool isCrawlspace = g_game->room->roomType == ROOM_DUNGEON; + + if (effect.state == 0) + { + bool isBouncing = effect.subtype == PARTICLE_BOUNCY && random_below(PARTICLE_STILL_ODDS) != 0; + effect.state = isBouncing ? PARTICLE_BOUNCING : PARTICLE_FALLING; + } + if (is_listed(ANIMATED_PARTICLES, variant) && effect.sprite.IsFinished() && effect.sprite.GetFrame() > 0) + effect.Remove(); + if (isCrawlspace) particle_drop(effect); + else particle_fall(effect); + + if (effect.state > PARTICLE_BOUNCING && isRock && effect.FrameCount() > PARTICLE_SHRINK_DELAY) + { + float shrink = PARTICLE_SHRINK; + if (effect.state == PARTICLE_SINKING) + { + effect.sprite.GetLayer(0)->color._tint[3] *= PARTICLE_SINK_FADE; + shrink = PARTICLE_SINK_SHRINK; + } + + Vector scale = vector_sub(effect.sprite.scale, vector_make(shrink, shrink)); + if (scale.x <= 0 || scale.y <= 0) + { + effect.Remove(); + return EFFECT_UPDATE_RETURN; + } + effect.sprite.scale = scale; + } + + if (isCrawlspace) return EFFECT_UPDATE_FINISH; + if (effect.height <= PARTICLE_GROUND_HEIGHT) + { + if (!isRock || effect.state < PARTICLE_BOUNCING) particle_room_pull(effect); + return EFFECT_UPDATE_FINISH; + } + if (isRock && (room_grid_collision_at(effect.pos) == COLLISION_PIT || effect.state == PARTICLE_SINKING)) + { + effect.state = PARTICLE_SINKING; + return EFFECT_UPDATE_FINISH; + } + if (effect.state < PARTICLE_BOUNCING) + { + particle_land(effect); + return EFFECT_UPDATE_FINISH; + } + + if (!isRock) particle_room_pull(effect); + effect.height = PARTICLE_GROUND_HEIGHT; + effect.posOffset.y = PARTICLE_GROUND_HEIGHT; + effect.fallingSpeed *= PARTICLE_BOUNCE; + effect.velocity = vector_scale(effect.velocity, PARTICLE_BOUNCE_SLOWDOWN); + effect.state = PARTICLE_BOUNCED; + if (!effect.sprite.IsPlaying() && !isRock) effect.sprite.Play(effect.sprite.GetAnimation(), PLAY_FORCED); + return EFFECT_UPDATE_FINISH; +} + +// A blood particle is a drop when another blood particle spat it. +static bool is_blood_drop(const Entity_Effect& effect) +{ + return effect.spawnerType == effect.type && (int)effect.spawnerVariant == effect.variant; +} + +// A blood particle's gib animation by its subtype. Past the known kinds it shows nothing. +static const char* blood_particle_animation(Entity_Effect& effect) +{ + switch (effect.subtype) + { + case BLOOD_PARTICLE_BLOOD: return BLOOD_GIBS[random_below((int)BLOOD_GIBS.size())]; + case BLOOD_PARTICLE_BONE: return BONES[random_below((int)BONES.size())]; + case BLOOD_PARTICLE_GUTS: return GUTS[random_below((int)GUTS.size())]; + case BLOOD_PARTICLE_EYE: return "Eye"; + case BLOOD_PARTICLE_GIB: return GIB_ANIMATIONS[random_below((int)GIB_ANIMATIONS.size())]; + default: + effect.isVisible = false; + return nullptr; + } +} + +// A blood particle's first frame: 23 high and rising, a drop on a random frame or a gib turned at random. +static void blood_particle_start(Entity_Effect& effect) +{ + effect.fallingAcceleration = PARTICLE_GRAVITY; + effect.height = PARTICLE_START_HEIGHT; + effect.posOffset.y = effect.height; + if (is_blood_drop(effect)) + { + effect.sprite.SetFrame("Particle", random_below(BLOOD_DROP_FRAMES)); + effect.fallingSpeed = GIB_FALL - random_unit() * BLOOD_DROP_RISE_RANGE; + } + else + { + effect.sprite.GetLayer(0)->rotation = random_unit() * FULL_TURN; + if (const char* animation = blood_particle_animation(effect)) effect.sprite.Play(animation); + effect.fallingSpeed = GIB_FALL - random_unit() * GIB_RISE_RANGE; + } + effect.state++; +} + +// A blood gib in the air leaves splats under it now and then, and drops in its first frames. +static void blood_particle_spatter(Entity_Effect& effect) +{ + bool isSplashing = !effect.HasEntityFlags(FLAG_NO_BLOOD_SPLASH); + + if (random_below(BLOOD_SPLAT_ODDS) == 0 && isSplashing) + { + Entity_Effect* stain = stain_spawn(effect); + float size = random_unit() * BLOOD_SPLAT_SCALE_RANGE + BLOOD_SPLAT_SCALE_MIN; + stain->sprite.scale = vector_make(size, size); + stain->Update(); + } + + bool isDripping = effect.state >= BLOOD_DRIP_FIRST_STATE && effect.state <= BLOOD_DRIP_LAST_STATE; + for (int i = 0; isDripping && isSplashing && effect.isVisible && i < random_below(effect.state); i++) + { + uint32_t seed = Random(); + Vector velocity = vector_scale(random_direction(), BLOOD_DRIP_SPEED); + Entity* drop = g_game->Spawn({effect.pos, velocity, &effect, 0, ENTITY_EFFECT, + static_cast(CombatEffect::BLOOD_PARTICLE), seed}); + drop->SetColor(effect.splatColor, -1, 255, false, true); + } + effect.state++; +} + +// A blood particle on the floor: one an effect spat stays out of its middle frames, a hidden gib goes, a shown one +// lies on its last frame. One that glows (an alpha over 1) fades from the floor instead, on whole pixels. +static void blood_particle_land(Entity_Effect& effect) +{ + if (effect.spawnerType == effect.type) + { + int frame = effect.sprite.GetFrame(); + if (frame >= BLOOD_DROP_GONE_FIRST && frame <= BLOOD_DROP_GONE_LAST) effect.Remove(); + else + { + effect.AddEntityFlags(FLAG_RENDER_FLOOR); + effect.sortingLayer = SORTING_BACKGROUND; + } + } + else if (!effect.isVisible) effect.Remove(); + else + { + effect.sprite.SetLastFrame(); + particle_land(effect); + } + + if (!effect.HasEntityFlags(FLAG_RENDER_FLOOR) || effect.color._tint[3] <= 1) return; + effect.ClearEntityFlags(FLAG_RENDER_FLOOR); + effect.state = PARTICLE_GLOWING; + effect.SetTimeout(PARTICLE_GLOW_FRAMES); + effect.fallingSpeed = 0; + effect.posOffset.y = 0; + effect.pos = pixel_snap(effect.pos); +} + +// A gory blood particle spins as it drops through a crawlspace, its blood, eye and guts trailing blood. +static void blood_gore_spin(Entity_Effect& effect) +{ + RNG rng = rng_make(effect.initSeed, GORE_SPIN_SHIFT); + float side = rng.RandomInt(2) == 0 ? -1.0f : 1.0f; + float spin = (rng.RandomFloat() * GORE_SPIN_RANGE + GORE_SPIN_MIN) * side; + bool isTrailing = effect.subtype == BLOOD_PARTICLE_BLOOD || effect.subtype == BLOOD_PARTICLE_EYE || + effect.subtype == BLOOD_PARTICLE_GUTS; + + effect.sprite.rotation += spin * effect.speedMultiplier; + if (!isTrailing || !effect.IsFrame(GORE_TRAIL_FRAMES, 0) || random_below(GORE_TRAIL_ODDS) != 0) return; + + uint32_t seed = Random(); + Vector velocity = vector_scale(effect.velocity, GORE_TRAIL_SPEED); + Entity* trail = g_game->Spawn({effect.pos, velocity, nullptr, GORE_TRAIL_SUBTYPE, ENTITY_EFFECT, + static_cast(CombatEffect::BLOOD_EXPLOSION), seed}); + trail->SetColor(effect.splatColor, -1, 255, false, true); + trail->Update(); +} + +// A glowing stain fading toward a color and half its alpha over its timeout, drawn into the floor at its end. +static void glow_fade(Entity_Effect& effect, const ColorMod& fade) +{ + float t = (float)effect.timeout / (float)effect.lifespan; + + effect.sprite.color = color_lerp(fade, effect.color, t); + effect.sprite.color._tint[3] = effect.color._tint[3] * ((1 - GLOW_ALPHA_MIN) * t + GLOW_ALPHA_MIN); + if (effect.isDead) effect.AddEntityFlags(FLAG_RENDER_FLOOR); +} + +// A blood particle's frame: a gib or drop falls, spattering in the air, and lands. In a crawlspace it drops through. +static void blood_particle_update(Entity_Effect& effect) +{ + if (effect.state == 0) return blood_particle_start(effect); + if (effect.state == PARTICLE_GLOWING) return glow_fade(effect, PARTICLE_GLOW_FADE); + + if (g_game->room->roomType == ROOM_DUNGEON) + { + if (effect.HasEntityFlags(FLAG_EXTRA_GORE)) blood_gore_spin(effect); + return particle_drop(effect); + } + + particle_fall(effect); + if (effect.height > PARTICLE_GROUND_HEIGHT) return blood_particle_land(effect); + if (effect.spawnerType != effect.type) blood_particle_spatter(effect); + particle_room_pull(effect); +} + +// A poop particle falls, pulled inside the walls, and lies on its last frame on the floor. +static void poop_particle_update(Entity_Effect& effect) +{ + if (g_game->room->roomType == ROOM_DUNGEON) return particle_drop(effect); + + particle_fall(effect); + if (effect.height <= PARTICLE_GROUND_HEIGHT) return particle_room_pull(effect); + effect.sprite.SetLastFrame(); + particle_land(effect); +} + +// A blood stain settles on its first update: the stain animation for the scale it was spawned at on a random frame, +// its own scale, random flips, a random strength for an opaque color, and the floor to be drawn into. A glowing one +// (an alpha over 1) instead sits on whole pixels and fades with a light of its color. +static void stain_update(Entity_Effect& effect) +{ + if (effect.state != 0) return glow_fade(effect, STAIN_GLOW_FADE); + + ANM2& sprite = effect.sprite; + float spawnScale = sprite.scale.x; + sprite.scale = vector_make(effect.scale, effect.scale); + + auto limit = std::find_if(STAIN_SCALE_LIMITS.begin(), STAIN_SCALE_LIMITS.end(), + [spawnScale](float scaleLimit) { return spawnScale < scaleLimit; }); + const char* animation = STAIN_ANIMATIONS[limit - STAIN_SCALE_LIMITS.begin()]; + if (const AnimationData* data = sprite.GetAnimationData(animation)) + sprite.SetFrame(animation, random_below(data->length)); + sprite.isFlipX = random_below(2) == 0; + sprite.isFlipY = random_below(2) == 0; + + bool isGlowing = effect.color._tint[3] > 1; + if (sprite.color._tint[3] >= 1) + sprite.color._tint[3] = (float)random_below(STAIN_ALPHA_STEPS) * STAIN_ALPHA_STEP + STAIN_ALPHA_MIN; + if (!isGlowing) return effect.AddEntityFlags(FLAG_RENDER_FLOOR); + + effect.state = 1; + effect.SetTimeout(random_below(STAIN_GLOW_FRAMES) + STAIN_GLOW_FRAMES); + effect.pos = pixel_snap(effect.pos); + + const ColorMod& glow = effect.color; + float red = (glow._tint[0] * STAIN_LIGHT_RED / COLOR_CHANNEL_MAX + glow._offset[0]) * STAIN_LIGHT_BOOST; + float green = (glow._tint[1] * STAIN_LIGHT_GREEN / COLOR_CHANNEL_MAX + glow._offset[1]) * STAIN_LIGHT_BOOST; + float blue = (glow._tint[2] * STAIN_LIGHT_BLUE / COLOR_CHANNEL_MAX + glow._offset[2]) * STAIN_LIGHT_BOOST; + int lightFrames = effect.timeout - STAIN_LIGHT_LEAD; + effect_light_create({.color = kcolor_rgba(red, green, blue, 1), + .position = effect.pos, + .scale = spawnScale * STAIN_LIGHT_SCALE, + .fadeFrames = lightFrames, + .timeout = lightFrames}); +} + +// A ripple first draws its small sizes larger with their own animations, then turns and ends as a poof. +static void ripple_update(Entity_Effect& effect) +{ + ANM2& sprite = effect.sprite; + + if (effect.state == 0) + { + if (sprite.scale.x <= RIPPLE_TINY_SCALE) + { + sprite.scale = vector_scale(sprite.scale, RIPPLE_TINY_GROWTH); + sprite.Play("Poof_Tiny"); + } + else if (sprite.scale.x <= RIPPLE_SMALL_SCALE) + { + sprite.scale = vector_scale(sprite.scale, RIPPLE_SMALL_GROWTH); + sprite.Play("Poof_Small"); + } + effect.state = 1; + } + poof_update(effect); +} + +// A bomb crater settles on its first update: its small kind drawn twice as big, a seeded frame, a random strength, a +// darker tint in the Dark Room, and the floor to be drawn into, or 150 frames for a temporary one, which fades out +// over its last 60. +static void crater_update(Entity_Effect& effect) +{ + ANM2& sprite = effect.sprite; + bool isTemporary = effect.subtype == CRATER_TEMPORARY; + + if (effect.state == 0) + { + Vector scale = sprite.scale; + if (scale.x > CRATER_SMALL_SCALE) sprite.SetAnimation("Idle"); + else + { + sprite.SetAnimation("IdleSmall"); + scale = vector_scale(scale, CRATER_SMALL_GROWTH); + } + sprite.scale = scale; + + RNG rng = rng_make(effect.initSeed, CRATER_FRAME_SHIFT); + uint32_t frame = rng.RandomInt((uint32_t)sprite.animState.GetAnimationLength()); + sprite.color._tint[3] = random_unit() * CRATER_ALPHA_RANGE + CRATER_ALPHA_MIN; + sprite.SetFrame((float)frame); + if (g_game->room->backdropType == BACKDROP_DARK_ROOM) + { + float* tint = sprite.GetLayer(0)->color._tint; + std::fill(tint, tint + 3, CRATER_DARK_TINT); + tint[3] = 1; + } + + if (effect.subtype == 0) effect.AddEntityFlags(FLAG_RENDER_FLOOR); + else effect.SetTimeout(CRATER_TEMPORARY_FRAMES); + effect.state++; + } + + if (!isTemporary || effect.timeout >= CRATER_FADE_FRAMES) return; + sprite.color._tint[3] = std::max(sprite.color._tint[3] - 1.0f / CRATER_FADE_FRAMES, 0.0f); + if (sprite.color._tint[3] <= 0) effect.Remove(); +} + +// A dust cloud turns, slows, grows and fades over its timeout, subtype 2 thickest halfway, and goes when it dies. +static void dust_cloud_update(Entity_Effect& effect) +{ + ANM2& sprite = effect.sprite; + float lifespan = (float)effect.lifespan; + float t = 1 - (float)effect.timeout / lifespan; + + sprite.rotation += effect.rotation; + effect.friction *= DUST_FRICTION; + if (effect.subtype == DUST_PULSE) + { + float fromPeak = t - DUST_PULSE_PEAK; + t = 1 - std::clamp(1 - fromPeak * DUST_PULSE_SHARPNESS * fromPeak, 0.0f, 1.0f); + } + sprite.scale = vector_add(sprite.scale, vector_make(DUST_GROWTH / lifespan, DUST_GROWTH / lifespan)); + sprite.color._tint[3] = effect.color._tint[3] * (1 - t); + if (effect.isDead) effect.Remove(); +} + +// A rock explosion throws a rock particle now and then on its second frame, glowing over lava, and goes when done. +static void rock_explosion_update(Entity_Effect& effect) +{ + if (effect.sprite.GetFrame() == ROCK_EXPLOSION_SPARK_FRAME) + { + int count = random_below(ROCK_EXPLOSION_SPARK_ODDS) == 0 ? 1 : 0; + game_particles_spawn({.position = effect.pos, + .speed = ROCK_EXPLOSION_SPARK_SPEED, + .count = count, + .variant = static_cast(CombatEffect::ROCK_PARTICLE)}); + if (g_game->room->HasLava()) + { + Entity_Effect* glow = effect_spawn(effect.pos, EFFECT_LIGHT); + glow->sprite.color = LAVA_GLOW_COLOR; + glow->SetTimeout(LAVA_GLOW_FRAMES); + glow->sprite.scale = vector_make(LAVA_GLOW_SCALE, LAVA_GLOW_SCALE); + glow->parent = &effect; + } + } + if (effect.sprite.IsFinished()) effect.Remove(); +} + +// Whether a dead tear lies within reach of a position (EntityList::QueryRadius over the tears). +static bool is_dead_tear_near(const Vector& position, float radius) +{ + EntityList_EL shots; + g_game->room->entityList.partitions[PARTITION_SHOTS].query_box(shots, position, vector_make(radius, radius)); + + for (Entity* shot : shots) + { + float reach = radius + shot->size; + bool isNear = vector_length_squared(vector_sub(shot->pos, position)) < reach * reach; + if (!shot->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && isNear && shot->type == ENTITY_TEAR && shot->isDead) + return true; + } + return false; +} + +// Pushes a worm out of the grid entity under it, other than a rock, to its cell's nearest edge. Still in a pit, it +// steps back and turns, nudged off at random when that is a pit too. +static void worm_grid_push(Entity_Effect& effect) +{ + Room& room = *g_game->room; + if (room_grid_collision_at(effect.pos) == COLLISION_NONE) return; + + int cellIndex = room.GetGridIndex(effect.pos); + GridEntity* grid = room.GetGridEntity((uint32_t)cellIndex); + if (!grid || grid->type == GRID_ROCK) return; + + Vector cell = room.GetGridPosition(cellIndex); + Vector toCell = vector_sub(cell, effect.pos); + if (std::fabs(toCell.x) <= std::fabs(toCell.y)) + { + effect.pos.y = cell.y + (toCell.y <= 0 ? WORM_CELL_EDGE : -WORM_CELL_EDGE); + effect.velocity.y *= WORM_EDGE_SLOWDOWN; + } + else + { + effect.pos.x = cell.x + (toCell.x <= 0 ? WORM_CELL_EDGE : -WORM_CELL_EDGE); + effect.velocity.x *= WORM_EDGE_SLOWDOWN; + } + + if (grid->type != GRID_PIT || room_grid_collision_at(effect.pos) == COLLISION_NONE) return; + effect.pos = effect.targetPosition; + effect.rotation = angle_wrap(random_unit() * FULL_TURN); + if (room_grid_collision_at(effect.pos) == COLLISION_PIT) effect.pos = vector_add(effect.pos, random_direction()); +} + +// A worm's frame: it wobbles and falls, turns from the walls, idles or crawls in bursts, crawls away from a player +// close by, keeps off grid entities, and splats when it dies: stepped on by a walking player or hit by a tear. +static void worm_update(Entity_Effect& effect) +{ + Room& room = *g_game->room; + float wobble = effect.state < 1 ? WORM_IDLE_WOBBLE : WORM_CRAWL_WOBBLE; + + effect.rotation = angle_wrap(random_unit() * wobble + effect.rotation - wobble * HALF); + effect.sprite.rotation = effect.rotation; + effect.pos = room.GetClampedPosition(effect.pos, WORM_INNER_MARGIN); + if (effect.posOffset.y >= 0) + { + effect.friction *= WORM_GROUND_FRICTION; + effect.shadowSize = 0; + } + else + { + effect.fallingSpeed = effect.fallingSpeed * WORM_FALL_DRAG + effect.fallingAcceleration; + effect.posOffset.y = std::min(effect.posOffset.y + effect.fallingSpeed, 0.0f); + effect.rotation = vector_angle(effect.velocity); + effect.friction *= WORM_FRICTION; + effect.shadowSize = std::min(effect.posOffset.y / WORM_SHADOW_HEIGHT * WORM_SHADOW, WORM_SHADOW); + } + + Vector inside = room.GetClampedPosition(effect.pos, WORM_WALL_MARGIN); + if (!vector_is_zero(vector_sub(inside, effect.pos))) + effect.rotation = angle_lerp(effect.rotation, vector_angle(vector_sub(inside, effect.pos)), WORM_WALL_TURN); + + float push = effect.subtype >= 1 && effect.subtype <= 2 ? WORM_PUSHES[effect.subtype] : WORM_PUSHES[0]; + if (effect.state >= 1) + { + effect.AddVelocity_divided(vector_scale(vector_from_angle(effect.rotation), random_unit() * push + push), false); + effect.state--; + } + else if (random_below(WORM_CRAWL_ODDS) == 0) effect.state = random_below(WORM_CRAWL_RANGE) + WORM_CRAWL_MIN; + else if (random_below(WORM_NUDGE_ODDS) == 0) + effect.AddVelocity_divided(vector_scale(vector_from_angle(effect.rotation), random_unit() * push), false); + + Entity_Player* player = game_nearest_player(effect.pos); + float distance = vector_length_squared(vector_sub(effect.pos, player->pos)); + if (distance < WORM_FLEE_RANGE_SQUARED && random_below(WORM_FLEE_ODDS) == 0) + { + float closeness = 1 - distance / WORM_FLEE_RANGE_SQUARED; + float away = vector_angle(vector_sub(effect.pos, player->pos)); + effect.rotation = angle_lerp(effect.rotation, away, WORM_FLEE_TURN); + Vector flee = vector_scale(vector_from_angle(effect.rotation), push * closeness * WORM_FLEE_PUSH); + effect.AddVelocity_divided(flee, false); + effect.state = random_below(WORM_FLEE_RANGE) + WORM_FLEE_MIN; + } + + worm_grid_push(effect); + effect.targetPosition = effect.pos; + if (effect.isDead) + { + Entity_Effect* stain = stain_spawn(effect); + stain->scale = WORM_SPLAT_SCALE; + stain->Update(); + effect.Remove(); + } + + bool isWalking = vector_length_squared(player->velocity) > WORM_STEP_SPEED_SQUARED; + if (distance < WORM_STEP_RANGE_SQUARED && isWalking && !player->IsFlying()) effect.isDead = true; + if (is_dead_tear_near(effect.pos, WORM_TEAR_RANGE)) effect.isDead = true; + + if (vector_length_squared(effect.velocity) <= WORM_STILL_SPEED_SQUARED) effect.sprite.Stop(); + else if (effect.subtype >= 0 && effect.subtype < (int)WORM_ANIMATIONS.size()) + effect.sprite.Play(WORM_ANIMATIONS[effect.subtype]); +} + +// A blood drop falls on its own speed until it lands, randomly flipped, splats there or off the room's edge, and +// faces its motion. +static void blood_drop_update(Entity_Effect& effect) +{ + ANM2& sprite = effect.sprite; + + if (effect.posOffset.y < 0) + { + effect.fallingSpeed = effect.fallingSpeed * DROPLET_DRAG + effect.fallingAcceleration; + effect.posOffset.y = std::min(effect.posOffset.y + effect.fallingSpeed, 0.0f); + } + else if (!effect.isDead) + { + effect.isDead = true; + sprite.isFlipX = random_below(2) == 0; + sprite.isFlipY = random_below(2) == 0; + } + + if (effect.isDead) + { + effect.sortingLayer = SORTING_BACKGROUND; + effect.velocity = {}; + sprite.Play("Splat"); + if (sprite.IsFinished()) effect.Remove(); + Vector inside = g_game->room->GetClampedPosition(effect.pos, 0); + if (inside.x != effect.pos.x || inside.y != effect.pos.y) effect.Remove(); + } + effect.friction *= DROPLET_FRICTION; + sprite.rotation = vector_angle(vector_add(effect.velocity, vector_make(0, effect.fallingSpeed))) - SPRITE_UP; +} + +EffectUpdateEnd combat_effect_update(Entity_Effect& effect) +{ + ANM2& sprite = effect.sprite; + + switch (variant_get(effect)) + { + case CombatEffect::BOMB_EXPLOSION: + explosion_sound_play(effect); + poof_update(effect); + break; + case CombatEffect::BLOOD_EXPLOSION: + case CombatEffect::POOF04: + case CombatEffect::POOP_EXPLOSION: + blood_explosion_update(effect); + break; + case CombatEffect::ROCK_PARTICLE: + if (effect.state == 0) rock_particle_start(effect); + return particle_update(effect); + case CombatEffect::WOOD_PARTICLE: + case CombatEffect::TOOTH_PARTICLE: + case CombatEffect::DIAMOND_PARTICLE: + case CombatEffect::NAIL_PARTICLE: + case CombatEffect::GOLD_PARTICLE: + case CombatEffect::COIN_PARTICLE: + case CombatEffect::CHAIN_GIB: + return particle_update(effect); + case CombatEffect::BLOOD_PARTICLE: blood_particle_update(effect); break; + case CombatEffect::BLOOD_SPLAT: stain_update(effect); break; + case CombatEffect::RIPPLE_POOF: ripple_update(effect); break; + case CombatEffect::BOMB_CRATER: crater_update(effect); break; + case CombatEffect::POOP_PARTICLE: poop_particle_update(effect); break; + case CombatEffect::DUST_CLOUD: dust_cloud_update(effect); break; + case CombatEffect::ROCK_EXPLOSION: rock_explosion_update(effect); break; + case CombatEffect::WORM: worm_update(effect); break; + case CombatEffect::BLOOD_DROP: blood_drop_update(effect); break; + case CombatEffect::BLOOD_GUSH: + if (!effect.parent) effect.Remove(); + break; + case CombatEffect::LARGE_BLOOD_EXPLOSION: + if (!sprite.IsFinished()) break; + sprite.Play("Idle"); + effect.sortingLayer = SORTING_BACKGROUND; + effect.AddEntityFlags(FLAG_RENDER_FLOOR); + break; + default: poof_update(effect); break; + } + return EFFECT_UPDATE_FINISH; +} diff --git a/src/entity_effect_combat.h b/src/entity_effect_combat.h new file mode 100644 index 0000000..a1fd2f7 --- /dev/null +++ b/src/entity_effect_combat.h @@ -0,0 +1,46 @@ +#pragma once + +#include "entity_effect.h" + +// The combat effects: blood, gibs and particles, explosions and their craters and ground breaks, the tear poofs and +// splashes, and the poofs pickups and items leave. Entity_Effect's Init and Update hand these variants here. +// Render draws them all with its shared draw. + +// Game::SpawnParticles' height that leaves the particles their own. +constexpr float PARTICLE_HEIGHT_KEPT = 100000; + +// What Game::SpawnParticles throws: a count of effects of a variant from a position at a speed, tinted, from a height. +struct ParticleSpawn +{ + ColorMod color = COLOR_DEFAULT; + Vector position{}; + float height = PARTICLE_HEIGHT_KEPT; + float speed = 0; + int count = 0; + int subType = 0; + int variant = 0; +}; + +// What Entity_Effect::CreateLight makes: a light's color, place, size and parent, how long it lasts (for good when +// not above 0) and the frames it fades over (6 when not above 0). +struct LightSpawn +{ + KColor color{}; + Vector position{}; + Entity* parent = nullptr; + float scale = 1; + int fadeFrames = 0; + int timeout = 0; +}; + +// Whether the variant is one of the combat effects. +bool is_combat_effect(int variant); + +// Starts a combat effect after Init's shared start and before its LoadGraphics: animation, fall, flips and layer. +void combat_effect_init(Entity_Effect& effect); + +// Runs a combat effect's own frame, between Update's shared start (time scale, pause, parent) and its shared end. +[[nodiscard]] EffectUpdateEnd combat_effect_update(Entity_Effect& effect); + +void game_particles_spawn(const ParticleSpawn& spawn); +Entity_Effect* effect_light_create(const LightSpawn& light); diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 664e769..1cae137 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -10,6 +10,7 @@ #include "manager.h" #include "platform.h" #include "room.h" +#include "room_grid.h" #include #include #include @@ -284,6 +285,7 @@ constexpr int CARD_SUIT_CHANCE = 10; // Pickup motion and timing. constexpr int COLLISION_COOLDOWN = 10; constexpr int SETTLE_FRAMES = 6; +constexpr float PICKUP_REPOSITION_STEP = 40; constexpr int APPEAR_KICK = 15; constexpr int TIMEOUT_BLINK = 30; constexpr int SEED_TIMEOUT_BLINK = 150; @@ -1216,7 +1218,7 @@ void Entity_Pickup::target_position_update() Room& room = *g_game->room; bool isFresh = room.roomType != ROOM_DUNGEON && g_game->frameCount - spawnFrame < SETTLE_FRAMES; if (isFresh && room.GetGridCollision(room.GetGridIndex(targetPosition)) != 0) - reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520"); + targetPosition = room_free_pickup_position_find({targetPosition, PICKUP_REPOSITION_STEP, true}); velocity = vector_sub(targetPosition, pos); } if (gridRepositionState == 1) diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 782bf64..333adea 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -8,6 +8,7 @@ #include "manager.h" #include "platform.h" #include "room.h" +#include "room_grid.h" #include #include @@ -118,11 +119,6 @@ static int card_roll(uint32_t seed, int runeChance, bool isPlaying) } // Room methods the room's takeover has not declared yet. -static Vector room_free_pickup_position(Vector, float) -{ - reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520"); -} - static Vector room_random_pickup_position() { reconstruction_missing("Room::get_random_pickup_position 00813460"); @@ -403,6 +399,7 @@ void Entity_Player::stats_reset() isBrokenRemotePending = false; cursedPennyPending = 0; vampireCharmKills = 0; + isActiveUsed = false; isPlayingExtraAnimation = false; isHurtPending = false; isPlayingItemAnimation = false; @@ -960,7 +957,7 @@ void Entity_Player::level_items_apply(bool isForced) for (int i = HasTrinket(TRINKET_LUCKY_SACK) ? GetTrinketMultiplier(TRINKET_LUCKY_SACK) : 0; i > 0; i--) { uint32_t seed = GetTrinketRNG(TRINKET_LUCKY_SACK).Next(); - Vector spot = room_free_pickup_position(pos, PICKUP_SPAWN_RADIUS); + Vector spot = room_free_pickup_position_find({pos, PICKUP_SPAWN_RADIUS}); game.Spawn( {.position = spot, .spawner = this, .type = ENTITY_PICKUP, .variant = PICKUP_GRAB_BAG, .seed = seed}); } diff --git a/src/entity_player.h b/src/entity_player.h index 7926ffe..17e27fb 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -1,5 +1,6 @@ #pragma once +#include "active_items.h" #include "entity.h" #include "item_config.h" #include "kage_graphics.h" @@ -642,6 +643,7 @@ public: int wildCardItem = 0; int wildCardVarData = 0; uint8_t wildCardItemType = WILD_CARD_NONE; + bool isActiveUsed = false; bool isHeldItemVisible = false; std::array weapons; @@ -918,13 +920,13 @@ public: void costume_heads_update(int blinkFrame); void costume_layers_map(int skinColor); void costume_skin_apply(CostumeSpriteDesc& costume, int skinColor); - void AddActiveCharge(int charge, int slot, bool isFlashHud, bool isOvercharge, bool isForce); + int AddActiveCharge(int charge, int slot, bool isFlashHud, bool isOvercharge, bool isForce); void RemoveCollectible(int type, bool isIgnoreModifiers, int activeSlot, bool isRemoveFromForm); Entity_Familiar* AddWisp(int collectible, Vector position, bool isAdjustOrbitLayer, bool isDontUpdate); void StoreGameState(GameStatePlayer* state, bool isSaveTemporaryFamiliars); void PlayCollectibleAnim(int collectible, bool isCheckBodyLayers, std::string_view animation, int frame); void PlayExtraAnimation(std::string_view animation, bool isUnknown); - void UseActiveItem(int item, uint32_t useFlags, int slot); + UseResult UseActiveItem(const ActiveUse& use); void trigger_collectible_effect_removed(ItemConfig_Item* item, int count); private: @@ -975,6 +977,7 @@ public: int GetBatteryCharge(int slot); void SetMinDamageCooldown(int cooldown); int GetActiveItem(int slot); + int GetActiveCharge(int slot); bool AreControlsEnabled(); bool IsItemQueueEmpty(); void StopExtraAnimation(); @@ -1047,7 +1050,7 @@ public: int GetWeaponModifiers(); void update_shooting(); TearFlags GetBombFlags(bool isRollChances); - TearFlags check_bomb_tearflags(const TearFlags& tearFlags); + float check_bomb_tearflags(const TearFlags& tearFlags); void update_bomb_input(); void trigger_fire_item_effects(Vector direction, bool isShotFired); const char* GetDeathAnimName(); @@ -1062,6 +1065,7 @@ public: int GetTotalActiveCharge(int slot); int GetCollectibleMaxCharge(int collectibleId, int varData); int GetActiveMaxCharge(int slot); + int GetActiveMinUsableCharge(int slot); void SetActiveCharge(int charge, int slot); void SetActiveVarData(int vardata, int slot); void ControlActiveItem(int slot); @@ -1110,8 +1114,9 @@ public: void AnimateSad(); void AddPrettyFly(); void PlayExtraAnimation(std::string_view animName); - void active_used_post(int slot, bool unk, int chargeBeforeUse); - void DischargeActiveItem(uint32_t slot, bool isUnknown); + void active_used_post(int slot, bool isRemoved, int chargeBeforeUse); + void DischargeActiveItem(uint32_t slot, bool isRemoved); + void TryRemoveCollectibleCostume(int collectibleId, bool isKeepPersistent); void TryRemoveTrinketCostume(int trinketId); void TryRemoveNullCostume(int nullItemId); uint32_t GetMaxPocketItems(); @@ -1120,9 +1125,9 @@ public: bool IsCollectibleAnimFinished(int collectible, std::string_view animName); void TriggerTrinketAdded(uint32_t trinketId, bool isFirstTime); void TriggerTrinketRemoved(uint32_t trinketId); - void RestoreGameState(GameStatePlayer* saveState); + void RestoreGameState(GameStatePlayer& saved); bool try_trigger_astral_projection(); - void spawn_dark_esau(void* gameStatePlayer); + void RestoreGameState_PostLevelInit(GameStatePlayer& saved); void DonateLuck(int luck); void UseCard(int cardType, uint32_t useFlag); void update_footprints(); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp new file mode 100644 index 0000000..5c97ccb --- /dev/null +++ b/src/entity_player_actives.cpp @@ -0,0 +1,1292 @@ +#include "entity_player.h" +#include "active_items.h" +#include "entity_bomb.h" +#include "entity_pickup.h" +#include "entity_tear.h" +#include "game.h" +#include "hud.h" +#include "kage_input.h" +#include "key_configs.h" +#include "log.h" +#include "lua_callbacks.h" +#include "lua_engine.h" +#include "manager.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "room.h" +#include +#include +#include +#include + +// The items and trinkets the active item code names (Lua's CollectibleType and TrinketType). +enum ActiveItemId : int +{ + COLLECTIBLE_BIBLE = 33, + COLLECTIBLE_BOOK_OF_BELIAL = 34, + COLLECTIBLE_NECRONOMICON = 35, + COLLECTIBLE_POOP = 36, + COLLECTIBLE_TAMMYS_HEAD = 38, + COLLECTIBLE_MOMS_BRA = 39, + COLLECTIBLE_KAMIKAZE = 40, + COLLECTIBLE_MOMS_PAD = 41, + COLLECTIBLE_YUM_HEART = 45, + COLLECTIBLE_DOCTORS_REMOTE = 47, + COLLECTIBLE_LEMON_MISHAP = 56, + COLLECTIBLE_BATTERY = 63, + COLLECTIBLE_ANARCHIST_COOKBOOK = 65, + COLLECTIBLE_HOURGLASS = 66, + COLLECTIBLE_BOOK_OF_REVELATIONS = 78, + COLLECTIBLE_9_VOLT = 116, + COLLECTIBLE_MONSTER_MANUAL = 123, + COLLECTIBLE_DEAD_SEA_SCROLLS = 124, + COLLECTIBLE_PONY = 130, + COLLECTIBLE_GUPPYS_PAW = 133, + COLLECTIBLE_SPIDER_BUTT = 171, + COLLECTIBLE_WHITE_PONY = 181, + COLLECTIBLE_MIDAS_TOUCH = 202, + COLLECTIBLE_SHARP_PLUG = 205, + COLLECTIBLE_D100 = 283, + COLLECTIBLE_D4 = 284, + COLLECTIBLE_FLUSH = 291, + COLLECTIBLE_SATANIC_BIBLE = 292, + COLLECTIBLE_MAGIC_FINGERS = 295, + COLLECTIBLE_BREATH_OF_LIFE = 326, + COLLECTIBLE_BOOMERANG = 338, + COLLECTIBLE_GLASS_CANNON = 352, + COLLECTIBLE_CAR_BATTERY = 356, + COLLECTIBLE_D12 = 386, + COLLECTIBLE_D8 = 406, + COLLECTIBLE_MINE_CRAFTER = 427, + COLLECTIBLE_BROKEN_GLASS_CANNON = 474, + COLLECTIBLE_POTATO_PEELER = 487, + COLLECTIBLE_MOVING_BOX = 523, + COLLECTIBLE_MR_ME = 527, + COLLECTIBLE_HALLOWED_GROUND = 543, + COLLECTIBLE_GOLDEN_RAZOR = 555, + COLLECTIBLE_WAVY_CAP = 582, + COLLECTIBLE_ETERNAL_D6 = 609, + COLLECTIBLE_LARYNX = 611, + COLLECTIBLE_SHARP_KEY = 623, + COLLECTIBLE_STITCHES = 635, + COLLECTIBLE_MAGIC_SKIN = 642, + COLLECTIBLE_4_5_VOLT = 647, + COLLECTIBLE_SPIN_TO_WIN = 655, + COLLECTIBLE_ESAU_JR = 703, + COLLECTIBLE_BERSERK = 704, + COLLECTIBLE_SUPLEX = 709, + COLLECTIBLE_BAG_OF_CRAFTING = 710, + COLLECTIBLE_FLIP = 711, + COLLECTIBLE_RECALL = 714, + COLLECTIBLE_EVERYTHING_JAR = 720, + COLLECTIBLE_ANIMA_SOLA = 722, + + TRINKET_BROKEN_REMOTE = 4, + TRINKET_MECONIUM = 91, + TRINKET_VIBRANT_BULB = 100, + TRINKET_DIM_BULB = 101, + TRINKET_M = 138, + TRINKET_PANIC_BUTTON = 149, + TRINKET_EXPANSION_PACK = 181 +}; + +// The sounds the active items play (Lua's SoundEffect). +enum ActiveSound : int +{ + ACTIVE_SOUND_BOOK_PAGE_TURN = 8, + ACTIVE_SOUND_DEATH_CARD = 33, + ACTIVE_SOUND_DEVIL_CARD = 34, + ACTIVE_SOUND_FART = 37, + ACTIVE_SOUND_GASCAN_POUR = 51, + ACTIVE_SOUND_VAMP_GULP = 157, + ACTIVE_SOUND_BATTERY_CHARGE = 170, + ACTIVE_SOUND_BEEP = 171, + ACTIVE_SOUND_ITEM_RECHARGE = 218, + ACTIVE_SOUND_VAMP_DOUBLE = 614, + ACTIVE_SOUND_D6_ROLL = 910, + ACTIVE_SOUND_ITEM_RAISE = 1017, + ACTIVE_SOUND_MOMS_BRA = 1035, + ACTIVE_SOUND_BIBLE = 1038, + ACTIVE_SOUND_RAZOR_BLADE = 1058 +}; + +// The entities and effects the active items look for or spawn (Lua's EntityType and EffectVariant). +enum ActiveEntity : int +{ + ACTIVE_ENTITY_MOM = 45, + ACTIVE_ENTITY_MOMS_HEART = 78, + ACTIVE_ENTITY_SATAN = 84, + ACTIVE_EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, + ACTIVE_EFFECT_BATTERY = 49 +}; + +// The kinds of poop The Poop drops (Lua's GridPoopVariant). +enum PoopVariant : int +{ + POOP_NORMAL = 0, + POOP_GOLDEN = 3, + POOP_BLACK = 5, + POOP_WHITE = 6 +}; + +constexpr uint32_t BULB_CACHE_FLAGS = + CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_SHOTSPEED | CACHE_RANGE | CACHE_SPEED | CACHE_LUCK; +constexpr int ACHIEVEMENT_HALO = 27; +constexpr int CHALLENGE_APRILS_FOOL = 32; +constexpr int CHARGE_FLASH_MAX = 12; +constexpr int DAMAGE_COUNTDOWN_FRAMES = 30; +constexpr int GLOWING_HOUR_GLASS_LIT_USES = 3; +constexpr int GOLDEN_RAZOR_PRICE = 5; +constexpr int INPUT_HOOK_PRESSED = 0; +constexpr int INPUT_HOOK_TRIGGERED = 1; +constexpr int INPUT_RAW_ACTION = 33; +constexpr int MECONIUM_CHANCES[] = {33, 66, 100}; +constexpr int MIDAS_POOP_CHANCE = 34; +constexpr int NINE_VOLT_RECHARGE_FRAMES = 450; +constexpr int NECROMANCER_FORM_ITEMS = 3; +constexpr int OVERLAY_DELAY = 3; +constexpr int PERCENT = 100; +constexpr int PLAYERFORM_NECROMANCER = 15; +constexpr int REVELATIONS_SOUL_HEARTS = 2; +constexpr int REVELATIONS_STATE_FLAG = 7; +constexpr int SUPLEX_AIMING = 2; +constexpr int TAMMY_TEAR_COUNT = 10; +constexpr int TIMED_RECHARGE_STEP = 1; +constexpr int YUM_HEART_OTHER_HEARTS = 1; +constexpr int YUM_HEART_OWN_HEARTS = 2; +constexpr uint8_t WILD_CARD_ACTIVE = 2; +constexpr uint64_t DAMAGE_RED_HEARTS = 1ull << 5; +constexpr uint64_t DAMAGE_INVINCIBLE = 1ull << 13; +constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; +constexpr uint64_t DAMAGE_IGNORE_ARMOR = 1ull << 30; +constexpr uint64_t KAMIKAZE_DAMAGE_FLAGS = DAMAGE_EXPLOSION | DAMAGE_NO_PENALTIES | DAMAGE_IGNORE_ARMOR; +constexpr uint64_t RAZOR_BLADE_DAMAGE_FLAGS = DAMAGE_RED_HEARTS | DAMAGE_INVINCIBLE; +constexpr uint64_t SPIDER_BUTT_DAMAGE_FLAGS = DAMAGE_IGNORE_ARMOR; +constexpr float BATTERY_EFFECT_DEPTH = 1; +constexpr float BATTERY_EFFECT_HEIGHT = -24; +constexpr float DEATHMATCH_RAZOR_DAMAGE = 10; +constexpr float FULL_CIRCLE = 360; +constexpr float KAMIKAZE_DAMAGE = 185; +constexpr float MIDAS_LUCK_SCALE = 10; +constexpr float RAZOR_BLADE_DAMAGE = 1; +constexpr float RAZOR_BLADE_FIRST_SCALE = 2; +constexpr float SPIDER_BUTT_DAMAGE = 10; +constexpr float SPIDER_BUTT_SLOW = 0.9f; +constexpr float TAMMY_TEAR_DAMAGE = 25; +constexpr float TAMMY_TEAR_SCALE = 1.355f; +constexpr float TAMMY_TEAR_SPEED = 10; +constexpr ColorMod SPIDER_BUTT_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.f, 40 / 255.f, 40 / 255.f}}; + +// The giant book a book or die from a slot shows over the screen. +struct UseOverlay +{ + int item = 0; + int overlay = 0; +}; + +constexpr UseOverlay USE_OVERLAYS[] = { + {COLLECTIBLE_BIBLE, 10}, {COLLECTIBLE_BOOK_OF_BELIAL, 34}, {COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE, 34}, + {COLLECTIBLE_NECRONOMICON, 1}, {COLLECTIBLE_MOMS_BRA, 7}, {COLLECTIBLE_MOMS_PAD, 8}, + {COLLECTIBLE_ANARCHIST_COOKBOOK, 9}, {COLLECTIBLE_HOURGLASS, 14}, {COLLECTIBLE_BOOK_OF_REVELATIONS, 11}, + {COLLECTIBLE_MONSTER_MANUAL, 2}, {COLLECTIBLE_DEAD_SEA_SCROLLS, 4}, {COLLECTIBLE_SPIDER_BUTT, 32}, + {COLLECTIBLE_D100, 28}, {COLLECTIBLE_D4, 17}, {COLLECTIBLE_FLUSH, 19}, + {COLLECTIBLE_SATANIC_BIBLE, 15}, {COLLECTIBLE_D12, 37}, {COLLECTIBLE_D8, 36}, + {COLLECTIBLE_GLOWING_HOUR_GLASS, 14}}; + +// The actives the original's dispatch has a case for. Any other item used only adds its room effect. +constexpr int CASED_ACTIVES[] = { + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 47, 49, 56, 58, 59, 65, 66, 78, 83, 84, 85, 86, 93, 97, 102, 105, + 107, 111, 123, 124, 126, 127, 130, 133, 135, 136, 145, 146, 147, 158, 160, 164, 166, 171, 175, 177, 181, 186, 192, + 263, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 323, 324, 325, 326, 338, 347, + 348, 349, 351, 352, 357, 382, 383, 386, 396, 406, 419, 421, 422, 427, 434, 437, 439, 441, 475, 476, 477, 478, 479, + 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 504, 507, 510, 512, 515, 521, 522, 523, 527, 536, 545, 550, + 552, 555, 556, 557, 577, 578, 580, 582, 584, 585, 604, 605, 609, 611, 622, 623, 625, 628, 631, 635, 636, 638, 639, + 640, 642, 650, 653, 685, 687, 703, 704, 705, 706, 709, 710, 711, 712, 713, 714, 715, 719, 720, 722, 723, 728, 729}; + +// The last collectible of each release, for the message where an unwritten active stops the game. +struct ActiveRelease +{ + int lastItem = 0; + const char* name = nullptr; +}; + +constexpr ActiveRelease ACTIVE_RELEASES[] = { + {346, "Rebirth"}, {441, "Afterbirth"}, {552, "Afterbirth+"}, {COLLECTIBLE_VANILLA_COUNT - 1, "Repentance"}}; + +// One active item use as its effect runs: the request, the item, and what the effect leaves for the end of the use. +struct ItemUse +{ + Entity_Player& player; + const ActiveUse& request; + ItemConfig_Item* item = nullptr; + UseResult result{}; + int id = 0; + bool isAddEffect = true; + bool isLuaAnimationAllowed = false; + bool isShowAnimation = false; + bool isWispAllowed = false; +}; + +// Plays a sound at the player's volume, unless the seeds swap it for a fart. +static void sound_play_local(Entity_Player& player, int sound) +{ + int id = sound; + + seed_fart_sound_override(&id); + g_manager->sfxManager.Play(id, {.volume = player.local_volume_get()}); +} + +// Holds the item up for its use animation, unless the use hides it. +static void use_animate(ItemUse& use) +{ + if (use.isShowAnimation) use.player.AnimateCollectible(use.id, "UseItem", "PlayerPickupSparkle"); +} + +// Turns a filled Broken Glass Cannon back into the Glass Cannon, held up. +static void glass_cannon_mend(Entity_Player& player, int slot) +{ + player.RemoveCollectible(COLLECTIBLE_BROKEN_GLASS_CANNON, false, slot, true); + player.AddCollectible(COLLECTIBLE_GLASS_CANNON, -1, false, slot, 0); + player.AnimateCollectible(COLLECTIBLE_GLASS_CANNON, "UseItem", "PlayerPickupSparkle"); +} + +// The entities the room updates, as Room::GetEntities lists them. +static EntityList_EL& room_entities() +{ + return g_game->room->GetEntities()->updateEL; +} + +// The enemies an item affects: vulnerable ones other than the player. +static bool is_item_target(Entity* entity, Entity_Player& player) +{ + return entity->IsVulnerableEnemy(nullptr) && entity != &player; +} + +// Spawns the battery spark over the player that an overcharge or a 9 Volt refill shows. +static void battery_effect_spawn(Entity_Player& player) +{ + EntitySpawn spawn = {.position = player.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = ACTIVE_EFFECT_BATTERY, + .seed = Random()}; + Entity* effect = g_game->Spawn(spawn); + + effect->sprite.offset = vector_make(0, BATTERY_EFFECT_HEIGHT); + effect->renderDepthOffset = BATTERY_EFFECT_DEPTH; +} + +// Whether an action meets a test on a controller, or on any connected device for -1, through the key configs. +static bool is_action_met(ButtonAction action, int controllerIndex, ActionTest test) +{ + KAGE::Input::Manager& input = KAGE::Input::manager; + + for (int i = 0; i < input.get_device_count(); i++) + { + std::shared_ptr device = input.get_device(i); + if (!device || !device->isConnected || (controllerIndex != -1 && device->id != controllerIndex)) continue; + + for (int button : g_manager->keyConfigs.binding_get(*device, action)) + { + if (button == KAGE::Input::BUTTON_NONE) continue; + if (test == ACTION_TRIGGERED ? device->is_button_triggered(button) : device->is_button_pressed(button)) + return true; + } + } + return false; +} + +// A mod's answer to an action test through MC_INPUT_ACTION, asked only in a run. +static std::optional action_hook_run(Entity* entity, int hook, ButtonAction action) +{ + if (g_manager->state != MANAGER_STATE_GAME || !g_luaEngine) return std::nullopt; + return lua_engine_get().InputAction(entity, hook, action); +} + +// 00956110 Whether an action is held on a controller, or on any device for -1. A mod may answer first. Netplay's +// remote devices are offline. +bool input_is_action_pressed(ButtonAction action, int controllerIndex, Entity* entity) +{ + std::optional isModPressed = action_hook_run(entity, INPUT_HOOK_PRESSED, action); + return isModPressed ? *isModPressed : is_action_met(action, controllerIndex, ACTION_PRESSED); +} + +// 009561e0 Whether an action was pressed this frame on a controller, or on any device for -1. A mod may answer first. +// Netplay's remote devices are offline. +bool input_is_action_triggered(ButtonAction action, int controllerIndex, Entity* entity) +{ + std::optional isModTriggered = action_hook_run(entity, INPUT_HOOK_TRIGGERED, action); + if (isModTriggered) return *isModTriggered; + if (action == INPUT_RAW_ACTION) + reconstruction_missing("input_is_action_triggered 009561e0 (the raw button action)"); + return is_action_met(action, controllerIndex, ACTION_TRIGGERED); +} + +// 005ca5a0 Whether the player can use an item now: charged enough in its slot (none for -1), and able to pay or move +// as the item needs. +bool is_active_usable(Entity_Player& player, int item, int slot) +{ + if (slot >= 0 && player.GetTotalActiveCharge(slot) < player.GetActiveMinUsableCharge(slot)) return false; + + bool isMoving = vector_length_squared(player.velocity) > 1; + switch (item) + { + case COLLECTIBLE_PONY: + case COLLECTIBLE_WHITE_PONY: + return isMoving; + case COLLECTIBLE_GUPPYS_PAW: + case COLLECTIBLE_POTATO_PEELER: + return player.maxHearts >= 2; + case COLLECTIBLE_MAGIC_FINGERS: + return player.numCoins > 0; + case COLLECTIBLE_GOLDEN_RAZOR: + return player.numCoins >= GOLDEN_RAZOR_PRICE; + case COLLECTIBLE_SHARP_KEY: + return player.numKeys > 0; + case COLLECTIBLE_MAGIC_SKIN: + return player.GetEffectiveMaxHearts() + player.soulHearts > 0; + case COLLECTIBLE_SUPLEX: + return player.suplexState == 0 && isMoving; + case COLLECTIBLE_BOOK_OF_VIRTUES: + return !player.queuedItem.item || player.queuedItem.item->type != ITEM_ACTIVE; + case COLLECTIBLE_RED_KEY: + case COLLECTIBLE_STITCHES: + case COLLECTIBLE_RECALL: + reconstruction_missing("is_active_usable 005ca5a0 (Red Key, Stitches and Recall)"); + } + return true; +} + +// 0042a2f0 The item in an active slot, none outside the four. +int Entity_Player::GetActiveItem(int slot) +{ + return slot >= 0 && slot < ACTIVE_SLOT_COUNT ? activeItems[slot].item : 0; +} + +// 00505c80 The charge of an active slot, none outside the four. +int Entity_Player::GetActiveCharge(int slot) +{ + return slot >= 0 && slot < ACTIVE_SLOT_COUNT ? activeItems[slot].charge : 0; +} + +// The battery charge an active slot holds past a full charge, none outside the four. +int Entity_Player::GetBatteryCharge(int slot) +{ + return slot >= 0 && slot < ACTIVE_SLOT_COUNT ? activeItems[slot].batteryCharge : 0; +} + +// 00841cb0 The frames 9 Volt counts toward an empty one-charge item, none outside the four. +int Entity_Player::GetActiveSubCharge(int slot) +{ + return slot >= 0 && slot < ACTIVE_SLOT_COUNT ? activeItems[slot].subCharge : 0; +} + +// 00791510 Sets the data an active slot keeps between uses. +void Entity_Player::SetActiveVarData(int vardata, int slot) +{ + activeItems[slot].varData = vardata; +} + +// 00793940 Whether the first active slot recharges over time. +bool Entity_Player::HasTimedItem() +{ + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(activeItems[ACTIVE_SLOT_PRIMARY].item); + return item && item->chargeType == CHARGE_TIMED; +} + +// 007911f0 The charges an item needs, as some items and characters change it: a die's or a jar's charges kept in its +// data, Tainted Eve's Sumptorium, Tainted Jacob's Anima Sola, Tainted Lazarus' Flip, an unlit Glowing Hour Glass and a +// Necromancer's Necronomicon. +int Entity_Player::GetCollectibleMaxCharge(int collectibleId, int varData) +{ + constexpr int VARDATA_CHARGED[] = {263, 286, 348, 510}; + constexpr int D_INFINITY = 489; + constexpr int SUMPTORIUM = 713; + constexpr int VARDATA_CHARGE_MASK = 0xffff; + constexpr int ANIMA_SOLA_BIRTHRIGHT_CHARGES = 300; + constexpr int FLIP_LAZARUS_CHARGES = 4; + constexpr int NECRONOMICON_FORM_CHARGES = 10; + constexpr int SUMPTORIUM_EVE_CHARGES = 30; + + if (varData > 0 && std::ranges::find(VARDATA_CHARGED, collectibleId) != std::end(VARDATA_CHARGED)) return varData; + switch (collectibleId) + { + case D_INFINITY: + if (varData & VARDATA_CHARGE_MASK) return varData & VARDATA_CHARGE_MASK; + break; + case SUMPTORIUM: + if (playerType == PLAYER_EVE_B) return SUMPTORIUM_EVE_CHARGES; + break; + case COLLECTIBLE_ANIMA_SOLA: + if (playerType != PLAYER_JACOB_B && playerType != PLAYER_JACOB2_B) break; + if (HasCollectible(COLLECTIBLE_BIRTHRIGHT)) return ANIMA_SOLA_BIRTHRIGHT_CHARGES; + break; + case COLLECTIBLE_FLIP: + if (playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B) return FLIP_LAZARUS_CHARGES; + break; + case COLLECTIBLE_GLOWING_HOUR_GLASS: + if (varData < GLOWING_HOUR_GLASS_LIT_USES) return 0; + break; + case COLLECTIBLE_NECRONOMICON: + if (HasPlayerForm(PLAYERFORM_NECROMANCER) && varData == 1) return NECRONOMICON_FORM_CHARGES; + break; + } + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + return item ? item->maxCharges : 0; +} + +// 00791320 The charges an active slot holds when full. The second pocket slot holds none, nor Red Redemption's key. +int Entity_Player::GetActiveMaxCharge(int slot) +{ + if (slot == ACTIVE_SLOT_POCKET2) return 0; + if (slot == ACTIVE_SLOT_POCKET && activeItems[slot].item == COLLECTIBLE_RED_KEY && + g_game->challenge == CHALLENGE_RED_REDEMPTION) + return 0; + return GetCollectibleMaxCharge(activeItems[slot].item, activeItems[slot].varData); +} + +// 00791380 The charges an active slot needs before it can be used: one for the items that spend what they have. +int Entity_Player::GetActiveMinUsableCharge(int slot) +{ + if (slot == ACTIVE_SLOT_POCKET2) return 0; + if (slot == ACTIVE_SLOT_POCKET && activeItems[slot].item == COLLECTIBLE_RED_KEY && + g_game->challenge == CHALLENGE_RED_REDEMPTION) + return 0; + + ActiveItemDesc& active = activeItems[slot]; + if (active.item == COLLECTIBLE_LARYNX || active.item == COLLECTIBLE_EVERYTHING_JAR || + active.item == COLLECTIBLE_NOTCHED_AXE) + return 1; + if (active.item == COLLECTIBLE_NECRONOMICON && HasPlayerForm(PLAYERFORM_NECROMANCER) && active.varData == 1) + return 1; + return GetCollectibleMaxCharge(active.item, active.varData); +} + +// 00791530 How an active slot charges. An empty slot counts as special, and so does the Necronomicon a +// Necromancer has filled. The original crashes on an item missing from the config: here it charges normally. +ChargeType active_charge_type(Entity_Player& player, int slot) +{ + ActiveItemDesc& active = player.activeItems[slot]; + bool isNecromancer = !player.hasCurseMistEffect && !player.isCoopGhost && + player.playerForms[PLAYERFORM_NECROMANCER] >= NECROMANCER_FORM_ITEMS; + bool isFilledNecronomicon = active.item == COLLECTIBLE_NECRONOMICON && isNecromancer && active.varData == 1; + + if (active.item == 0 || isFilledNecronomicon) return CHARGE_SPECIAL; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(active.item); + return item ? item->chargeType : CHARGE_NORMAL; +} + +// 007910f0 The charge an active slot has with its battery charge, and the soul or blood charges Bethany and Tainted +// Bethany spend on it. A bar item counts those only as filling it, a held item not at all. +int Entity_Player::GetTotalActiveCharge(int slot) +{ + ActiveItemDesc& active = activeItems[slot]; + int total = active.charge + active.batteryCharge; + int storeCharge = playerType == PLAYER_BETHANY ? effectiveSoulCharge + : playerType == PLAYER_BETHANY_B ? effectiveBloodCharge + : 0; + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(active.item); + if (!item) return total + storeCharge; + switch (item->discharge_get()) + { + case DISCHARGE_BAR: + return storeCharge > 0 && total < item->maxCharges ? item->maxCharges : total; + case DISCHARGE_HELD: + return total; + default: + return total + storeCharge; + } +} + +// The bulb trinkets reread the stats when a slot's total charge moved from totalBefore. +static void bulbs_update(Entity_Player& player, int totalBefore, int slot) +{ + if (player.GetTotalActiveCharge(slot) == totalBefore) return; + if (!player.HasTrinket(TRINKET_VIBRANT_BULB) && !player.HasTrinket(TRINKET_DIM_BULB)) return; + + player.cacheFlags |= BULB_CACHE_FLAGS; + player.EvaluateItems(); +} + +// A slot's charge changed: the bulbs reread the stats, and the HUD redraws the player's part. +static void charge_changed_apply(Entity_Player& player, int totalBefore, int slot) +{ + bulbs_update(player, totalBefore, slot); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// 00791420 Sets an active slot's charge, what passes a full charge going to its battery, or every slot's for -1. +void Entity_Player::SetActiveCharge(int charge, int slot) +{ + if (slot < 0) + { + for (int each = 0; each < ACTIVE_SLOT_COUNT; each++) SetActiveCharge(charge, each); + return; + } + if (slot >= ACTIVE_SLOT_COUNT) return; + + int totalBefore = GetTotalActiveCharge(slot); + ActiveItemDesc& active = activeItems[slot]; + if (active.item != 0) + { + int maxCharge = GetActiveMaxCharge(slot); + active.charge = std::min(charge, maxCharge); + active.batteryCharge = std::min(std::max(charge - maxCharge, 0), maxCharge); + } + charge_changed_apply(*this, totalBefore, slot); +} + +// 007915a0 Adds charge to an active slot, or to every slot for -1, flashing its bar. A timed item fills from any +// charge, a special one takes none unless forced. Past a full charge, The Battery or an overcharge fills the battery. +// A filled Broken Glass Cannon mends. The charge added, negative when taken. +int Entity_Player::AddActiveCharge(int charge, int slot, bool isFlashHud, bool isOvercharge, bool isForce) +{ + if (slot < 0) + { + int added = 0; + for (int each = 0; each < ACTIVE_SLOT_COUNT; each++) + added += AddActiveCharge(charge, each, isFlashHud, isOvercharge, isForce); + return added; + } + + int totalBefore = GetTotalActiveCharge(slot); + int added = 0; + ActiveItemDesc& active = activeItems[slot]; + if (active.item != 0) + { + ChargeType chargeType = active_charge_type(*this, slot); + if (charge > 0 && !isForce && chargeType != CHARGE_NORMAL) + { + if (chargeType != CHARGE_TIMED) return 0; + charge = GetActiveMaxCharge(slot); + } + + int maxCharge = GetActiveMaxCharge(slot); + bool isFlash = isFlashHud || (chargeType != CHARGE_TIMED && maxCharge <= CHARGE_FLASH_MAX); + if (charge < 0) + { + int fromBattery = std::min(-charge, std::max(active.batteryCharge, 0)); + active.batteryCharge -= fromBattery; + int fromCharge = std::min(-(charge + fromBattery), std::max(active.charge, 0)); + active.charge -= fromCharge; + added = -fromBattery - fromCharge; + } + else if (charge > 0) + { + added = std::min(charge, std::max(maxCharge - active.charge, 0)); + int overflow = charge - added; + active.charge += added; + if ((HasCollectible(COLLECTIBLE_BATTERY) || isOvercharge) && overflow > 0) + { + overflow = std::min(overflow, std::max(maxCharge - active.batteryCharge, 0)); + if (overflow > 0) + { + active.batteryCharge += overflow; + added += overflow; + if (isFlash) + { + g_game->hud.FlashChargeBar(this, slot); + sound_play(ACTIVE_SOUND_BATTERY_CHARGE); + battery_effect_spawn(*this); + } + } + } + else if (added > 0 && isFlash) + { + g_game->hud.FlashChargeBar(this, slot); + sound_play(active.charge < maxCharge ? ACTIVE_SOUND_BEEP : ACTIVE_SOUND_ITEM_RECHARGE); + } + } + + bool isGlassCannonMended = active.item == COLLECTIBLE_BROKEN_GLASS_CANNON && active.charge >= maxCharge; + if (isGlassCannonMended) glass_cannon_mend(*this, slot); + } + + // The original compares the first slot's total with this slot's, kept as it is. + charge_changed_apply(*this, totalBefore, ACTIVE_SLOT_PRIMARY); + return added; +} + +// 007c3810 Whether an active slot, or any for -1, can take charge: an active that is not special nor chargeless and +// not full, its battery too with The Battery. +bool Entity_Player::NeedsCharge(int slot) +{ + if (slot < 0) + { + for (int each = 0; each < ACTIVE_SLOT_COUNT; each++) + if (NeedsCharge(each)) return true; + return false; + } + if (slot >= ACTIVE_SLOT_COUNT || activeItems[slot].item == 0) return false; + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(activeItems[slot].item); + ChargeType chargeType = active_charge_type(*this, slot); + if (!item || item->type != ITEM_ACTIVE || chargeType == CHARGE_SPECIAL) return false; + + int maxCharge = GetActiveMaxCharge(slot); + if (maxCharge == 0) return false; + if (activeItems[slot].charge < maxCharge) return true; + return HasCollectible(COLLECTIBLE_BATTERY) && activeItems[slot].batteryCharge < maxCharge; +} + +// 007c38c0 Fills an active slot, or every slot for -1, flashing its bar: twice its charges so a battery fills too, +// half for an unforced Mega Blast. Whether any charge was added, as the original's byte of it. +bool Entity_Player::FullCharge(int slot, bool isForce, bool isOvercharge) +{ + constexpr int MEGA_BLAST = 441; + + if (slot < 0) + { + uint8_t added = 0; + for (int each = 0; each < ACTIVE_SLOT_COUNT; each++) added += (uint8_t)FullCharge(each, isForce, false); + return added != 0; + } + if (slot >= ACTIVE_SLOT_COUNT || !g_manager->itemConfig.GetCollectible(activeItems[slot].item)) return false; + + int maxCharge = GetActiveMaxCharge(slot); + int charge = activeItems[slot].item == MEGA_BLAST && !isForce ? maxCharge / 2 : maxCharge * 2; + return (uint8_t)AddActiveCharge(charge, slot, true, isOvercharge, isForce) != 0; +} + +// 007ac7e0 Spends an active slot's charge after a use, its battery charge becoming the charge. Bethany pays what was +// missing in soul or blood charges, 9 Volt gives one back. Esau Jr. and Flip move the item, the rest is the after use. +void Entity_Player::DischargeActiveItem(uint32_t slot, bool isRemoved) +{ + if (slot >= (uint32_t)ACTIVE_SLOT_COUNT || activeItems[slot].item == 0) return; + + ActiveItemDesc& active = activeItems[slot]; + int newCharge = active.batteryCharge; + int maxCharge = GetActiveMaxCharge(slot); + int minCharge = GetActiveMinUsableCharge(slot); + if (active.charge < maxCharge) + { + int spent = active.charge - maxCharge; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(active.item); + if (item && item->discharge_get() != DISCHARGE_HELD) + { + if (item->discharge_get() == DISCHARGE_BAR) spent = -1; + bool isBloodPaid = GetEffectiveSoulCharge() < 1 || + (playerType == PLAYER_BETHANY && HasCollectible(COLLECTIBLE_BIRTHRIGHT) && + GetCollectibleRNG(COLLECTIBLE_BIRTHRIGHT).RandomInt(2) == 0); + if (!isBloodPaid) AddSoulCharge(spent); + else if (GetEffectiveBloodCharge() > 0) AddBloodCharge(spent); + } + } + + if (HasCollectible(COLLECTIBLE_9_VOLT) && newCharge + 1 < minCharge) + { + if (g_manager->itemConfig.GetCollectible(active.item)) + { + ChargeType chargeType = active_charge_type(*this, slot); + if (chargeType == CHARGE_TIMED) newCharge = std::max(newCharge + 1, maxCharge / 2); + else if (chargeType == CHARGE_NORMAL) + { + newCharge++; + sound_play(ACTIVE_SOUND_BEEP); + } + } + battery_effect_spawn(*this); + } + + int chargeBefore = active.charge; + SetActiveCharge(newCharge, slot); + isActiveUsed = false; + if (active.item == COLLECTIBLE_ESAU_JR) + reconstruction_missing("Entity_Player::DischargeActiveItem 007ac7e0 (Esau Jr.'s swap)"); + if (active.item == COLLECTIBLE_FLIP && slot == ACTIVE_SLOT_POCKET && (twinPlayer || backupPlayer)) + reconstruction_missing("Entity_Player::DischargeActiveItem 007ac7e0 (Flip's item for the other Lazarus)"); + + active_used_post(slot, isRemoved, chargeBefore); + if (slot == ACTIVE_SLOT_POCKET2) SetPocketActiveItem(0, ACTIVE_SLOT_POCKET2, false); +} + +// 007abf80 After a slot's item was spent: a Broken Glass Cannon mends, the first slot's use feeds Book of Virtues and +// Judas' Birthright. M!, Butter! and Expansion Pack are not written yet. +void Entity_Player::active_used_post(int slot, bool isRemoved, int chargeBeforeUse) +{ + if (activeItems[slot].item == COLLECTIBLE_BROKEN_GLASS_CANNON) glass_cannon_mend(*this, slot); + if (slot != ACTIVE_SLOT_PRIMARY) return; + + TriggerBookOfVirtues(activeItems[0].item, chargeBeforeUse); + trigger_book_of_belial_passive(activeItems[0].item, chargeBeforeUse); + if (HasTrinket(TRINKET_M) || (HasTrinket(TRINKET_BUTTER) && !isRemoved) || HasTrinket(TRINKET_EXPANSION_PACK)) + reconstruction_missing("Entity_Player::active_used_post 007abf80 (M!, Butter! and Expansion Pack)"); +} + +// 005ca470 Book of Virtues' wisps for an active used. +void Entity_Player::TriggerBookOfVirtues(int, int) +{ + if (!HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return; + reconstruction_missing("Entity_Player::TriggerBookOfVirtues 005ca470 (the wisps)"); +} + +// 005c9930 Judas' Birthright: the bonus an active gives when Book of Belial's passive is held. +void Entity_Player::trigger_book_of_belial_passive(int, int) +{ + if (!HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) return; + reconstruction_missing("Entity_Player::trigger_book_of_belial_passive 005c9930 (the active's bonus)"); +} + +// 007ad330 Takes off an item's costume unless its effect still runs (Shoop da Whoop's always goes), or it came with +// the item's pickup and the item is still owned. The original crashes on an item missing from the config. +void Entity_Player::TryRemoveCollectibleCostume(int collectibleId, bool) +{ + constexpr int SHOOP_DA_WHOOP = 49; + + if (collectibleId == 0 || + (temporaryEffects.HasCollectibleEffect(collectibleId) && collectibleId != SHOOP_DA_WHOOP)) + return; + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (!item || (item->isAddCostumeOnPickup && HasCollectible(collectibleId))) return; + RemoveCostume(item); +} + +// 00505cc0 Whether the player takes input: enabled and not cooling down. +bool Entity_Player::AreControlsEnabled() +{ + return isControlsEnabled && controlsCooldown <= 0; +} + +// 007a6300 Fires Bird's Eye's or Ghost Pepper's flame, a random one of the two with both, against the way the player +// walks (up when still). The original ignores its argument. +void Entity_Player::ShootCandle(Vector) +{ + constexpr int GHOST_PEPPER = 495; + constexpr int BIRDS_EYE = 616; + + Vector direction = vector_is_zero(movementVector) ? vector_make(0, -1) : vector_scale(movementVector, -1); + bool isRed = HasCollectible(BIRDS_EYE); + bool isBlue = HasCollectible(GHOST_PEPPER); + if (!isRed && !isBlue) return; + + if (isRed && (!isBlue || (Random() & 1) == 0)) ShootRedCandle(direction); + else ShootBlueCandle(direction); +} + +// Bible: kills Mom or Mom's Heart (earning Halo), or Satan kills the player. Flight comes from the room effect. +static void bible_use(ItemUse& use) +{ + Entity_Player& player = use.player; + + sound_play(ACTIVE_SOUND_BOOK_PAGE_TURN); + sound_play(ACTIVE_SOUND_BIBLE); + for (Entity* entity : room_entities()) + { + if (entity->type == ACTIVE_ENTITY_MOM || entity->type == ACTIVE_ENTITY_MOMS_HEART) + { + entity->Kill(EntityRef(&player)); + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_HALO); + break; + } + if (entity->type == ACTIVE_ENTITY_SATAN) + { + player.lastDamageSource = EntityRef(entity); + player.Kill(EntityRef(&player)); + break; + } + } + use_animate(use); +} + +// Book of Belial: the devil card's sound and the item raised. The damage comes from the room effect. +static void book_of_belial_use(ItemUse& use) +{ + sound_play(ACTIVE_SOUND_DEVIL_CARD); + use_animate(use); +} + +// Whether a grid entity covers the floor in a way a poop must not hide: a trapdoor, stairs, a pressure plate or a +// teleporter, as the original's is_grid_type_floor_special tells. +static bool is_grid_floor_special(GridEntityType type) +{ + return type == GRID_TRAPDOOR || type == GRID_STAIRS || type == GRID_PRESSURE_PLATE || type == GRID_TELEPORTER; +} + +// The Poop: a poop where the player stands, white with Hallowed Ground, black from Meconium, golden from Midas' Touch, +// and a fart. The candles of Bird's Eye and Ghost Pepper fire too. +static void poop_use(ItemUse& use) +{ + Entity_Player& player = use.player; + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(player.pos); + GridEntity* grid = room.GetGridEntity(gridIndex); + + bool isFree = room.roomType != ROOM_DUNGEON && room.GetGridCollision(gridIndex) == 0; + if (isFree && !(grid && is_grid_floor_special(grid->type))) + { + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_POOP); + int variant = POOP_NORMAL; + if (player.HasCollectible(COLLECTIBLE_HALLOWED_GROUND) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HALLOWED_GROUND)) + variant = POOP_WHITE; + if (player.HasTrinket(TRINKET_MECONIUM)) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_MECONIUM); + int chance = multiplier == 2 || multiplier == 3 ? MECONIUM_CHANCES[multiplier - 1] : MECONIUM_CHANCES[0]; + if (player.GetTrinketRNG(TRINKET_MECONIUM).RandomInt(PERCENT) < (uint32_t)chance) variant = POOP_BLACK; + } + if (player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH) && + (int)(rng.RandomInt(PERCENT) - (int)(player.luck * MIDAS_LUCK_SCALE)) < MIDAS_POOP_CHANCE) + variant = POOP_GOLDEN; + + room.SpawnGridEntity(gridIndex, GRID_POOP, variant, rng.Next(), 0); + reconstruction_missing("Game::ButterBeanFart 00704360 (The Poop's fart)"); + } + sound_play(ACTIVE_SOUND_FART); + player.ShootCandle(Vector{}); +} + +// Tammy's Head: a ring of ten tears turned at random, bigger and with bonus damage a data value scales in percent. +// The rings of the other weapons are not written yet. +static void tammys_head_use(ItemUse& use) +{ + Entity_Player& player = use.player; + float turn = random_unit(); + float scale = use.request.varData != 0 ? use.request.varData / (float)PERCENT : 1; + + bool isOtherWeapon = player.HasWeaponType(WEAPON_BOMBS) || player.HasWeaponType(WEAPON_BRIMSTONE) || + player.HasWeaponType(WEAPON_LASER) || player.HasWeaponType(WEAPON_KNIFE); + if (player.megaBlastLaser || isOtherWeapon) + reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (Tammy's Head with another weapon)"); + + float bonus = TAMMY_TEAR_DAMAGE * scale; + for (int i = 0; i < TAMMY_TEAR_COUNT; i++) + { + Vector direction = vector_from_angle(((float)i / TAMMY_TEAR_COUNT + turn) * FULL_CIRCLE); + PosVel shot = {player.pos, vector_resized(direction, TAMMY_TEAR_SPEED)}; + Entity_Tear* tear = player.FireTear(shot, TEAR_FIRE_EXTRA_SHOT, nullptr, 1); + tear->SetScale(tear->fScale * TAMMY_TEAR_SCALE); + tear->SetCollisionDamage(tear->collisionDamage + bonus); + } +} + +// Mom's Bra: freezes every enemy for the item's cooldown. +static void moms_bra_use(ItemUse& use) +{ + Entity_Player& player = use.player; + EntityList_EL& entities = room_entities(); + + sound_play(ACTIVE_SOUND_MOMS_BRA); + for (size_t i = 0; i < entities.size(); i++) + { + int duration = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MOMS_BRA)->maxCooldown; + if (is_item_target(entities[i], player)) entities[i]->AddFreeze(EntityRef(&player), duration, false); + } + use_animate(use); +} + +// Kamikaze!: an explosion on the player carrying its bomb effects, through boss armor. +static void kamikaze_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + explosion_effects({.tearFlags = player.GetBombFlags(false), .position = player.pos, .source = &player, + .damageFlags = KAMIKAZE_DAMAGE_FLAGS, .damage = KAMIKAZE_DAMAGE, .isDamageSource = true, + .isLineCheck = false}); +} + +// Teleport!: off to a random room of the floor, as Game::MoveToRandomRoom does it, which game.h does not declare yet. +static void teleport_use(ItemUse& use) +{ + Entity_Player& player = use.player; + Game& game = *g_game; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + uint32_t seed = player.GetCollectibleRNG(COLLECTIBLE_TELEPORT).Next(); + game.leaveDoor = -1; + game.StartRoomTransition( + {.player = &player, .animation = TRANSITION_TELEPORT, .roomIndex = game.GetRandomRoomIndex(false, seed)}); +} + +// Yum Heart: a red heart for the player, half a heart for every other player. +static void yum_heart_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + sound_play(player.playerType == PLAYER_MAGDALENE_B ? ACTIVE_SOUND_VAMP_DOUBLE : ACTIVE_SOUND_VAMP_GULP); + for (Entity_Player* each : g_game->playerManager.playerList) + each->AddHearts(each == &player ? YUM_HEART_OWN_HEARTS : YUM_HEART_OTHER_HEARTS, false, false); +} + +// Lemon Mishap: a pool of lemon creep under the player. +static void lemon_mishap_use(ItemUse& use) +{ + Entity_Player& player = use.player; + EntitySpawn spawn = {.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, + .variant = ACTIVE_EFFECT_PLAYER_CREEP_LEMON_MISHAP, .seed = Random()}; + + sound_play(ACTIVE_SOUND_GASCAN_POUR); + g_game->Spawn(spawn)->Update(); + use_animate(use); +} + +// Book of Revelations: a soul heart, and a horseman for the floor's boss. +static void book_of_revelations_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + player.AddSoulHearts(REVELATIONS_SOUL_HEARTS, false); + g_game->ForceHorsemanBoss(player.GetCollectibleRNG(COLLECTIBLE_BOOK_OF_REVELATIONS).Next()); + g_game->SetStateFlag(REVELATIONS_STATE_FLAG, true); +} + +// The D6 and the Eternal D6: every pedestal item of the room rerolled, which Entity_Pickup does not declare yet. +static void d6_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant == PLAYER_VARIANT_PLAYER) + { + EntityList_EL& entities = room_entities(); + + g_game->itemPool.ResetRoomBlacklist(); + for (size_t i = 0; i < entities.size(); i++) + { + Entity* entity = entities[i]; + if (entity->type != ENTITY_PICKUP || entity->variant != PICKUP_COLLECTIBLE) continue; + if (entity->isDead || entity->subtype == 0) continue; + + Entity_Pickup* pickup = static_cast(entity); + if (pickup->CanReroll() && (pickup->optionsPickupIndex == 0 || pickup->timeout < 0)) + reconstruction_missing("Entity_Pickup::Morph 006e30a0 (the D6's reroll)"); + } + if (use.id == COLLECTIBLE_ETERNAL_D6 && player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) + reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the Eternal D6's wisps)"); + } + if (!use.isShowAnimation) return; + + sound_play_local(player, ACTIVE_SOUND_D6_ROLL); + use_animate(use); +} + +// Razor Blade: hurts the player for half a red heart, a whole one on the room's first use, which the room effect pays +// back in damage. +static void razor_blade_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + float damage = g_game->deathmatchManager.is_active() ? DEATHMATCH_RAZOR_DAMAGE : RAZOR_BLADE_DAMAGE; + bool isFirst = player.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_RAZOR_BLADE) <= 0; + player.damageCooldown = 0; + player.TakeDamage(damage * (isFirst ? RAZOR_BLADE_FIRST_SCALE : 1), RAZOR_BLADE_DAMAGE_FLAGS, EntityRef(), + DAMAGE_COUNTDOWN_FRAMES); + sound_play(ACTIVE_SOUND_RAZOR_BLADE); +} + +// Spider Butt: every enemy slowed for the item's cooldown, hurt, and set to leave a spider when it dies. +static void spider_butt_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + EntityList_EL& entities = room_entities(); + sound_play(ACTIVE_SOUND_DEATH_CARD); + for (size_t i = 0; i < entities.size(); i++) + { + Entity* entity = entities[i]; + if (!is_item_target(entity, player) || entity->HasEntityFlags(FLAG_FRIENDLY)) continue; + + int duration = g_manager->itemConfig.GetCollectible(COLLECTIBLE_SPIDER_BUTT)->maxCooldown; + entity->AddSlowing(EntityRef(&player), duration, SPIDER_BUTT_SLOW, SPIDER_BUTT_COLOR, false); + entity->AddEntityFlags(FLAG_SPAWN_STICKY_SPIDERS); + entity->TakeDamage(SPIDER_BUTT_DAMAGE, SPIDER_BUTT_DAMAGE_FLAGS, EntityRef(&player), DAMAGE_COUNTDOWN_FRAMES); + } +} + +// Runs an item's own effect. The items without one of their own only add their room effect, and the ones not +// written yet stop the game, named by the release that added them. +static void item_effect_run(ItemUse& use) +{ + switch (use.id) + { + case COLLECTIBLE_BIBLE: + return bible_use(use); + case COLLECTIBLE_BOOK_OF_BELIAL: + return book_of_belial_use(use); + case COLLECTIBLE_POOP: + return poop_use(use); + case COLLECTIBLE_TAMMYS_HEAD: + return tammys_head_use(use); + case COLLECTIBLE_MOMS_BRA: + return moms_bra_use(use); + case COLLECTIBLE_KAMIKAZE: + return kamikaze_use(use); + case COLLECTIBLE_TELEPORT: + return teleport_use(use); + case COLLECTIBLE_YUM_HEART: + return yum_heart_use(use); + case COLLECTIBLE_LEMON_MISHAP: + return lemon_mishap_use(use); + case COLLECTIBLE_BOOK_OF_REVELATIONS: + return book_of_revelations_use(use); + case COLLECTIBLE_D6: + case COLLECTIBLE_ETERNAL_D6: + return d6_use(use); + case COLLECTIBLE_RAZOR_BLADE: + return razor_blade_use(use); + case COLLECTIBLE_SPIDER_BUTT: + return spider_butt_use(use); + } + if (std::ranges::find(CASED_ACTIVES, use.id) == std::end(CASED_ACTIVES)) return; + + const ActiveRelease* release = std::ranges::find_if(ACTIVE_RELEASES, [&](const ActiveRelease& each) + { return use.id <= each.lastItem; }); + std::string name = std::string("Entity_Player::UseActiveItem 005b39d0 (the ") + release->name + " active " + + std::to_string(use.id) + ")"; + reconstruction_missing(name.c_str()); +} + +// 005b39d0 Uses an active item: co-op babies copy the main player's first use since a discharge, the item is raised +// with its sound, its own effect runs, mods see the use, its room effect and costume go on and the stats are reread. +// What its slot does next: discharge unless an item state holds the item, and remove it if a mod asks. +UseResult Entity_Player::UseActiveItem(const ActiveUse& request) +{ + UseResult result; + if (request.item == 0 || request.slot >= ACTIVE_SLOT_COUNT) return result; + lua_callback_check(MC_PRE_USE_ITEM, "Entity_Player::UseActiveItem 005b39d0: LuaEngine::PreUseItem 00863760"); + + if (variant == PLAYER_VARIANT_PLAYER && !isActiveUsed) + for (Entity_Player* each : g_game->playerManager.playerList) + if (each->variant == PLAYER_VARIANT_COOP_BABY) each->UseActiveItem({.item = request.item}); + + ItemUse use = {.player = *this, .request = request}; + use.id = request.item == COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE ? COLLECTIBLE_BOOK_OF_BELIAL : request.item; + use.item = g_manager->itemConfig.GetCollectible(use.id); + use.isShowAnimation = variant == PLAYER_VARIANT_PLAYER && !(request.flags & USE_NOANIM); + use.isLuaAnimationAllowed = use.isShowAnimation; + use.isWispAllowed = use.isShowAnimation || (request.flags & USE_ALLOWWISPSPAWN); + if (use.id < 0) reconstruction_missing("Entity_Player::UseActiveItem 005b39d0: glitched_item_effects_run 009e01b0"); + + if (use.isShowAnimation) sound_play(ACTIVE_SOUND_ITEM_RAISE); + if (!use.item) + { + // The original goes on to read the missing item's cache flags and crashes: here the use ends. + log_printf(LOG_INFO, "Undefined collectible used %d\n", use.id); + return result; + } + item_effect_run(use); + + LuaItemUse lua = {.player = this, .rng = &GetCollectibleRNG(use.id), .activeSlot = request.slot, + .collectibleType = use.id, .customVarData = request.varData, .useFlags = request.flags, + .isDischarge = use.result.isDischarge, .isRemove = use.result.isRemove}; + if (lua_engine_get().UseItem(lua) && use.isLuaAnimationAllowed) + AnimateCollectible(use.id, "UseItem", "PlayerPickupSparkle"); + use.result = {.isDischarge = lua.isDischarge, .isRemove = lua.isRemove}; + if (use.result.isRemove && (request.flags & USE_VOID)) + { + RemoveCollectible(use.id, false, ACTIVE_SLOT_NONE, true); + use.result.isRemove = false; + } + use.result.isDischarge = use.result.isDischarge && (itemState == 0 || itemState == COLLECTIBLE_DOCTORS_REMOTE); + + bool isCostume = !(request.flags & USE_NOCOSTUME); + cacheFlags |= use.item->cacheFlags; + if (use.isAddEffect) temporaryEffects.AddEffect(TemporaryEffect(use.item), isCostume, 1); + if (cacheFlags) EvaluateItems(); + if (isCostume) AddCostume(use.item, false); + if (use.id == COLLECTIBLE_WAVY_CAP) update_mini_mush_costume(); + else if (use.id == COLLECTIBLE_BERSERK) g_game->UpdateBackwardsPathStages(); + + isActiveUsed = true; + return use.result; +} + +// The first slot's frame for every slot: recharge cooldowns count down, a timed item fills a charge a frame and beeps +// when full, 9 Volt refills an empty one-charge item after a while in a room with enemies, 4.5 Volt's partial charge +// settles. +static void timed_items_recharge(Entity_Player& player) +{ + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + ActiveItemDesc& active = player.activeItems[slot]; + if (active.timeRechargeCooldown > 0) active.timeRechargeCooldown--; + if (active.item == 0) continue; + + int maxCharge = player.GetActiveMaxCharge(slot); + int minCharge = player.GetActiveMinUsableCharge(slot); + ChargeType chargeType = active_charge_type(player, slot); + if (active.timeRechargeCooldown < 1) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(active.item); + if (item && item->chargeType == CHARGE_TIMED) + { + if (active.item == COLLECTIBLE_WAVY_CAP) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Wavy Cap's recharge)"); + + int step = TIMED_RECHARGE_STEP; + if (active.charge < maxCharge) + { + int added = std::min(maxCharge - active.charge, step); + active.charge += added; + step -= added; + if (active.charge >= maxCharge) + { + g_game->hud.FlashChargeBar(&player, slot); + sound_play(ACTIVE_SOUND_BEEP); + } + } + if (player.HasCollectible(COLLECTIBLE_BATTERY) && active.batteryCharge < maxCharge && step > 0) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (a timed item's battery)"); + } + + bool isNineVoltCounting = player.HasCollectible(COLLECTIBLE_9_VOLT) && minCharge == 1 && + active.charge == 0 && chargeType == CHARGE_NORMAL && + (active.subCharge != 0 || g_game->room->GetAliveEnemiesCount() > 0); + if (!isNineVoltCounting) active.subCharge = 0; + else if (++active.subCharge >= NINE_VOLT_RECHARGE_FRAMES) + { + active.charge = 1; + active.subCharge = 0; + } + } + + bool isBatteryUnfilled = player.HasCollectible(COLLECTIBLE_BATTERY) && active.batteryCharge < maxCharge; + bool isPartlyCharged = active.charge < maxCharge || isBatteryUnfilled; + if (player.HasCollectible(COLLECTIBLE_4_5_VOLT) && chargeType == CHARGE_NORMAL && isPartlyCharged) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (4.5 Volt's partial charge)"); + active.partialCharge = 0; + } +} + +// Shows the giant book a book or die plays over the screen when it is used from a slot. +static void use_overlay_show(Entity_Player& player, int item, int slot) +{ + int varData = player.activeItems[slot].varData; + bool isSkipped = false; + switch (item) + { + case COLLECTIBLE_BOOK_OF_BELIAL: + case COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE: + isSkipped = player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BOOK_OF_BELIAL); + break; + case COLLECTIBLE_NECRONOMICON: + isSkipped = player.HasPlayerForm(PLAYERFORM_NECROMANCER) && varData != 0; + break; + case COLLECTIBLE_DEAD_SEA_SCROLLS: + isSkipped = player.itemState != 0; + break; + case COLLECTIBLE_GLOWING_HOUR_GLASS: + isSkipped = varData < GLOWING_HOUR_GLASS_LIT_USES; + break; + } + + const UseOverlay* overlay = + std::ranges::find_if(USE_OVERLAYS, [&](const UseOverlay& each) { return each.item == item; }); + if (isSkipped || overlay == std::end(USE_OVERLAYS)) return; + g_game->itemOverlay.Show(overlay->overlay, item == COLLECTIBLE_FLUSH ? 0 : OVERLAY_DELAY, nullptr); +} + +// Uses a slot's item from the item button: only when charged and payable, else Sharp Plug may pay health for it. A +// zero-charge item waits out its room effect. The use discharges the slot or removes the item as it asks, and Car +// Battery uses it again. +static void active_slot_use(Entity_Player& player, int slot, int itemStateBefore) +{ + constexpr uint32_t CAR_BATTERY_FLAGS = USE_NOANIM | USE_CARBATTERY | USE_ALLOWWISPSPAWN | USE_CUSTOMVARDATA; + + int item = player.activeItems[slot].item; + ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(item); + int maxCharge = player.GetActiveMaxCharge(slot); + if (!is_active_usable(player, item, slot)) + { + if (item == COLLECTIBLE_MINE_CRAFTER) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Mine Crafter's barrels)"); + if (player.HasCollectible(COLLECTIBLE_SHARP_PLUG) && player.itemState == 0 && config && + config->discharge_get() != DISCHARGE_HELD) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Sharp Plug)"); + return; + } + if (maxCharge == 0 && player.temporaryEffects.GetCollectibleEffect(item) && config->maxCooldown != 0) return; + + use_overlay_show(player, item, slot); + int varData = player.activeItems[slot].varData; + if (g_game->challenge == CHALLENGE_APRILS_FOOL && slot == ACTIVE_SLOT_PRIMARY) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (April's Fool's random actives)"); + if (player.itemState != 0 && item != player.itemState) player.ResetItemState(); + player.wildCardItemType = WILD_CARD_ACTIVE; + player.wildCardItem = item; + player.wildCardVarData = varData; + UseResult result = player.UseActiveItem({.item = item, .flags = USE_OWNED, .slot = slot}); + + int used = player.activeItems[slot].item; + bool isCarBatteryUse = player.HasCollectible(COLLECTIBLE_CAR_BATTERY) && player.itemState == 0 && + itemStateBefore == 0 && !result.isRemove && used != 0 && maxCharge > 0 && + used != COLLECTIBLE_MOVING_BOX && used != COLLECTIBLE_MR_ME; + if (isCarBatteryUse) player.UseActiveItem({.item = used, .flags = CAR_BATTERY_FLAGS, .varData = varData}); + if (result.isDischarge) player.DischargeActiveItem(slot, result.isRemove); + if (result.isRemove) player.RemoveCollectible(player.activeItems[slot].item, false, slot, true); + if (player.HasTrinket(TRINKET_BROKEN_REMOTE) && slot == ACTIVE_SLOT_PRIMARY) player.isBrokenRemotePending = true; +} + +// The item button pressed for a slot: Notched Axe goes back in hand, a charged item is used. An item state the press +// did not change is put away after. +static void active_trigger(Entity_Player& player, int slot) +{ + constexpr int ACTION_TRIGGER_ITEM = 0x10; + constexpr int SHOOP_DA_WHOOP = 49; + constexpr int UNHIDDEN_STATES[] = {0, COLLECTIBLE_PONY, COLLECTIBLE_WHITE_PONY, COLLECTIBLE_BOOMERANG}; + + int itemStateBefore = player.itemState; + int item = player.activeItems[slot].item; + player.lastActionTriggers |= ACTION_TRIGGER_ITEM; + if (item == COLLECTIBLE_NOTCHED_AXE && player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_NOTCHED_AXE)) + { + player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_NOTCHED_AXE, -1); + player.AnimateCollectible(COLLECTIBLE_NOTCHED_AXE, "HideItem", "PlayerPickupSparkle"); + } + else if (item == COLLECTIBLE_ANIMA_SOLA || item == COLLECTIBLE_DECAP_ATTACK) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Anima Sola's and Decap Attack's recall)"); + else if (item != 0) active_slot_use(player, slot, itemStateBefore); + + if (player.itemState == 0 || player.itemState != itemStateBefore || player.itemStateCooldown >= 1) return; + int costumeItem = player.itemState == SHOOP_DA_WHOOP ? SHOOP_DA_WHOOP : player.activeItems[slot].item; + player.TryRemoveCollectibleCostume(costumeItem, false); + player.ResetItemState(); + if (std::ranges::find(UNHIDDEN_STATES, itemStateBefore) == std::end(UNHIDDEN_STATES)) + player.AnimateCollectible(itemStateBefore, "HideItem", "PlayerPickupSparkle"); +} + +// 00791a40 Reads the item button for an active slot (the first from the frame, the pocket ones from the pocket button): +// Suplex's aim, the items held down, the timed recharges, and a press that uses the slot's item. The bulb trinkets +// reread the stats when the first slot's charge changed. A pending forced use the original keeps is never set. +void Entity_Player::ControlActiveItem(int slot) +{ + if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost || IsHologram() || playerType == PLAYER_THESOUL_B) return; + if (playerType == PLAYER_JACOB || playerType == PLAYER_ESAU) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Jacob and Esau's shared item button)"); + + ButtonAction action = slot != ACTIVE_SLOT_PRIMARY ? ACTION_PILL_CARD : ACTION_ITEM; + bool isPressed = input_is_action_pressed(action, controllerIndex, this); + bool isTriggered = input_is_action_triggered(action, controllerIndex, this); + if (HasEntityFlags(FLAG_FEAR) || hasCurseMistEffect || isCoopGhost) + { + isPressed = false; + isTriggered = false; + } + if (itemStateCooldown != 0 && itemState != 0) return; + + int chargeBefore = GetTotalActiveCharge(slot); + if (itemState == COLLECTIBLE_SUPLEX || suplexState != 0) + { + if (suplexState == SUPLEX_AIMING && isTriggered && suplexAimCountdown >= 2) suplexAimCountdown = 1; + return; + } + + bool isInterpolating = HasEntityFlags(FLAG_INTERPOLATION_UPDATE); + int item = activeItems[slot].item; + if (slot == ACTIVE_SLOT_PRIMARY && !isPressed && !isInterpolating && HasTrinket(TRINKET_PANIC_BUTTON) && item != 0) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Panic Button)"); + if (item == COLLECTIBLE_BREATH_OF_LIFE || item == COLLECTIBLE_SPIN_TO_WIN) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Breath of Life and Spin to Win held down)"); + if (item == COLLECTIBLE_BAG_OF_CRAFTING && slot == ACTIVE_SLOT_POCKET && !isInterpolating) + { + if (itemState == COLLECTIBLE_BAG_OF_CRAFTING && AreControlsEnabled() && isPressed) + reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (crafting with the Bag of Crafting)"); + bagOfCraftingHoldFrames = 0; + } + + if (slot == ACTIVE_SLOT_PRIMARY && !isInterpolating) timed_items_recharge(*this); + if (AreControlsEnabled() && isTriggered) active_trigger(*this, slot); + if (slot == ACTIVE_SLOT_PRIMARY) bulbs_update(*this, chargeBefore, slot); +} diff --git a/src/entity_player_bombs.cpp b/src/entity_player_bombs.cpp new file mode 100644 index 0000000..b34e6ba --- /dev/null +++ b/src/entity_player_bombs.cpp @@ -0,0 +1,231 @@ +#include "entity_player.h" +#include "active_items.h" +#include "entity_bomb.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "sfx_manager.h" +#include +#include +#include + +// The items a player's bombs ask about (Lua's CollectibleType and TrinketType). +constexpr int COLLECTIBLE_BOBBY_BOMB = 125; +constexpr int COLLECTIBLE_BOBS_CURSE = 140; +constexpr int COLLECTIBLE_BUTT_BOMBS = 209; +constexpr int COLLECTIBLE_SAD_BOMBS = 220; +constexpr int COLLECTIBLE_HOT_BOMBS = 256; +constexpr int COLLECTIBLE_STRANGE_ATTRACTOR = 315; +constexpr int COLLECTIBLE_BOMBER_BOY = 353; +constexpr int COLLECTIBLE_SCATTER_BOMBS = 366; +constexpr int COLLECTIBLE_STICKY_BOMBS = 367; +constexpr int COLLECTIBLE_MR_MEGA = 106; +constexpr int COLLECTIBLE_BLACK_POWDER = 420; +constexpr int COLLECTIBLE_GLITTER_BOMBS = 432; +constexpr int COLLECTIBLE_FAST_BOMBS = 517; +constexpr int COLLECTIBLE_NANCY_BOMBS = 563; +constexpr int COLLECTIBLE_ROCKET_IN_A_JAR = 583; +constexpr int COLLECTIBLE_BLOOD_BOMBS = 614; +constexpr int COLLECTIBLE_BRIMSTONE_BOMBS = 646; +constexpr int COLLECTIBLE_GHOST_BOMBS = 727; +constexpr int TRINKET_BOBS_BLADDER = 71; +constexpr int TRINKET_SHORT_FUSE = 133; +constexpr int TRINKET_RING_CAP = 164; + +// The frames between bombs (one with Fast Bombs), the push a placed bomb keeps, a bigger bomb's scale and extra +// damage, the spread of extra bombs, Short Fuse's fuse and extra damage, and the consumables the HUD redraws. +constexpr int BOMB_DELAY = 30; +constexpr int BOMB_DELAY_FAST = 1; +constexpr int BOMB_FUSE = 45; +constexpr float BOMB_INHERIT = 0.1f; +constexpr float BOMB_SCALE_BIG = 1.5f; +constexpr float BOMB_DAMAGE_BIG = 85; +constexpr float EXTRA_BOMB_SPREAD = 8; +constexpr int SHORT_FUSE = 22; +constexpr std::array SHORT_FUSE_DAMAGE = {15.000001f, 30.000002f, 50}; +constexpr int BOMBS_MAX = 99; +constexpr int CONSUMABLE_BOMBS = 1 << 2; +constexpr int CONSUMABLE_GIGA_BOMBS = 1 << 6; +constexpr int SOUND_FETUS_LAND = 40; +constexpr int SOUND_GLITTER_FUSE = 867; +constexpr int PLACE_SOUND_DELAY = 4; + +// A bomb item's tear effect: always, or by a chance out of 100 that luck raises, when the chances are rolled. +struct BombItem +{ + int collectible; + int flag; + int chance; + float luckChance; +}; + +constexpr std::array BOMB_ITEMS = {{{COLLECTIBLE_BOBBY_BOMB, TEAR_HOMING, 0, 0}, + {COLLECTIBLE_BOBS_CURSE, TEAR_POISON, 0, 0}, + {COLLECTIBLE_BUTT_BOMBS, TEAR_BUTT_BOMB, 18, 3}, + {COLLECTIBLE_HOT_BOMBS, TEAR_BURN, 25, 6}, + {COLLECTIBLE_SAD_BOMBS, TEAR_SAD_BOMB, 10, 3}, + {COLLECTIBLE_SCATTER_BOMBS, TEAR_SCATTER_BOMB, 33, 8}, + {COLLECTIBLE_STICKY_BOMBS, TEAR_STICKY, 0, 0}, + {COLLECTIBLE_GLITTER_BOMBS, TEAR_GLITTER_BOMB, 10, 3}, + {COLLECTIBLE_STRANGE_ATTRACTOR, TEAR_ATTRACTOR, 0, 0}, + {COLLECTIBLE_BOMBER_BOY, TEAR_CROSS_BOMB, 0, 0}}}; + +// Whether a chance item's effect comes up: always unrolled, else a roll out of 100 under its chance and luck. +static bool is_rolled(const Entity_Player& player, const BombItem& item, bool isRollChances) +{ + if (item.chance == 0 || !isRollChances) return true; + return (int)(Random() % 100) <= item.chance - (int)((double)player.luck * -item.luckChance); +} + +// 00780560 The tear effects the player's bombs carry from its items, those with chances rolled when asked (Lua's +// GetBombFlags): Bobby-Bomb to Bomber Boy, Bob's Bladder, a golden bomb and Fast Bombs (unrolled only), Blood, +// Brimstone and Ghost Bombs, and Nancy Bombs' random picks. +TearFlags Entity_Player::GetBombFlags(bool isRollChances) +{ + TearFlags flags; + for (const BombItem& item : BOMB_ITEMS) + if (HasCollectible(item.collectible) && is_rolled(*this, item, isRollChances)) flags.set(item.flag); + if (HasCollectible(COLLECTIBLE_STICKY_BOMBS)) flags.set(TEAR_EGG_FLAG); + if (GetTrinketMultiplier(TRINKET_BOBS_BLADDER) > 0) flags.set(TEAR_CREEP_TRAIL); + if (hasGoldenBomb && !isRollChances) flags.set(TEAR_GOLDEN_BOMB); + if (HasCollectible(COLLECTIBLE_FAST_BOMBS) && !isRollChances) flags.set(TEAR_FAST_BOMB); + if (HasCollectible(COLLECTIBLE_BLOOD_BOMBS)) flags.set(TEAR_BLOOD_BOMB); + if (HasCollectible(COLLECTIBLE_BRIMSTONE_BOMBS) && is_rolled(*this, {0, 0, 10, 3}, isRollChances)) + flags.set(TEAR_BRIMSTONE_BOMB); + if (HasCollectible(COLLECTIBLE_GHOST_BOMBS) && is_rolled(*this, {0, 0, 33, 8}, isRollChances)) + flags.set(TEAR_GHOST_BOMB); + if (HasCollectible(COLLECTIBLE_NANCY_BOMBS) && is_rolled(*this, {0, 0, 50, 8}, isRollChances)) + reconstruction_missing("Entity_Player::GetBombFlags 00780560: Nancy Bombs' random effects"); + if (flags[TEAR_GHOST_BOMB]) flags.set(TEAR_SPECTRAL); + return flags; +} + +// 00780ec0 The scale of the player's bombs: bigger with Mr. Mega, a persistent effect or Black Powder. +float Entity_Player::check_bomb_tearflags(const TearFlags& tearFlags) +{ + bool isBig = HasCollectible(COLLECTIBLE_MR_MEGA) || tearFlags[TEAR_PERSISTENT] || HasCollectible(COLLECTIBLE_BLACK_POWDER); + return isBig ? BOMB_SCALE_BIG : 1; +} + +// Asks the HUD to redraw the players' corners on the next frame but one, unless a full redraw is pending. +static void hud_refresh_players() +{ + HUD& hud = g_game->hud; + if (hud.hudRefreshType == HUD_REFRESH_FULL) return; + hud.hudRefreshType = HUD_REFRESH_PLAYER; + hud.hudRefreshCountdown = 2; +} + +// Plays a sound through the fart seeds. +static void bomb_sound_play(int sound, int frameDelay) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = frameDelay}); +} + +// Dresses a placed bomb: its size, effects and costumes, a big bomb's extra damage, a giga bomb lit at its end, Short +// Fuse's quick fuse and Fast Bombs' steady footing. +static void placed_bomb_setup(Entity_Player& player, Entity_Bomb& bomb, const TearFlags& flags, bool isGiga) +{ + float scale = isGiga ? 1 : player.check_bomb_tearflags(flags); + bomb.scale = scale; + bomb.rocketAngle = 0; + bomb.tearFlags = flags; + bomb.isLoadCostumes = true; + if (flags[TEAR_GLITTER_BOMB]) bomb_sound_play(SOUND_GLITTER_FUSE, 2); + if (scale >= BOMB_SCALE_BIG) bomb.explosionDamage += BOMB_DAMAGE_BIG; + if (isGiga) + { + if (const AnimationData* data = bomb.sprite.animState.animData) bomb.sprite.animState.AdvancePosition(data->length - 1); + bomb.SetExplosionCountdown(BOMB_FUSE); + } + int shortFuse = player.GetTrinketMultiplier(TRINKET_SHORT_FUSE); + if (shortFuse > 0) + { + bomb.SetExplosionCountdown(SHORT_FUSE); + if (shortFuse <= (int)SHORT_FUSE_DAMAGE.size()) bomb.explosionDamage += SHORT_FUSE_DAMAGE[shortFuse - 1]; + } + if (flags[TEAR_FAST_BOMB]) bomb.AddEntityFlags(FLAG_NO_KNOCKBACK); +} + +// Takes the first placed bomb from the player's count, a giga bomb from its giga bombs, unless it was free. +static void bomb_count_take(Entity_Player& player, bool isFree) +{ + player.numGigaBombs = std::max(0, std::min(player.numGigaBombs - 1, player.numBombs)); + player.ConsumableCountChanged(CONSUMABLE_GIGA_BOMBS); + hud_refresh_players(); + if (isFree) return; + + player.numBombs = std::clamp(player.numBombs - 1, 0, BOMBS_MAX); + player.ConsumableCountChanged(CONSUMABLE_BOMBS); + hud_refresh_players(); +} + +// 00780f40 Places a bomb when the bomb action is pressed and the last one was long enough ago: one from the player's +// count, a golden bomb's for free, a giga bomb while it has them, and more spread around with Ring Cap. Tainted ??? +// casts poop spells instead, and Tainted Forgotten's soul places none. +void Entity_Player::update_bomb_input() +{ + if (isCoopGhost || IsHologram() || playerType == PLAYER_THESOUL_B) return; + if (playerType == PLAYER_BLUEBABY_B) + { + bool isCast = isControlsEnabled && controlsCooldown < 1 && !HasEntityFlags(FLAG_FEAR) && + input_is_action_triggered(ACTION_BOMB, controllerIndex, this); + if (isCast) lastActionTriggers |= 1; + if (isCast && poopMana > 0) reconstruction_missing("Entity_Player::update_bomb_input 00780f40: poop spells"); + return; + } + if (bombPlaceDelay >= 1) + { + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) bombPlaceDelay--; + return; + } + if (!AreControlsEnabled() || HasEntityFlags(FLAG_FEAR) || !input_is_action_triggered(ACTION_BOMB, controllerIndex, this)) + return; + + lastActionTriggers |= 1; + for (Entity* partner : {twinPlayer.get(), parent && parent->is_player() ? parent.get() : nullptr}) + { + Entity_Player* other = partner ? partner->ToPlayer() : nullptr; + if (other && other->bombPlaceDelay == (other->HasCollectible(COLLECTIBLE_FAST_BOMBS) ? BOMB_DELAY_FAST : BOMB_DELAY)) + reconstruction_missing("Entity_Player::update_bomb_input 00780f40: the bomb a twin places with its partner"); + } + bool isFree = hasGoldenBomb; + bool isGiga = numGigaBombs > 0; + if (numBombs < 1 && !isFree && HasCollectible(COLLECTIBLE_BLOOD_BOMBS)) + reconstruction_missing("Entity_Player::update_bomb_input 00780f40: Blood Bombs' bomb for health"); + if (numBombs < 1 && !isFree) return; + + bombPlaceDelay = HasCollectible(COLLECTIBLE_FAST_BOMBS) ? BOMB_DELAY_FAST : BOMB_DELAY; + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::update_bomb_input 00780f40: a versus match's bomb delay"); + int bombCount = 1 + (HasTrinket(TRINKET_RING_CAP) ? GetTrinketMultiplier(TRINKET_RING_CAP) : 0); + for (int i = 0; i < bombCount; i++) + { + TearFlags flags = GetBombFlags(false); + Vector bombVelocity = vector_scale(velocity, BOMB_INHERIT); + bool isAiming = fireDirection != DIRECTION_NONE && !vector_is_zero(aimDirection); + if (HasCollectible(COLLECTIBLE_ROCKET_IN_A_JAR) && isAiming) + reconstruction_missing("Entity_Player::update_bomb_input 00780f40: Rocket in a Jar's rockets"); + + Entity* spawned = g_game->Spawn({.position = pos, .velocity = bombVelocity, .spawner = this, .type = ENTITY_BOMB, + .variant = isGiga ? BOMB_GIGA : BOMB_NORMAL, .seed = Random()}); + Entity_Bomb& bomb = *static_cast(spawned); + if (bombCount > 1) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + bomb.pos = vector_make(std::cos(angle) * EXTRA_BOMB_SPREAD + pos.x, std::sin(angle) * EXTRA_BOMB_SPREAD + pos.y); + } + placed_bomb_setup(*this, bomb, flags, isGiga); + if (i == 0) + { + bomb_count_take(*this, isFree); + bomb_sound_play(SOUND_FETUS_LAND, PLACE_SOUND_DELAY); + } + bomb.Update(); + } +} diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index 4fd73e1..8bf1711 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -247,7 +247,7 @@ void Entity_Player::death_update() Game& game = *g_game; std::string_view animation = GetDeathAnimName(); - bool isTransitioning = game.roomTransition.mode != TRANSITION_NONE || game.stageTransition._state != 0; + bool isTransitioning = game.roomTransition.mode != TRANSITION_NONE || game.stageTransition.state != 0; if (!isTransitioning && sprite.GetAnimation() != animation) { @@ -361,7 +361,7 @@ void Entity_Player::room_exit(bool isKeepHolyMantle) ItemConfig_Item* item = items.GetCollectible(id); if (item && (!item->isAddCostumeOnPickup || !HasCollectible(id))) RemoveCostume(item); } - if (itemState != COLLECTIBLE_MOMS_BRACELET || game.stageTransition._state != 0) + if (itemState != COLLECTIBLE_MOMS_BRACELET || game.stageTransition.state != 0) { bodySprite.Reset(); isPlayingItemAnimation = false; diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp new file mode 100644 index 0000000..a3f034d --- /dev/null +++ b/src/entity_player_evaluate.cpp @@ -0,0 +1,1064 @@ +#include "entity_player.h" +#include "entity_familiar.h" +#include "entity_tear.h" +#include "game.h" +#include "lua_engine.h" +#include "room.h" +#include "log.h" +#include "manager.h" +#include +#include +#include + +// The stat evaluation's constants: the tears formula, the base stats and the clamps that end it. +constexpr float TEARS_CURVE_SCALE = 1.3f; +constexpr float TEARS_DELAY_BASE = 16; +constexpr float TEARS_DELAY_STEP = 6; +constexpr float TEARS_DELAY_MIN = 5; +constexpr float FIRE_RATE_FRAMES = 30; +constexpr float CRACKED_CROWN_FIRE_RATE = 2.7272727f; +constexpr float NEGATIVE_TEARS_SCALE = 0.686655f; +constexpr float DAMAGE_CURVE_SCALE = 1.2f; +constexpr float DAMAGE_BASE = 3.5f; +constexpr float RANGE_BASE = 260; +constexpr float TEAR_HEIGHT_BASE = -23.75f; +constexpr float RANGE_MIN = 40; +constexpr float SPEED_MAX = 2; +constexpr float SPEED_MIN = 0.1f; +constexpr float SHOT_SPEED_MIN = 0.6f; +constexpr float DAMAGE_MIN = 0.5f; +constexpr float MAX_FIRE_DELAY_MIN = -0.75f; +constexpr float TEAR_HEIGHT_MAX = -5; +constexpr float FALL_SPEED_RANGE_SCALE = 10; +constexpr float FALL_SPEED_DECAY = 0.9f; +constexpr float FALL_SPEED_SLOPE = -9.49122142791748f; +constexpr float FALL_SPEED_MIN_SLOPE = 0.01f; +constexpr float G_FUEL_SPEED = 0.2f; +constexpr uint32_t DEBUG_HIGH_DAMAGE = 1 << 3; +constexpr uint32_t DEBUG_HIGH_LUCK = 1 << 8; +constexpr float DEBUG_DAMAGE_BONUS = 40; +constexpr float DEBUG_LUCK_BONUS = 50; +constexpr int PILL_TEARS_DOWN = 15; +constexpr int PILL_RANGE_DOWN = 11; +constexpr int PILL_RANGE_UP = 12; +constexpr int PILL_SPEED_DOWN = 13; +constexpr int PILL_SPEED_UP = 14; +constexpr int PILL_LUCK_DOWN = 17; +constexpr int PILL_LUCK_UP = 18; +constexpr int PILL_SHOT_SPEED_DOWN = 47; +constexpr int PILL_SHOT_SPEED_UP = 48; +constexpr int PLAYER_FORM_SPUN = 5; +constexpr int PLAYER_FORM_CONJOINED = 7; +constexpr int PLAYER_FORM_LEVIATHAN = 14; +constexpr int TRINKET_CRACKED_CROWN = 92; +constexpr int FAMILIAR_ITEM_WISP = 206; +constexpr int COLLECTIBLE_FORTUNE_COOKIE = 557; +constexpr int COOP_BUFF_DAMAGE = 0; +constexpr int COOP_BUFF_TEARS = 1; +constexpr int COOP_BUFF_SPEED = 2; +constexpr int COOP_BUFF_RANGE = 3; +constexpr int COOP_BUFF_LUCK = 4; + +// The run states the evaluation is reconstructed for: the stat changes of other characters, effects, trinkets, +// seeds, challenges, procedural items, wisps and the items below stop the game until reached. +// Candy Heart, Soul Locket, Experimental Treatment, Libra, Rock Bottom, Adrenaline, the pill items, Mega Mush, +// Berserk!, Jupiter, Dogma, Purity. +constexpr std::array EVALUATION_UNHANDLED_ITEMS = {671, 686, 240, 304, 562, 493, 654, 407, 625, 704, 594, 633, 556}; +// The weapon items, which the frame does not handle yet: Ludovico, Tech X, Spirit Sword, C Section, Dr. Fetus, +// Technology, Mom's Knife, Brimstone, Epic Fetus, Monstro's Lung. +constexpr std::array WEAPON_ITEMS = {329, 395, 579, 678, 52, 68, 114, 118, 168, 229}; + +// The constants of the other sections: the collectibles, trinkets, null items and characters they ask about. +constexpr int COLLECTIBLE_BINGE_EATER = 664; +constexpr int COLLECTIBLE_PASSIVE_DAMOCLES = 656; +constexpr int PLAYER_FORM_SPIDER_BABY = 12; +constexpr int PILL_TEARS_UP = 16; +constexpr int PILL_LARGER = 32; +constexpr int PILL_SMALLER = 33; +constexpr int COOP_BUFF_SMALLER = 5; +constexpr int COOP_BUFF_LARGER = 6; +constexpr int BABY_SKIN_SPOON = 4; +constexpr int BABY_SKIN_BONE = 57; +constexpr int BABY_SKIN_GHOST_A = 58; +constexpr int BABY_SKIN_GHOST_B = 59; +constexpr int TRINKET_AZAZELS_STUMP = 162; +constexpr int NULLITEM_BLOODY_BABYLON = 110; +constexpr int NULLITEM_SPIRIT_SHACKLES_SOUL = 101; +constexpr int NULLITEM_REVERSE_DEVIL = 67; +constexpr int NULLITEM_ESAU_JR = 100; +constexpr int NULLITEM_HUGE_GROWTH = 41; +constexpr int COLLECTIBLE_SPIRIT_SWORD = 579; +constexpr int COLLECTIBLE_C_SECTION = 678; +constexpr int COLLECTIBLE_EPIC_FETUS = 168; +constexpr int COLLECTIBLE_MOMS_KNIFE = 114; +constexpr int COLLECTIBLE_HAEMOLACRIA = 531; +constexpr int COLLECTIBLE_MONSTROS_LUNG = 229; +constexpr int COLLECTIBLE_DR_FETUS = 52; +constexpr int COLLECTIBLE_TECH_X = 395; +constexpr int COLLECTIBLE_TECHNOLOGY = 68; +constexpr int COLLECTIBLE_LUDOVICO = 329; +constexpr int COLLECTIBLE_BERSERK = 704; +constexpr int COLLECTIBLE_SPIRIT_SHACKLES = 677; +constexpr int COLLECTIBLE_ANTI_GRAVITY = 222; +constexpr int COLLECTIBLE_2SPOOKY = 554; +constexpr int COLLECTIBLE_VIRUS = 13; +constexpr int COLLECTIBLE_TOXIC_SHOCK = 350; +constexpr int COLLECTIBLE_LUSTY_BLOOD = 411; +constexpr int SPRITE_SCALE_UNLOCK = 3; +constexpr int ACHIEVEMENT_HUGE = 361; +constexpr float SIZE_STEP = 0.322f; +constexpr float SIZE_SCALE_KNEE = 2; +constexpr float SIZE_SCALE_SLOPE = 2.77259f; +constexpr float SIZE_SCALE_AT_KNEE = 4; +constexpr int DAILY_BIG_SIZE = 45; +constexpr float DAILY_BIG_SIZE_BONUS = 0.485f; +constexpr float BIG_HEAD_BONUS = 1.585f; +constexpr int BLOOD_LUST_COLOR_CAP = 6; +constexpr float BLOOD_LUST_COLOR_STEP = 0.125f; +constexpr float BERSERK_CHARGE_FULL = 100000; +constexpr float HOLOGRAM_ALPHA = 0.2f; +constexpr float COLOR_OFFSET_UNIT = 0.003921569f; +constexpr float HELD_THROW_SCALE = 0.1f; +constexpr int COLLECTIBLE_MOMS_BRACELET = 604; +constexpr int COLLECTIBLE_SUPLEX = 709; + +// Whether the player owns any of the listed collectibles. +static bool is_owning_any(Entity_Player& player, std::span collectibles) +{ + return std::ranges::any_of(collectibles, [&](int id) { return player.HasCollectible(id); }); +} + +// Whether the player owns an item whose cache flags ask for a section. +static bool is_cache_owned(Entity_Player& player, uint32_t flag) +{ + ItemConfig& items = g_manager->itemConfig; + for (int id = 0; id < (int)player.collectibleCounts.size(); id++) + if (player.collectibleCounts[id] > 0) + if (ItemConfig_Item* item = items.GetCollectible(id); item && (item->cacheFlags & flag)) return true; + return false; +} + +// How often a pill effect was taken, 0 for one never seen. +static float pill_uses(Entity_Player& player, int pillEffect) +{ + return pillEffect < (int)player.pillEffectUses.size() ? (float)player.pillEffectUses[pillEffect] : 0; +} + +// Whether the character and run are ones the evaluation is reconstructed for (see EVALUATION_UNHANDLED_ITEMS). +bool Entity_Player::is_character_plain() +{ + Game& game = *g_game; + bool isSmelted = std::ranges::any_of(smeltedTrinkets, [](SmeltedTrinket& t) { return t.count || t.goldenCount; }); + return playerType == PLAYER_ISAAC && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && !hasCurseMistEffect && + game.challenge == 0 && game.dailyChallenge._id == 0 && game.seedEffects.CountSeedEffects() == 0 && + !game.deathmatchManager.is_active() && temporaryEffects.effects.empty() && + trinkets == std::array{} && !isSmelted && proceduralItems.empty() && + itemWispsList.empty(); +} + +// The bonuses Binge Eater's foods give: damage, tears, range, shot speed, speed and luck, each food also slowing. +struct StatBonuses +{ + float damage = 0; + float tears = 0; + float range = 0; + float shotSpeed = 0; + float speed = 0; + float luck = 0; +}; + +// The part of 00763570 before the sections: Binge Eater's foods add to the stats it lowers speed for. +static StatBonuses stat_bonuses_get(Entity_Player& player) +{ + constexpr float FOOD_SLOW = 0.15f; + StatBonuses bonus; + + if (!player.HasCollectible(COLLECTIBLE_BINGE_EATER)) return bonus; + auto food = [&](int id, std::initializer_list stats) + { + float count = (float)player.GetCollectibleNum(id); + for (float* stat : stats) *stat = count + *stat; + bonus.speed = bonus.speed - count * FOOD_SLOW; + }; + food(22, {&bonus.tears, &bonus.range}); + food(23, {&bonus.tears, &bonus.shotSpeed}); + food(24, {&bonus.damage, &bonus.shotSpeed}); + food(25, {&bonus.range, &bonus.shotSpeed}); + food(26, {&bonus.damage, &bonus.range}); + food(346, {&bonus.luck, &bonus.shotSpeed}); + food(456, {&bonus.damage, &bonus.luck}); + food(707, {&bonus.tears, &bonus.luck}); + return bonus; +} + +// The fire delay section of 00763570: tears ups through the tears curve, fire rate items, then the multipliers of +// the shot changing items, as frames between shots. +static void fire_delay_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) +{ + auto n = [&](int id) { return (float)p.GetCollectibleNum(id); }; + auto has = [&](int id) { return p.HasCollectible(id); }; + + float tears = pill_uses(p, PILL_TEARS_UP) * 0.5f - pill_uses(p, PILL_TEARS_DOWN) * 0.4f; + for (int id : {32, 80, 381, 1, 370, 341, 342, 183, 394, 547, 601}) tears = n(id) + tears; + tears = (n(598) + tears) * 0.7f; + tears = n(6) * 1.5f + tears; + tears = (n(669) + n(564) + n(255) + n(115) + n(72)) * 0.5f + tears; + tears = (float)(p.GetCollectibleNum(196) - p.GetCollectibleNum(182)) * 0.4f + tears; + tears = (float)(p.GetCollectibleNum(189) + p.GetCollectibleNum(101) + p.GetCollectibleNum(90)) * 0.2f + tears; + tears = tears - (float)(p.GetCollectibleNum(331) + p.GetCollectibleNum(237)) * 0.3f; + tears = n(438) * 0.75f + tears; + tears = n(443) * 0.3f + tears; + tears = n(465) * 0.35f + tears; + float bonusTears = bonus.tears * 0.5f; + if (bonusTears < 0) bonusTears *= NEGATIVE_TEARS_SCALE; + tears = bonusTears + tears; + if (p.HasPlayerForm(PLAYER_FORM_CONJOINED)) tears = tears - 0.3f; + if (p.coopBabyBuffTimers[COOP_BUFF_TEARS] > 0) tears = tears + 1; + + float curve = std::sqrt(std::max(tears * TEARS_CURVE_SCALE + 1, 0.0f)); + float delay = std::max(TEARS_DELAY_BASE - curve * TEARS_DELAY_STEP - std::min(tears, 0.0f) * TEARS_DELAY_STEP, + TEARS_DELAY_MIN); + float rate = FIRE_RATE_FRAMES / (delay + 1); + if (has(600)) rate *= 1.2f; + if (crownScale != 1 && rate > CRACKED_CROWN_FIRE_RATE) rate = rate + (rate - CRACKED_CROWN_FIRE_RATE) * (crownScale - 1); + + float zodiacA = p.GetZodiacEffect() == 307 ? 1.0f : 0.0f; + float zodiacB = p.GetZodiacEffect() == 309 ? 1.0f : 0.0f; + float pairs = (float)(p.GetCollectibleNum(307) + p.GetCollectibleNum(228) + p.GetCollectibleNum(224) + + p.GetCollectibleNum(206)) + zodiacA; + pairs = (n(309) + pairs + zodiacB + (float)p.fireDelayModifier) * 0.5f; + float flat = (float)p.brittleBonesUpgrades * 0.4f + pairs; + flat = n(397) + flat; + rate = flat + rate; + if (has(120)) rate = n(120) * 0.7f + 1 + rate; + rate = n(554) * 0.5f + rate; + if (!p.HasWeaponType(WEAPON_BRIMSTONE)) rate = n(222) + rate; + rate = (float)p.g_fuel_count() * 0.5f + rate; + if (p.grantedCollectibleCountdown > 0) rate = rate + 1.5f; + + if (!has(245)) + { + if (has(153) || (has(169) && !p.HasWeaponType(WEAPON_FETUS))) rate *= 0.42f; + else if (has(2)) rate *= 0.51f; + } + if (has(149) && (p.HasWeaponType(WEAPON_TEARS) || p.HasWeaponType(WEAPON_MONSTROS_LUNGS) || + p.HasWeaponType(WEAPON_LASER))) + rate /= 3; + if (has(531)) + { + if (!has(149) && p.HasWeaponType(WEAPON_TEARS)) rate *= 0.5f; + float frames = FIRE_RATE_FRAMES / rate; + float pause = p.HasWeaponType(WEAPON_FETUS) ? 4.0f : 10.0f; + rate = rate - rate * pause / (frames + pause); + float charge = has(118) ? 20.0f : has(52) ? 10.0f : 0.0f; + if (p.HasWeaponType(WEAPON_MONSTROS_LUNGS)) charge *= 0.5f; + rate = rate - charge * rate / (FIRE_RATE_FRAMES / rate + charge); + } + if (p.HasWeaponType(WEAPON_BRIMSTONE)) rate /= 3; + else if (p.HasWeaponType(WEAPON_BOMBS)) rate /= 2.5f; + else if (p.HasWeaponType(WEAPON_BONE)) rate *= 0.5f; + if (has(152)) rate /= 1.5f; + if (has(310)) rate *= 0.66f; + if (p.HasWeaponType(WEAPON_MONSTROS_LUNGS)) rate /= 4.3f; + else if (p.HasWeaponType(WEAPON_TECH_X) && has(229)) rate /= 3.1f; + if (has(561)) rate *= 4; + else if (has(330)) rate *= 5.5f; + if (p.hallowedGroundCountdown != 0) rate *= 2.5f; + if (has(368) && p.epiphoraCharge > 0) rate *= (float)p.epiphoraCharge / 180 + 1; + if (p.peeBurstCooldown > 0) rate = ((float)p.peeBurstCooldown * 5 / (float)p.maxPeeBurstCooldown + 1) * rate; + if (has(695) && !p.temporaryEffects.isDisabled) + { + float lust = std::clamp((float)p.bloodLustCounter, 0.0f, 6.0f); + rate = lust * 0.05f * lust + lust * 0.2f + rate; + } + + p.maxFireDelay = FIRE_RATE_FRAMES / (rate * p.d8FireDelayModifier) - 1; + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_FIREDELAY); + p.maxFireDelay = std::max(p.maxFireDelay, MAX_FIRE_DELAY_MIN); +} + +// The damage section of 00763570: damage ups through the damage curve on 3.5, then the multiplying items. +static void damage_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) +{ + auto n = [&](int id) { return p.GetCollectibleNum(id); }; + auto has = [&](int id) { return p.HasCollectible(id); }; + float damage = 0; + + p.meleeDamage = 0; + for (int id : {7, 90, 216}) + if (has(id)) damage = damage + 1; + if (p.HasPlayerForm(PLAYER_FORM_SPUN)) damage = damage + 2; + if (p.HasPlayerForm(PLAYER_FORM_CONJOINED)) damage = damage - 0.3f; + if (has(109)) damage = (float)p.numCoins * 0.04f + damage; + if (p.redStewBonusDuration > 0 && !p.temporaryEffects.isDisabled) + damage = (float)(p.redStewBonusDuration / 10) * 0.04f + damage; + if (has(716)) damage = (float)((p.keepersSackBonus / 3 + 2) / 3) * 0.5f + damage; + if (p.grantedCollectibleCountdown > 0) damage = damage + 1; + + int ups = n(708) + n(592) + n(572) + n(531) + n(345) + n(328) + n(259) + n(208) + n(206) + n(165) + n(121) + + n(79) + n(70) + n(51) + n(50) + std::max(n(118) - 1, 0); + float sum = (float)ups; + sum = (float)n(732) + sum; + sum = (float)n(730) * 0.75f + sum; + sum = (float)p.g_fuel_count() * 0.75f + sum; + sum = (float)((int)has(261) + n(669) + n(331) + n(307) + n(197) + n(80) + n(4)) * 0.5f + sum; + sum = (float)(n(463) + n(445) + n(201) + n(193) + n(189) + n(138) + n(101) + n(62) + n(12)) * 0.3f + sum; + float mushrooms = (float)n(633); + damage = (float)(n(359) + n(237) + n(230) + n(5)) * 1.5f + sum + mushrooms + mushrooms + damage; + if (has(694)) damage = (float)p.brokenHearts * 0.25f + damage; + if (has(120)) damage = damage * 0.9f - 0.4f; + if (p.coopBabyBuffTimers[COOP_BUFF_DAMAGE] > 0) damage = damage + 2; + + damage = std::sqrt(std::max(damage * DAMAGE_CURVE_SCALE + 1, 0.0f)) * DAMAGE_BASE; + if (has(169)) + damage = !has(2) && !has(153) && !p.HasWeaponType(WEAPON_FETUS) && !has(245) ? damage + 4 + damage + 4 + : damage + 5; + damage = (float)(p.potatoPeelerBandageCounter + p.potatoPeelerCounter) * 0.2f + damage; + damage = std::max((float)p.damageModifier + bonus.damage + damage, DAMAGE_MIN); + if (has(513)) damage = damage + 0.1f; + if (p.HasWeaponType(WEAPON_BONE) && has(114)) damage = damage + 4; + if (has(182)) damage = damage * 2.3f + 1; + if (has(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && has(COLLECTIBLE_PASSIVE_DAMOCLES)) damage = damage * 1.4f + 1; + if (has(573) || p.hallowedGroundCountdown > 0) damage = damage * 1.2f; + if (has(157) && !p.temporaryEffects.isDisabled) + { + float cap = has(COLLECTIBLE_BIRTHRIGHT) && p.playerType == PLAYER_SAMSON ? 10.0f : 6.0f; + float lust = std::clamp((float)p.bloodLustCounter, 0.0f, cap); + damage = lust * 0.1f * lust + lust * 0.4f + damage; + } + + if (has(531)) damage = damage * 1.5f; + float melee = damage; + if (has(149)) + { + bool isTears = p.HasWeaponType(WEAPON_TEARS) || p.HasWeaponType(WEAPON_MONSTROS_LUNGS) || + p.HasWeaponType(WEAPON_FETUS); + damage = damage + (isTears ? 40.0f : 2.0f); + melee = melee + 2; + } + if (has(4) || has(12)) + { + damage = damage * 1.5f; + melee = melee * 1.5f; + } + if (has(310)) + { + damage = damage + damage; + melee = melee + melee; + } + if (has(561) || has(330)) + { + float scale = has(561) ? 0.3f : 0.2f; + damage = damage * scale; + melee = melee * scale; + } + if (has(245)) + { + damage = damage * 0.8f; + melee = melee * 0.8f; + } + if (has(373)) + { + float scale = (float)p.deadEyeCharges * 0.125f + 1; + damage = scale * damage; + melee = scale * melee; + } + else + { + p.deadEyeMisses = 0; + p.deadEyeCharges = 0; + } + if (p.damageMultiplierStacks > 0) + { + float scale = std::pow(1.5f, (float)p.damageMultiplierStacks); + damage = scale * damage; + melee = scale * melee; + } + damage = p.d8DamageModifier * damage; + melee = p.d8DamageModifier * melee; + if (crownScale != 0 && damage > DAMAGE_BASE) + { + damage = (damage - DAMAGE_BASE) * (crownScale - 1) + damage; + melee = (melee - DAMAGE_BASE) * (crownScale - 1) + melee; + } + p.damage = damage; + p.meleeDamage = melee; + + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_DAMAGE); + if (g_game->debugFlags & DEBUG_HIGH_DAMAGE) + { + p.damage = p.damage + DEBUG_DAMAGE_BONUS; + p.meleeDamage = p.meleeDamage + DEBUG_DAMAGE_BONUS; + } + p.damage = std::max(p.damage, DAMAGE_MIN); + p.meleeDamage = std::max(p.meleeDamage, DAMAGE_MIN); +} + +// The shot speed section of 00763570: shot speed ups and downs on 1. +static void shot_speed_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) +{ + auto n = [&](int id) { return p.GetCollectibleNum(id); }; + auto has = [&](int id) { return p.HasCollectible(id); }; + + float pills = (float)(int)(pill_uses(p, PILL_SHOT_SPEED_UP) - pill_uses(p, PILL_SHOT_SPEED_DOWN)); + int occult = std::min(n(572), 1); + int mascara = std::min(n(310), 1); + float ups = (float)(n(176) + n(669) + ((n(183) - occult) - n(342)) + n(397) + n(341) + n(339) + n(194)) * 0.16f; + float drops = (float)(n(564) + n(255) + n(143)) * 0.2f; + float speed = (float)n(165) * 0.23f + 1 + drops + ups + pills * 0.15f; + speed = speed - (float)n(182) * 0.25f; + speed = speed - (float)n(213) * 0.15f; + speed = speed - (float)mascara * 0.5f; + speed = speed - (float)n(336) * 0.4f; + speed = speed - (float)n(331) * 0.3f; + speed = ((float)p.shotSpeedModifier + bonus.shotSpeed) * 0.2f + (float)n(329) * 0.2f + speed; + if (p.coopBabyBuffTimers[COOP_BUFF_RANGE] > 0) speed = speed + 0.5f; + speed = (float)n(554) * 0.2f + speed; + if (has(5)) speed = speed * 1.6f; + if (has(149)) speed = speed * 0.8f; + if (crownScale != 1 && speed - 1 > 0) speed = (crownScale - 1) * (speed - 1) + speed; + p.shotSpeed = speed; + + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_SHOTSPEED); + p.shotSpeed = std::max(p.shotSpeed, SHOT_SPEED_MIN); +} + +// The range section of 00763570: range ups in tiles of 100, the height and fall of the tears, and the range items. +static void range_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) +{ + auto n = [&](int id) { return (float)p.GetCollectibleNum(id); }; + auto has = [&](int id) { return p.HasCollectible(id); }; + + p.tearRange = RANGE_BASE; + p.tearHeight = TEAR_HEIGHT_BASE; + p.tearFallingSpeed = 0; + p.tearFallingAcceleration = 0; + + float pills = pill_uses(p, PILL_RANGE_UP) * 0.5f - pill_uses(p, PILL_RANGE_DOWN) * 0.4f; + float ups = (float)(p.tearRangeModifier + p.GetCollectibleNum(71) + p.GetCollectibleNum(12)) + bonus.range; + ups = n(30) + ups; + ups = n(31) * 1.5f + ups; + ups = n(397) + ups; + ups = n(29) + ups + pills; + for (int id : {339, 345, 14, 370, 189, 455, 355, 659}) ups = n(id) + ups; + ups = (n(669) + ups) * 100; + float tiles = (float)(p.GetCollectibleNum(462) + p.GetCollectibleNum(453) + p.GetCollectibleNum(197) + + p.GetCollectibleNum(121) + p.GetCollectibleNum(110) + p.GetCollectibleNum(101)) * 60 + ups; + tiles = tiles - n(336) * 60; + tiles = n(369) * 120 + tiles; + p.tearRange = n(394) * 120 + tiles + p.tearRange; + + if (has(572)) + { + p.tearHeight = p.tearHeight - 8; + p.tearRange = p.tearRange + 80; + } + if (has(594)) p.tearHeight = p.tearHeight - 8; + if (has(598)) p.tearHeight = p.tearHeight * 0.4f; + if (has(716)) p.tearRange = (float)((p.keepersSackBonus / 3 + 1) / 3) * 10 + p.tearRange; + if (p.coopBabyBuffTimers[COOP_BUFF_RANGE] > 0) p.tearRange = p.tearRange + 80; + if (has(149) || has(531)) + { + if (!has(229)) + { + p.tearFallingAcceleration = 0.8f; + p.tearRange = p.tearRange * 0.8f; + } + } + else if (has(224)) p.tearRange = p.tearRange * 0.8f; + if (has(233)) + { + p.tearRange = p.tearRange + RANGE_BASE; + p.tearFallingAcceleration = p.tearFallingAcceleration * 0.01f; + } + if (has(307) || p.GetZodiacEffect() == 307) p.tearRange = p.tearRange + 30; + if (has(214)) p.tearRange = p.tearRange + 60; + if (has(6)) + { + p.tearHeight = p.tearHeight + 18; + p.tearRange = std::min(p.tearRange, std::max(p.tearRange - 60, 200.0f) * 0.8f); + } + else if (has(440)) p.tearHeight = p.tearHeight + 18; + if (has(5)) p.tearRange = p.tearRange + p.tearRange + 60; + p.tearRange = p.tearRange * p.d8RangeModifier; + if (crownScale != 1 && p.tearRange > RANGE_BASE) + p.tearRange = (p.tearRange - RANGE_BASE) * (crownScale - 1) + p.tearRange; + + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_RANGE); + if (p.tearRange < RANGE_MIN) p.tearRange = RANGE_MIN; + if (p.tearFallingAcceleration > 0) + p.tearFallingAcceleration = p.shotSpeed * p.shotSpeed * p.tearFallingAcceleration; +} + +// The speed section of 00763570: speed ups on 1, and the items that set or cap it. +static void speed_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) +{ + auto n = [&](int id) { return p.GetCollectibleNum(id); }; + auto has = [&](int id) { return p.HasCollectible(id); }; + + float pills = pill_uses(p, PILL_SPEED_UP) * 0.5f - pill_uses(p, PILL_SPEED_DOWN) * 0.4f; + int rollers = p.g_fuel_count() < 1 ? n(143) : 0; + float ups = (float)(n(232) + n(119) + n(28) + n(27)) + pills; + for (int id : {340, 12, 71, 101, 120}) ups = (float)n(id) + ups; + ups = ups + (float)rollers; + ups = (float)n(82) + ups; + ups = (float)n(571) + ups; + float quick = ups * 0.3f; + float steady = (float)n(70) * 0.5f; + steady = (float)n(590) + steady; + steady = steady * 0.4f; + int sharp = std::min(n(14), 1); + int slow = std::min(n(13), 1); + float speed = (float)((((slow - n(90)) - n(129)) - n(121)) + n(669) + n(189) + n(79)) * 0.2f + + (float)sharp * 0.3f + 1 + steady + quick; + p.moveSpeed = ((float)p.speedModifier + bonus.speed) * 0.2f + (float)n(445) * 0.1f + speed; + + if (has(695) && !p.temporaryEffects.isDisabled) + { + float lust = std::clamp((float)p.bloodLustCounter, 0.0f, 6.0f); + p.moveSpeed = lust * 0.02f * lust + lust * 0.05f + p.moveSpeed; + } + if (has(716)) p.moveSpeed = (float)(p.keepersSackBonus / 9) * 0.03f + p.moveSpeed; + if (p.coopBabyBuffTimers[COOP_BUFF_SPEED] > 0) p.moveSpeed = p.moveSpeed + 0.15f; + if (has(230)) p.moveSpeed = p.moveSpeed + 0.2f; + if (p.HasPlayerForm(PLAYER_FORM_SPUN)) p.moveSpeed = p.moveSpeed + 0.15f; + if (p.HasPlayerForm(PLAYER_FORM_LEVIATHAN)) p.moveSpeed = p.moveSpeed + 0.2f; + if (has(130) || has(181)) p.moveSpeed = std::max(p.moveSpeed, 1.5f); + if (has(COLLECTIBLE_TAURUS) || p.GetZodiacEffect() == COLLECTIBLE_TAURUS) p.moveSpeed = p.moveSpeed - 0.3f; + if (has(300) || p.GetZodiacEffect() == 300) p.moveSpeed = p.moveSpeed + 0.25f; + if (has(306) || p.GetZodiacEffect() == 306) p.moveSpeed = p.moveSpeed + 0.2f; + if (has(307) || p.GetZodiacEffect() == 307) p.moveSpeed = p.moveSpeed + 0.1f; + if (has(314)) p.moveSpeed = p.moveSpeed - 0.4f; + p.moveSpeed = p.d8SpeedModifier * p.moveSpeed; + if (crownScale != 1 && p.moveSpeed > 1) p.moveSpeed = (p.moveSpeed - 1) * (crownScale - 1) + p.moveSpeed; + + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_SPEED); +} + +// The luck section of 00763570: luck ups, and Fortune Cookie's wisps. +static void luck_evaluate(Entity_Player& p, const StatBonuses& bonus) +{ + auto n = [&](int id) { return (float)p.GetCollectibleNum(id); }; + + float pills = pill_uses(p, PILL_LUCK_UP) - pill_uses(p, PILL_LUCK_DOWN); + float luck = (float)p.luckModifier + bonus.luck + pills + (float)p.donateLuck + p.edenLuck + n(253); + for (int id : {46, 343, 355, 439}) luck = n(id) + luck; + luck = luck - n(5); + luck = n(669) + luck; + luck = (float)(p.GetCollectibleNum(632) * 2) + luck; + p.luck = n(730) + luck; + + int wisps = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity && entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_ITEM_WISP && + entity->subtype == COLLECTIBLE_FORTUNE_COOKIE && static_cast(entity)->player == &p) + wisps++; + p.luck = (float)wisps * 0.2f + p.luck; + if (p.coopBabyBuffTimers[COOP_BUFF_LUCK] > 0) p.luck = p.luck + 2; + if (p.HasCollectible(492)) p.luck = p.luck + 1; + if (g_game->debugFlags & DEBUG_HIGH_LUCK) p.luck = p.luck + DEBUG_LUCK_BONUS; + + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_LUCK); +} + +// How fast a tear falls to reach its range at its shot speed from its height (0067da40). +static float tear_fall_speed(float height, float range, float shotSpeed, float acceleration) +{ + float flight = range / shotSpeed; + float slope = std::max((std::pow(FALL_SPEED_DECAY, flight) - 1) * FALL_SPEED_SLOPE, FALL_SPEED_MIN_SLOPE); + return ((TEAR_HEIGHT_MAX - height) - (acceleration * FALL_SPEED_RANGE_SCALE + 1) * (flight - slope)) / slope; +} + +// The flag (and a second one, or -1) an item gives tears, the item or (when isEffectToo) its temporary effect. +struct TearFlagGrant +{ + int collectible = 0; + bool isEffectToo = false; + int bit = 0; + int otherBit = -1; +}; + +// The tear flags of single items: Eye of the Occult, Uranus, Terra, Playdough Cookie, Lump of Coal, Technology Zero, +// Proptosis, Polyphemus, Parasite, My Reflection, Tiny Planet, Cricket's Body, Rubber Cement, Strange Attractor, +// Godhead, Continuum, Tractor Beam, Trisagion, Fire Mind, Mysterious Liquid, Dark Matter, Compound Fracture, Eye of +// Belial, Jacob's Ladder, Lachryphagy, Pop!, Flat Stone and Backstabber. +constexpr std::array TEAR_FLAG_GRANTS = {{{572, true, TEAR_OCCULT}, + {596, true, TEAR_ICE_FLAG}, + {592, true, TEAR_ROCK_FLAG}, + {570, false, TEAR_RAINBOW}, + {132, false, TEAR_GROW}, + {524, false, TEAR_LASER}, + {261, true, TEAR_SHRINK}, + {169, false, TEAR_PERSISTENT}, + {104, false, TEAR_SPLIT}, + {5, true, TEAR_BOOMERANG}, + {233, false, TEAR_ORBIT, TEAR_SPECTRAL}, + {224, false, TEAR_QUADSPLIT}, + {221, false, TEAR_BOUNCE}, + {315, false, TEAR_ATTRACTOR}, + {331, false, TEAR_GLOW}, + {369, false, TEAR_CONTINUUM, TEAR_SPECTRAL}, + {397, false, TEAR_TRACTOR_BEAM}, + {533, false, TEAR_LASERSHOT}, + {257, true, TEAR_BURN}, + {317, true, TEAR_MYSTERIOUS_LIQUID_CREEP}, + {259, true, TEAR_DARK_MATTER_FLAG}, + {453, false, TEAR_BONE_FLAG}, + {462, false, TEAR_PIERCING, TEAR_BELIAL_FLAG}, + {494, false, TEAR_JACOBS}, + {532, false, TEAR_ABSORB}, + {529, false, TEAR_POP}, + {540, false, TEAR_HYDROBOUNCE}, + {506, false, TEAR_BACKSTAB}}}; + +// The tear flags of the worm trinkets: Brain, Wiggle, Hook, Pulse, Ring, Flat and Ouroboros Worm. +constexpr std::array WORM_GRANTS = {{{144, false, TEAR_TURN_HORIZONTAL}, + {10, false, TEAR_WIGGLE, TEAR_SPECTRAL}, + {26, false, TEAR_SQUARE, TEAR_SPECTRAL}, + {9, false, TEAR_PULSE}, + {11, false, TEAR_SPIRAL, TEAR_SPECTRAL}, + {12, false, TEAR_FLAT}, + {96, false, TEAR_BIG_SPIRAL, TEAR_SPECTRAL}}}; + +// Whether the player has a collectible, or its temporary effect. +static bool is_having(Entity_Player& p, int collectible) +{ + return p.HasCollectible(collectible) || p.temporaryEffects.HasCollectibleEffect(collectible); +} + +// Whether the player is one of the spirits whose tears and lasers glow and pass through rocks: the Lost and its +// tainted and cursed forms, the Soul, the ghost babies, co-op ghosts, Spirit Shackles' soul, and the nulls doing so. +static bool is_spirit(Entity_Player& p) +{ + TemporaryEffects& effects = p.temporaryEffects; + bool isGhostBaby = p.variant == PLAYER_VARIANT_COOP_BABY && + (p.babySkin == BABY_SKIN_GHOST_B || p.babySkin == BABY_SKIN_GHOST_A); + return p.playerType == PLAYER_THELOST || p.playerType == PLAYER_THELOST_B || p.playerType == PLAYER_JACOB2_B || + p.playerType == PLAYER_THESOUL || isGhostBaby || p.isCoopGhost || + effects.GetCollectibleEffectNum(COLLECTIBLE_SPIRIT_SHACKLES) == 1 || + effects.HasNullEffect(NULLITEM_REVERSE_SUN) || effects.HasNullEffect(NULLITEM_SPIRIT_SHACKLES_SOUL) || + effects.HasNullEffect(NULLITEM_LOST_CURSE); +} + +// The tear flags section of 00763570: the flags of single items and worms, then those several items share. +static void tear_flags_evaluate(Entity_Player& p) +{ + auto has = [&](int id) { return p.HasCollectible(id); }; + auto add = [&](std::initializer_list bits) + { + for (int bit : bits) + if (bit >= 0) p.tearFlags.set(bit); + }; + TemporaryEffects& effects = p.temporaryEffects; + bool isLudovico = p.HasWeaponType(WEAPON_LUDOVICO_TECHNIQUE); + + p.tearFlags.reset(); + for (const TearFlagGrant& grant : TEAR_FLAG_GRANTS) + if (grant.isEffectToo ? is_having(p, grant.collectible) : has(grant.collectible)) add({grant.bit, grant.otherBit}); + for (const TearFlagGrant& grant : WORM_GRANTS) + if (p.HasTrinket(grant.collectible)) add({grant.bit, grant.otherBit}); + + bool isHoming = has(182) || is_having(p, 3) || effects.HasCollectibleEffect(192) || has(331) || + (p.variant == PLAYER_VARIANT_COOP_BABY && p.babySkin == BABY_SKIN_SPOON) || + p.hallowedGroundCountdown > 0; + bool isSpectral = has(185) || is_having(p, 115) || has(159) || isLudovico || has(336) || has(379) || + is_having(p, 358) || is_spirit(p); + bool isPiercing = has(48) || is_having(p, 237) || has(306) || p.GetZodiacEffect() == 306 || isLudovico || has(336); + bool isWaiting = has(222) && !isLudovico && !p.HasWeaponType(WEAPON_MONSTROS_LUNGS) && + (!p.HasWeaponType(WEAPON_TEARS) || (!has(316) && !has(69))); + bool isKnockback = has(309) || p.GetZodiacEffect() == 309 || has(359) || p.HasTrinket(77) || has(592); + if (isHoming) add({TEAR_HOMING}); + if (isSpectral) add({TEAR_SPECTRAL}); + if (isPiercing) add({TEAR_PIERCING}); + if (has(305) || p.GetZodiacEffect() == 305) add({TEAR_POISON}); + if (has(149) && (!isLudovico || has(540))) add({TEAR_EXPLOSIVE, TEAR_POISON}); + if (isWaiting) add({TEAR_WAIT}); + if (isKnockback) add({TEAR_KNOCKBACK}); + if (has(213) || effects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN)) add({TEAR_SHIELDED}); + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_TEARFLAG); +} + +// A colour with only its tint, colorize and offset set. +static constexpr ColorMod color_make(std::array tint, std::array colorize = {}, + std::array offset = {}) +{ + return {{tint[0], tint[1], tint[2], tint[3]}, + {colorize[0], colorize[1], colorize[2], colorize[3]}, + {offset[0], offset[1], offset[2]}}; +} + +// A colorized white colour, offset alike on every channel. +static constexpr ColorMod colorized(float r, float g, float b, float offset = 0) +{ + return color_make({1, 1, 1, 1}, {r, g, b, 1}, {offset, offset, offset}); +} + +// An offset given in 0 to 255 steps (00683010). +static constexpr std::array offset_255(int r, int g, int b) +{ + return {(float)r * COLOR_OFFSET_UNIT, (float)g * COLOR_OFFSET_UNIT, (float)b * COLOR_OFFSET_UNIT}; +} + +// The first colour whose condition holds, or the default. +static ColorMod color_pick(std::initializer_list> choices) +{ + for (const auto& [isMatch, color] : choices) + if (isMatch) return color; + return COLOR_DEFAULT; +} + +// Whether two colours match on every channel (00753560). +static bool color_equals(const ColorMod& a, const ColorMod& b) +{ + return std::ranges::equal(a._tint, b._tint) && std::ranges::equal(a._colorize, b._colorize) && + std::ranges::equal(a._offset, b._offset); +} + +// The laser colour part of 00763570: the first item in a fixed order picks it. +static ColorMod laser_color_get(Entity_Player& p) +{ + auto has = [&](int id) { return p.HasCollectible(id); }; + bool isSpoon = is_having(p, 3) || p.temporaryEffects.HasCollectibleEffect(192) || + (p.variant == PLAYER_VARIANT_COOP_BABY && p.babySkin == BABY_SKIN_SPOON); + bool isPoison = has(103) || has(317) || has(305) || p.GetZodiacEffect() == 305 || has(459); + + return color_pick({{is_having(p, 429), colorized(6, 4, 1)}, + {has(149), colorized(1.8f, 3, 1)}, + {has(182) || p.hallowedGroundCountdown > 0, colorized(5, 6, 6)}, + {has(596), colorized(4, 4.4f, 6, 0.1f)}, + {is_having(p, 572), colorized(3, 0.5f, 3)}, + {has(257), colorized(5, 3, 1)}, + {isPoison, colorized(1.8f, 4, 1)}, + {has(104), colorized(3, 1.5f, 0.4f)}, + {has(89), colorized(5.2f, 5.2f, 5)}, + {is_having(p, 315) || has(401) || has(617), colorized(1, 1, 1)}, + {has(618), colorized(5, 1, 0)}, + {has(553), colorized(2, 2, 4)}, + {has(494), colorized(3.8f, 4.9f, 6, 0.1f)}, + {is_having(p, 6), colorized(5, 4.9f, 1)}, + {isSpoon, colorized(3, 1, 3.5f)}, + {has(200), colorized(4, 1, 3.5f)}, + {is_having(p, 398), colorized(1.2f, 1.2f, 4)}, + {has(69), colorized(3, 1.7f, 1.7f)}, + {has(561), colorized(5.6f, 5.2f, 3.8f)}, + {has(330), colorized(5.6f, 5, 4.2f)}, + {has(132), color_make({3, 3, 3, 1}, {1.3f, 1.2f, 1.2f, 1}, {-0.5f, -0.5f, -0.5f})}, + {has(259), color_make({3, 3, 3, 1}, {1, 1, 1, 1}, {-0.5f, -0.5f, -0.5f})}, + {p.playerType == PLAYER_BLUEBABY_B, color_make({2, 2, 2, 1}, {0.7f, 0.3f, 0.1f, 1})}}); +} + +// The tear colour part of 00763570: the first item in a fixed order picks it. +static ColorMod tear_color_get(Entity_Player& p) +{ + auto has = [&](int id) { return p.HasCollectible(id); }; + bool isSpoon = is_having(p, 3) || p.temporaryEffects.HasCollectibleEffect(192) || + (p.variant == PLAYER_VARIANT_COOP_BABY && p.babySkin == BABY_SKIN_SPOON); + + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (the deathmatch's tear colour)"); + return color_pick( + {{is_having(p, 317), color_make({1, 1, 1, 1}, {0.2f, 1, 0.2f, 1}, {0, 0.2f, 0})}, + {is_having(p, 257), color_make({1, 1, 1, 1}, {1.8f, 0.9f, 0.3f, 1}, {0.3f, 0, 0})}, + {is_having(p, 259), colorized(0.3f, 0.3f, 0.3f)}, + {has(149) && !p.HasWeaponType(WEAPON_BOMBS), color_make({0.5f, 0.9f, 0.4f, 1})}, + {has(182) || p.hallowedGroundCountdown > 0, color_make({1.5f, 2, 2, 1})}, + {is_having(p, 572), colorized(0.3f, 0, 0.25f)}, + {has(132), color_make({0.2f, 0.09f, 0.065f, 1})}, + {has(104), color_make({0.9f, 0.3f, 0.08f, 1})}, + {has(69), color_make({0.33f, 0.18f, 0.18f, 1}, {}, offset_255(66, 40, 40))}, + {is_having(p, 6), color_make({1, 1, 0, 1}, {}, offset_255(45, 15, 0))}, + {isSpoon, color_make({0.4f, 0.15f, 0.38f, 1}, {}, offset_255(71, 0, 116))}, + {has(310), color_make({0.2f, 0.2f, 0.2f, 1})}, + {has(221), color_make({1, 1, 0.8f, 1}, {}, {0.1f, 0.1f, 0.1f})}, + {has(336), color_make({0.5f, 0.25f, 0.1f, 0.9f})}, + {has(561), color_make({1.8f, 1.7f, 1, 1})}, + {has(330), color_make({1.5f, 2, 2, 1})}, + {is_having(p, 398) && p.HasWeaponType(WEAPON_KNIFE), color_make({0.5f, 0.5f, 1, 1})}, + {p.HasWeaponType(WEAPON_BONE) && has(COLLECTIBLE_HAEMOLACRIA), color_make({0.92f, 0.05f, 0.03f, 1})}, + {p.playerType == PLAYER_BLUEBABY_B && !has(COLLECTIBLE_C_SECTION), + color_make({1.5f, 1.5f, 1.5f, 1}, {0.7f, 0.6f, 0.5f, 1}, {-0.4f, -0.45f, -0.4f})}}); +} + +// The tear colour section of 00763570: the laser and tear colours, both glowing for spirits and faded for holograms. +static void tear_color_evaluate(Entity_Player& p) +{ + constexpr ColorMod SPIRIT_GLOW = color_make({1.5f, 2, 2, 0.5f}); + + p.laserColor = laser_color_get(p); + p.tearColor = tear_color_get(p); + if (is_having(p, 115) || p.HasCollectible(159) || p.HasCollectible(185) || is_spirit(p)) + { + color_multiply(p.tearColor, SPIRIT_GLOW); + color_multiply(p.laserColor, SPIRIT_GLOW); + } + if (p.IsHologram()) + { + p.tearColor._tint[3] = HOLOGRAM_ALPHA; + p.laserColor._tint[3] = HOLOGRAM_ALPHA; + } + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_TEARCOLOR); +} + +// Whether the player flies: the flying items and transformations, the flying characters, effects and nulls. +static bool is_flying(Entity_Player& p) +{ + TemporaryEffects& effects = p.temporaryEffects; + int wings = effects.GetCollectibleEffectNum(20); + for (int id : {185, 184, 181, 179, 159, 130, 82, 20}) wings += p.GetCollectibleNum(id); + if (wings >= 1 || p.HasPlayerForm(0) || p.HasPlayerForm(1) || p.HasPlayerForm(8)) return true; + + bool isFlyingType = p.variant == PLAYER_VARIANT_COOP_BABY || p.playerType == PLAYER_THELOST || + p.playerType == PLAYER_THELOST_B || p.playerType == PLAYER_JACOB2_B || + p.playerType == PLAYER_THESOUL_B || p.playerType == PLAYER_AZAZEL || + p.playerType == PLAYER_THESOUL; + return isFlyingType || p.HasPlayerForm(3) || effects.HasCollectibleEffect(33) || effects.HasCollectibleEffect(20) || + effects.HasCollectibleEffect(409) || effects.HasTrinketEffect(118) || p.HasPlayerForm(14) || + effects.GetCollectibleEffectNum(COLLECTIBLE_SPIRIT_SHACKLES) == 1 || + effects.HasNullEffect(NULLITEM_REVERSE_SUN) || effects.HasNullEffect(NULLITEM_REVERSE_DEVIL) || + effects.HasNullEffect(NULLITEM_ESAU_JR) || effects.HasNullEffect(NULLITEM_SPIRIT_SHACKLES_SOUL) || + effects.HasNullEffect(NULLITEM_LOST_CURSE) || effects.HasTrinketEffect(TRINKET_AZAZELS_STUMP) || + (effects.HasCollectibleEffect(714) && p.playerType == PLAYER_THEFORGOTTEN_B) || p.HasCollectible(643) || + p.HasCollectible(633); +} + +// The flying section of 00763570: flight and the grid collision it gives. Losing flight asks whether the player can +// walk back to the entrance (the original keeps it flying by a Transcendence effect if not), which stops the game. +static void flying_evaluate(Entity_Player& p) +{ + bool wasFlying = p.canFly; + + p.canFly = is_flying(p); + p.entityGridCollisionClass = p.canFly ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + if (wasFlying && !p.canFly) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Room::is_reachable_from_player 00823be0)"); + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_FLYING); + p.entityGridCollisionClass = p.canFly ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + if (p.canFly != wasFlying) p.UpdateCostumes(); +} + +// The scale a size step gives: doubling each step up to two, then growing in a line. +static float size_scale(float steps) +{ + return steps < SIZE_SCALE_KNEE ? std::pow(SIZE_SCALE_KNEE, steps) + : (steps - SIZE_SCALE_KNEE) * SIZE_SCALE_SLOPE + SIZE_SCALE_AT_KNEE; +} + +// The size section of 00763570: the sprite and head grow or shrink by the size items, pills and co-op buffs. +static void size_evaluate(Entity_Player& p) +{ + auto n = [&](int id) { return p.GetCollectibleNum(id); }; + auto effect = [&](int id) { return p.temporaryEffects.GetCollectibleEffectNum(id); }; + Game& game = *g_game; + bool isMistOrGhost = p.hasCurseMistEffect || p.isCoopGhost; + + int pills = isMistOrGhost ? 0 : (int)pill_uses(p, PILL_LARGER) - (int)pill_uses(p, PILL_SMALLER); + int steps = (int)(p.coopBabyBuffTimers[COOP_BUFF_LARGER] > 0) - (int)(p.coopBabyBuffTimers[COOP_BUFF_SMALLER] > 0) + + pills - n(71) - effect(71); + float body = (float)(n(12) + (steps - n(438)) + effect(12)) * SIZE_STEP + 0; + body = (float)n(302) * 0.263f + body; + body = body - (float)n(340) * 0.152f; + body = (float)p.temporaryEffects.GetNullEffectNum(NULLITEM_HUGE_GROWTH) * 0.678f + body; + body = body - (float)(n(598) + effect(688)); + float head = (float)(effect(121) + ((n(121) - n(120)) - effect(120))) * 0.152f + 0; + if (game.seedEffects.HasSeedEffect(SEED_BIG_HEAD)) head = head + BIG_HEAD_BONUS; + if (game.seedEffects.HasSeedEffect(SEED_SMALL_HEAD)) head = head - 1; + if (game.dailyChallenge._id == DAILY_BIG_SIZE) body = body + DAILY_BIG_SIZE_BONUS; + + float bodyScale = size_scale(body); + float headScale = size_scale(head); + p.playerSpriteScale = vector_make(bodyScale, bodyScale); + p.headScale = vector_make(headScale, headScale); + p.bodyScale = vector_make(1, 1); + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_SIZE); + if (std::min(p.playerSpriteScale.x, p.playerSpriteScale.y) >= SPRITE_SCALE_UNLOCK) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_HUGE); +} + +// The color section of 00763570: the character's and items' tints over the colour override, then a red flush with +// Taurus, Lusty Blood, Bloody Lust and Tainted Samson's berserk charge. A sprite showing the entity's colour follows. +static void color_evaluate(Entity_Player& p) +{ + constexpr ColorMod SOUL_TINT = color_make({1.5f, 1.7f, 2, 1}, {}, {0.05f, 0.12f, 0.2f}); + constexpr ColorMod ANTI_GRAVITY_TINT = color_make({1.4f, 2, 1.8f, 1}); + constexpr ColorMod SPOOKY_TINT = color_make({1, 1, 1, 1}, {}, {0, -0.5f, -0.5f}); + constexpr ColorMod TOXIC_TINT = color_make({1, 1, 1, 1}, {}, {0, 0.2f, 0}); + constexpr ColorMod FLUSH_RED = color_make({1, 0, 0, 1}); + TemporaryEffects& effects = p.temporaryEffects; + bool isSynced = color_equals(p.sprite.color, p.color); + + ColorMod base = COLOR_DEFAULT; + if (p.playerType == PLAYER_THESOUL || effects.HasNullEffect(NULLITEM_SPIRIT_SHACKLES_SOUL) || + p.playerType == PLAYER_THESOUL_B) + color_multiply(base, SOUL_TINT); + else if (p.HasCollectible(COLLECTIBLE_ANTI_GRAVITY)) color_multiply(base, ANTI_GRAVITY_TINT); + if (p.HasCollectible(COLLECTIBLE_2SPOOKY)) color_multiply(base, SPOOKY_TINT); + + p.color = base; + color_multiply(p.color, p.colorOverride); + if (p.HasCollectible(COLLECTIBLE_VIRUS)) std::ranges::copy(std::array{1.25f, 1.25f, 1.25f, 0.25f}, p.color._colorize); + if (p.HasCollectible(COLLECTIBLE_TOXIC_SHOCK)) + { + std::ranges::copy(std::array{0.0f, 1.0f, 0.0f, 0.5f}, p.color._colorize); + color_multiply(p.color, TOXIC_TINT); + } + + float flush = 0; + if (TemporaryEffect* taurus = effects.GetCollectibleEffect(COLLECTIBLE_TAURUS); taurus && taurus->cooldown == 0) + flush = std::max(flush, p.taurusSpeedBonus * 0.5f); + int lustyBlood = effects.GetCollectibleEffectNum(COLLECTIBLE_LUSTY_BLOOD); + if (p.bloodLustCounter > 0 || lustyBlood > 0) + flush = std::max(flush, (float)std::min(std::max((int)p.bloodLustCounter, lustyBlood), BLOOD_LUST_COLOR_CAP) * + BLOOD_LUST_COLOR_STEP); + if (p.playerType == PLAYER_SAMSON_B) + flush = std::max(flush, std::clamp((float)p.samsonBerserkCharge / BERSERK_CHARGE_FULL, 0.0f, 1.0f)); + if (flush > 0) + { + ColorMod red = base; + color_multiply(red, FLUSH_RED); + p.color = color_lerp(p.color, red, flush); + } + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_COLOR); + if (isSynced) p.ResetColor(); +} + +// The familiars section of 00763570, not written yet: it stops the game when an owned item, effect or trinket asks +// for familiars, and otherwise only hands the section to the mods. +static void familiars_check(Entity_Player& p) +{ + bool isAsked = is_cache_owned(p, CACHE_FAMILIARS) || !p.temporaryEffects.effects.empty() || + std::ranges::any_of(p.trinkets, [](uint32_t trinket) { return trinket != 0; }) || + p.numLeprosy > 0 || p.tonsilCount > 0 || p.potatoPeelerCounter > 0 || + p.potatoPeelerBandageCounter > 0 || p.HasPlayerForm(PLAYER_FORM_SPIDER_BABY); + if (isAsked) reconstruction_missing("Entity_Player::EvaluateItems 00763570 (familiars)"); + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_FAMILIARS); +} + +// The weapon the player's items and character give, before the pairs that cancel out. +static WeaponType weapon_type_get(Entity_Player& p) +{ + auto has = [&](int id) { return p.HasCollectible(id); }; + TemporaryEffects& effects = p.temporaryEffects; + bool isLung = has(COLLECTIBLE_MONSTROS_LUNG); + bool isAzazel = p.playerType == PLAYER_AZAZEL || effects.HasTrinketEffect(TRINKET_AZAZELS_STUMP) || + p.playerType == PLAYER_AZAZEL_B; + bool isBone = p.playerType == PLAYER_THEFORGOTTEN || p.playerType == PLAYER_THEFORGOTTEN_B || + (p.variant == PLAYER_VARIANT_COOP_BABY && p.babySkin == BABY_SKIN_BONE) || + effects.HasCollectibleEffect(COLLECTIBLE_BERSERK); + + if (isBone) return WEAPON_BONE; + if (effects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) return WEAPON_TEARS; + if (effects.HasNullEffect(NULLITEM_BLOODY_BABYLON)) return WEAPON_KNIFE; + if (has(COLLECTIBLE_SPIRIT_SWORD)) return has(COLLECTIBLE_C_SECTION) ? WEAPON_FETUS : WEAPON_SPIRIT_SWORD; + if (has(COLLECTIBLE_EPIC_FETUS)) return WEAPON_ROCKETS; + if (has(COLLECTIBLE_C_SECTION)) return WEAPON_FETUS; + if (has(COLLECTIBLE_MOMS_KNIFE)) return WEAPON_KNIFE; + if (has(COLLECTIBLE_HAEMOLACRIA)) return isLung ? WEAPON_MONSTROS_LUNGS : WEAPON_TEARS; + if (has(COLLECTIBLE_DR_FETUS)) return isLung ? WEAPON_MONSTROS_LUNGS : WEAPON_BOMBS; + if ((has(COLLECTIBLE_BRIMSTONE) || isAzazel) && !has(COLLECTIBLE_TECH_X)) return WEAPON_BRIMSTONE; + if (has(COLLECTIBLE_TECH_X)) return WEAPON_TECH_X; + if (has(COLLECTIBLE_TECHNOLOGY)) return WEAPON_LASER; + if (has(COLLECTIBLE_LUDOVICO)) return WEAPON_LUDOVICO_TECHNIQUE; + return isLung ? WEAPON_MONSTROS_LUNGS : WEAPON_TEARS; +} + +// The weapon section of 00763570: the weapon types the items give, and new weapons when they changed (dropping what +// the player holds up first), which asks for the damage again. +static void weapons_evaluate(Entity_Player& p) +{ + std::array previous = p.weaponTypes; + bool isAzazel = p.playerType == PLAYER_AZAZEL || p.temporaryEffects.HasTrinketEffect(TRINKET_AZAZELS_STUMP) || + p.playerType == PLAYER_AZAZEL_B; + bool isBrimstoneKept = (p.HasCollectible(COLLECTIBLE_BRIMSTONE) || isAzazel) && !p.HasCollectible(COLLECTIBLE_TECH_X); + + p.weaponTypes.fill(false); + p.EnableWeaponType(weapon_type_get(p), true); + if (p.HasWeaponType(WEAPON_BRIMSTONE) && p.HasWeaponType(WEAPON_KNIFE)) p.EnableWeaponType(WEAPON_BRIMSTONE, false); + if (p.HasWeaponType(WEAPON_FETUS) && isBrimstoneKept) + { + p.EnableWeaponType(WEAPON_FETUS, false); + p.EnableWeaponType(WEAPON_BRIMSTONE, true); + } + if (p.HasWeaponType(WEAPON_MONSTROS_LUNGS) && p.HasWeaponType(WEAPON_BOMBS)) p.EnableWeaponType(WEAPON_BOMBS, false); + if (p.HasWeaponType(WEAPON_BRIMSTONE) && p.HasWeaponType(WEAPON_LASER)) p.EnableWeaponType(WEAPON_LASER, false); + static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_WEAPON); + if (p.weaponTypes == previous) return; + + bool isHeldThrowable = p.itemState != COLLECTIBLE_MOMS_BRACELET && p.itemState != COLLECTIBLE_SUPLEX; + if (p.heldEntity && isHeldThrowable) + { + if (p.heldEntity->IsEnemy()) + p.ThrowHeldEntity(vector_make(p.velocity.x * HELD_THROW_SCALE, p.velocity.y * HELD_THROW_SCALE)); + else p.heldEntity->Remove(); + } + for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) p.weapons[slot].reset(); + int slot = 1; + for (int type = 0; type < WEAPON_TYPE_COUNT && slot < WEAPON_SLOT_COUNT; type++) + if (p.weaponTypes[type]) p.weapons[slot++] = weapon_create((WeaponType)type, &p); + p.cacheFlags |= CACHE_DAMAGE; +} + +// 00763570 Recomputes what the cache flags ask for: the weapons, then fire delay, damage, shot speed, range, speed and +// luck from the items, pills, modifiers and Binge Eater's foods, then the tear flags and colours, flight, size and +// colour, each section handed to the mods. Then it clamps the stats and works out how fast tears fall. A shot speed +// change redoes the range. Familiars, other characters, effects, trinkets and run modifiers stop the game when they +// have work to do. +void Entity_Player::EvaluateItems() +{ + if (!is_character_plain() || is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS)) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (characters, effects, trinkets or special items)"); + + StatBonuses bonus = stat_bonuses_get(*this); + float crownScale = (float)GetTrinketMultiplier(TRINKET_CRACKED_CROWN) * 0.2f + 1; + if (cacheFlags & CACHE_WEAPON) weapons_evaluate(*this); + if (cacheFlags & CACHE_SHOTSPEED) cacheFlags |= CACHE_RANGE; + if (cacheFlags & CACHE_FIREDELAY) fire_delay_evaluate(*this, bonus, crownScale); + if (cacheFlags & CACHE_DAMAGE) damage_evaluate(*this, bonus, crownScale); + if (cacheFlags & CACHE_SHOTSPEED) shot_speed_evaluate(*this, bonus, crownScale); + if (cacheFlags & CACHE_RANGE) range_evaluate(*this, bonus, crownScale); + if (cacheFlags & CACHE_SPEED) speed_evaluate(*this, bonus, crownScale); + if (cacheFlags & CACHE_TEARFLAG) tear_flags_evaluate(*this); + if (cacheFlags & CACHE_TEARCOLOR) tear_color_evaluate(*this); + if (cacheFlags & CACHE_FLYING) flying_evaluate(*this); + if ((cacheFlags & CACHE_FAMILIARS) && variant == PLAYER_VARIANT_PLAYER && isValid) familiars_check(*this); + if (cacheFlags & CACHE_LUCK) luck_evaluate(*this, bonus); + if ((cacheFlags & CACHE_SIZE) && variant == PLAYER_VARIANT_PLAYER) size_evaluate(*this); + if (cacheFlags & CACHE_COLOR) color_evaluate(*this); + + if ((cacheFlags & CACHE_SPEED) && std::ranges::any_of(g_game->playerManager.playerList, + [this](Entity_Player* other) { return other->parent == this; })) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (the speed of a player's helpers)"); + if (cacheFlags & CACHE_PICKUP_VISION) g_game->room->isPickupVisionInvalid = true; + if (cacheFlags & CACHE_SPEED) moveSpeed = std::max(SPEED_MIN, std::min(SPEED_MAX, moveSpeed)); + shotSpeed = std::max(shotSpeed, SHOT_SPEED_MIN); + if (tearHeight > TEAR_HEIGHT_MAX) tearHeight = TEAR_HEIGHT_MAX; + tearRange = std::max(tearRange, RANGE_MIN); + damage = std::max(damage, DAMAGE_MIN); + maxFireDelay = std::max(maxFireDelay, MAX_FIRE_DELAY_MIN); + if (cacheFlags & (CACHE_SHOTSPEED | CACHE_RANGE)) + tearFallingSpeed = -tear_fall_speed(tearHeight, tearRange, shotSpeed * FALL_SPEED_RANGE_SCALE, + tearFallingAcceleration); + if ((cacheFlags & CACHE_SPEED) && g_fuel_count() > 0) moveSpeed = (float)g_fuel_count() * G_FUEL_SPEED + moveSpeed; + cacheFlags = 0; +} + +// The collectibles the frame (00782af0) and the tear parameters (007bf6c0) look at themselves, which their plain +// paths do not cover yet. +constexpr std::array FRAME_ITEMS = {375, 397, 465, 493, 497, 534, 575, 593, 619, 632, 641, 59, 202, 210, 399}; +constexpr std::array TEAR_HIT_ITEMS = { + 7, 48, 52, 59, 68, 69, 80, 89, 90, 103, 110, 118, 138, 150, 154, 155, 183, 200, 201, 213, 228, 229, 230, 231, + 237, 247, 254, 259, 261, 305, 306, 309, 315, 316, 330, 336, 359, 374, 379, 393, 395, 398, 399, 401, 418, 429, + 440, 443, 444, 453, 459, 460, 461, 462, 463, 496, 503, 529, 531, 532, 553, 561, 570, 592, 596, 606, 617, 618, + 637, 659, 708, 731}; + +// Whether the player's frame runs its plain path: a plain character holding none of the items the frame handles. +bool Entity_Player::is_frame_plain() +{ + return is_character_plain() && !is_owning_any(*this, FRAME_ITEMS) && !is_owning_any(*this, WEAPON_ITEMS) && + !is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS); +} + +// Whether the player's tears take their plain parameters: a plain character holding none of the tear items. +bool Entity_Player::is_tear_hit_plain() +{ + return is_frame_plain() && !is_owning_any(*this, TEAR_HIT_ITEMS); +} diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index e7bd250..793b1ae 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -373,11 +373,33 @@ bool Entity_Player::walking_items_has() return false; } +// Holds the lifted item where the body's held null is, shown while that null shows. Whether the item is lifted. +static bool held_item_pose_update(Entity_Player& player) +{ + const NullFrame* held = player.bodySprite.GetNullFrameById(0); + if (!held) return false; + + for (LayerState& layer : player.heldSprite.layerStates) + { + layer.pos = vector_make(held->pos.x * player.sprite.scale.x, held->pos.y * player.sprite.scale.y); + layer.isVisible = held->isVisible; + } + return held->isVisible; +} + // Plays the walk animation the body moves in, or stands still on the idle frame, at a speed following the velocity. +// While an item is lifted the arms stay up (the PickupWalk animations) with the item over the head. The queued item +// is added once the lift ends, or on the room's first frame, or as soon as an extra animation ends. +// This is a part of 00782af0. void Entity_Player::walk_animation_update() { - if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || (!IsExtraAnimationFinished() && !IsHoldingItem())) return; - if (queuedItem.item) FlushQueueItem(); + bool isHolding = IsHoldingItem(); + bool isLifted = isHolding && held_item_pose_update(*this); + bool isFlushDue = isHolding ? (isHeldItemVisible && !isLifted) || g_game->room->GetFrameCount() == 0 + : IsExtraAnimationFinished(); + isHeldItemVisible = IsHeldItemVisible(); + if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || (!IsExtraAnimationFinished() && !isHolding)) return; + if (isFlushDue) FlushQueueItem(); Vector direction = GetBodyMoveDirection(); bool isPlayer = variant == PLAYER_VARIANT_PLAYER && !isCoopGhost; @@ -385,14 +407,17 @@ void Entity_Player::walk_animation_update() { bool isVertical = std::fabs(direction.x) <= std::fabs(direction.y); float axis = isVertical ? direction.y : direction.x; - std::string_view animation = - isVertical ? (axis > 0 ? "WalkDown" : "WalkUp") : (axis > 0 ? "WalkRight" : "WalkLeft"); + std::string_view animation = isLifted ? (isVertical ? (axis > 0 ? "PickupWalkDown" : "PickupWalkUp") + : (axis > 0 ? "PickupWalkRight" : "PickupWalkLeft")) + : (isVertical ? (axis > 0 ? "WalkDown" : "WalkUp") + : (axis > 0 ? "WalkRight" : "WalkLeft")); if (isPlayer) sprite.Play(animation); } else if (isPlayer) { - if (!canFly || playerType == PLAYER_THEFORGOTTEN_B) sprite.SetFrame("WalkDown", 0); - else sprite.Play("WalkDown"); + std::string_view idle = isLifted ? "PickupWalkDown" : "WalkDown"; + if (!canFly || playerType == PLAYER_THEFORGOTTEN_B) sprite.SetFrame(idle, 0); + else sprite.Play(idle); } float speed = 1; @@ -515,7 +540,7 @@ void Entity_Player::update_shooting() if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_BUTTER_BEAN) reconstruction_missing("Entity_Player::update_shooting 0077b020 (the Butter Bean daily)"); - if (game.stageTransition._state == 0 && isInputAllowed && fireBlockCooldown < 1) + if (game.stageTransition.state == 0 && isInputAllowed && fireBlockCooldown < 1) shootHeldFrames = isShootHeld ? shootHeldFrames + 1 : 0; if (megaBlastDuration > 0 || azazelsRageLaser) canFire = false; canFire = canFire && fireBlockCooldown < 1; @@ -543,7 +568,7 @@ void Entity_Player::update_shooting() for (int item : SHOOTING_ITEMS) if (HasCollectible(item)) reconstruction_missing("Entity_Player::update_shooting 0077b020 (shooting items)"); - bool isFireReady = IsExtraAnimationFinished() && game.stageTransition._state == 0 && isInputAllowed; + bool isFireReady = IsExtraAnimationFinished() && game.stageTransition.state == 0 && isInputAllowed; if (isFireReady && playerType == PLAYER_EVE_B && !isInterpolation) reconstruction_missing("Entity_Player::update_shooting 0077b020 (Tainted Eve's clots)"); @@ -633,9 +658,9 @@ void Entity_Player::Update() if (isDead) return death_update(); if (!is_frame_plain() || heldEntity) reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and item animations)"); - for (ButtonAction action : {ACTION_BOMB, ACTION_ITEM, ACTION_PILL_CARD, ACTION_DROP}) + for (ButtonAction action : {ACTION_PILL_CARD, ACTION_DROP}) if (isControlsEnabled && action_value(action, controllerIndex) > 0) - reconstruction_missing("Entity_Player::Update 00782af0 (bombs, items, pockets and drop)"); + reconstruction_missing("Entity_Player::Update 00782af0 (items, pockets and drop)"); Entity::Update(); if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) @@ -648,9 +673,14 @@ void Entity_Player::Update() reconstruction_missing("Entity_Player::Update 00782af0 (body costumes following the walk)"); } update_body_animations(); + update_bomb_input(); + ControlActiveItem(ACTIVE_SLOT_PRIMARY); update_shooting(); walk_animation_update(); if (damageCooldown > 0) damageCooldown--; + if (controlsCooldown > 0) controlsCooldown--; + if (fireBlockCooldown > 0) fireBlockCooldown--; + if (itemHoldCooldown > 0) itemHoldCooldown--; } // 0078ca00 Draws the player at its place, lifted by its flight and its offset: blinking while hurt, the held entity diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 81f6454..15d9bc4 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -1,8 +1,11 @@ #include "entity_player.h" #include "entity_familiar.h" +#include "entity_pickup.h" +#include "stage_transition.h" #include "game.h" #include "lua_engine.h" #include "room.h" +#include "room_grid.h" #include "log.h" #include "manager.h" #include "platform.h" @@ -11,6 +14,7 @@ #include constexpr int ROOM_TRINKET_ROLL_SHIFT = 13; +constexpr float PICKUP_SPAWN_STEP = 40; constexpr int RAINBOW_WORM_FRAMES = 90; constexpr uint32_t DAILY_RAINBOW_TRINKETS = 28; constexpr int ERROR_TRINKET_RANGE = 189; @@ -549,20 +553,18 @@ void Entity_Player::TriggerNewRoom_TemporaryEffects() constexpr int COLLECTIBLE_BINGE_EATER = 664; constexpr int COLLECTIBLE_PASSIVE_DAMOCLES = 656; constexpr int COLLECTIBLE_BOOK_OF_BELIAL_ACTIVE = 34; -constexpr int COLLECTIBLE_MORE_OPTIONS = 254; -constexpr int COLLECTIBLE_DADS_KEY = 221; +constexpr int COLLECTIBLE_BLOOD_CLOT = 254; +constexpr int COLLECTIBLE_RUBBER_CEMENT = 221; constexpr int COLLECTIBLE_COUNT_UNLOCK = 50; constexpr int ACHIEVEMENT_MANY_COLLECTIBLES = 330; constexpr int ACHIEVEMENT_TEARS_UP_ITEMS = 378; constexpr int TEARS_UP_UNLOCK_COUNT = 10; -constexpr int EVENT_MORE_OPTIONS = 200; -constexpr int EVENT_DADS_KEY = 201; +constexpr int EVENT_BLOOD_CLOT = 200; +constexpr int EVENT_RUBBER_CEMENT = 201; constexpr int PILL_TEARS_UP = 16; constexpr int BINGE_EATER_STEW_FRAMES = 900; constexpr int T_BETHANY_HEART_CAP = 12; constexpr int HISTORY_POOL_NONE = -1; -constexpr int STAGE_TRANSITION_OUT = 3; -constexpr int STAGE_TRANSITION_DONE = 4; // An unlock earned by holding more than a number of items of a tag (Dead, Syringe, Mom, Tech, Battery, Stars). struct TagUnlock @@ -579,13 +581,38 @@ constexpr std::array TAG_UNLOCKS = {{{TAG_DEAD, 1, 31}, {TAG_BATTERY, 1, 367}}}; constexpr TagUnlock STARS_UNLOCK = {TAG_STARS, 2, 406}; -// The collectibles whose pickup does something of its own in 0075f0e0 (maps, spawns, health, transformations, pools, -// rerolls and the like), which is not reconstructed yet. -constexpr std::array PICKUP_EFFECT_ITEMS = { - 12, 21, 29, 31, 35, 54, 72, 75, 76, 81, 91, 116, 122, 139, 141, 142, 155, 179, 194, 195, 196, 198, 201, - 230, 232, 240, 246, 251, 252, 258, 260, 262, 263, 302, 313, 333, 340, 343, 344, 350, 354, 370, 381, 392, 402, 407, - 412, 413, 415, 424, 425, 439, 440, 442, 451, 454, 455, 458, 497, 501, 537, 538, 541, 547, 549, 551, 580, 588, 589, - 593, 594, 595, 601, 602, 603, 619, 621, 624, 633, 644, 654, 668, 671, 685, 686, 692, 693, 694, 716, 721, 732}; +// The pickups, sounds and stand-ins the collectibles' own pickup effects (in 0075f0e0) use. +constexpr int COIN_LUCKY_PENNY = 5; +constexpr int TRINKET_MATCH_STICK = 41; +constexpr int SOUND_KISS_LIPS = 219; +constexpr int SOUND_PEEPER_POP = 237; +constexpr int DEAD_CAT_LIVES = 9; +constexpr int ROSARY_BIBLE_UPGRADE = 5; +constexpr int RED_STEW_FRAMES = 5400; +constexpr int RED_STEW_DEATHMATCH_FRAMES = 600; +constexpr int DOGMA_HEAL_CAP = 12; +constexpr int HEARTBREAK_KEEPER_CAP = 1; +constexpr int HEARTBREAK_CAP = 3; +constexpr int HEARTBREAK_MIN_LIMIT = 9; +constexpr int EVENT_EDENS_BLESSING = 114; +constexpr int SWARM_FLIES = 8; +constexpr int EXPERIMENTAL_STATS = 7; +constexpr int EXPERIMENTAL_CHANGES = 6; +constexpr int EXPERIMENTAL_UPS = 4; +constexpr int PLAYER_FORM_STOMPY = 13; +constexpr int PLAYER_FORM_PAGES = 15; +constexpr uint32_t CURSES_ALL = 0xffffffff; +constexpr uint32_t CHAOS_PICKUP_MASK = 7; +constexpr int CHAOS_PICKUP_MAX = 6; + +// The pickups The Box gives, and those Chaos draws from, in order. +constexpr std::array BOX_PICKUPS = {PICKUP_TRINKET, PICKUP_PILL, PICKUP_COIN, PICKUP_HEART, + PICKUP_TAROTCARD, PICKUP_KEY, PICKUP_BOMB}; +constexpr std::array CHAOS_PICKUPS = {PICKUP_TRINKET, PICKUP_PILL, PICKUP_COIN, PICKUP_HEART, + PICKUP_TAROTCARD, PICKUP_KEY, PICKUP_BOMB, PICKUP_LIL_BATTERY}; +// The hearts Mr. Dolly rolls between. +constexpr std::array DOLLY_HEARTS = {HEART_RED, HEART_SOUL, HEART_BLACK}; + // 007aa800 Whether the player may take a collectible now: not while the hold cooldown runs, and a helper player never // takes an active. @@ -758,7 +785,7 @@ void Entity_Player::IncrementPlayerFormCounter(int ePlayerForm, int num) reconstruction_missing("Entity_Player::IncrementPlayerFormCounter 0075e320 (a transformation)"); } -// The run's unlocks for holding many items: the tag sets, More Options' and Dad's Key's counters, ten tears ups and +// The run's unlocks for holding many items: the tag sets, Blood Clot's and Rubber Cement's counters, ten tears ups and // three star items. void Entity_Player::collectible_unlocks_check(int collectibleId, ItemConfig_Item& item) { @@ -766,8 +793,8 @@ void Entity_Player::collectible_unlocks_check(int collectibleId, ItemConfig_Item for (const TagUnlock& unlock : TAG_UNLOCKS) if (item.HasTags(unlock.tag) && tagged_item_count(unlock.tag) > unlock.above) save.TryUnlock(unlock.achievement); - if (collectibleId == COLLECTIBLE_MORE_OPTIONS) save.IncreaseEventCounter(EVENT_MORE_OPTIONS, 1); - else if (collectibleId == COLLECTIBLE_DADS_KEY) save.IncreaseEventCounter(EVENT_DADS_KEY, 1); + if (collectibleId == COLLECTIBLE_BLOOD_CLOT) save.IncreaseEventCounter(EVENT_BLOOD_CLOT, 1); + else if (collectibleId == COLLECTIBLE_RUBBER_CEMENT) save.IncreaseEventCounter(EVENT_RUBBER_CEMENT, 1); int tearsUps = PILL_TEARS_UP < (int)pillEffectUses.size() ? pillEffectUses[PILL_TEARS_UP] : 0; for (ItemConfig_Item* tagged : g_manager->itemConfig.GetTaggedItems(TAG_TEARS_UP)) @@ -801,10 +828,451 @@ void Entity_Player::collectible_pickups_add(ItemConfig_Item& item) if (isCapped) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (heart containers over the cap)"); } +// What taking a collectible passes its own pickup effect: the item, the charge (Dead Cat's lives), the active slot and +// whether it is the first time it is taken. +struct CollectibleGain +{ + int type = 0; + int charge = 0; + int slot = 0; + bool isFirstTime = false; +}; + +// A pickup an item's effect drops near the player, the seed and the spawner as the original passes them. +struct PickupDrop +{ + int variant = 0; + int subType = 0; + uint32_t seed = 0; + Entity* spawner = nullptr; +}; + +// A free spot near a position, as most pickup effects search for one. +static Vector pickup_spawn_position(Vector position) +{ + return room_free_pickup_position_find({position, PICKUP_SPAWN_STEP}); +} + +// Drops a pickup at a spot, staggered by a drop delay when it is one of several. +static void pickup_drop(Vector position, const PickupDrop& drop, int dropDelay = -1) +{ + Entity* pickup = g_game->Spawn({.position = position, .spawner = drop.spawner, .subType = drop.subType, + .type = ENTITY_PICKUP, .variant = drop.variant, .seed = drop.seed}); + if (dropDelay >= 0) static_cast(pickup)->dropDelay = dropDelay; +} + +// Drops pickups one at a time, each spot found before its seed is drawn. +static void pickups_drop(Entity_Player& p, RNG& rng, std::span variants, int subType) +{ + for (int i = 0; i < (int)variants.size(); i++) + { + Vector position = pickup_spawn_position(p.pos); + pickup_drop(position, {variants[i], subType, rng.Next(), &p}, i); + } +} + +// Dead Cat's lives, and on its first pickup one heart container of the player's kind of health, filled. +static void dead_cat_gain(Entity_Player& p, const CollectibleGain& gain) +{ + p.deadCatLives = (short)(p.deadCatLives + (gain.charge > 0 ? gain.charge : DEAD_CAT_LIVES)); + if (!gain.isFirstTime) return; + + switch (p.GetHealthType()) + { + case HEALTH_NO_HEALTH: + break; + case HEALTH_SOUL: + p.soulHearts = 2; + p.UpdateBlackHeartMask(); + break; + case HEALTH_BONE: + p.boneHearts = 0; + p.AddBoneHearts(1); + break; + default: + p.maxHearts = 0; + p.AddMaxHearts(2, false); + } + p.AddHearts(2, true, false); +} + +// Experimental Treatment's first pickup: four random stats up and two down, the hearts only while some are left. +static void experimental_treatment_gain(Entity_Player& p, RNG& rng) +{ + std::array stats = {0, 1, 2, 3, 4, 5, 6}; + for (int i = EXPERIMENTAL_STATS - 1; i > 0; i--) std::swap(stats[i], stats[rng.RandomInt(i + 1)]); + + for (int i = 0; i < EXPERIMENTAL_CHANGES; i++) + { + int step = i < EXPERIMENTAL_UPS ? 1 : -1; + switch (stats[i]) + { + case 0: + if (p.variant == PLAYER_VARIANT_PLAYER && + (p.soulHearts + p.boneHearts * 2 + p.maxHearts > 2 || i < EXPERIMENTAL_UPS)) + p.AddMaxHearts(step * 2, false); + break; + case 1: + p.speedModifier += step; + break; + case 2: + p.fireDelayModifier += step; + break; + case 3: + p.damageModifier += step; + break; + case 4: + p.tearRangeModifier += step; + break; + case 5: + p.shotSpeedModifier += step; + break; + default: + p.luckModifier += step; + } + } +} + +// Heartbreak's broken hearts: one for the Keeper's coins, else up to three while the heart limit allows. +static void heartbreak_gain(Entity_Player& p) +{ + int cap = HEARTBREAK_KEEPER_CAP; + if (p.GetHealthType() != HEALTH_COIN) + { + if (p.GetHeartLimit(true) < HEARTBREAK_MIN_LIMIT) return; + cap = HEARTBREAK_CAP; + } + int broken = std::min((p.GetHeartLimit(false) - 2) / 2, cap); + if (broken > 0) p.AddBrokenHearts(broken); +} + +// Dogma's first pickup: red then soul hearts up to six hearts, and a Holy Mantle shield. +static void dogma_gain(Entity_Player& p) +{ + auto missing = [&] { return std::min(p.GetHeartLimit(false), DOGMA_HEAL_CAP) - p.soulHearts - p.redHearts; }; + if (missing() > 0) + { + p.AddHearts(missing(), true, false); + if (missing() > 0) p.AddSoulHearts(missing(), false); + } + p.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, true, 1); +} + +// The first pickup's drops of the items that drop a fixed set of pickups. Whether the item is one of them. +static bool collectible_drops_apply(Entity_Player& p, const CollectibleGain& gain, RNG& rng) +{ + auto dropOne = [&](PickupDrop drop) + { + Vector position = pickup_spawn_position(p.pos); + drop.seed = rng.Next(); + pickup_drop(position, drop); + }; + auto drawnFirst = [&](int variant, int subType, int count) + { + for (int i = 0; i < count; i++) + { + uint32_t seed = rng.Next(); + pickup_drop(pickup_spawn_position(p.pos), {variant, subType, seed, &p}, i); + } + }; + + switch (gain.type) + { + case 31: + dropOne({PICKUP_HEART, 0, 0, &p}); + sound_play(SOUND_KISS_LIPS); + return true; + case 139: + case 354: + case 458: + dropOne({PICKUP_TRINKET, 0, 0, &p}); + return true; + case 195: + pickups_drop(p, rng, std::array{PICKUP_PILL, PICKUP_PILL, PICKUP_PILL, PICKUP_PILL}, 0); + return true; + case 196: + pickups_drop(p, rng, std::array{PICKUP_HEART, PICKUP_HEART}, HEART_SOUL); + return true; + case 198: + pickups_drop(p, rng, BOX_PICKUPS, 0); + return true; + case 343: + drawnFirst(PICKUP_KEY, 0, 2); + return true; + case 344: + drawnFirst(PICKUP_BOMB, 0, 3); + if (g_game->itemPool.RemoveTrinket(TRINKET_MATCH_STICK)) + { + uint32_t seed = rng.Next(); + pickup_drop(pickup_spawn_position(p.pos), {PICKUP_TRINKET, TRINKET_MATCH_STICK, seed, &p}, 3); + } + return true; + case 370: + for (int i = 0; i < 3; i++) + { + int heart = DOLLY_HEARTS[rng.Next() % DOLLY_HEARTS.size()]; + Vector position = pickup_spawn_position(p.pos); + pickup_drop(position, {PICKUP_HEART, heart, rng.Next(), &p}, i); + } + return true; + case 402: + { + int count = (int)rng.RandomInt(CHAOS_PICKUP_MAX) + 1; + for (int i = 0; i < count; i++) + { + Vector position = pickup_spawn_position(p.pos); + rng.Next(); + int variant = CHAOS_PICKUPS[rng._seed & CHAOS_PICKUP_MASK]; + pickup_drop(position, {variant, 0, rng.Next(), &p}, i); + } + return true; + } + case 424: + dropOne({PICKUP_GRAB_BAG, 0, 0, &p}); + return true; + case 454: + { + Vector position = pickup_spawn_position(p.pos); + uint32_t seed = rng.Next(); + pickup_drop(position, {rng.RandomInt(2) != 0 ? PICKUP_PILL : PICKUP_TAROTCARD, 0, seed, &p}); + return true; + } + case 455: + dropOne({PICKUP_COIN, COIN_LUCKY_PENNY, 0, &p}); + return true; + case 537: + dropOne({PICKUP_PILL, 0, 0, &p}); + return true; + case 538: + pickups_drop(p, rng, std::array{PICKUP_TRINKET, PICKUP_TRINKET, PICKUP_TRINKET}, 0); + return true; + case 541: + p.AddBoneHearts(1); + pickups_drop(p, rng, std::array{PICKUP_HEART, PICKUP_HEART, PICKUP_HEART}, HEART_RED); + return true; + case 603: + for (int slot = 0; slot < ACTIVE_SLOT_COUNT && !p.FullCharge(slot, false, false); slot++) {} + for (int i = 0; i < 3; i++) + { + Vector position = pickup_spawn_position(p.pos); + pickup_drop(position, {PICKUP_LIL_BATTERY, i == 0, rng.Next(), nullptr}, i); + } + return true; + case 671: + dropOne({PICKUP_HEART, HEART_RED, 0, nullptr}); + return true; + case 686: + dropOne({PICKUP_HEART, HEART_SOUL, 0, nullptr}); + return true; + case 716: + dropOne({PICKUP_KEY, 0, 0, nullptr}); + for (int i = 0; i < 3; i++) dropOne({PICKUP_COIN, 0, 0, nullptr}); + return true; + } + return false; +} + +// The part of 0075f0e0 a main player's collectible runs for itself: maps, transformation counters, heals, charges, +// curses lifted, effects started, and on the first pickup the pickups it drops. The items not written yet stop the +// game until reached. An active slot past the four reads past them in the original, here it is ignored. +static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& gain) +{ + Game& game = *g_game; + RNG& rng = p.GetCollectibleRNG(gain.type); + bool isFirst = gain.isFirstTime; + + if (isFirst && collectible_drops_apply(p, gain, rng)) return; + switch (gain.type) + { + case 12: + case 302: + p.IncrementPlayerFormCounter(PLAYER_FORM_STOMPY, 1); + return; + case 21: + game.ApplyCompassEffect(true); + return; + case 29: + if (isFirst) p.AddBlueFlies((int)rng.RandomInt(4) + 3, p.pos, nullptr); + return; + case 35: + case 262: + p.IncrementPlayerFormCounter(PLAYER_FORM_PAGES, 1); + return; + case 54: + game.ApplyMapEffect(); + return; + case 72: + for (ItemPool_Item& pool : game.itemPool.pools) pool.bibleUpgrade += ROSARY_BIBLE_UPGRADE; + return; + case 76: + case 91: + game.UpdateVisibility(); + return; + case 81: + dead_cat_gain(p, gain); + return; + case 116: + for (int slot = 0; isFirst && slot < ACTIVE_SLOT_COUNT && !p.FullCharge(slot, false, false); slot++) {} + return; + case 122: + p.UpdateHeartDependentEffects(); + return; + case 142: + p.temporaryEffects.AddCollectibleEffect(142, true, 1); + return; + case 155: + sound_play(SOUND_PEEPER_POP); + return; + case 179: + case 601: + if (isFirst) p.AddEternalHearts(1); + return; + case 201: + if (int slot = p.GetActiveItemSlot(COLLECTIBLE_NOTCHED_AXE); isFirst && slot >= 0) p.FullCharge(slot, true, false); + return; + case 232: + g_manager->musicManager.targetPitch = game.room->time_scale_update(); + return; + case 246: + game.ApplyBlueMapEffect(); + return; + case 260: + if (isFirst) game.RemoveCurses(CURSES_ALL); + return; + case 313: + p.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, true, 1); + p.PlayCollectibleAnim(COLLECTIBLE_HOLY_MANTLE, true, "Shimmer", -1); + return; + case 333: + game.ApplyMapEffect(); + game.ApplyCompassEffect(true); + game.ApplyBlueMapEffect(); + return; + case 381: + if (isFirst && game.challenge == 0 && game.dailyChallenge._id == 0) + g_manager->persistentGameData.eventCounters[EVENT_EDENS_BLESSING]++; + return; + case 412: + p.cambionConceptionState = 0; + p.trigger_immaculate_conception(true); + return; + case 413: + p.immaculateConceptionState = 0; + p.trigger_immaculate_conception(false); + return; + case 425: + game.RemoveCurses((uint32_t)CURSE_OF_DARKNESS); + return; + case 501: + p.update_greeds_gullet(); + return; + case 580: + game.room->UpdateRedKey(); + return; + case 594: + p.jupiterCharge = 1; + return; + case 602: + game.room->TrySpawnSecretShop(false); + return; + case 621: + if (isFirst) + p.redStewBonusDuration = + game.deathmatchManager.is_active() ? RED_STEW_DEATHMATCH_FRAMES : RED_STEW_FRAMES; + return; + case 633: + if (isFirst) dogma_gain(p); + return; + case 685: + if (gain.slot >= 0 && gain.slot < ACTIVE_SLOT_COUNT) + p.activeItems[gain.slot].varData = std::max(p.activeItems[gain.slot].varData, 2); + return; + case 692: + game.room->spawn_sanguine_bond_spikes(false); + return; + case 693: + for (int i = 0; isFirst && i < SWARM_FLIES; i++) p.AddSwarmFlyOrbital(p.pos); + return; + case 694: + heartbreak_gain(p); + return; + case 75: + case 141: + case 194: + case 230: + case 251: + case 252: + case 263: + case 350: + case 439: + case 451: + case 497: + case 547: + case 549: + case 551: + case 588: + case 589: + case 593: + case 595: + case 619: + case 624: + case 644: + case 654: + case 668: + case 721: + case 732: + reconstruction_missing( + (std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + + std::to_string(gain.type) + ")").c_str()); + } +} + +// The pickup effects 0075f0e0 runs for any player after Binge Eater's: Experimental Treatment's stats, Missing No.'s +// reroll, Caffeine Pill's pill, Zodiac's sign, Purity, the crowns and Kidney Stone's timer. +static void collectible_late_effect_apply(Entity_Player& p, const CollectibleGain& gain) +{ + RNG& rng = p.GetCollectibleRNG(gain.type); + + switch (gain.type) + { + case 240: + if (gain.isFirstTime) experimental_treatment_gain(p, rng); + return; + case 340: + if (gain.isFirstTime && p.variant == PLAYER_VARIANT_PLAYER) + { + uint32_t seed = rng.Next(); + pickup_drop(pickup_spawn_position(p.pos), {PICKUP_PILL, 0, seed, &p}); + } + return; + case 392: + if (ItemConfig_Item* sign = g_manager->itemConfig.GetCollectible(p.GetZodiacEffect())) + p.cacheFlags |= sign->cacheFlags; + return; + case 415: + if (p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) return; + p.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT, true, 1); + p.crownOfLightSprite.Play("FloatGlow"); + return; + case 440: + p.nextUrethraBlockFrame = g_game->frameCount; + return; + case 442: + if (!p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN)) + p.darkPrincesCrownSprite.Play("FloatNoGlow"); + return; + case 258: + case 407: + reconstruction_missing( + (std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + + std::to_string(gain.type) + ")").c_str()); + } +} + // 0075f0e0 Gives the player a collectible: Tainted Jacob's ghost passes it to Jacob, it joins the collection, the // counts and the history, its first pickup gives its pickups and hearts, the unlocks for many items are checked, its -// cache flags are evaluated, transformations count it, and its costume goes on. Book of Virtues takes its slot. -// Actives, the items with a pickup effect of their own and procedural items stop the game until reached. +// own pickup effect runs, its cache flags are evaluated, transformations count it, and its costume goes on. Book of +// Virtues takes its slot. Actives, procedural items and the pickup effects not written yet stop the game. void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData) { Game& game = *g_game; @@ -812,8 +1280,8 @@ void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int a if (!item) return log_printf(LOG_INFO, "[warn] no config for collectible %d.\n", type); int slot = std::clamp(activeSlot, 0, ACTIVE_SLOT_COUNT - 1); - int transition = game.stageTransition._state; - if (transition != 0 && transition != STAGE_TRANSITION_OUT && transition != STAGE_TRANSITION_DONE) + StageTransitionState transition = game.stageTransition.state; + if (transition != STAGE_TRANSITION_NONE && transition != STAGE_TRANSITION_IN && transition != STAGE_TRANSITION_LANDING) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (during a stage transition)"); Entity_Player* twin = twin_get(); if (playerType == PLAYER_JACOB2_B && twin && item->type != ITEM_ACTIVE) @@ -846,13 +1314,15 @@ void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int a cacheFlags |= item->cacheFlags; if (HasCollectible(COLLECTIBLE_BINGE_EATER) && item->HasTags(TAG_FOOD)) cacheFlags |= g_manager->itemConfig.GetCollectible(COLLECTIBLE_BINGE_EATER)->cacheFlags; - if (std::ranges::find(PICKUP_EFFECT_ITEMS, type) != PICKUP_EFFECT_ITEMS.end()) - reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (the item's pickup effect)"); - if (HasCollectible(COLLECTIBLE_BINGE_EATER) && item->HasTags(TAG_FOOD) && isFirstTime) + CollectibleGain gain{type, charge, activeSlot, isFirstTime}; + if (variant == PLAYER_VARIANT_PLAYER) collectible_effect_apply(*this, gain); + if (variant == PLAYER_VARIANT_PLAYER && HasCollectible(COLLECTIBLE_BINGE_EATER) && item->HasTags(TAG_FOOD) && + isFirstTime) { redStewBonusDuration = std::max(redStewBonusDuration, BINGE_EATER_STEW_FRAMES); AddHearts(2, false, false); } + collectible_late_effect_apply(*this, gain); if (variant == PLAYER_VARIANT_PLAYER && isFirstTime) { @@ -870,571 +1340,6 @@ void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int a UpdateBookOfVirtues(type == COLLECTIBLE_BOOK_OF_VIRTUES); } -// The stat evaluation's constants: the tears formula, the base stats and the clamps that end it. -constexpr float TEARS_CURVE_SCALE = 1.3f; -constexpr float TEARS_DELAY_BASE = 16; -constexpr float TEARS_DELAY_STEP = 6; -constexpr float TEARS_DELAY_MIN = 5; -constexpr float FIRE_RATE_FRAMES = 30; -constexpr float CRACKED_CROWN_FIRE_RATE = 2.7272727f; -constexpr float NEGATIVE_TEARS_SCALE = 0.686655f; -constexpr float DAMAGE_CURVE_SCALE = 1.2f; -constexpr float DAMAGE_BASE = 3.5f; -constexpr float RANGE_BASE = 260; -constexpr float TEAR_HEIGHT_BASE = -23.75f; -constexpr float RANGE_MIN = 40; -constexpr float SPEED_MAX = 2; -constexpr float SPEED_MIN = 0.1f; -constexpr float SHOT_SPEED_MIN = 0.6f; -constexpr float DAMAGE_MIN = 0.5f; -constexpr float MAX_FIRE_DELAY_MIN = -0.75f; -constexpr float TEAR_HEIGHT_MAX = -5; -constexpr float FALL_SPEED_RANGE_SCALE = 10; -constexpr float FALL_SPEED_DECAY = 0.9f; -constexpr float FALL_SPEED_SLOPE = -9.49122142791748f; -constexpr float FALL_SPEED_MIN_SLOPE = 0.01f; -constexpr float G_FUEL_SPEED = 0.2f; -constexpr uint32_t DEBUG_HIGH_DAMAGE = 1 << 3; -constexpr uint32_t DEBUG_HIGH_LUCK = 1 << 8; -constexpr float DEBUG_DAMAGE_BONUS = 40; -constexpr float DEBUG_LUCK_BONUS = 50; -constexpr int PILL_TEARS_DOWN = 15; -constexpr int PILL_RANGE_DOWN = 11; -constexpr int PILL_RANGE_UP = 12; -constexpr int PILL_SPEED_DOWN = 13; -constexpr int PILL_SPEED_UP = 14; -constexpr int PILL_LUCK_DOWN = 17; -constexpr int PILL_LUCK_UP = 18; -constexpr int PILL_SHOT_SPEED_DOWN = 47; -constexpr int PILL_SHOT_SPEED_UP = 48; -constexpr int PLAYER_FORM_SPUN = 5; -constexpr int PLAYER_FORM_CONJOINED = 7; -constexpr int PLAYER_FORM_LEVIATHAN = 14; -constexpr int TRINKET_CRACKED_CROWN = 92; -constexpr int FAMILIAR_ITEM_WISP = 206; -constexpr int COLLECTIBLE_FORTUNE_COOKIE = 557; -constexpr int COOP_BUFF_DAMAGE = 0; -constexpr int COOP_BUFF_TEARS = 1; -constexpr int COOP_BUFF_SPEED = 2; -constexpr int COOP_BUFF_RANGE = 3; -constexpr int COOP_BUFF_LUCK = 4; - -// The run states the evaluation is reconstructed for: the stat changes of other characters, effects, trinkets, -// seeds, challenges, procedural items, wisps and the items below stop the game until reached. -// Candy Heart, Soul Locket, Experimental Treatment, Libra, Rock Bottom, Adrenaline, the pill and weapon items, Purity. -constexpr std::array EVALUATION_UNHANDLED_ITEMS = {671, 686, 240, 304, 562, 493, 654, 407, 329, 395, 579, 625, - 678, 704, 52, 68, 114, 118, 168, 229, 594, 633, 556}; - -// The items each other cache flag's section looks at, which stop the game when that section has work to do: -// tear flags, tear color, flying, size and color. -constexpr std::array TEAR_FLAG_ITEMS = { - 257, 259, 261, 305, 306, 309, 315, 316, 317, 331, 336, 358, 359, 369, 379, 397, 453, 462, 494, 506, 524, 529, - 532, 533, 540, 570, 572, 592, 596, 677, 48, 69, 104, 115, 132, 149, 159, 169, 182, 185, 192, 213, 221, 222, - 224, 233, 237, 3, 5, 6, 330, 310}; -constexpr std::array TEAR_COLOR_ITEMS = {398, 401, 429, 459, 531, 553, 561, 617, 618, 678, 89, 103, - 200, 330, 310, 257, 259, 305, 315, 317, 336, 572, 596}; -constexpr std::array FLYING_ITEMS = {20, 409, 33, 633, 643, 677, 714, 82, 130, 159, 179, 181, 184, 185}; -constexpr std::array SIZE_COLOR_ITEMS = {302, 340, 438, 598, 688, 71, 120, 121, 12, 350, 411, 554, 13, 222, 299}; - -// Whether the player owns any of the listed collectibles. -static bool is_owning_any(Entity_Player& player, std::span collectibles) -{ - return std::ranges::any_of(collectibles, [&](int id) { return player.HasCollectible(id); }); -} - -// Whether the player owns an item whose cache flags ask for a section. -static bool is_cache_owned(Entity_Player& player, uint32_t flag) -{ - ItemConfig& items = g_manager->itemConfig; - for (int id = 0; id < (int)player.collectibleCounts.size(); id++) - if (player.collectibleCounts[id] > 0) - if (ItemConfig_Item* item = items.GetCollectible(id); item && (item->cacheFlags & flag)) return true; - return false; -} - -// How often a pill effect was taken, 0 for one never seen. -static float pill_uses(Entity_Player& player, int pillEffect) -{ - return pillEffect < (int)player.pillEffectUses.size() ? (float)player.pillEffectUses[pillEffect] : 0; -} - -// Whether the character and run are ones the evaluation is reconstructed for (see EVALUATION_UNHANDLED_ITEMS). -bool Entity_Player::is_character_plain() -{ - Game& game = *g_game; - bool isSmelted = std::ranges::any_of(smeltedTrinkets, [](SmeltedTrinket& t) { return t.count || t.goldenCount; }); - return playerType == PLAYER_ISAAC && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && !hasCurseMistEffect && - game.challenge == 0 && game.dailyChallenge._id == 0 && game.seedEffects.CountSeedEffects() == 0 && - !game.deathmatchManager.is_active() && temporaryEffects.effects.empty() && - trinkets == std::array{} && !isSmelted && proceduralItems.empty() && - itemWispsList.empty(); -} - -// The bonuses Binge Eater's foods give: damage, tears, range, shot speed, speed and luck, each food also slowing. -struct StatBonuses -{ - float damage = 0; - float tears = 0; - float range = 0; - float shotSpeed = 0; - float speed = 0; - float luck = 0; -}; - -// The part of 00763570 before the sections: Binge Eater's foods add to the stats it lowers speed for. -static StatBonuses stat_bonuses_get(Entity_Player& player) -{ - constexpr float FOOD_SLOW = 0.15f; - StatBonuses bonus; - - if (!player.HasCollectible(COLLECTIBLE_BINGE_EATER)) return bonus; - auto food = [&](int id, std::initializer_list stats) - { - float count = (float)player.GetCollectibleNum(id); - for (float* stat : stats) *stat = count + *stat; - bonus.speed = bonus.speed - count * FOOD_SLOW; - }; - food(22, {&bonus.tears, &bonus.range}); - food(23, {&bonus.tears, &bonus.shotSpeed}); - food(24, {&bonus.damage, &bonus.shotSpeed}); - food(25, {&bonus.range, &bonus.shotSpeed}); - food(26, {&bonus.damage, &bonus.range}); - food(346, {&bonus.luck, &bonus.shotSpeed}); - food(456, {&bonus.damage, &bonus.luck}); - food(707, {&bonus.tears, &bonus.luck}); - return bonus; -} - -// The fire delay section of 00763570: tears ups through the tears curve, fire rate items, then the multipliers of -// the shot changing items, as frames between shots. -static void fire_delay_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) -{ - auto n = [&](int id) { return (float)p.GetCollectibleNum(id); }; - auto has = [&](int id) { return p.HasCollectible(id); }; - - float tears = pill_uses(p, PILL_TEARS_UP) * 0.5f - pill_uses(p, PILL_TEARS_DOWN) * 0.4f; - for (int id : {32, 80, 381, 1, 370, 341, 342, 183, 394, 547, 601}) tears = n(id) + tears; - tears = (n(598) + tears) * 0.7f; - tears = n(6) * 1.5f + tears; - tears = (n(669) + n(564) + n(255) + n(115) + n(72)) * 0.5f + tears; - tears = (float)(p.GetCollectibleNum(196) - p.GetCollectibleNum(182)) * 0.4f + tears; - tears = (float)(p.GetCollectibleNum(189) + p.GetCollectibleNum(101) + p.GetCollectibleNum(90)) * 0.2f + tears; - tears = tears - (float)(p.GetCollectibleNum(331) + p.GetCollectibleNum(237)) * 0.3f; - tears = n(438) * 0.75f + tears; - tears = n(443) * 0.3f + tears; - tears = n(465) * 0.35f + tears; - float bonusTears = bonus.tears * 0.5f; - if (bonusTears < 0) bonusTears *= NEGATIVE_TEARS_SCALE; - tears = bonusTears + tears; - if (p.HasPlayerForm(PLAYER_FORM_CONJOINED)) tears = tears - 0.3f; - if (p.coopBabyBuffTimers[COOP_BUFF_TEARS] > 0) tears = tears + 1; - - float curve = std::sqrt(std::max(tears * TEARS_CURVE_SCALE + 1, 0.0f)); - float delay = std::max(TEARS_DELAY_BASE - curve * TEARS_DELAY_STEP - std::min(tears, 0.0f) * TEARS_DELAY_STEP, - TEARS_DELAY_MIN); - float rate = FIRE_RATE_FRAMES / (delay + 1); - if (has(600)) rate *= 1.2f; - if (crownScale != 1 && rate > CRACKED_CROWN_FIRE_RATE) rate = rate + (rate - CRACKED_CROWN_FIRE_RATE) * (crownScale - 1); - - float zodiacA = p.GetZodiacEffect() == 307 ? 1.0f : 0.0f; - float zodiacB = p.GetZodiacEffect() == 309 ? 1.0f : 0.0f; - float pairs = (float)(p.GetCollectibleNum(307) + p.GetCollectibleNum(228) + p.GetCollectibleNum(224) + - p.GetCollectibleNum(206)) + zodiacA; - pairs = (n(309) + pairs + zodiacB + (float)p.fireDelayModifier) * 0.5f; - float flat = (float)p.brittleBonesUpgrades * 0.4f + pairs; - flat = n(397) + flat; - rate = flat + rate; - if (has(120)) rate = n(120) * 0.7f + 1 + rate; - rate = n(554) * 0.5f + rate; - if (!p.HasWeaponType(WEAPON_BRIMSTONE)) rate = n(222) + rate; - rate = (float)p.g_fuel_count() * 0.5f + rate; - if (p.grantedCollectibleCountdown > 0) rate = rate + 1.5f; - - if (!has(245)) - { - if (has(153) || (has(169) && !p.HasWeaponType(WEAPON_FETUS))) rate *= 0.42f; - else if (has(2)) rate *= 0.51f; - } - if (has(149) && (p.HasWeaponType(WEAPON_TEARS) || p.HasWeaponType(WEAPON_MONSTROS_LUNGS) || - p.HasWeaponType(WEAPON_LASER))) - rate /= 3; - if (has(531)) - { - if (!has(149) && p.HasWeaponType(WEAPON_TEARS)) rate *= 0.5f; - float frames = FIRE_RATE_FRAMES / rate; - float pause = p.HasWeaponType(WEAPON_FETUS) ? 4.0f : 10.0f; - rate = rate - rate * pause / (frames + pause); - float charge = has(118) ? 20.0f : has(52) ? 10.0f : 0.0f; - if (p.HasWeaponType(WEAPON_MONSTROS_LUNGS)) charge *= 0.5f; - rate = rate - charge * rate / (FIRE_RATE_FRAMES / rate + charge); - } - if (p.HasWeaponType(WEAPON_BRIMSTONE)) rate /= 3; - else if (p.HasWeaponType(WEAPON_BOMBS)) rate /= 2.5f; - else if (p.HasWeaponType(WEAPON_BONE)) rate *= 0.5f; - if (has(152)) rate /= 1.5f; - if (has(310)) rate *= 0.66f; - if (p.HasWeaponType(WEAPON_MONSTROS_LUNGS)) rate /= 4.3f; - else if (p.HasWeaponType(WEAPON_TECH_X) && has(229)) rate /= 3.1f; - if (has(561)) rate *= 4; - else if (has(330)) rate *= 5.5f; - if (p.hallowedGroundCountdown != 0) rate *= 2.5f; - if (has(368) && p.epiphoraCharge > 0) rate *= (float)p.epiphoraCharge / 180 + 1; - if (p.peeBurstCooldown > 0) rate = ((float)p.peeBurstCooldown * 5 / (float)p.maxPeeBurstCooldown + 1) * rate; - if (has(695) && !p.temporaryEffects.isDisabled) - { - float lust = std::clamp((float)p.bloodLustCounter, 0.0f, 6.0f); - rate = lust * 0.05f * lust + lust * 0.2f + rate; - } - - p.maxFireDelay = FIRE_RATE_FRAMES / (rate * p.d8FireDelayModifier) - 1; - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_FIREDELAY); - p.maxFireDelay = std::max(p.maxFireDelay, MAX_FIRE_DELAY_MIN); -} - -// The damage section of 00763570: damage ups through the damage curve on 3.5, then the multiplying items. -static void damage_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) -{ - auto n = [&](int id) { return p.GetCollectibleNum(id); }; - auto has = [&](int id) { return p.HasCollectible(id); }; - float damage = 0; - - p.meleeDamage = 0; - for (int id : {7, 90, 216}) - if (has(id)) damage = damage + 1; - if (p.HasPlayerForm(PLAYER_FORM_SPUN)) damage = damage + 2; - if (p.HasPlayerForm(PLAYER_FORM_CONJOINED)) damage = damage - 0.3f; - if (has(109)) damage = (float)p.numCoins * 0.04f + damage; - if (p.redStewBonusDuration > 0 && !p.temporaryEffects.isDisabled) - damage = (float)(p.redStewBonusDuration / 10) * 0.04f + damage; - if (has(716)) damage = (float)((p.keepersSackBonus / 3 + 2) / 3) * 0.5f + damage; - if (p.grantedCollectibleCountdown > 0) damage = damage + 1; - - int ups = n(708) + n(592) + n(572) + n(531) + n(345) + n(328) + n(259) + n(208) + n(206) + n(165) + n(121) + - n(79) + n(70) + n(51) + n(50) + std::max(n(118) - 1, 0); - float sum = (float)ups; - sum = (float)n(732) + sum; - sum = (float)n(730) * 0.75f + sum; - sum = (float)p.g_fuel_count() * 0.75f + sum; - sum = (float)((int)has(261) + n(669) + n(331) + n(307) + n(197) + n(80) + n(4)) * 0.5f + sum; - sum = (float)(n(463) + n(445) + n(201) + n(193) + n(189) + n(138) + n(101) + n(62) + n(12)) * 0.3f + sum; - float mushrooms = (float)n(633); - damage = (float)(n(359) + n(237) + n(230) + n(5)) * 1.5f + sum + mushrooms + mushrooms + damage; - if (has(694)) damage = (float)p.brokenHearts * 0.25f + damage; - if (has(120)) damage = damage * 0.9f - 0.4f; - if (p.coopBabyBuffTimers[COOP_BUFF_DAMAGE] > 0) damage = damage + 2; - - damage = std::sqrt(std::max(damage * DAMAGE_CURVE_SCALE + 1, 0.0f)) * DAMAGE_BASE; - if (has(169)) - damage = !has(2) && !has(153) && !p.HasWeaponType(WEAPON_FETUS) && !has(245) ? damage + 4 + damage + 4 - : damage + 5; - damage = (float)(p.potatoPeelerBandageCounter + p.potatoPeelerCounter) * 0.2f + damage; - damage = std::max((float)p.damageModifier + bonus.damage + damage, DAMAGE_MIN); - if (has(513)) damage = damage + 0.1f; - if (p.HasWeaponType(WEAPON_BONE) && has(114)) damage = damage + 4; - if (has(182)) damage = damage * 2.3f + 1; - if (has(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && has(COLLECTIBLE_PASSIVE_DAMOCLES)) damage = damage * 1.4f + 1; - if (has(573) || p.hallowedGroundCountdown > 0) damage = damage * 1.2f; - if (has(157) && !p.temporaryEffects.isDisabled) - { - float cap = has(COLLECTIBLE_BIRTHRIGHT) && p.playerType == PLAYER_SAMSON ? 10.0f : 6.0f; - float lust = std::clamp((float)p.bloodLustCounter, 0.0f, cap); - damage = lust * 0.1f * lust + lust * 0.4f + damage; - } - - if (has(531)) damage = damage * 1.5f; - float melee = damage; - if (has(149)) - { - bool isTears = p.HasWeaponType(WEAPON_TEARS) || p.HasWeaponType(WEAPON_MONSTROS_LUNGS) || - p.HasWeaponType(WEAPON_FETUS); - damage = damage + (isTears ? 40.0f : 2.0f); - melee = melee + 2; - } - if (has(4) || has(12)) - { - damage = damage * 1.5f; - melee = melee * 1.5f; - } - if (has(310)) - { - damage = damage + damage; - melee = melee + melee; - } - if (has(561) || has(330)) - { - float scale = has(561) ? 0.3f : 0.2f; - damage = damage * scale; - melee = melee * scale; - } - if (has(245)) - { - damage = damage * 0.8f; - melee = melee * 0.8f; - } - if (has(373)) - { - float scale = (float)p.deadEyeCharges * 0.125f + 1; - damage = scale * damage; - melee = scale * melee; - } - else - { - p.deadEyeMisses = 0; - p.deadEyeCharges = 0; - } - if (p.damageMultiplierStacks > 0) - { - float scale = std::pow(1.5f, (float)p.damageMultiplierStacks); - damage = scale * damage; - melee = scale * melee; - } - damage = p.d8DamageModifier * damage; - melee = p.d8DamageModifier * melee; - if (crownScale != 0 && damage > DAMAGE_BASE) - { - damage = (damage - DAMAGE_BASE) * (crownScale - 1) + damage; - melee = (melee - DAMAGE_BASE) * (crownScale - 1) + melee; - } - p.damage = damage; - p.meleeDamage = melee; - - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_DAMAGE); - if (g_game->debugFlags & DEBUG_HIGH_DAMAGE) - { - p.damage = p.damage + DEBUG_DAMAGE_BONUS; - p.meleeDamage = p.meleeDamage + DEBUG_DAMAGE_BONUS; - } - p.damage = std::max(p.damage, DAMAGE_MIN); - p.meleeDamage = std::max(p.meleeDamage, DAMAGE_MIN); -} - -// The shot speed section of 00763570: shot speed ups and downs on 1. -static void shot_speed_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) -{ - auto n = [&](int id) { return p.GetCollectibleNum(id); }; - auto has = [&](int id) { return p.HasCollectible(id); }; - - float pills = (float)(int)(pill_uses(p, PILL_SHOT_SPEED_UP) - pill_uses(p, PILL_SHOT_SPEED_DOWN)); - int occult = std::min(n(572), 1); - int mascara = std::min(n(310), 1); - float ups = (float)(n(176) + n(669) + ((n(183) - occult) - n(342)) + n(397) + n(341) + n(339) + n(194)) * 0.16f; - float drops = (float)(n(564) + n(255) + n(143)) * 0.2f; - float speed = (float)n(165) * 0.23f + 1 + drops + ups + pills * 0.15f; - speed = speed - (float)n(182) * 0.25f; - speed = speed - (float)n(213) * 0.15f; - speed = speed - (float)mascara * 0.5f; - speed = speed - (float)n(336) * 0.4f; - speed = speed - (float)n(331) * 0.3f; - speed = ((float)p.shotSpeedModifier + bonus.shotSpeed) * 0.2f + (float)n(329) * 0.2f + speed; - if (p.coopBabyBuffTimers[COOP_BUFF_RANGE] > 0) speed = speed + 0.5f; - speed = (float)n(554) * 0.2f + speed; - if (has(5)) speed = speed * 1.6f; - if (has(149)) speed = speed * 0.8f; - if (crownScale != 1 && speed - 1 > 0) speed = (crownScale - 1) * (speed - 1) + speed; - p.shotSpeed = speed; - - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_SHOTSPEED); - p.shotSpeed = std::max(p.shotSpeed, SHOT_SPEED_MIN); -} - -// The range section of 00763570: range ups in tiles of 100, the height and fall of the tears, and the range items. -static void range_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) -{ - auto n = [&](int id) { return (float)p.GetCollectibleNum(id); }; - auto has = [&](int id) { return p.HasCollectible(id); }; - - p.tearRange = RANGE_BASE; - p.tearHeight = TEAR_HEIGHT_BASE; - p.tearFallingSpeed = 0; - p.tearFallingAcceleration = 0; - - float pills = pill_uses(p, PILL_RANGE_UP) * 0.5f - pill_uses(p, PILL_RANGE_DOWN) * 0.4f; - float ups = (float)(p.tearRangeModifier + p.GetCollectibleNum(71) + p.GetCollectibleNum(12)) + bonus.range; - ups = n(30) + ups; - ups = n(31) * 1.5f + ups; - ups = n(397) + ups; - ups = n(29) + ups + pills; - for (int id : {339, 345, 14, 370, 189, 455, 355, 659}) ups = n(id) + ups; - ups = (n(669) + ups) * 100; - float tiles = (float)(p.GetCollectibleNum(462) + p.GetCollectibleNum(453) + p.GetCollectibleNum(197) + - p.GetCollectibleNum(121) + p.GetCollectibleNum(110) + p.GetCollectibleNum(101)) * 60 + ups; - tiles = tiles - n(336) * 60; - tiles = n(369) * 120 + tiles; - p.tearRange = n(394) * 120 + tiles + p.tearRange; - - if (has(572)) - { - p.tearHeight = p.tearHeight - 8; - p.tearRange = p.tearRange + 80; - } - if (has(594)) p.tearHeight = p.tearHeight - 8; - if (has(598)) p.tearHeight = p.tearHeight * 0.4f; - if (has(716)) p.tearRange = (float)((p.keepersSackBonus / 3 + 1) / 3) * 10 + p.tearRange; - if (p.coopBabyBuffTimers[COOP_BUFF_RANGE] > 0) p.tearRange = p.tearRange + 80; - if (has(149) || has(531)) - { - if (!has(229)) - { - p.tearFallingAcceleration = 0.8f; - p.tearRange = p.tearRange * 0.8f; - } - } - else if (has(224)) p.tearRange = p.tearRange * 0.8f; - if (has(233)) - { - p.tearRange = p.tearRange + RANGE_BASE; - p.tearFallingAcceleration = p.tearFallingAcceleration * 0.01f; - } - if (has(307) || p.GetZodiacEffect() == 307) p.tearRange = p.tearRange + 30; - if (has(214)) p.tearRange = p.tearRange + 60; - if (has(6)) - { - p.tearHeight = p.tearHeight + 18; - p.tearRange = std::min(p.tearRange, std::max(p.tearRange - 60, 200.0f) * 0.8f); - } - else if (has(440)) p.tearHeight = p.tearHeight + 18; - if (has(5)) p.tearRange = p.tearRange + p.tearRange + 60; - p.tearRange = p.tearRange * p.d8RangeModifier; - if (crownScale != 1 && p.tearRange > RANGE_BASE) - p.tearRange = (p.tearRange - RANGE_BASE) * (crownScale - 1) + p.tearRange; - - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_RANGE); - if (p.tearRange < RANGE_MIN) p.tearRange = RANGE_MIN; - if (p.tearFallingAcceleration > 0) - p.tearFallingAcceleration = p.shotSpeed * p.shotSpeed * p.tearFallingAcceleration; -} - -// The speed section of 00763570: speed ups on 1, and the items that set or cap it. -static void speed_evaluate(Entity_Player& p, const StatBonuses& bonus, float crownScale) -{ - auto n = [&](int id) { return p.GetCollectibleNum(id); }; - auto has = [&](int id) { return p.HasCollectible(id); }; - - float pills = pill_uses(p, PILL_SPEED_UP) * 0.5f - pill_uses(p, PILL_SPEED_DOWN) * 0.4f; - int rollers = p.g_fuel_count() < 1 ? n(143) : 0; - float ups = (float)(n(232) + n(119) + n(28) + n(27)) + pills; - for (int id : {340, 12, 71, 101, 120}) ups = (float)n(id) + ups; - ups = ups + (float)rollers; - ups = (float)n(82) + ups; - ups = (float)n(571) + ups; - float quick = ups * 0.3f; - float steady = (float)n(70) * 0.5f; - steady = (float)n(590) + steady; - steady = steady * 0.4f; - int sharp = std::min(n(14), 1); - int slow = std::min(n(13), 1); - float speed = (float)((((slow - n(90)) - n(129)) - n(121)) + n(669) + n(189) + n(79)) * 0.2f + - (float)sharp * 0.3f + 1 + steady + quick; - p.moveSpeed = ((float)p.speedModifier + bonus.speed) * 0.2f + (float)n(445) * 0.1f + speed; - - if (has(695) && !p.temporaryEffects.isDisabled) - { - float lust = std::clamp((float)p.bloodLustCounter, 0.0f, 6.0f); - p.moveSpeed = lust * 0.02f * lust + lust * 0.05f + p.moveSpeed; - } - if (has(716)) p.moveSpeed = (float)(p.keepersSackBonus / 9) * 0.03f + p.moveSpeed; - if (p.coopBabyBuffTimers[COOP_BUFF_SPEED] > 0) p.moveSpeed = p.moveSpeed + 0.15f; - if (has(230)) p.moveSpeed = p.moveSpeed + 0.2f; - if (p.HasPlayerForm(PLAYER_FORM_SPUN)) p.moveSpeed = p.moveSpeed + 0.15f; - if (p.HasPlayerForm(PLAYER_FORM_LEVIATHAN)) p.moveSpeed = p.moveSpeed + 0.2f; - if (has(130) || has(181)) p.moveSpeed = std::max(p.moveSpeed, 1.5f); - if (has(COLLECTIBLE_TAURUS) || p.GetZodiacEffect() == COLLECTIBLE_TAURUS) p.moveSpeed = p.moveSpeed - 0.3f; - if (has(300) || p.GetZodiacEffect() == 300) p.moveSpeed = p.moveSpeed + 0.25f; - if (has(306) || p.GetZodiacEffect() == 306) p.moveSpeed = p.moveSpeed + 0.2f; - if (has(307) || p.GetZodiacEffect() == 307) p.moveSpeed = p.moveSpeed + 0.1f; - if (has(314)) p.moveSpeed = p.moveSpeed - 0.4f; - p.moveSpeed = p.d8SpeedModifier * p.moveSpeed; - if (crownScale != 1 && p.moveSpeed > 1) p.moveSpeed = (p.moveSpeed - 1) * (crownScale - 1) + p.moveSpeed; - - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_SPEED); -} - -// The luck section of 00763570: luck ups, and Fortune Cookie's wisps. -static void luck_evaluate(Entity_Player& p, const StatBonuses& bonus) -{ - auto n = [&](int id) { return (float)p.GetCollectibleNum(id); }; - - float pills = pill_uses(p, PILL_LUCK_UP) - pill_uses(p, PILL_LUCK_DOWN); - float luck = (float)p.luckModifier + bonus.luck + pills + (float)p.donateLuck + p.edenLuck + n(253); - for (int id : {46, 343, 355, 439}) luck = n(id) + luck; - luck = luck - n(5); - luck = n(669) + luck; - luck = (float)(p.GetCollectibleNum(632) * 2) + luck; - p.luck = n(730) + luck; - - int wisps = 0; - for (Entity* entity : g_game->room->entityList.updateEL) - if (entity && entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_ITEM_WISP && - entity->subtype == COLLECTIBLE_FORTUNE_COOKIE && static_cast(entity)->player == &p) - wisps++; - p.luck = (float)wisps * 0.2f + p.luck; - if (p.coopBabyBuffTimers[COOP_BUFF_LUCK] > 0) p.luck = p.luck + 2; - if (p.HasCollectible(492)) p.luck = p.luck + 1; - if (g_game->debugFlags & DEBUG_HIGH_LUCK) p.luck = p.luck + DEBUG_LUCK_BONUS; - - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_LUCK); -} - -// How fast a tear falls to reach its range at its shot speed from its height (0067da40). -static float tear_fall_speed(float height, float range, float shotSpeed, float acceleration) -{ - float flight = range / shotSpeed; - float slope = std::max((std::pow(FALL_SPEED_DECAY, flight) - 1) * FALL_SPEED_SLOPE, FALL_SPEED_MIN_SLOPE); - return ((TEAR_HEIGHT_MAX - height) - (acceleration * FALL_SPEED_RANGE_SCALE + 1) * (flight - slope)) / slope; -} - -// A section the evaluation is not reconstructed for: it stops the game when an owned item asks for it. -static void section_check(Entity_Player& p, uint32_t flag, std::span collectibles, std::string_view what) -{ - if ((p.cacheFlags & flag) && (is_cache_owned(p, flag) || is_owning_any(p, collectibles))) - reconstruction_missing((std::string("Entity_Player::EvaluateItems 00763570 (") + std::string(what) + ")").c_str()); - if (p.cacheFlags & flag) static_cast(g_luaEngine)->EvaluateItems(&p, (int)flag); -} - -// 00763570 Recomputes the stats the cache flags ask for: fire delay, damage, shot speed, range, speed and luck from -// the items, pills, modifiers and Binge Eater's foods, each section handed to the mods, then clamps them and works -// out how fast tears fall. A shot speed change redoes the range. The other sections (weapons, tear flags and color, -// flying, familiars, size and color) and other characters, effects, trinkets and run modifiers stop the game when -// they have work to do. -void Entity_Player::EvaluateItems() -{ - if (!is_character_plain() || is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS)) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (characters, effects, trinkets or special items)"); - - StatBonuses bonus = stat_bonuses_get(*this); - float crownScale = (float)GetTrinketMultiplier(TRINKET_CRACKED_CROWN) * 0.2f + 1; - if (cacheFlags & CACHE_WEAPON) static_cast(g_luaEngine)->EvaluateItems(this, CACHE_WEAPON); - if (cacheFlags & CACHE_SHOTSPEED) cacheFlags |= CACHE_RANGE; - if (cacheFlags & CACHE_FIREDELAY) fire_delay_evaluate(*this, bonus, crownScale); - if (cacheFlags & CACHE_DAMAGE) damage_evaluate(*this, bonus, crownScale); - if (cacheFlags & CACHE_SHOTSPEED) shot_speed_evaluate(*this, bonus, crownScale); - if (cacheFlags & CACHE_RANGE) range_evaluate(*this, bonus, crownScale); - if (cacheFlags & CACHE_SPEED) speed_evaluate(*this, bonus, crownScale); - section_check(*this, CACHE_TEARFLAG, TEAR_FLAG_ITEMS, "tear flags"); - section_check(*this, CACHE_TEARCOLOR, TEAR_COLOR_ITEMS, "tear color"); - section_check(*this, CACHE_FLYING, FLYING_ITEMS, "flying"); - section_check(*this, CACHE_FAMILIARS, {}, "familiars"); - if (cacheFlags & CACHE_LUCK) luck_evaluate(*this, bonus); - section_check(*this, CACHE_SIZE, SIZE_COLOR_ITEMS, "size"); - section_check(*this, CACHE_COLOR, SIZE_COLOR_ITEMS, "color"); - - if ((cacheFlags & CACHE_SPEED) && std::ranges::any_of(g_game->playerManager.playerList, - [this](Entity_Player* other) { return other->parent == this; })) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (the speed of a player's helpers)"); - if (cacheFlags & CACHE_PICKUP_VISION) g_game->room->isPickupVisionInvalid = true; - if (cacheFlags & CACHE_SPEED) moveSpeed = std::max(SPEED_MIN, std::min(SPEED_MAX, moveSpeed)); - shotSpeed = std::max(shotSpeed, SHOT_SPEED_MIN); - if (tearHeight > TEAR_HEIGHT_MAX) tearHeight = TEAR_HEIGHT_MAX; - tearRange = std::max(tearRange, RANGE_MIN); - damage = std::max(damage, DAMAGE_MIN); - maxFireDelay = std::max(maxFireDelay, MAX_FIRE_DELAY_MIN); - if (cacheFlags & (CACHE_SHOTSPEED | CACHE_RANGE)) - tearFallingSpeed = -tear_fall_speed(tearHeight, tearRange, shotSpeed * FALL_SPEED_RANGE_SCALE, - tearFallingAcceleration); - if ((cacheFlags & CACHE_SPEED) && g_fuel_count() > 0) moveSpeed = (float)g_fuel_count() * G_FUEL_SPEED + moveSpeed; - cacheFlags = 0; -} - // The costumes AddCostume swaps for a second copy of their item (Brimstone and two others): the null items worn // instead. Then the Intruder's pairing with Transcendence, Eden's hairs, Sack Head's daily and Holy Grail's challenge. constexpr int COLLECTIBLE_DOUBLED_COSTUME_A = 665; @@ -1667,27 +1572,6 @@ void Entity_Player::UpdateCostumes() isUpdating = false; } -// The collectibles the frame (00782af0) and the tear parameters (007bf6c0) look at themselves, which their plain -// paths do not cover yet. -constexpr std::array FRAME_ITEMS = {375, 397, 465, 493, 497, 534, 575, 593, 619, 632, 641, 59, 202, 210, 399}; -constexpr std::array TEAR_HIT_ITEMS = { - 7, 48, 52, 59, 68, 69, 80, 89, 90, 103, 110, 118, 138, 150, 154, 155, 183, 200, 201, 213, 228, 229, 230, 231, - 237, 247, 254, 259, 261, 305, 306, 309, 315, 316, 330, 336, 359, 374, 379, 393, 395, 398, 399, 401, 418, 429, - 440, 443, 444, 453, 459, 460, 461, 462, 463, 496, 503, 529, 531, 532, 553, 561, 570, 592, 596, 606, 617, 618, - 637, 659, 708, 731}; - -// Whether the player's frame runs its plain path: a plain character holding none of the items the frame handles. -bool Entity_Player::is_frame_plain() -{ - return is_character_plain() && !is_owning_any(*this, FRAME_ITEMS) && !is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS); -} - -// Whether the player's tears take their plain parameters: a plain character holding none of the tear items. -bool Entity_Player::is_tear_hit_plain() -{ - return is_frame_plain() && !is_owning_any(*this, TEAR_HIT_ITEMS); -} - // The head costume part of 0077b020: each head costume shows the head's animation at the blink frame (or plays a // looping one, its layer stepped down a frame per blink), with its overlay animation. Costumes playing an item's own // animation keep it. An idle head animation stops the game until reached. diff --git a/src/entity_player_kills.cpp b/src/entity_player_kills.cpp new file mode 100644 index 0000000..80bbc41 --- /dev/null +++ b/src/entity_player_kills.cpp @@ -0,0 +1,241 @@ +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "game.h" +#include "item_config.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include + +constexpr int COLLECTIBLE_CHARM_OF_THE_VAMPIRE = 62; +constexpr int COLLECTIBLE_LUSTY_BLOOD = 411; +constexpr int COLLECTIBLE_JUMPER_CABLES = 520; +constexpr int COLLECTIBLE_DEATHS_LIST = 530; +constexpr int COLLECTIBLE_BERSERK_KILLS = 704; +constexpr int TRINKET_SAMSONS_LOCK = 58; +constexpr int TRINKET_EVES_BIRD_FOOT = 60; +constexpr int TRINKET_BAT_WING_KILLS = 118; +constexpr int TRINKET_SIGIL_OF_BAPHOMET = 189; +constexpr int NULLITEM_BAT_WING = 40; +constexpr int EFFECT_HEART = 49; +constexpr int SOUND_VAMP_GULP = 157; +constexpr int SOUND_VAMP_DOUBLE = 614; +constexpr int SOUND_BOOK_SHADOWS_SIGIL = 1028; + +// Charm of the Vampire heals every 13 kills, every 8 in a versus match. The heart rises 24 above the player. +constexpr int VAMPIRE_KILLS = 13; +constexpr int VAMPIRE_KILLS_VERSUS = 8; +constexpr float HEART_EFFECT_RISE = -24; +constexpr int VERSUS_LUSTY_BLOOD_EXTRA = 4; + +// Samson's Lock rolls out of 10000 and Eve's Bird Foot out of 1000, by trinket multiplier, plus luck scaled up. +constexpr int SAMSONS_LOCK_ROLL = 10000; +constexpr int SAMSONS_LOCK_ODDS = 666; +constexpr int SAMSONS_LOCK_ODDS_DOUBLE = 1300; +constexpr int SAMSONS_LOCK_ODDS_TRIPLE = 2500; +constexpr float SAMSONS_LOCK_LUCK_SCALE = 1000; +constexpr int EVES_BIRD_FOOT_ROLL = 1000; +constexpr int EVES_BIRD_FOOT_ODDS = 50; +constexpr int EVES_BIRD_FOOT_ODDS_DOUBLE = 100; +constexpr int EVES_BIRD_FOOT_ODDS_TRIPLE = 150; +constexpr float EVES_BIRD_FOOT_LUCK_SCALE = 125; + +// Bat Wing flies one kill in 20 (10 doubled, 7 tripled). +constexpr int BAT_WING_ODDS = 20; +constexpr int BAT_WING_ODDS_DOUBLE = 10; +constexpr int BAT_WING_ODDS_TRIPLE = 7; + +// Red Stew's bonus lasts 30 frames more each kill, up to 9000. +constexpr int RED_STEW_KILL_FRAMES = 30; +constexpr int RED_STEW_MAX_FRAMES = 9000; + +// Berserk lasts up to 30 frames more each gory kill (90 for Tainted Samson with his Birthright), and the kill +// destroys enemy shots within 60. +constexpr int BERSERK_KILL_FRAMES = 30; +constexpr int BERSERK_KILL_FRAMES_BIRTHRIGHT = 90; +constexpr float BERSERK_SHOT_RADIUS = 60; + +// Sigil of Baphomet grants Book of Shadows for 30 frames a kill up to 150, more for golden or stacked sigils. +constexpr int SIGIL_FRAMES = 30; +constexpr int SIGIL_FRAMES_DOUBLE = 45; +constexpr int SIGIL_FRAMES_TRIPLE = 60; +constexpr int SIGIL_MAX_FRAMES = 150; +constexpr int SIGIL_MAX_FRAMES_DOUBLE = 225; +constexpr int SIGIL_MAX_FRAMES_TRIPLE = 300; + +// The heart that rises above a player healed by a kill. +static void heart_effect_spawn(Entity_Player& player) +{ + Entity* heart = g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, + .seed = Random()}); + heart->sprite.offset = vector_make(0, HEART_EFFECT_RISE); + heart->renderDepthOffset = 1; +} + +// One chance in roll that a luck-scaled trinket procs. +// A sum below zero compares as a huge unsigned number, so the original procs every time at negative luck. Kept. +static bool is_luck_roll_won(Entity_Player& player, int odds, float luckScale, int roll) +{ + uint32_t chance = (uint32_t)(odds + (int)(player.luck * luckScale)); + return Random() % (uint32_t)roll < chance; +} + +// Samson's Lock and Eve's Bird Foot: a chance at their temporary effect. +static void luck_trinkets_update(Entity_Player& player) +{ + int lock = player.GetTrinketMultiplier(TRINKET_SAMSONS_LOCK); + if (lock > 0) + { + int odds = lock == 2 ? SAMSONS_LOCK_ODDS_DOUBLE : lock >= 3 ? SAMSONS_LOCK_ODDS_TRIPLE : SAMSONS_LOCK_ODDS; + if (is_luck_roll_won(player, odds, SAMSONS_LOCK_LUCK_SCALE, SAMSONS_LOCK_ROLL)) + player.temporaryEffects.AddTrinketEffect(TRINKET_SAMSONS_LOCK, true, 1); + } + + int foot = player.GetTrinketMultiplier(TRINKET_EVES_BIRD_FOOT); + if (foot <= 0) return; + + int odds = foot == 2 ? EVES_BIRD_FOOT_ODDS_DOUBLE : foot >= 3 ? EVES_BIRD_FOOT_ODDS_TRIPLE : EVES_BIRD_FOOT_ODDS; + if (is_luck_roll_won(player, odds, EVES_BIRD_FOOT_LUCK_SCALE, EVES_BIRD_FOOT_ROLL)) + player.temporaryEffects.AddTrinketEffect(TRINKET_EVES_BIRD_FOOT, true, 1); +} + +// Bat Wing: while it is not flying, one kill in 20 (10 doubled, 7 tripled) gives its flight and wings. +static void bat_wing_update(Entity_Player& player) +{ + int multiplier = player.GetTrinketMultiplier(TRINKET_BAT_WING_KILLS); + if (multiplier <= 0 || player.temporaryEffects.HasTrinketEffect(TRINKET_BAT_WING_KILLS)) return; + + int odds = multiplier == 2 ? BAT_WING_ODDS_DOUBLE : multiplier == 3 ? BAT_WING_ODDS_TRIPLE : BAT_WING_ODDS; + if (player.trinketRNGs[TRINKET_BAT_WING_KILLS].RandomInt(odds) != 0) return; + + player.temporaryEffects.AddTrinketEffect(TRINKET_BAT_WING_KILLS, true, 1); + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_BAT_WING), false); +} + +// Death's List: killing the marked enemy moves the mark to where it died, killing another fails the list. +static void deaths_list_update(Entity_Player& player, Entity& npc) +{ + Room& room = *g_game->room; + if (!player.HasCollectible(COLLECTIBLE_DEATHS_LIST) || room.isDeathsListDone || !room.deathsListTarget) return; + + if (&npc != room.deathsListTarget && !npc.HasEntityFlags(FLAG_FRIENDLY)) room.isDeathsListDone = true; + room.deathsListTarget = nullptr; + if (!room.isDeathsListDone) room.deathsListOffset = npc.pos; +} + +// Berserk: a gory kill lengthens it and destroys the enemy shots around the player. +static void berserk_update(Entity_Player& player, Entity& npc) +{ + TemporaryEffect* berserk = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BERSERK_KILLS); + if (!npc.HasEntityFlags(FLAG_EXTRA_GORE) || !berserk) return; + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BERSERK_KILLS); + bool isLong = player.playerType == PLAYER_SAMSON_B && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT); + TemporaryEffect added; + added.item = item; + added.cooldown = std::min(item->maxCooldown - berserk->cooldown, + isLong ? BERSERK_KILL_FRAMES_BIRTHRIGHT : BERSERK_KILL_FRAMES); + player.temporaryEffects.AddEffect(added, false, 1); + + for (Entity* shot : entity_query_radius(player.pos, BERSERK_SHOT_RADIUS, QUERY_PROJECTILES)) + { + bool isStoppable = !(static_cast(shot)->projectileFlags & PROJECTILE_CANT_BE_STOPPED); + if (shot->type == ENTITY_PROJECTILE && !shot->isDead && isStoppable) shot->isDead = true; + } +} + +// Sigil of Baphomet: each kill grants Book of Shadows for a while, up to a cap. A fresh shield plays its sound. +static void sigil_update(Entity_Player& player) +{ + int multiplier = player.GetTrinketMultiplier(TRINKET_SIGIL_OF_BAPHOMET); + if (multiplier <= 0) return; + + int frames = multiplier == 2 ? SIGIL_FRAMES_DOUBLE : multiplier == 3 ? SIGIL_FRAMES_TRIPLE : SIGIL_FRAMES; + int maxFrames = multiplier == 2 ? SIGIL_MAX_FRAMES_DOUBLE + : multiplier == 3 ? SIGIL_MAX_FRAMES_TRIPLE + : SIGIL_MAX_FRAMES; + TemporaryEffect* shadows = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BOOK_OF_SHADOWS); + if (shadows && shadows->cooldown >= maxFrames) return; + + TemporaryEffect added; + added.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BOOK_OF_SHADOWS); + added.cooldown = shadows ? std::min(frames, maxFrames - shadows->cooldown) : frames; + if (!shadows) + { + sound_play(SOUND_BOOK_SHADOWS_SIGIL); + added.unknown = 1; + } + player.temporaryEffects.AddEffect(added, true, 1); +} + +// The kill rewards that need a rewarded kill: Gamekid's healing, Lusty Blood, the luck trinkets, Charm of the Vampire, +// Jumper Cables, Bat Wing, the score of a room's first visit, and Death's List. +static void kill_rewards_trigger(Entity_Player& player, Entity& npc, Entity_NPC* killedNpc) +{ + Game& game = *g_game; + TemporaryEffects& effects = player.temporaryEffects; + + bool isGamekidFrame = !game.IsPaused() && (game.frameCount & 1) == 0; + if (effects.HasCollectibleEffect(COLLECTIBLE_GAMEKID) && !player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && + isGamekidFrame) + player.AddHearts(1, false, false); + + if (player.HasCollectible(COLLECTIBLE_LUSTY_BLOOD)) + { + effects.AddCollectibleEffect(COLLECTIBLE_LUSTY_BLOOD, false, 1); + if (npc.type == ENTITY_PLAYER && game.deathmatchManager.is_active()) + for (int i = 0; i < VERSUS_LUSTY_BLOOD_EXTRA; i++) + effects.AddCollectibleEffect(COLLECTIBLE_LUSTY_BLOOD, false, 1); + } + + luck_trinkets_update(player); + player.trigger_vampire_charm_kill(); + if (player.HasCollectible(COLLECTIBLE_JUMPER_CABLES)) + reconstruction_missing("Entity_Player::trigger_npc_death 007a0080: Jumper Cables' kill counter (+0x160c, which " + "Entity_Player has no field for)"); + bat_wing_update(player); + + if (game.room->isFirstVisit && killedNpc && killedNpc->spawnGridIndex >= 0 && &player == game.GetPlayer(0)) + game.scoreSheet.AddKilledEnemy(*killedNpc); + deaths_list_update(player, npc); +} + +// 007a0080 Reacts to an NPC's death: the kill's item rewards (unless the kill gives none), Red Stew and Berserk, the +// TMTRAINER kill triggers, Sigil of Baphomet, and the bestiary's kill count. +void Entity_Player::trigger_npc_death(Entity* npc) +{ + Entity_NPC* killedNpc = dynamic_cast(npc); + + if (!npc->HasEntityFlags(FLAG_NO_REWARD)) kill_rewards_trigger(*this, *npc, killedNpc); + if (redStewBonusDuration > 0) + { + temporaryEffects.isEvaluateCachePending = true; + temporaryEffects.cacheFlags |= CACHE_DAMAGE; + redStewBonusDuration = std::min(redStewBonusDuration + RED_STEW_KILL_FRAMES, RED_STEW_MAX_FRAMES); + } + berserk_update(*this, *npc); + + if (!proceduralItems.empty()) + reconstruction_missing("Entity_Player::trigger_npc_death 007a0080: the TMTRAINER kill triggers " + "(trigger_set_dispatch 009e0680)"); + sigil_update(*this); + + if (killedNpc) g_manager->persistentGameData.AddBestiaryKill(killedNpc->type, killedNpc->variant); +} + +// 007d3350 Charm of the Vampire: every 13 kills (8 in a versus match) heals a heart with a gulp, a double gulp for +// Tainted Magdalene. +void Entity_Player::trigger_vampire_charm_kill() +{ + int kills = g_game->deathmatchManager.is_active() ? VAMPIRE_KILLS_VERSUS : VAMPIRE_KILLS; + if (!HasCollectible(COLLECTIBLE_CHARM_OF_THE_VAMPIRE)) return; + if ((int)++vampireCharmKills < kills || isDead) return; + + sound_play(playerType == PLAYER_MAGDALENE_B ? SOUND_VAMP_DOUBLE : SOUND_VAMP_GULP); + AddHearts(1, true, false); + vampireCharmKills -= kills; + heart_effect_spawn(*this); +} diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 9d6f48f..42ed81f 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -5,10 +5,6 @@ bool Entity_Player::TryThrow(const EntityRef&, const Vector&, float) { reconstruction_missing("Entity_Player::TryThrow 007d2930"); } -void Entity_Player::AddActiveCharge(int, int, bool, bool, bool) -{ - reconstruction_missing("Entity_Player::AddActiveCharge 007915a0"); -} void Entity_Player::RemoveCollectible(int, bool, int, bool) { reconstruction_missing("Entity_Player::RemoveCollectible 0078f840"); @@ -17,21 +13,14 @@ Entity_Familiar* Entity_Player::AddWisp(int, Vector, bool, bool) { reconstruction_missing("Entity_Player::AddWisp 005c93b0"); } -void Entity_Player::UseActiveItem(int, uint32_t, int) -{ - reconstruction_missing("Entity_Player::UseActiveItem 005b39d0"); -} void Entity_Player::trigger_collectible_effect_removed(ItemConfig_Item*, int) { reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970"); } -int Entity_Player::GetBatteryCharge(int) { reconstruction_missing("Entity_Player::GetBatteryCharge 0042a2f0"); } void Entity_Player::SetMinDamageCooldown(int) { reconstruction_missing("Entity_Player::SetMinDamageCooldown 004361d0"); } -int Entity_Player::GetActiveItem(int) { reconstruction_missing("Entity_Player::GetActiveItem 00505c80"); } -bool Entity_Player::AreControlsEnabled() { reconstruction_missing("Entity_Player::AreControlsEnabled 00505cc0"); } void Entity_Player::StopExtraAnimation() { reconstruction_missing("Entity_Player::StopExtraAnimation 0058e230"); } void Entity_Player::moms_bracelet_grab() { reconstruction_missing("Entity_Player::moms_bracelet_grab 005b1a20"); } void Entity_Player::UseRedKey() { reconstruction_missing("Entity_Player::UseRedKey 005b2360"); } @@ -44,19 +33,7 @@ Entity_Familiar* Entity_Player::AddItemWisp(int, Vector, bool) { reconstruction_missing("Entity_Player::AddItemWisp 005c96f0"); } -void Entity_Player::trigger_book_of_belial_passive(int, int) -{ - reconstruction_missing("Entity_Player::trigger_book_of_belial_passive 005c9930"); -} -void Entity_Player::TriggerBookOfVirtues(int, int) -{ - reconstruction_missing("Entity_Player::TriggerBookOfVirtues 005ca470"); -} void Entity_Player::console_spawn(int*, bool) { reconstruction_missing("Entity_Player::console_spawn 005caa70"); } -void Entity_Player::update_mini_mush_costume() -{ - reconstruction_missing("Entity_Player::update_mini_mush_costume 005cb480"); -} void Entity_Player::ResetDamageCooldown() { reconstruction_missing("Entity_Player::ResetDamageCooldown 0060d090"); } Vector Entity_Player::SpriteScale() { reconstruction_missing("Entity_Player::SpriteScale 0060d0a0"); } bool Entity_Player::IsP2Appearing() { reconstruction_missing("Entity_Player::IsP2Appearing 0065cf60"); } @@ -134,12 +111,6 @@ bool Entity_Player::TryRemoveSmeltedTrinket(uint32_t) } bool Entity_Player::replace_trinket() { reconstruction_missing("Entity_Player::replace_trinket 00772530"); } void Entity_Player::SetFullHearts() { reconstruction_missing("Entity_Player::SetFullHearts 007791f0"); } -TearFlags Entity_Player::GetBombFlags(bool) { reconstruction_missing("Entity_Player::GetBombFlags 00780560"); } -TearFlags Entity_Player::check_bomb_tearflags(const TearFlags&) -{ - reconstruction_missing("Entity_Player::check_bomb_tearflags 00780ec0"); -} -void Entity_Player::update_bomb_input() { reconstruction_missing("Entity_Player::update_bomb_input 00780f40"); } uint32_t Entity_Player::CanTurnHead() { reconstruction_missing("Entity_Player::CanTurnHead 00782a60"); } void Entity_Player::RemoveCollectibleByHistoryIndex(int, bool) { @@ -149,19 +120,8 @@ void Entity_Player::TriggerCollectibleRemoved(int) { reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90"); } -int Entity_Player::GetTotalActiveCharge(int) { reconstruction_missing("Entity_Player::GetTotalActiveCharge 007910f0"); } -int Entity_Player::GetCollectibleMaxCharge(int, int) -{ - reconstruction_missing("Entity_Player::GetCollectibleMaxCharge 007911f0"); -} -int Entity_Player::GetActiveMaxCharge(int) { reconstruction_missing("Entity_Player::GetActiveMaxCharge 00791320"); } -void Entity_Player::SetActiveCharge(int, int) { reconstruction_missing("Entity_Player::SetActiveCharge 00791420"); } -void Entity_Player::SetActiveVarData(int, int) { reconstruction_missing("Entity_Player::SetActiveVarData 00791510"); } -void Entity_Player::ControlActiveItem(int) { reconstruction_missing("Entity_Player::ControlActiveItem 00791a40"); } -bool Entity_Player::HasTimedItem() { reconstruction_missing("Entity_Player::HasTimedItem 00793940"); } void Entity_Player::update_effects() { reconstruction_missing("Entity_Player::update_effects 00794e50"); } void Entity_Player::update_ladder() { reconstruction_missing("Entity_Player::update_ladder 0079f3c0"); } -void Entity_Player::trigger_npc_death(Entity*) { reconstruction_missing("Entity_Player::trigger_npc_death 007a0080"); } Entity_Bomb* Entity_Player::FireBomb(Vector, Vector, Entity*) { reconstruction_missing("Entity_Player::FireBomb 007a0970"); @@ -181,9 +141,7 @@ void Entity_Player::pockets_rotate() { reconstruction_missing("Entity_Player::po void Entity_Player::SwapActiveItems() { reconstruction_missing("Entity_Player::SwapActiveItems 007a4760"); } void Entity_Player::RemovePocketItem(int) { reconstruction_missing("Entity_Player::RemovePocketItem 007a4850"); } void Entity_Player::DropPocketItem(int, Vector) { reconstruction_missing("Entity_Player::DropPocketItem 007a48f0"); } -void Entity_Player::ShootCandle(Vector) { reconstruction_missing("Entity_Player::ShootCandle 007a6300"); } int Entity_Player::GetTrinket(uint32_t) { reconstruction_missing("Entity_Player::GetTrinket 007a6430"); } -void Entity_Player::TriggerRoomClear() { reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0"); } void Entity_Player::AnimateCollectible(int, std::string_view, std::string_view) { reconstruction_missing("Entity_Player::AnimateCollectible 007ab380"); @@ -209,14 +167,6 @@ void Entity_Player::AnimateTeleport(bool) { reconstruction_missing("Entity_Playe void Entity_Player::AnimateHappy() { reconstruction_missing("Entity_Player::AnimateHappy 007abd30"); } void Entity_Player::AnimateSad() { reconstruction_missing("Entity_Player::AnimateSad 007abd90"); } void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } -void Entity_Player::active_used_post(int, bool, int) -{ - reconstruction_missing("Entity_Player::active_used_post 007abf80"); -} -void Entity_Player::DischargeActiveItem(uint32_t, bool) -{ - reconstruction_missing("Entity_Player::DischargeActiveItem 007ac7e0"); -} void Entity_Player::TryRemoveTrinketCostume(int) { reconstruction_missing("Entity_Player::TryRemoveTrinketCostume 007ad3a0"); @@ -241,11 +191,6 @@ void Entity_Player::TriggerTrinketRemoved(uint32_t) { reconstruction_missing("Entity_Player::TriggerTrinketRemoved 007adb30"); } -void Entity_Player::RestoreGameState(GameStatePlayer*) -{ - reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0"); -} -void Entity_Player::spawn_dark_esau(void*) { reconstruction_missing("Entity_Player::spawn_dark_esau 007b0070"); } void Entity_Player::DonateLuck(int) { reconstruction_missing("Entity_Player::DonateLuck 007b2200"); } void Entity_Player::UseCard(int, uint32_t) { reconstruction_missing("Entity_Player::UseCard 007b2230"); } void Entity_Player::update_footprints() { reconstruction_missing("Entity_Player::update_footprints 007b8cb0"); } @@ -290,8 +235,6 @@ bool Entity_Player::CanPickSoulHearts() { reconstruction_missing("Entity_Player: bool Entity_Player::CanPickBlackHearts() { reconstruction_missing("Entity_Player::CanPickBlackHearts 007c3550"); } void Entity_Player::RemoveSkinCostume() { reconstruction_missing("Entity_Player::RemoveSkinCostume 007c3620"); } void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Player::SetShootingCooldown 007c37f0"); } -bool Entity_Player::NeedsCharge(int) { reconstruction_missing("Entity_Player::NeedsCharge 007c3810"); } -bool Entity_Player::FullCharge(int, bool, bool) { reconstruction_missing("Entity_Player::FullCharge 007c38c0"); } void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } bool Entity_Player::CanUsePill(int) { reconstruction_missing("Entity_Player::CanUsePill 007c40e0"); } void Entity_Player::UsePill(int, int, uint32_t) { reconstruction_missing("Entity_Player::UsePill 007c4180"); } @@ -389,10 +332,6 @@ int Entity_Player::GetEffectiveBloodCharge() } void Entity_Player::AddRottenHearts(int, bool) { reconstruction_missing("Entity_Player::AddRottenHearts 007d2fc0"); } bool Entity_Player::CanPickRottenHearts() { reconstruction_missing("Entity_Player::CanPickRottenHearts 007d3180"); } -void Entity_Player::trigger_vampire_charm_kill() -{ - reconstruction_missing("Entity_Player::trigger_vampire_charm_kill 007d3350"); -} void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Player::AddUrnSouls 007d3480"); } void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::AddGigaBombs 007d34f0"); } void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } @@ -462,7 +401,6 @@ void Entity_Player::twins_duplicate_familiars(int) } const std::string& Entity_Player::GetName() { reconstruction_missing("Entity_Player::GetName 007e9280"); } void Entity_Player::TriggerRoomExit() { reconstruction_missing("Entity_Player::TriggerRoomExit 00832850"); } -int Entity_Player::GetActiveSubCharge(int) { reconstruction_missing("Entity_Player::GetActiveSubCharge 00841cb0"); } int Entity_Player::GetPoopSpell(int) { reconstruction_missing("Entity_Player::GetPoopSpell 00841cd0"); } bool Entity_Player::HasFullHeartsAndSoulHearts() { diff --git a/src/entity_tear.h b/src/entity_tear.h index 33d3297..7934890 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -9,34 +9,72 @@ enum TearFlagBit : int { TEAR_SPECTRAL = 0, TEAR_PIERCING = 1, - TEAR_PERSISTENT = 9, - TEAR_BOUNCE = 19, - TEAR_STICKY = 37, - TEAR_BOOGER_FLAG = 48, - TEAR_BELIAL_FLAG = 52, - TEAR_ORBIT_ADVANCED = 69, - TEAR_ROCK_FLAG = 70, - TEAR_SPORE_FLAG = 77, - TEAR_TELEPORT = 81, - TEAR_THROUGH_COOLDOWN = 100, - TEAR_NO_GRID_DAMAGE = 105, - TEAR_FETUS_FLAG = 114, - TEAR_CHAIN = 123, + TEAR_HOMING = 2, + TEAR_POISON = 4, + TEAR_SPLIT = 6, TEAR_GROW = 7, + TEAR_BOOMERANG = 8, + TEAR_PERSISTENT = 9, + TEAR_WIGGLE = 10, TEAR_EXPLOSIVE = 12, + TEAR_ORBIT = 16, TEAR_WAIT = 17, TEAR_QUADSPLIT = 18, + TEAR_BOUNCE = 19, + TEAR_SHRINK = 21, TEAR_BURN = 22, + TEAR_ATTRACTOR = 23, + TEAR_KNOCKBACK = 24, + TEAR_PULSE = 25, + TEAR_SPIRAL = 26, + TEAR_FLAT = 27, + TEAR_SAD_BOMB = 28, + TEAR_BUTT_BOMB = 29, + TEAR_SQUARE = 30, TEAR_GLOW = 31, TEAR_MYSTERIOUS_LIQUID_CREEP = 33, TEAR_SHIELDED = 34, + TEAR_GLITTER_BOMB = 35, + TEAR_SCATTER_BOMB = 36, + TEAR_STICKY = 37, + TEAR_CONTINUUM = 38, TEAR_LIGHT_FROM_HEAVEN = 39, TEAR_TRACTOR_BEAM = 42, + TEAR_CROSS_BOMB = 45, + TEAR_BIG_SPIRAL = 46, + TEAR_BOOGER_FLAG = 48, + TEAR_EGG_FLAG = 49, + TEAR_BONE_FLAG = 51, + TEAR_BELIAL_FLAG = 52, TEAR_JACOBS = 55, TEAR_HORN = 56, + TEAR_LASER = 57, TEAR_POP = 58, + TEAR_ABSORB = 59, + TEAR_LASERSHOT = 60, + TEAR_HYDROBOUNCE = 61, + TEAR_CREEP_TRAIL = 63, + TEAR_ICE_FLAG = 65, + TEAR_OCCULT = 68, + TEAR_ORBIT_ADVANCED = 69, + TEAR_ROCK_FLAG = 70, + TEAR_TURN_HORIZONTAL = 71, + TEAR_BLOOD_BOMB = 72, + TEAR_BRIMSTONE_BOMB = 75, TEAR_RIFT = 76, + TEAR_SPORE_FLAG = 77, + TEAR_GHOST_BOMB = 78, + TEAR_TELEPORT = 81, + TEAR_THROUGH_COOLDOWN = 100, + TEAR_NO_GRID_DAMAGE = 105, + TEAR_BACKSTAB = 106, + TEAR_FETUS_FLAG = 114, + TEAR_GIGA_BOMB = 119, + TEAR_RAINBOW = 121, + TEAR_CHAIN = 123, TEAR_DARK_MATTER_FLAG = 124, + TEAR_GOLDEN_BOMB = 125, + TEAR_FAST_BOMB = 126, TEAR_LUDOVICO = 127 }; diff --git a/src/game.cpp b/src/game.cpp index 6ca02e2..7e57006 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -579,8 +579,6 @@ constexpr float OLD_TV_TIME_SCALE = 0.05f; constexpr float ASCENT_FADE_FRAMES = 90; constexpr uint32_t DEBUG_FLAG_PLAYER_INFO = 1 << 11; constexpr uint32_t DEBUG_FLAG_LUA_MEMORY = 1 << 13; -constexpr int STAGE_TRANSITION_OUT = 2; -constexpr int STAGE_TRANSITION_IN = 3; constexpr int ITEM_OVERLAY_SHOWING = 1; constexpr float PI = std::numbers::pi_v; @@ -630,9 +628,8 @@ static void screen_size_set(const KAGE::Graphics::ImageBase& surface) // A stage transition decides with StageTransition's own check (009301d0), which waits for its takeover. static bool is_pixelating(Game& game) { - int stageState = game.stageTransition._state; - if (stageState == STAGE_TRANSITION_OUT || stageState == STAGE_TRANSITION_IN) - reconstruction_missing("Game::Render 006fbc10: StageTransition's pixelation check 009301d0"); + int stageState = game.stageTransition.state; + if (stageState == STAGE_TRANSITION_OUT || stageState == STAGE_TRANSITION_IN) return game.stageTransition.is_pixelated(); return game.roomTransition.get_fade_progress() >= 0 && game.roomTransition.animation == TRANSITION_PIXELATION; } @@ -730,7 +727,7 @@ static void overlays_render(Game& game) KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; PopupQueue& popups = g_manager->popupQueue; bool isFighting = game.deathmatchManager.state == DEATHMATCH_FIGHT; - int stageState = game.stageTransition._state; + int stageState = game.stageTransition.state; popups.render_layer(0); game.hud.Render(); @@ -879,7 +876,7 @@ bool Game::IsPaused() if (console.state != CONSOLE_CLOSED && isOffline) return true; return freezeFrames > 0 || gameOver.state != GAME_OVER_HIDDEN || leaderboard.displayState != LEADERBOARD_HIDDEN || - stageTransition._state != 0 || roomTransition.mode != 0 || itemOverlay._state == ITEM_OVERLAY_ACTIVE || + stageTransition.state != 0 || roomTransition.mode != 0 || itemOverlay._state == ITEM_OVERLAY_ACTIVE || (pauseScreen.is_pausing() && isOffline) || g_manager->state != MANAGER_STATE_GAME || genericPrompt.IsActive() || onlineStatsScreen.isActive; } diff --git a/src/game.h b/src/game.h index 80d9490..7eec5b3 100644 --- a/src/game.h +++ b/src/game.h @@ -24,6 +24,7 @@ #include "revive_player_menu.h" #include "room_config.h" #include "room_transition.h" +#include "stage_transition.h" #include "score_sheet.h" #include "seeds.h" #include @@ -147,6 +148,13 @@ enum FadeOutTarget : int FADEOUT_TARGET_COUNT }; +// Whether restore_game_state continues a saved run, starting its players and pools anew, or rewinds the running one. +enum GameRestore +{ + RESTORE_REWIND, + RESTORE_CONTINUE +}; + // Whether a fade in shows the loading icon. enum FadeIcon { @@ -305,6 +313,7 @@ public: void StartRoomTransition(RoomTransitionRequest request); void Fadeout(float speed, FadeOutTarget target, KColor color = kcolor_rgba(0, 0, 0, 1)); void store_game_state(GameState& state); + void restore_game_state(GameState& state, GameRestore restore); static void Exit(bool isSaving); void Update(); void interpolate_update(); diff --git a/src/game_restore.cpp b/src/game_restore.cpp new file mode 100644 index 0000000..772bb95 --- /dev/null +++ b/src/game_restore.cpp @@ -0,0 +1,756 @@ +#include "entity_familiar.h" +#include "entity_npc.h" +#include "game.h" +#include "game_state_player.h" +#include "log.h" +#include "manager.h" +#include "room.h" +#include "texture_cache.h" +#include +#include +#include +#include +#include + +constexpr uint32_t ROOM_REF_MERGED = 0x80000000; +constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000; +constexpr uint32_t ROOM_REF_STAGE_MASK = 0xffff; +constexpr uint32_t ROOM_REF_HALF_MASK = 0xffff; +constexpr int ROOM_REF_MODE_SHIFT = 16; +constexpr int ROOM_REF_HALF_SHIFT = 16; +constexpr uint32_t ROOM_REF_MODE_MASK = 0xff; + +constexpr uint32_t PLAYER_RNG_SHIFT = 34; +constexpr uint32_t FORTUNE_RNG_SHIFT = 35; +constexpr uint32_t ITEM_RNG_SHIFT = 35; +constexpr uint32_t GLITCH_BABY_SHIFT = 35; +constexpr uint32_t ITEM_POOL_SHIFT = 3; +constexpr uint32_t TRINKET_POOL_SHIFT = 2; +constexpr uint32_t DEVIL_ANGEL_SHIFT = 2; +constexpr uint8_t HOLY_MANTLE_SAVED = 2; +constexpr const char* ITEM_POOLS_XML = "itempools.xml"; +constexpr uint32_t STAGE_CAVES_I = 3; +constexpr uint32_t STAGE_CAVES_II = 4; +constexpr uint32_t STAGE_DEPTHS_II = 6; +constexpr uint32_t STAGE_DARK_ROOM = 11; +constexpr int DIMENSION_ALTERNATE = 1; +constexpr int LEVEL_STATE_MINESHAFT_ESCAPE = 22; +constexpr int MINI_MUSH_STACKS_SECOND = 4; +constexpr int MINI_MUSH_STACKS_THIRD = 7; +constexpr int NULLITEM_WAVY_CAP_1 = 71; +constexpr int NULLITEM_WAVY_CAP_2 = 72; +constexpr int NULLITEM_WAVY_CAP_3 = 73; +constexpr int COLLECTIBLE_WAVY_CAP = 582; +constexpr double WAVY_CAP_STACKS_PER_DIZZINESS = 10; +constexpr float WAVY_CAP_DIZZINESS_SPEED = 0.001f; +constexpr uint32_t ALL_CACHE_FLAGS = 0xffff; +constexpr std::array, 4> TWIN_PLAYER_TYPES = { + {{PLAYER_JACOB, PLAYER_ESAU}, + {PLAYER_LAZARUS_B, PLAYER_LAZARUS2_B}, + {PLAYER_THEFORGOTTEN_B, PLAYER_THESOUL_B}, + {PLAYER_LAZARUS2_B, PLAYER_LAZARUS_B}}}; + +// 007474a0 The room config a saved run names: a stage's room by type and variant (a generated mirror of it when +// mirrored), or for a merged room its two halves joined again from the merged configs (second half first). +// A merged room without the list, or a config of type 0, is none. A room the configs lack is none, where the original +// mirrors it anyway. +RoomConfig_Room* room_config_ref_load(const RoomConfigRef& ref, const std::vector* mergedConfigs) +{ + RoomConfig& configs = g_game->roomConfig; + + if (ref.packed == ROOM_REF_MERGED) + { + if (!mergedConfigs) return nullptr; + + // The half at an index of the merged configs. + auto half_load = [&](uint32_t index) + { + const std::vector& halves = *mergedConfigs; + return index < halves.size() ? room_config_ref_load(halves[index], mergedConfigs) : nullptr; + }; + RoomConfig_Room* second = half_load(ref.variant >> ROOM_REF_HALF_SHIFT & ROOM_REF_HALF_MASK); + RoomConfig_Room* first = half_load(ref.variant & ROOM_REF_HALF_MASK); + return first && second ? configs.MergeRoomsIntoGenerated(*first, *second, (RoomShape)ref.type) : nullptr; + } + if (ref.type == 0) return nullptr; + + RoomMode mode = (RoomMode)(ref.packed >> ROOM_REF_MODE_SHIFT & ROOM_REF_MODE_MASK); + RoomConfig_Room* room = configs.GetRoomByStageTypeAndVariant(ref.packed & ROOM_REF_STAGE_MASK, (int)ref.type, + (int)ref.variant, mode); + if (!room || !(ref.packed & ROOM_REF_MIRRORED)) return room; + return configs.mirrored_room_make(*room); +} + +// 006f8140 Rebuilds the run from a game state: its rules, counters and histories, then (continuing a saved run rather +// than rewinding) the first player, the pools, the fortune generator and whether achievements may unlock. The +// generators, pools, TMTRAINER items, the Ascent's stages, the versus rules, the players, the floor with the room the +// players are in, the nightmare stage bar, the ambush, the score and each player's Wavy Cap costume follow. +// Netplay is offline. The versus rules keep no players offline. +void Game::restore_game_state(GameState& state, GameRestore restore) +{ + Manager& manager = *g_manager; + uint64_t savedFlagsMask = (1ull << SAVED_GAME_STATE_FLAG_COUNT) - 1; + + seedEffects = state.seeds; + challenge = (uint32_t)state.challenge; + isConsoleUsedThisRun = state.isConsoleUsedThisRun || manager.isConsoleEnabled; + difficulty = (Difficulty)state.difficulty; + gameStateFlags = (gameStateFlags & ~savedFlagsMask) | state.gameStateFlags.to_ullong(); + + lastDevilRoomStage = state.lastDevilRoomStage; + treasureRoomsVisited = state.treasureRoomsVisited; + planetariumsVisited = state.planetariumsVisited; + stagesWithoutHeartsPicked = state.stagesWithoutHeartsPicked; + stagesWithoutDamage = state.stagesWithoutDamage; + devilRoomDeals = state.devilRoomDeals; + shopVisits = state.shopVisits; + donationModGreed = state.donationModGreed; + donationModAngel = state.donationModAngel; + reviveMachineCoinsLeft = state.reviveMachineCoinsLeft; + reviveMachineUses = state.reviveMachineUses; + bossRushParTime = state.bossRushParTime; + blueWombParTime = state.blueWombParTime; + frameCount = state.frameCount; + timeCounter = state.timeCounter; + stageNameNumeral = state.stageNameNumeral; + victoryLap = state.victoryLap; + lastLevelWithoutHalfHp = state.lastLevelWithoutHalfHp; + isRerun = state.isRerun; + lastLevelWithDamage = state.lastLevelWithDamage; + encounteredBosses = state.encounteredBosses; + magicSkinUses = state.magicSkinUses; + erasedEntities = state.erasedEntities; + pixelationTimer = state.pixelationTimer; + pixelationDuration = state.pixelationDuration; + + if (restore == RESTORE_CONTINUE) + { + proceduralItemManager.Init(); + int playerType = state.players.empty() ? state.playerType : state.players[0].playerType; + seedEffects.GetStartSeed(); + playerManager.init_main_player(playerType, seedEffects.playerInitSeed); + itemPool.Init(state.itemPool.seed, manager.modManager.TryRedirectPath(ITEM_POOLS_XML)); + bossPool.init(seedEffects.GetStartSeed()); + fortuneRNG.SetSeed(state.fortuneSeed, FORTUNE_RNG_SHIFT); + + uint32_t startSeed = seedEffects.GetStartSeed(); + std::string seedText = Seeds::Seed2String(seedEffects.GetStartSeed()); + log_printf(LOG_INFO, "RNG Start Seed: %s (%u) [Continue, %d]\n", seedText.c_str(), startSeed, + manager.currentSaveSlot); + bool isReadOnly = seedEffects.isCustomRun || seedEffects.AchievementUnlocksDisallowed() || + Manager::AchievementUnlocksDisallowed() || isRerun || victoryLap > 0; + if (!manager.isNetworkPlay) manager.persistentGameData.SetReadOnly(isReadOnly); + } + + playerManager.rng.SetSeed(state.playerManagerSeed, PLAYER_RNG_SHIFT); + fortuneRNG.SetSeed(state.fortuneSeed, FORTUNE_RNG_SHIFT); + itemPool.RestoreGameState(state.itemPool); + bossPool.restore_game_state(state.bossPool); + proceduralItemManager.items_restore(state.proceduralItemSeeds); + ascentTimer = state.isAscent ? 1 : 0; + backwardsStages = state.backwardsStages; + deathCertificateExitTimer = (int16_t)state.deathCertificateExitTimer; + + deathmatchManager.state = DEATHMATCH_OFF; + deathmatchManager.timer = 0; + deathmatchManager.set_type((DeathmatchRules)state.versusRules); + + playerManager.RestoreGameState(state); + Level::RestoreGameState(state); + playerManager.RestoreGameState_PostLevelInit(state); + manager.nightmareScene.stageIcons = state.nightmareStageIcons; + ambush._isActive = state.isAmbushActive; + ambush._currentWave = state.ambushWave; + if (ambush._isActive) reconstruction_missing("Game::restore_game_state 006f8140: an ambush in progress (Ambush)"); + scoreSheet.restore_state(state.scoreSheet); + for (Entity_Player* player : playerManager.playerList) player->update_mini_mush_costume(); +} + +// 00736530 Restores the pools from a save: each pool's weights in draw order (as many as both have) and its Bible +// chance, the seeds, the collectibles removed and the trinkets still in the pool (counting those available), the +// pill colors' effects and which are identified, and the Genesis counts. +void ItemPool::RestoreGameState(const GameStateItemPool& state) +{ + for (size_t i = 0; i < pools.size(); i++) + { + std::vector& items = pools[i].poolList; + const std::vector& weights = state.poolsItemWeights[i]; + + for (size_t j = 0; j < std::min(items.size(), weights.size()); j++) items[j].weight = weights[j]; + pools[i].bibleUpgrade = state.bibleUpgrades[i]; + } + + seed = state.seed; + lastPool = state.lastPool; + itemPoolRNG.SetSeed(state.itemPoolRNGseed, ITEM_POOL_SHIFT); + trinketPoolRNG.SetSeed(state.trinketPoolRNGseed, TRINKET_POOL_SHIFT); + unkFloat674 = state.unkFloat674; + unkFloat678 = state.unkFloat678; + for (size_t i = 0; i < std::min(removedCollectibles.size(), state.removedCollectibles.size()); i++) + removedCollectibles[i] = state.removedCollectibles[i]; + for (size_t i = 0; i < std::min(trinketPoolItems.size(), state.trinketPoolItems.size()); i++) + trinketPoolItems[i].isInPool = state.trinketPoolItems[i]; + auto isDrawable = [](TrinketPoolItem& slot) { return slot.isInPool && slot.isAvailable; }; + numAvailableTrinkets = (int)std::ranges::count_if(trinketPoolItems, isDrawable); + + pillEffects = state.pillEffects; + identifiedPillEffects = state.identifiedPillEffects; + remainingGenesisItems = state.remainingGenesisItems; +} + +// 007475b0 Restores the floor from a save and enters its room: the stage, curses, flags, Greed waves and seeds, the +// maps and every room descriptor with its config named again, the rooms the players are in and came from, and the +// Ventricle Razor portals. Backasswards resumed in the uncleared boss room starts over in the first room and walks back +// in. A new stage starts for the players, the camera catches up, and the room's watch speed and slowdown come back. +// The Death Certificate's return room is not kept by the curated game state, and the mineshaft escape's Mother's shadow +// waits for its takeover. +void Level::RestoreGameState(GameState& state) +{ + Game& game = *g_game; + bool isNewLevel = false; + + if (stage != state.stage) + { + isNewLevel = !game.isRestoringGlowingHourglassState; + stage = state.stage; + } + stageType = state.stageType; + startingRoomIdx = state.startingRoomIdx; + lastBossRoomListIdx = state.lastBossRoomListIdx; + curses = state.curses; + dungeonPlacementSeed = state.dungeonPlacementSeed; + devilAngelRoomRNG.SetSeed(state.devilAngelRoomSeed, DEVIL_ANGEL_SHIFT); + angelRoomChance = state.angelRoomChance; + bombPickupsSpawned = state.bombPickupsSpawned; + isHeartPicked = state.isHeartPicked; + isDevilRoomDisabled = state.isDevilRoomDisabled; + isCanSeeEverything = state.isCanSeeEverything; + isBossChallenge = state.isBossChallenge; + uint32_t savedFlagsMask = (1u << LEVEL_STATE_FLAG_COUNT) - 1; + levelStateFlags = (levelStateFlags & ~savedFlagsMask) | (uint32_t)state.levelStateFlags.to_ulong(); + greedWaveSeeds = state.greedWaveSeeds; + greedModeTreasureRoomIdx = state.greedModeTreasureRoomIdx; + greedLastBeatenWave = state.greedLastBeatenWave; + greedModeWave = (int)std::min((uint32_t)state.greedModeWave, (uint32_t)greedLastBeatenWave); + greedLastPaidWave = state.greedLastPaidWave; + + game.seedEffects.GetStartSeed(); + generationRNG.Next(); + if (game.challenge == CHALLENGE_RED_REDEMPTION) InitStageSeeds(); + reset_room_list(false); + roomMap = state.roomMap; + game.roomConfig.ClearGeneratedRooms(); + nbRooms = state.roomCount; + for (size_t i = 0; i < std::min(roomList.size(), state.rooms.size()); i++) + { + roomList[i] = state.rooms[i].desc; + roomList[i].data = room_config_ref_load(state.rooms[i].config, &state.mergedRoomConfigs); + } + + currentRoomIdx = state.currentRoomIdx; + currentDimensionIdx = state.currentDimensionIdx; + currentRoomMap = roomMap.data() + currentDimensionIdx * LEVEL_GRID_CELLS; + lastRoomDimensionIdx = state.lastRoomDimensionIdx; + lastRoomIdx = state.lastRoomIdx; + dungeonReturnPosition = state.dungeonReturnPosition; + dungeonReturnRoomIndex = state.dungeonReturnRoomIndex; + enterDoor = state.enterDoor; + ventricleRazorPortals = state.ventricleRazorPortals; + + int bossCell = game.roomList[game.lastBossRoomListIdx].gridIndex; + bool isBackasswardsBoss = game.challenge == CHALLENGE_BACKASSWARDS && stage != STAGE_DARK_ROOM && + currentRoomIdx == bossCell && + !(GetRoomByIdx(currentRoomIdx)->flags & ROOM_DESCRIPTOR_FLAG_CLEAR); + if (isBackasswardsBoss) + { + for (Entity_Player* player : game.playerManager.playerList) + { + player->isPlayingExtraAnimation = false; + player->isPlayingItemAnimation = false; + } + lastRoomIdx = currentRoomIdx = startingRoomIdx; + leaveDoor = -1; + load_room(); + game.roomTransition.start({.animation = TRANSITION_BOSS_FORCED, .roomIndex = bossCell}); + game.roomTransition.Update(); + GetRoomByIdx(startingRoomIdx)->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; + UpdateVisibility(); + } + else + { + load_room(); + room->PlayMusic(); + for (MinimapConfig& map : game.minimap.configs) map.refresh(); + if (game.hud.hudRefreshType != HUD_REFRESH_FULL) + { + game.hud.hudRefreshType = HUD_REFRESH_PLAYER; + game.hud.hudRefreshCountdown = 2; + } + } + if (isNewLevel) game.playerManager.trigger_level_start(); + + bool isBackwards = stage >= 1 && stage <= STAGE_DEPTHS_II && game.GetStateFlag(GAME_STATE_BACKWARDS_PATH); + bool isMinesFloor = stage == STAGE_CAVES_II || (stage == STAGE_CAVES_I && (GetCurses() & CURSE_OF_LABYRINTH)); + bool isMineshaftEscape = currentDimensionIdx == DIMENSION_ALTERNATE && !game.IsGreedMode() && !isBackwards && + (stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B) && + isMinesFloor && (levelStateFlags & 1u << LEVEL_STATE_MINESHAFT_ESCAPE); + if (isMineshaftEscape) + reconstruction_missing("Level::RestoreGameState 007475b0: the mineshaft escape's Mother's shadow"); + + room->camera->DoUpdate(false); + room->brokenWatchState = (BrokenWatchState)(int8_t)state.brokenWatchState; + g_manager->musicManager.targetPitch = room->time_scale_update(); + room->slowdownDuration = std::max(room->slowdownDuration, state.slowdownDuration); + TextureCache::Purge(); +} + +// 009bc790 The players a save's players are restored into, by save index: each saved main player matched to the first +// room player of its controller. Spawning, the room players left unmatched are removed (the last first) and each saved +// main player still without one gets a new co-op player of its character. A backup player matches none. +std::vector PlayerManager::match_saved_players(GameState& state, PlayerMatch match) +{ + std::vector matched(state.players.size(), nullptr); + std::vector unmatched; + + for (Entity_Player* player : playerList) + if (player->variant == PLAYER_VARIANT_PLAYER) unmatched.push_back(player); + for (size_t i = 0; i < state.players.size(); i++) + { + if (state.players[i].isBackupPlayer) continue; + + auto found = std::ranges::find(unmatched, state.players[i].controllerIndex, &Entity_Player::controllerIndex); + if (found == unmatched.end()) continue; + matched[i] = *found; + unmatched.erase(found); + } + if (match == MATCH_FIND) return matched; + + for (Entity_Player* player : std::views::reverse(unmatched)) RemoveCoPlayer(player); + for (size_t i = 0; i < state.players.size(); i++) + if (!state.players[i].isBackupPlayer && !matched[i]) matched[i] = SpawnCoPlayer2(state.players[i].playerType); + return matched; +} + +// Ties a restored player to the later saved players of its twin character on its controller, both ways. +static void twins_link(std::vector& matched, size_t index) +{ + Entity_Player& player = *matched[index]; + auto twin = std::ranges::find(TWIN_PLAYER_TYPES, player.playerType, &std::pair::first); + if (twin == TWIN_PLAYER_TYPES.end()) return; + + for (size_t i = index + 1; i < matched.size(); i++) + { + Entity_Player* other = matched[i]; + if (!other || other->playerType != twin->second) continue; + if (other->controllerIndex != player.controllerIndex || other->twinPlayer.get()) continue; + player.twinPlayer = other; + other->twinPlayer = &player; + } +} + +// 009bcaa0 Restores the saved players: each matched player from its save (its twin forgotten first), then the twins, +// the parents, the backup players and the Esau Jr. players, the glitched baby generator and random babies from the +// first saved player, the join seats and the HUDs. +void PlayerManager::RestoreGameState(GameState& state) +{ + std::vector matched = match_saved_players(state, MATCH_SPAWN); + + for (size_t i = 0; i < matched.size(); i++) + { + if (!matched[i]) continue; + matched[i]->twinPlayer = nullptr; + matched[i]->RestoreGameState(state.players[i]); + } + for (size_t i = 0; i < matched.size(); i++) + { + GameStatePlayer& saved = state.players[i]; + int parentIndex = saved.parentIndex; + + if (saved.isBackupPlayer && i > 0 && matched[i - 1]) + reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0: a backup player (Tainted Lazarus)"); + else if (saved.isBackupPlayer || !matched[i]) continue; + else if (parentIndex < 0) twins_link(matched, i); + else if ((size_t)parentIndex < matched.size() && matched[parentIndex]) + matched[i]->parent = matched[parentIndex]; + } + + for (size_t i = 0; i < esauJrState.size(); i++) + { + delete esauJrState[i]; + esauJrState[i] = nullptr; + if (i < state.esauJrStates.size() && state.esauJrStates[i].playerType != -1) + reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0: an Esau Jr. player"); + } + if (!state.players.empty()) + { + GameStatePlayer& first = state.players.front(); + glitchBabyRng.SetSeed((uint32_t)first.glitchBabySeed, GLITCH_BABY_SHIFT); + randomBabyCount = first.randomBabyCount; + randomBabies = first.randomBabies; + } + coop_slots_reset(); + g_game->hud.AssignPlayerHUDs(); +} + +// 009bd010 Finishes the saved players once their floor is entered (their familiars, charmed enemies, effects and +// stats), then clears the join seats and refreshes the HUDs and the crafting bag's item. +void PlayerManager::RestoreGameState_PostLevelInit(GameState& state) +{ + std::vector matched = match_saved_players(state, MATCH_FIND); + HUD& hud = g_game->hud; + + for (size_t i = 0; i < matched.size(); i++) + if (matched[i]) matched[i]->RestoreGameState_PostLevelInit(state.players[i]); + coop_slots_reset(); + hud.AssignPlayerHUDs(); + hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + hud.InvalidateCraftingItem(nullptr); +} + +// 009bf530 Hands the controllers out again after a continue: every player lets go of its own, then the players without +// one take, in order, the menu's controller and every other connected device. +void PlayerManager::restore_controller_assignment() +{ + std::vector controllers = {g_manager->activeControllerIndex}; + + for (Entity_Player* player : playerList) player->SetControllerIndex(-1, true); + for (int i = 0; i < KAGE::Input::manager.get_device_count(); i++) + { + std::shared_ptr device = KAGE::Input::manager.get_device(i); + if (device && device->id != g_manager->activeControllerIndex && device->isConnected) + controllers.push_back(device->id); + } + + auto next = controllers.begin(); + for (Entity_Player* player : playerList) + { + if (next == controllers.end()) break; + if (player->controllerIndex == -1) player->SetControllerIndex(*next++, true); + } + coop_slots_reset(); + g_game->hud.AssignPlayerHUDs(); +} + +// An item by its kind as a save names it: a null item, a trinket (its golden flag ignored) or a collectible. +static ItemConfig_Item* item_by_kind(int type, int id) +{ + ItemConfig& items = g_manager->itemConfig; + + if (type == ITEM_NULL) return items.GetNullItem(id); + if (type == ITEM_TRINKET) return items.GetTrinket((uint32_t)id); + return items.GetCollectible(id); +} + +// 007ae430 Gives a sub player or co-op baby its saved character (unless it holds a player index) and hearts. +static void co_player_restore(Entity_Player& player, const CoPlayerState& saved) +{ + if (player.playerIndex < 0) player.playerType = saved.playerType; + player.redHearts = saved.redHearts; + player.maxHearts = saved.maxHearts; + player.soulHearts = saved.soulHearts; + player.blackHearts = saved.blackHearts; + player.eternalHearts = saved.eternalHearts; + player.goldenHearts = saved.goldenHearts; + player.brokenHearts = saved.brokenHearts; + player.rottenHearts = saved.rottenHearts; + player.boneHearts = saved.boneHearts; + player.boneHeartsMask = saved.boneHeartsMask; +} + +// Seeds as many of a player's item RNGs as the save and the item configs have. +static void rng_seeds_restore(std::vector& rngs, const std::vector& seeds, size_t configCount) +{ + for (size_t i = 0; i < std::min({rngs.size(), seeds.size(), configCount}); i++) + rngs[i].SetSeed(seeds[i], ITEM_RNG_SHIFT); +} + +// 007ae4b0 Restores a player from its save: its controller (and character, rewinding), its name, collectible counts, +// trinkets (an unknown first one dropped for the second), voided items, Moving Box, forms, costumes and item RNGs, +// its health (hearts added again), sub player, history and inventory with the smelted trinkets counted from the +// history, its consumables, counters and stats, actives (unknown ones kept as they were), pockets (an unknown card +// dropped, the later slots moving up) and the rest of what it keeps. It is alive again and may start Astral Projection. +// A replaced player keeps its state. The Moving Box's saved entities take their spawner type as their 64-bit storage, +// as the original's copy does. The fields the curated player lacks are left out, as Entity_Player::StoreGameState +// leaves them out. +void Entity_Player::RestoreGameState(GameStatePlayer& saved) +{ + Game& game = *g_game; + ItemConfig& items = g_manager->itemConfig; + std::vector& configs = g_manager->entityConfig.players; + + if (replacedPlayer) return; + SetControllerIndex(saved.controllerIndex, true); + if (playerType >= (int)configs.size()) playerType = PLAYER_ISAAC; + if (game.isRestoringGlowingHourglassState) + { + if (playerType != saved.playerType) + { + RemoveSkinCostume(); + stop_costume_item_anims(); + playerType = saved.playerType; + update_player_skin(); + ResetColor(); + } + if (isCoopGhost && !saved.isCoopGhost) RevivePlayerGhost(); + } + if (playerType < 0 || playerType >= (int)configs.size()) + log_printf(LOG_ERROR, "Could not load config for player type %d\n", playerType); + else name = configs[playerType].GetDisplayName(); + + size_t countCount = std::min({collectibleCounts.size(), saved.collectibleCounts.size(), items.collectibles.size()}); + std::copy_n(saved.collectibleCounts.begin(), countCount, collectibleCounts.begin()); + trinkets = saved.trinkets; + for (size_t i = 0; i < trinkets.size(); i++) + { + if ((trinkets[i] & TRINKET_ID_MASK) < items.trinkets.size()) continue; + if (i == 0) trinkets[0] = trinkets[1]; + trinkets[1] = 0; + } + voidedCollectibles.clear(); + for (int id : saved.voidedCollectibles) + if (id < (int)items.collectibles.size()) voidedCollectibles.push_back(id); + voidedPassives.clear(); + for (VoidedPassive passive : saved.voidedPassives) + if (passive.id < (int)items.collectibles.size()) voidedPassives.push_back(passive.id); + movingBoxContents = saved.movingBoxContents; + for (EntitySaveState& box : movingBoxContents) box.int64Storage = box.spawnerType; + playerForms = saved.playerForms; + playerFormsRewarded = saved.playerFormsRewarded; + + ClearCostumes(); + for (CostumeItem costume : saved.costumes) + if ((uint32_t)costume.id < items.collectibles.size() && (uint32_t)costume.type <= ITEM_FAMILIAR) + if (ItemConfig_Item* item = item_by_kind(costume.type, costume.id)) AddCostume(item, false); + for (size_t i = 0; i < std::min(pillEffectUses.size(), saved.pillEffectUses.size()); i++) + pillEffectUses[i] = saved.pillEffectUses[i]; + rng_seeds_restore(collectibleRNGs, saved.collectibleRngSeeds, items.collectibles.size()); + rng_seeds_restore(trinketRNGs, saved.trinketRngSeeds, items.trinkets.size()); + rng_seeds_restore(pillRNGs, saved.pillRngSeeds, items.pillEffects.size()); + rng_seeds_restore(cardRNGs, saved.cardRngSeeds, items.cards.size()); + + goldenHearts = 0; + eternalHearts = 0; + boneHearts = 0; + blackHearts = 0; + soulHearts = 0; + maxHearts = 0; + redHearts = 0; + brokenHearts = 0; + rottenHearts = 0; + AddMaxHearts(saved.maxHearts, true); + blackHearts = saved.blackHearts; + AddSoulHearts(saved.soulHearts, false); + eternalHearts = saved.eternalHearts; + boneHearts = saved.boneHearts; + boneHeartsMask = saved.boneHeartsMask; + AddHearts(saved.redHearts, true, false); + if (saved.subPlayer && subPlayer) co_player_restore(*subPlayer, *saved.subPlayer); + if (!saved.coopBabies.empty()) reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0: the co-op babies"); + + history.historyItems = saved.history; + inventory = saved.inventory; + game.hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + std::ranges::fill(smeltedTrinkets, SmeltedTrinket{}); + for (HistoryItem& item : history.historyItems) + { + uint32_t id = (uint32_t)item.id & TRINKET_ID_MASK; + if (!item.isTrinket || id >= smeltedTrinkets.size()) continue; + if (item.id & TRINKET_GOLDEN_FLAG) smeltedTrinkets[id].goldenCount++; + else smeltedTrinkets[id].count++; + } + + jarHearts = saved.jarHearts; + jarFlies = saved.jarFlies; + numCoins = saved.numCoins; + numKeys = saved.numKeys; + numBombs = saved.numBombs; + hasGoldenKey = saved.hasGoldenKey; + hasGoldenBomb = saved.hasGoldenBomb; + monkeyPawCounter = (uint16_t)saved.monkeyPawCounter; + totalDamageTaken = (uint16_t)saved.totalDamageTaken; + holyMantleState = saved.isHolyMantle ? HOLY_MANTLE_SAVED : 0; + tonsilCounter = saved.tonsilCounter; + tonsilCount = saved.tonsilCount; + numLeprosy = saved.numLeprosy; + speedModifier = saved.speedModifier; + fireDelayModifier = saved.fireDelayModifier; + damageModifier = saved.damageModifier; + tearRangeModifier = saved.tearRangeModifier; + shotSpeedModifier = saved.shotSpeedModifier; + luckModifier = saved.luckModifier; + donateLuck = saved.donateLuck; + potatoPeelerCounter = saved.potatoPeelerCounter; + potatoPeelerBandageCounter = saved.potatoPeelerBandageCounter; + brittleBonesUpgrades = saved.brittleBonesUpgrades; + redStewBonusDuration = saved.redStewBonusDuration; + brokenHearts = saved.brokenHearts; + rottenHearts = saved.rottenHearts; + effectiveSoulCharge = saved.effectiveSoulCharge; + urnSouls = saved.urnSouls; + numGigaBombs = saved.numGigaBombs; + rockBottomDamage = saved.rockBottomDamage; + rockBottomMaxFireDelay = saved.rockBottomMaxFireDelay; + rockBottomLuck = saved.rockBottomLuck; + rockBottomTearRange = saved.rockBottomTearRange; + rockBottomMoveSpeed = saved.rockBottomMoveSpeed; + rockBottomShotSpeed = saved.rockBottomShotSpeed; + reverseEmpressMaxHearts = saved.reverseEmpressMaxHearts; + reverseSunBoneHearts = saved.reverseSunBoneHearts; + forgottenBodyRoomIdx = saved.forgottenBodyRoomIdx; + forgottenBodyPos = saved.forgottenBodyPos; + maggyHealthDrainCooldown = saved.maggyHealthDrainCooldown; + echoChamberItems.clear(); + for (PocketItem item : saved.echoChamberItems) echoChamberItems.push_back(item.id); + std::ranges::copy(saved.bagOfCraftingContent | std::views::take(bagOfCraftingContent.size()), + bagOfCraftingContent.begin()); + std::ranges::copy(saved.poopSpellQueue | std::views::take(poopSpellQueue.size()), poopSpellQueue.begin()); + poopMana = saved.poopMana; + effectiveBloodCharge = saved.effectiveBloodCharge; + itemCards = saved.itemCards; + modelingClayEffect = saved.modelingClayEffect; + keepersSackBonus = saved.keepersSackBonus; + isLevelStartPending = saved.isLevelStartPending; + hasCurseMistEffect = saved.hasCurseMistEffect; + consumablesBackup = saved.consumablesBackup; + if (!saved.curseMistFamiliars.empty()) + reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0: Curse of the Mist's familiars"); + curseMistRedHearts = saved.curseMistRedHearts; + curseMistPocketItems = saved.curseMistPocketItems; + curseMistTrinkets = saved.curseMistTrinkets; + isCoopGhost = saved.isCoopGhost; + ghostPocketItems = saved.ghostPocketItems; + ghostTrinkets = saved.ghostTrinkets; + wildCardItemType = saved.wildCardItemType; + wildCardItem = saved.wildCardItem; + wildCardVarData = saved.wildCardVarData; + samsonBerserkCharge = saved.samsonBerserkCharge; + ibsCharge = saved.ibsCharge; + proceduralItems = saved.proceduralItems; + if (!proceduralItems.empty()) reconstruction_missing("GlitchedItemSet::recalculate 009e0500 (TMTRAINER items)"); + + edenSpeed = saved.edenSpeed; + edenFireDelay = saved.edenFireDelay; + edenDamage = saved.edenDamage; + edenTearRange = saved.edenTearRange; + edenShotSpeed = saved.edenShotSpeed; + edenLuck = saved.edenLuck; + vampireCharmKills = saved.vampireCharmKills; + for (size_t i = 0; i < activeItems.size(); i++) + { + const ActiveItemDesc& active = saved.activeItems[i]; + if (active.item >= (int)items.collectibles.size()) continue; + activeItems[i].item = active.item; + activeItems[i].unknown = active.unknown; + activeItems[i].charge = active.charge; + activeItems[i].batteryCharge = active.batteryCharge; + activeItems[i].partialCharge = active.partialCharge; + activeItems[i].varData = active.varData; + } + playerSpriteScale = saved.playerSpriteScale; + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) + { + headScale = saved.headScale; + bodyScale = saved.bodyScale; + } + pocketItems = saved.pocketItems; + for (size_t i = 0; i < pocketItems.size(); i++) + { + PocketItem& pocket = pocketItems[i]; + if (pocket.type != POCKET_CARD || pocket.id == 0 || pocket.id < (int)items.cards.size()) continue; + std::shift_left(pocketItems.begin() + (long)i, pocketItems.end(), 1); + pocketItems.back().id = 0; + } + + rUaWizardTimer = saved.rUaWizardTimer; + bloodLustCounter = saved.bloodLustCounter; + deadCatLives = saved.deadCatLives; + friendBallEnemy = saved.friendBallEnemy; + purityState = saved.purityState; + immaculateConceptionState = saved.immaculateConceptionState; + cambionConceptionState = saved.cambionConceptionState; + conceptionFamiliarFlags = saved.conceptionFamiliarFlags; + d8DamageModifier = saved.d8DamageModifier; + d8SpeedModifier = saved.d8SpeedModifier; + d8RangeModifier = saved.d8RangeModifier; + d8FireDelayModifier = saved.d8FireDelayModifier; + goldenHearts = saved.goldenHearts; + planCKillCountdown = saved.planCKillCountdown; + imExcitedSpeedupCountdown = saved.imExcitedSpeedupCountdown; + holyMantleStacks = saved.holyMantleStacks; + ductTapeMode = saved.ductTapeMode; + isDead = false; + try_trigger_astral_projection(); +} + +// 007b0070 Finishes a saved player once its floor is entered: its familiars around it, then (unless it was replaced) +// the Forgotten's body for the Soul, its charmed enemies, the items whose effect lasts the floor, its bleeding, Greed's +// Gullet, the item it held up, its temporary effects (rebuilt from the persistent ones when it saved none), Dark Esau, +// the co-op ghost's entrance and a sub player the Soul of the Forgotten no longer needs. Its stats are evaluated again. +// The familiars, charmed enemies, Dark Esau and the co-op ghost wait for their takeovers. +void Entity_Player::RestoreGameState_PostLevelInit(GameStatePlayer& saved) +{ + if (!saved.familiars.empty()) + reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the familiars (00630560)"); + if (replacedPlayer) return; + + if (playerType == PLAYER_THESOUL) spawn_forgotten_body(); + if (!saved.charmedEnemies.empty()) + reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the charmed enemies"); + levelEffectItems = saved.levelEffectItems; + bleedOutHealth = saved.bleedOutHealth; + if (bleedOutHealth > 0) + { + flags |= FLAG_BLEED_OUT; + bleedSource = EntityRef(this); + } + greedsGulletHearts = (short)saved.greedsGulletHearts; + greedsGulletOverflow = saved.greedsGulletOverflow; + queuedItem.item = saved.queuedItem.item; + queuedItem.charge = saved.queuedItem.charge; + queuedItem.flags = (uint8_t)saved.queuedItem.flags; + temporaryEffects.effects = saved.temporaryEffects; + strengthMaxHearts = saved.strengthMaxHearts; + if (temporaryEffects.effects.empty()) + for (PersistentEffect& effect : saved.persistentEffects) + { + TemporaryEffect& restored = temporaryEffects.effects.emplace_back(); + restored.item = item_by_kind(effect.type, effect.id); + restored.count = effect.count; + restored.cooldown = effect.cooldown; + } + + if (saved.darkEsauHealth > 0) + reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: Dark Esau"); + if (isCoopGhost) reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the co-op ghost"); + if (temporaryEffects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN) && parent.get() && subPlayer) + reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: removing the sub player"); + UpdateCanShoot(); + cacheFlags |= ALL_CACHE_FLAGS; + EvaluateItems(); + g_game->RemoveCompassEffect(); + isPostLevelInitFinished = true; +} + +// 005cb480 Dresses the player in the Wavy Cap costume its stacks of the effect call for: none, the first from one +// stack, the second from four and the third from seven, and sets the screen's dizziness to a tenth of the stacks. +// The original's co-op pass compares the player's stacks with its own, which changes nothing, so it is left out. +void Entity_Player::update_mini_mush_costume() +{ + ItemConfig& items = g_manager->itemConfig; + std::array costumes = {items.GetNullItem(NULLITEM_WAVY_CAP_1), + items.GetNullItem(NULLITEM_WAVY_CAP_2), + items.GetNullItem(NULLITEM_WAVY_CAP_3)}; + int stacks = temporaryEffects.isDisabled ? 0 + : temporaryEffects.GetNullEffectNum(NULLITEM_WAVY_CAP_1) + + temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_WAVY_CAP); + + bool isRemoved = std::erase_if(costumeSpriteDescs, [&](CostumeSpriteDesc& worn) + { return std::ranges::find(costumes, worn.item) != costumes.end(); }) > 0; + if (stacks >= MINI_MUSH_STACKS_THIRD) AddCostume(costumes[2], false); + else if (stacks >= MINI_MUSH_STACKS_SECOND) AddCostume(costumes[1], false); + else if (stacks >= 1) AddCostume(costumes[0], false); + else if (isRemoved) UpdateCostumes(); + + g_game->dizzyTargetIntensity = (float)(stacks / WAVY_CAP_STACKS_PER_DIZZINESS); + g_game->dizzyIntensityChangeSpeed = WAVY_CAP_DIZZINESS_SPEED; +} diff --git a/src/game_state.h b/src/game_state.h index 4930736..165aec3 100644 --- a/src/game_state.h +++ b/src/game_state.h @@ -190,4 +190,5 @@ struct GlowingHourglassState }; void room_config_ref_save(RoomConfig_Room& config, RoomConfigRef& ref, std::vector* mergedConfigs); +RoomConfig_Room* room_config_ref_load(const RoomConfigRef& ref, const std::vector* mergedConfigs); bool is_valid_item_config_id(int itemKind, int id); diff --git a/src/game_transition.cpp b/src/game_transition.cpp index fb37629..571e7b6 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -83,7 +83,7 @@ void Game::StartRoomTransition(RoomTransitionRequest request) { if (!IsGreedMode()) { - reconstruction_missing("Game::StartStageTransition 006fdc10, the Glowing Hourglass back to the stage start"); + stageTransition.start({.type = STAGE_TRANSITION_HOME}); if (!player) return; player->PlayExtraAnimation(ANIMATION_TELEPORT_UP); return sound_play(SOUND_TELEPORT_UP); diff --git a/src/game_update.cpp b/src/game_update.cpp index 6a9fa60..857a3e5 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -44,8 +44,6 @@ constexpr float ROOM_SURFACE_MARGIN = 52; constexpr int EVENT_EDEN_TOKENS = 21; constexpr int EVENT_STREAK_COUNTER = 22; -constexpr int STAGE_TRANSITION_START = 1; -constexpr int STAGE_TRANSITION_LANDING = 4; // The menu each menu fade out returns to. constexpr std::array FADEOUT_MENUS = {MENU_NONE, MENU_SAVE, MENU_GAME, MENU_ONLINE, MENU_TITLE}; @@ -309,7 +307,7 @@ static void timers_update(Game& game) game.screenShakeTimer = 0; game.ascentTimer = 0; game.screenShakeOffset = {}; - reconstruction_missing("Game::StartStageTransition 006fdc10, at the Ascent's end"); + game.stageTransition.start({.type = STAGE_TRANSITION_ASCENT}); } } if (game.deathCertificateExitTimer > 0) @@ -382,7 +380,7 @@ void Game::Update() } if (gameOver.state != GAME_OVER_HIDDEN) return gameOver.Update(); if (leaderboard.displayState != LEADERBOARD_HIDDEN) return leaderboard.Update(); - if (stageTransition._state != 0) + if (stageTransition.state != 0) { stageTransition.Update(); return hud.PostUpdate(); @@ -441,7 +439,7 @@ void Game::interpolate_update() if (entity.is_player()) { player_update(entity); - if (isStageTransition) reconstruction_missing("StageTransition::update_player_trapdoor_scale 0092f050"); + if (isStageTransition) stageTransition.update_player_trapdoor_scale(*entity.ToPlayer(), TRAPDOOR_SCALE_INTERPOLATE); } else if (entity.flags & FLAG_TRANSITION_UPDATE) entity.Interpolate(); } @@ -449,7 +447,7 @@ void Game::interpolate_update() if (console.update_state()) return; - int stageState = stageTransition._state; + int stageState = stageTransition.state; if (roomTransition.mode != TRANSITION_NONE) { if (roomTransition.frame != roomTransition.duration) roomTransition.progress += 0.5f / roomTransition.duration; diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 8599ee2..c2a8d8f 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -8,6 +8,7 @@ #include "manager.h" #include "npc_ai.h" #include "room.h" +#include "room_grid.h" #include #include #include @@ -109,19 +110,6 @@ constexpr std::span AMBUSH_VOID[] = {AMBUSH_BASEMENT, AMBUSH AMBUSH_WOMB, AMBUSH_BLUE_WOMB, AMBUSH_SHEOL, AMBUSH_CATHEDRAL, AMBUSH_DARK_ROOM, AMBUSH_CHEST}; -// Where a pickup can go near a position, past the active entities or not. -enum PickupSpot -{ - SPOT_ANYWHERE, - SPOT_AVOID_ACTIVE -}; - -// A free spot near a position (Room::FindFreePickupSpawnPosition 00813520, which Room does not have yet). -static Vector pickup_position_find(Vector, PickupSpot) -{ - reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520"); -} - static Entity* entity_spawn(int type, int variant, Vector position, uint32_t seed) { return g_game->Spawn({.position = position, .type = type, .variant = variant, .seed = seed}); @@ -328,7 +316,7 @@ static Vector slot_position_get(Vector position) if ((isFree(GRID_CELL_SIZE, 0) || isFree(-GRID_CELL_SIZE, 0)) && (isFree(0, GRID_CELL_SIZE) || isFree(0, -GRID_CELL_SIZE))) return position; - return pickup_position_find(Room::GetCenterPos(), SPOT_AVOID_ACTIVE); + return room_free_pickup_position_find({.position = Room::GetCenterPos(), .isAvoidActiveEntities = true}); } // A reward plate's reward, by a roll out of 100: a trapdoor (golden poop where none may open), golden poop, poop, an @@ -338,11 +326,11 @@ static void plate_reward_spawn(GridEntity& plate, RNG& rng) Room& room = *g_game->room; grid_sound_play(SOUND_THUMBSUP); - Vector position = pickup_position_find(plate.Position(), SPOT_AVOID_ACTIVE); + Vector position = room_free_pickup_position_find({.position = plate.Position(), .isAvoidActiveEntities = true}); int roll = (int)(rng.Next() % REWARD_ROLLS); auto pickupsSpawn = [&](int variant, uint32_t most) { for (int i = (int)rng.RandomInt(most) + 1; i > 0; i--) - entity_spawn(ENTITY_PICKUP, variant, pickup_position_find(plate.Position(), SPOT_AVOID_ACTIVE), rng.Next()); + entity_spawn(ENTITY_PICKUP, variant, room_free_pickup_position_find({.position = plate.Position(), .isAvoidActiveEntities = true}), rng.Next()); }; if (roll < ROLL_TRAPDOOR && g_game->CanSpawnTrapDoor()) @@ -459,7 +447,7 @@ static void plate_ambush_spawn(GridEntity& plate, RNG& rng) for (int i = first; i < first + count; i++) { uint32_t seed = seeds.Next(); - Vector position = pickup_position_find(positions[(size_t)i % positions.size()], SPOT_ANYWHERE); + Vector position = room_free_pickup_position_find({.position = positions[(size_t)i % positions.size()]}); float angle = random_unit() * RANDOM_HALF_TURN; angle += angle; float distance = random_unit() * AMBUSH_SCATTER; diff --git a/src/grid_entity_rock.cpp b/src/grid_entity_rock.cpp index cffdc21..abe2f13 100644 --- a/src/grid_entity_rock.cpp +++ b/src/grid_entity_rock.cpp @@ -1,4 +1,9 @@ #include "grid_entity_rock.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "npc_ai.h" #include "game.h" #include "log.h" #include "manager.h" @@ -18,6 +23,9 @@ constexpr int BIG_FRAME_WIDE_RIGHT = 1; constexpr int BIG_FRAME_TALL_TOP = 2; constexpr int BIG_FRAME_TALL_BOTTOM = 3; constexpr int BIG_FRAME_TOP_LEFT = 4; +constexpr int BIG_FRAME_TOP_RIGHT = 5; +constexpr int BIG_FRAME_BOTTOM_LEFT = 6; +constexpr int BIG_FRAME_BOTTOM_RIGHT = 7; constexpr uint32_t BIG_ROCK_RIGHT = 1 << 0; constexpr uint32_t BIG_ROCK_BELOW = 1 << 1; constexpr uint32_t BIG_ROCK_DIAGONAL = 1 << 2; @@ -55,6 +63,26 @@ constexpr int SPIDER_CHECK_FRAMES = 15; constexpr uint32_t SPIDER_ODDS = 100; constexpr int EFFECT_POOF01 = 15; +// A bomb rock's blast, the particles a breaking rock throws, and the worms one in so many rocks hides. +constexpr float BOMB_ROCK_DAMAGE = 40; +constexpr float BOMB_ROCK_RADIUS = 62; +constexpr float ROCK_PARTICLE_SPEED = 5; +constexpr int EFFECT_BOMB_EXPLOSION = 1; +constexpr int EFFECT_ROCK_PARTICLE = 4; +constexpr int EFFECT_WORM = 63; +constexpr uint32_t WORM_ODDS = 50; +constexpr uint32_t WORM_MAX = 5; +constexpr float WORM_DISTANCE = 20; + +// Stud Finder's chance of a crawlspace, Lucky Rock's of a coin, the most Lucky Rocks that count, and the countdown an +// event rock or pit beside a broken rock starts. +constexpr int TRINKET_LUCKY_ROCK = 15; +constexpr int TRINKET_STUD_FINDER = 74; +constexpr int STUD_FINDER_ODDS = 200; +constexpr uint32_t LUCKY_ROCK_ODDS = 3; +constexpr int LUCKY_ROCK_MAX = 16; +constexpr int EVENT_COUNTDOWN_START = 13; + // The event counters breaking rocks advance. constexpr int EVENT_ROCKS_DESTROYED = 2; constexpr int EVENT_TINTED_ROCKS_DESTROYED = 3; @@ -62,7 +90,6 @@ constexpr int EVENT_SS_ROCKS_DESTROYED = 4; // The break sounds: the alternate rocks' by their kind, the fleshy floors', and the plain one. constexpr int ALT_ROCK_SOUNDS[] = {0, 78, 79, 137, 77, 138}; -constexpr int SOUND_MEAT_IMPACTS = 77; constexpr int SOUND_ROCK_CRUMBLE = 137; constexpr int FLESHY_BACKDROPS[] = {10, 11, 12, 13, 34, 43, 44, 48}; @@ -366,23 +393,6 @@ void GridEntity_Rock::Update() previousState = state; } -// The room's floor color laid over a sprite's own (the original's Color::__mul): tints multiply, colorizes average in, -// offsets add. -static ColorMod color_multiply(ColorMod color, const ColorMod& other) -{ - for (int i = 0; i < 4; i++) - color._tint[i] *= other._tint[i]; - if (other._colorize[0] + other._colorize[1] + other._colorize[2] != 0) - { - bool isUncolored = color._colorize[0] + color._colorize[1] + color._colorize[2] == 0; - for (int i = 0; i < 4; i++) - color._colorize[i] = isUncolored ? other._colorize[i] : (color._colorize[i] + other._colorize[i]) * 0.5f; - } - for (int i = 0; i < 3; i++) - color._offset[i] += other._offset[i]; - return color; -} - // 00719ad0 Draws a standing rock, or a broken one's rubble, each bit on the next frame of the rubble animation, in the // floor's color over the rock's own. // A missing rubble animation leaves the floor's color on the sprite. @@ -391,7 +401,7 @@ void GridEntity_Rock::Render(const Vector& offset) Vector position = get_render_position(); SpriteDraw draw = {.position = vector_make(position.x + offset.x, position.y + offset.y)}; ColorMod saved = sprite.color; - sprite.color = color_multiply(g_game->room->floorColor, saved); + color_multiply(sprite.color, g_game->room->floorColor); if (state == ROCK_STATE_STANDING || state == ROCK_STATE_CRACKED) sprite.Render(draw); else if (state == ROCK_STATE_BROKEN) @@ -430,7 +440,7 @@ void GridEntity_Rock::RenderTop(const Vector& offset) Vector position = get_render_position(); SpriteDraw draw = {.position = vector_make(position.x + offset.x, position.y + offset.y)}; ColorMod saved = sprite.color; - sprite.color = color_multiply(g_game->room->floorColor, saved); + color_multiply(sprite.color, g_game->room->floorColor); LayerState* top = sprite.GetLayer(1); if (top) top->isVisible = true; @@ -440,11 +450,58 @@ void GridEntity_Rock::RenderTop(const Vector& offset) sprite.color = saved; } -// 007197d0 Breaks the rock: a bomb rock is primed and blows, a super secret rock cracks first. Pillars and metal blocks -// stand. -bool GridEntity_Rock::Destroy(bool, const EntityRef&) +// 007197d0 Breaks the rock: a standing one counts and may let worms out, a bomb rock is primed and blows on its own, +// a super secret rock cracks first, and pillars and metal blocks stand. Broken, it crumbles with rock particles, big +// rocks around it fall apart, and it leaves its drops and maybe a ladder. +// The original reads the rock's cell after a ladder may have replaced it. Here the cell is kept from before. +bool GridEntity_Rock::Destroy(bool isImmediate, const EntityRef& source) { - reconstruction_missing("GridEntity_Rock::Destroy 007197d0"); + Vector position = Position(); + if (state == ROCK_STATE_STANDING) + { + RegisterRockDestroyed(type); + TrySpawnWorms(); + } + if (type == GRID_ROCK_BOMB && !isImmediate) + { + if (state == ROCK_STATE_BROKEN) return false; + if (state == ROCK_STATE_STANDING || fuseFrames > 0) + { + state = ROCK_STATE_PRIMED; + return true; + } + if (state != ROCK_STATE_PRIMED) return true; + + state = ROCK_STATE_BROKEN; + collisionClass = COLLISION_NONE; + path_set(GRID_PATH_FREED); + explosion_damage({.position = position, .damage = BOMB_ROCK_DAMAGE, .radius = BOMB_ROCK_RADIUS}); + bomb_crater_spawn(position, nullptr, 1); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + return true; + } + if (type == GRID_ROCK_SS && state == ROCK_STATE_STANDING) + { + state = ROCK_STATE_CRACKED; + anim = "ss_broken"; + UpdateAnimFrame(); + return false; + } + if (type == GRID_ROCKB || type == GRID_PILLAR) return false; + if (state != ROCK_STATE_STANDING && state != ROCK_STATE_CRACKED) return false; + + PlayBreakSound(type, 0); + state = ROCK_STATE_BROKEN; + collisionClass = COLLISION_NONE; + path_set(GRID_PATH_FREED); + game_particles_spawn({.position = position, .speed = ROCK_PARTICLE_SPEED, .count = (int)(Random() & 1) + 2, + .variant = EFFECT_ROCK_PARTICLE}); + UpdateNeighbors(); + int cell = gridIndex; + SpawnDrops(position, type, variant, spawnSeed, 0, source.entity); + TrySpawnLadder(); + grid_mark_neighbors_dirty(cell); + return true; } // 0071deb0 Water clips around the rock until it breaks. @@ -510,10 +567,63 @@ void GridEntity_Rock::UpdateAnimFrame() sprite.animState.isPlaying = false; } -// 0071aaf0 Updates the rocks around a broken one: big rocks fall apart and tinted neighbours show. +// The rock on the cell beside a cell, if any. +static GridEntity_Rock* rock_beside(int gridIndex, int columnStep, int rowStep) +{ + Room& room = *g_game->room; + int column = gridIndex % room.gridWidth + columnStep; + int row = gridIndex / room.gridWidth + rowStep; + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + return isInside ? dynamic_cast(room.GetGridEntity((uint32_t)(row * room.gridWidth + column))) : nullptr; +} + +// Shows a frame of a big rock on a rock beside this one, or a single rock for -1. +static void neighbor_frame_set(int gridIndex, int columnStep, int rowStep, int frame) +{ + if (GridEntity_Rock* rock = rock_beside(gridIndex, columnStep, rowStep)) rock->SetBigRockFrame(frame); +} + +// 0071aaf0 Breaks up the big rock a broken part of it belonged to: two wide or tall leave a single rock, a part of four +// leaves the two beside it a big rock two tall or wide and the third a single rock. void GridEntity_Rock::UpdateNeighbors() { - reconstruction_missing("GridEntity_Rock::UpdateNeighbors 0071aaf0"); + if ((uint32_t)variant < BIG_ROCK_VARIANT) return; + + switch (variant - BIG_ROCK_VARIANT) + { + case BIG_FRAME_WIDE_LEFT: + neighbor_frame_set(gridIndex, 1, 0, -1); + break; + case BIG_FRAME_WIDE_RIGHT: + neighbor_frame_set(gridIndex, -1, 0, -1); + break; + case BIG_FRAME_TALL_TOP: + neighbor_frame_set(gridIndex, 0, 1, -1); + break; + case BIG_FRAME_TALL_BOTTOM: + neighbor_frame_set(gridIndex, 0, -1, -1); + break; + case BIG_FRAME_TOP_LEFT: + neighbor_frame_set(gridIndex, 1, 1, BIG_FRAME_WIDE_RIGHT); + neighbor_frame_set(gridIndex, 0, 1, BIG_FRAME_WIDE_LEFT); + neighbor_frame_set(gridIndex, 1, 0, -1); + break; + case BIG_FRAME_TOP_RIGHT: + neighbor_frame_set(gridIndex, 0, 1, BIG_FRAME_WIDE_RIGHT); + neighbor_frame_set(gridIndex, -1, 1, BIG_FRAME_WIDE_LEFT); + neighbor_frame_set(gridIndex, -1, 0, -1); + break; + case BIG_FRAME_BOTTOM_LEFT: + neighbor_frame_set(gridIndex, 1, 0, BIG_FRAME_TALL_BOTTOM); + neighbor_frame_set(gridIndex, 1, -1, BIG_FRAME_TALL_TOP); + neighbor_frame_set(gridIndex, 0, -1, -1); + break; + case BIG_FRAME_BOTTOM_RIGHT: + neighbor_frame_set(gridIndex, -1, 0, BIG_FRAME_TALL_BOTTOM); + neighbor_frame_set(gridIndex, -1, -1, BIG_FRAME_TALL_TOP); + neighbor_frame_set(gridIndex, 0, -1, -1); + break; + } } // 0071af10 Counts a broken rock toward the achievements: any but a metal block, tinted and super secret rocks again. @@ -530,10 +640,20 @@ void GridEntity_Rock::RegisterRockDestroyed(GridEntityType type) data.IncreaseEventCounter(EVENT_SS_ROCKS_DESTROYED, 1); } -// 0071af60 Spawns the worms a rock on certain floors hides. +// 0071af60 Lets a few worms out of one rock in 50, by its seed: not from metal blocks, pillars or alternate rocks. void GridEntity_Rock::TrySpawnWorms() { - reconstruction_missing("GridEntity_Rock::TrySpawnWorms 0071af60"); + Vector position = Position(); + RNG rng = {spawnSeed, 2, 7, 9}; + bool isWormy = rng.Next() % WORM_ODDS == 0; + if (!isWormy || type == GRID_ROCKB || type == GRID_PILLAR || type == GRID_ROCK_ALT || type == GRID_ROCK_ALT2) return; + + for (uint32_t worms = rng.RandomInt(rng.RandomInt(WORM_MAX) + 1); worms > 0; worms--) + { + uint32_t seed = Random(); + Vector at = vector_add(position, vector_scale(random_direction(), WORM_DISTANCE)); + g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_WORM, .seed = seed})->Update(); + } } // 0071b100 Plays a rock breaking: the alternate rocks' own sound, flesh on the womb's floors, or crumbling. The @@ -550,14 +670,86 @@ void GridEntity_Rock::PlayBreakSound(GridEntityType type, int backdropType) grid_sound_play(sound); } -// 0071b1c0 Puts a ladder over the pit beside a broken rock in a crawlspace. +// 0071b1c0 Opens a crawlspace under the floor's chosen rock, or under one rock in 200 with Stud Finder (more often +// for a stronger one), once a floor. The stairs replace the rock. bool GridEntity_Rock::TrySpawnLadder() { - reconstruction_missing("GridEntity_Rock::TrySpawnLadder 0071b1c0"); + if (type == GRID_ROCKB) return false; + + Game& game = *g_game; + RNG* studFinder = nullptr; + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER || !player->HasTrinket(TRINKET_STUD_FINDER)) continue; + studFinder = &player->GetTrinketRNG(TRINKET_STUD_FINDER); + break; + } + bool isDone = game.levelStateFlags & LEVEL_STATE_DUNGEON_ROCK_BROKEN; + bool isChosen = game.currentRoomIdx >= 0 && (isDone ? -1 : game.room->dungeonRockIdx) == gridIndex; + if (!isChosen && (isDone || !studFinder)) return false; + if (!isChosen) + { + int odds = STUD_FINDER_ODDS / game.playerManager.GetTrinketMultiplier(TRINKET_STUD_FINDER); + if (studFinder->RandomInt((uint32_t)odds) != 0) return false; + } + + GridEntity* here = game.room->GetGridEntity((uint32_t)gridIndex); + if (here && here->collisionClass > COLLISION_NONE) here->collisionClass = COLLISION_NONE; + game.room->SpawnGridEntity(gridIndex, GRID_STAIRS, 0, Random(), 0); + game.levelStateFlags |= LEVEL_STATE_DUNGEON_ROCK_BROKEN; + return true; } -// 0071b410 Spawns what a broken rock of a type drops: pickups, chests, items, spiders, troll bombs and the rest. -void GridEntity_Rock::SpawnDrops(const Vector&, GridEntityType, int, uint32_t, int, Entity*) +// 0071b410 Spawns what a broken rock of a type drops: Lucky Rock's coins (a third of the time each) for any rock, and +// Keeper's Kin's spiders. Gold, tinted, super secret and alternate rocks' own drops are left to come. +// The knife swing that breaks rocks (Entity_Knife::UpdateSwingHits) is not curated, so no swinging player rolls again +// or makes wisps here. +void GridEntity_Rock::SpawnDrops(const Vector& position, GridEntityType type, int, uint32_t seed, int, Entity* source) { - reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410"); + bool isOwnDrop = type == GRID_ROCK_GOLD || type == GRID_ROCKT || type == GRID_ROCK_SS || type == GRID_ROCK_ALT || + type == GRID_ROCK_ALT2; + if (isOwnDrop) reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: gold, tinted and alternate rocks' drops"); + + RNG dropRng = {seed, 5, 9, 7}; + RNG velocityRng = {seed, 1, 9, 29}; + int luckyRocks = 0; + if (!g_game->deathmatchManager.is_active()) luckyRocks = g_game->playerManager.GetTrinketMultiplier(TRINKET_LUCKY_ROCK); + for (Entity* ancestor = source; ancestor && g_game->deathmatchManager.is_active(); ancestor = ancestor->spawnerEntity) + { + if (!ancestor->is_player()) continue; + luckyRocks = ancestor->ToPlayer()->GetTrinketMultiplier(TRINKET_LUCKY_ROCK); + break; + } + for (int i = 0; i < std::min(luckyRocks, LUCKY_ROCK_MAX); i++) + { + if (dropRng.Next() % LUCKY_ROCK_ODDS != 0) continue; + + uint32_t coinSeed = dropRng.Next(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); + g_game->Spawn({.position = position, .velocity = velocity, .subType = 1, .type = ENTITY_PICKUP, .variant = PICKUP_COIN, + .seed = coinSeed}) + ->Update(); + } + if (g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_KEEPERS_KIN, seed, nullptr)) + reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: Keeper's Kin's spiders"); +} + +// 0071dee0 Sets the countdown on the event rocks and empty event pits beside a cell, so they break or fill in turn. +void grid_mark_neighbors_dirty(int gridIndex) +{ + constexpr std::array, 4> SIDES = {{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}}; + Room& room = *g_game->room; + int column = gridIndex % room.gridWidth; + int row = gridIndex / room.gridWidth; + for (const std::array& side : SIDES) + { + int x = column + side[0]; + int y = row + side[1]; + if (x < 0 || x >= room.gridWidth || y < 0 || y >= room.gridHeight) continue; + + GridEntity* grid = room.GetGridEntity((uint32_t)(y * room.gridWidth + x)); + bool isEventRock = grid && grid->type == GRID_ROCK && grid->varData == 1 && grid->state == ROCK_STATE_STANDING; + bool isEventPit = grid && grid->type == GRID_PIT && grid->varData == 1 && grid->state == 0; + if (isEventRock || isEventPit) grid->varData = EVENT_COUNTDOWN_START; + } } diff --git a/src/grid_entity_rock.h b/src/grid_entity_rock.h index d7dff5b..e4dc1c4 100644 --- a/src/grid_entity_rock.h +++ b/src/grid_entity_rock.h @@ -46,3 +46,5 @@ struct GridEntity_Rock : GridEntity static void SpawnDrops(const Vector& position, GridEntityType type, int variant, uint32_t seed, int backdropType, Entity* source); }; + +void grid_mark_neighbors_dirty(int gridIndex); diff --git a/src/grid_entity_tnt.cpp b/src/grid_entity_tnt.cpp index a71ffb8..af14c6a 100644 --- a/src/grid_entity_tnt.cpp +++ b/src/grid_entity_tnt.cpp @@ -1,33 +1,105 @@ #include "grid_entity_tnt.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "game.h" #include "log.h" +#include "manager.h" +#include "room.h" #include "seeds.h" #include -// 0071ee90 Loads the barrel. -void GridEntity_TNT::subclass_init() +// The barrel's fuse once it is ready to blow, its blast, and the wood its pieces show. +constexpr int TNT_FUSE = 3; +constexpr float TNT_DAMAGE = 100; +constexpr float TNT_RADIUS = 75; +constexpr uint64_t DAMAGE_TNT = 1ull << 12; +constexpr int EFFECT_BOMB_EXPLOSION = 1; +constexpr int EFFECT_WOOD_PARTICLE = 27; +constexpr int WOOD_COUNT_MIN = 2; +constexpr uint32_t WOOD_COUNT_EXTRA = 3; +constexpr float WOOD_SPEED_MIN = 2; +constexpr float WOOD_SPEED_EXTRA = 4; +constexpr uint32_t TRINKET_DROP_ODDS = 100; + +// 0071f3f0 Throws the barrel's wooden pieces about. +static void wood_particles_spawn(const Vector& position) { - reconstruction_missing("GridEntity_TNT::subclass_init 0071ee90"); + float speed = (float)Random() * 2.3283064e-10f * WOOD_SPEED_EXTRA + WOOD_SPEED_MIN; + int count = (int)(Random() % WOOD_COUNT_EXTRA) + WOOD_COUNT_MIN; + game_particles_spawn({.position = position, .speed = speed, .count = count, .variant = EFFECT_WOOD_PARTICLE}); } -// 0071f090 Shows the barrel's damage and explodes it when its fuse runs out. +// 0071f4b0 One blown barrel in 100, by its seed, leaves a trinket. +static void trinket_drop_try(uint32_t seed) +{ + RNG rng = {seed, 1, 5, 16}; + if (rng.Next() % TRINKET_DROP_ODDS == 0) + reconstruction_missing("GridEntity_TNT 0071f4b0: the trinket a blown barrel drops"); +} + +// 0071ee90 Loads the barrel, blocking its cell, with the wooden pieces' sprite ready, and lights a standing one's +// fuse for once it is ready to blow. +void GridEntity_TNT::subclass_init() +{ + path_set(GRID_PATH_SOLID); + sprite.Load("gfx/grid/grid_tnt.anm2", GRAPHICS_LOAD); + EntityConfig& config = g_manager->entityConfig; + if (EntityConfig_Entity* wood = config.GetEntity(ENTITY_EFFECT, EFFECT_WOOD_PARTICLE, 0)) config.PreloadResources(wood); + sprite.Play("Idle"); + fuseFrames = state < TNT_STATE_BLOWN ? TNT_FUSE : -1; +} + +// 0071f090 Shows the barrel's damage, and once blown counts its fuse down to the blast: an explosion, a crater, the +// damage, the wooden pieces and maybe a trinket. void GridEntity_TNT::Update() { - reconstruction_missing("GridEntity_TNT::Update 0071f090"); + collisionClass = state > TNT_STATE_READY ? COLLISION_NONE : COLLISION_OBJECT; + if (state == 0 || state == 1) return sprite.Play("Idle"); + if (state == 2) return sprite.Play("IdleMedium"); + if (state == TNT_STATE_READY) return sprite.Play("ReadyToExplode"); + if (state != TNT_STATE_BLOWN) return; + + if (sprite.IsPlaying("Blown")) + { + if (fuseFrames >= 1) sprite.Play("ReadyToExplode"); + return; + } + if (--fuseFrames >= 1) return sprite.Play("ReadyToExplode"); + + sprite.Play("Blown"); + if (fuseFrames != 0) return; + Vector position = Position(); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + bomb_crater_spawn(position, nullptr, 1); + explosion_damage({.position = position, .damageFlags = DAMAGE_EXPLOSION | DAMAGE_TNT, .damage = TNT_DAMAGE, + .radius = TNT_RADIUS, .isLineCheck = false}); + wood_particles_spawn(position); + trinket_drop_try(spawnSeed); + path_set(GRID_PATH_FREED); } // 0071f250 Damages the barrel a stage or more, one time in three a stage more. bool GridEntity_TNT::Hurt(int damage, const EntityRef&) { int stages = Random() % 3 == 0 ? std::min(damage + 1, TNT_STATE_BLOWN) : damage; - if (stages < 1 || state > TNT_STATE_READY) - return false; + if (stages < 1 || state > TNT_STATE_READY) return false; state = std::min(state + stages, (int)TNT_STATE_BLOWN); return true; } -// 0071f2b0 Lights the barrel's fuse. -bool GridEntity_TNT::Destroy(bool, const EntityRef&) +// 0071f2b0 Blows the barrel at once into its pieces, without a blast. Not at once, it is hurt as by a bomb. +bool GridEntity_TNT::Destroy(bool isImmediate, const EntityRef&) { - reconstruction_missing("GridEntity_TNT::Destroy 0071f2b0"); + if (!isImmediate) return Hurt(4, EntityRef()); + if (state > TNT_STATE_READY) return false; + + collisionClass = COLLISION_NONE; + sprite.Play("Blown"); + wood_particles_spawn(Position()); + path_set(GRID_PATH_FREED); + state = TNT_STATE_BLOWN; + fuseFrames = -1; + return true; } diff --git a/src/grid_entity_trap_door.cpp b/src/grid_entity_trap_door.cpp index 6b7bd9d..54c0212 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -1,16 +1,386 @@ #include "grid_entity_trap_door.h" +#include "entity_effect.h" +#include "entity_list.h" +#include "entity_player.h" +#include "game.h" +#include "level.h" #include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_render.h" +#include "seeds.h" +#include "stage_transition.h" +#include +#include -// 0071f630 Loads the trapdoor for where it leads. -void GridEntity_TrapDoor::subclass_init() +constexpr const char* TRAPDOOR_ANM2 = "gfx/grid/Door_11_TrapDoor.anm2"; +constexpr const char* VOID_ANM2 = "gfx/grid/VoidTrapdoor.anm2"; +constexpr const char* DOWNPOUR_ANM2 = "gfx/grid/trapdoor_downpour.anm2"; +constexpr const char* MINES_ANM2 = "gfx/grid/trapdoor_mines.anm2"; +constexpr const char* MAUSOLEUM_ANM2 = "gfx/grid/trapdoor_mausoleum.anm2"; +constexpr const char* CORPSE_BIG_ANM2 = "gfx/grid/trapdoor_corpse_big.anm2"; +constexpr const char* WOMBHOLE_ANM2 = "gfx/grid/Door_11_Wombhole.anm2"; +constexpr const char* WOMBHOLE_BLUE_PNG = "gfx/grid/door_11_wombhole_blue.png"; +constexpr const char* CORPSEHOLE_PNG = "gfx/grid/door_11_corpsehole.png"; +constexpr std::string_view TRAPDOOR_SHEET_PREFIX = "gfx/grid/Door_11_TrapDoor"; + +constexpr std::string_view ANIM_CLOSED = "Closed"; +constexpr std::string_view ANIM_OPENING = "Open Animation"; +constexpr std::string_view ANIM_OPENED = "Opened"; +constexpr std::string_view ANIM_PLAYER_FALL = "Trapdoor"; + +// The stages (with a labyrinth counted as the next) whose exits are holes in the floor or the Void's portal. +constexpr int STAGE_WOMB_I = 7; +constexpr int STAGE_BLUE_WOMB = 9; +constexpr int STAGE_DEPTHS_I = 5; +constexpr int STAGE_DEPTHS_II = 6; +constexpr int STAGE_CAVES_I = 3; +constexpr int STAGE_LAST_CHAPTER = 10; + +constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; +constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; +constexpr int COLLECTIBLE_KNIFE_PIECE_2 = 627; +constexpr int GAME_STATE_BACKWARDS_PATH_INIT = 47; + +// Mother's boss room in the special rooms. +constexpr int STAGE_ID_SPECIAL_ROOMS = 0; +constexpr int BOSS_MOTHER = 88; +constexpr int MINES_LAYER_HIDDEN = 1; +constexpr int EFFECT_MINES_TRAPDOOR_COVER = 139; + +constexpr float PLAYER_FAR = 1e9f; +constexpr float PLAYER_CLEARANCE = 50; +constexpr float REACH = 21; +constexpr float MOTHER_HOLE_REACH = 34; +constexpr float FORGOTTEN_BODY_RADIUS = 20; +constexpr int FAMILIAR_FORGOTTEN_BODY = 900; +constexpr int SOUND_SHOVEL_HOLE_OPEN = 917; +constexpr int SOUND_TRAP_DOOR_LEVEL = 1052; + +constexpr int VOID_SHOCKWAVE_FRAMES = 15; +constexpr float VOID_SHOCKWAVE_AMPLITUDE = 0.05f; +constexpr float MEGA_SATAN_SHOCKWAVE_AMPLITUDE = 0.03f; +constexpr float CLOSED_SHOCKWAVE_SCALE = 0.2f; +constexpr float SHOCKWAVE_SPEED = 0.013f; +constexpr int VOID_SHOCKWAVE_DURATION = 13; +constexpr int MEGA_SATAN_SHOCKWAVE_DURATION = 6; + +static bool room_is_cleared(Room& room) { - reconstruction_missing("GridEntity_TrapDoor::subclass_init 0071f630"); + return room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; } -// 0071fef0 Opens once the players stand clear and takes a player falling in to the next floor. +// The labyrinth's stage, counted as the next one but in Greed. +static int labyrinth_stage_get(bool isGreedIgnored) +{ + Game& game = *g_game; + bool isLabyrinth = game.filter_curses(CURSE_OF_LABYRINTH); + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + return (int)game.stage + (isLabyrinth && !(isGreedIgnored && isGreed) ? 1 : 0); +} + +// 0071f630 Loads the trapdoor for where it leads: the Void's portal, the secret exits' holes, Mother's big hole, the +// womb holes (blue to the Blue Womb, the corpse's on the alternate path) or the plain trapdoor, closed. +void GridEntity_TrapDoor::subclass_init() +{ + Game& game = *g_game; + Room& room = *game.room; + int stage = labyrinth_stage_get(true); + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + RoomConfig_Room* config = room.descriptor->data; + + if ((stage == STAGE_BLUE_WOMB && game.currentRoomIdx == ROOM_THE_VOID_IDX) || varData == TRAPDOOR_VOID_PORTAL) + { + sprite.Load(VOID_ANM2, GRAPHICS_LOAD); + variant = 1; + } + else if (room.roomType == ROOM_SECRET_EXIT) + { + int exit = config ? config->subtype : 0; + if (exit == SECRET_EXIT_DOWNPOUR) sprite.Load(DOWNPOUR_ANM2, GRAPHICS_LOAD); + else if (exit == SECRET_EXIT_MINES) + { + sprite.Load(MINES_ANM2, GRAPHICS_LOAD); + if (sprite.layerStates.size() > MINES_LAYER_HIDDEN) sprite.GetLayer(MINES_LAYER_HIDDEN)->isVisible = false; + sprite.Play(ANIM_CLOSED); + auto* cover = static_cast(g_game->Spawn({.position = Position(), + .type = ENTITY_EFFECT, + .variant = EFFECT_MINES_TRAPDOOR_COVER, + .seed = Random()})); + cover->state = gridIndex; + cover->Update(); + } + else sprite.Load(exit == SECRET_EXIT_MAUSOLEUM ? MAUSOLEUM_ANM2 : TRAPDOOR_ANM2, GRAPHICS_LOAD); + } + else if (room.roomType == ROOM_BOSS && config->stageId == STAGE_ID_SPECIAL_ROOMS && config->subtype == BOSS_MOTHER) + sprite.Load(CORPSE_BIG_ANM2, GRAPHICS_LOAD); + else if (((stage == STAGE_DEPTHS_II || stage == STAGE_WOMB_I) && !isGreed) || (stage == STAGE_CAVES_I && isGreed) || + game.currentRoomIdx == ROOM_BLUE_WOMB_IDX) + { + sprite.Load(WOMBHOLE_ANM2, GRAPHICS_DEFER); + bool isCorpse = + game.IsMausoleumHeartStage() || (stage == STAGE_WOMB_I && game.IsAltPath()) || + ((stage == STAGE_DEPTHS_II || (stage == STAGE_DEPTHS_I && game.filter_curses(CURSE_OF_LABYRINTH))) && + game.GetChallengeParams().pathType == PATH_TYPE_REPENTANCE); + if (game.currentRoomIdx == ROOM_BLUE_WOMB_IDX) sprite.ReplaceSpritesheet(0, WOMBHOLE_BLUE_PNG); + else if (isCorpse) sprite.ReplaceSpritesheet(0, CORPSEHOLE_PNG); + sprite.LoadGraphics(); + } + else sprite.Load(TRAPDOOR_ANM2, GRAPHICS_LOAD); + + state = 0; + sprite.Play(ANIM_CLOSED); +} + +// (00703ab0) Game::GetNearestPlayerEx for the main players only: the nearest player itself (not a co-op ghost, baby, +// twin's hold or hologram) that collides with entities. +static Entity_Player* main_player_nearest(const Vector& position) +{ + Entity_Player* nearest = nullptr; + float best = 1e10f; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = vector_length_squared(vector_sub(position, player->pos)); + if (distance >= best) continue; + if (player->variant != 0 || player->isCoopGhost || player->parent || player->IsHologram()) continue; + if (player->entityCollisionClass == ENTCOLL_NONE) continue; + + nearest = player; + best = distance; + } + return nearest; +} + +// Whether The Forgotten's body lies on the trapdoor (EntityList::QueryRadius over the familiars). +static bool is_forgotten_body_on(const Vector& position) +{ + EntityList& list = g_game->room->entityList; + EntityList_EL found; + + list.partitions[PARTITION_FAMILIARS].query_box(found, position, + vector_make(FORGOTTEN_BODY_RADIUS, FORGOTTEN_BODY_RADIUS)); + for (Entity* entity : found) + { + float reach = FORGOTTEN_BODY_RADIUS + entity->size; + bool isNear = vector_length_squared(vector_sub(entity->pos, position)) < reach * reach; + if (isNear && !entity->HasEntityFlags(FLAG_NO_QUERY) && entity->type == ENTITY_FAMILIAR && + entity->variant == FAMILIAR_FORGOTTEN_BODY) + return true; + } + return false; +} + +// Whether Mother's room holds the hole to the Corpse's last floor. +static bool is_mother_hole(GridEntity_TrapDoor& trapDoor) +{ + Room& room = *g_game->room; + RoomConfig_Room* config = room.descriptor->data; + return room.roomType == ROOM_BOSS && config->stageId == STAGE_ID_SPECIAL_ROOMS && config->subtype == BOSS_MOTHER && + trapDoor.varData != TRAPDOOR_VOID_PORTAL; +} + +// Whether the alternate path's knife pieces are missing: the first on Downpour or Dross II, the second on Mines or +// Ashpit II. +static bool is_knife_piece_missing() +{ + Game& game = *g_game; + bool isLabyrinth = game.filter_curses(CURSE_OF_LABYRINTH); + int stage = (int)game.stage; + bool isFirstPieceFloor = game.IsAltPath() && (stage == 2 || (stage == 1 && isLabyrinth)); + bool isSecondPieceFloor = game.IsAltPath() && (stage == 4 || (stage == 3 && isLabyrinth)); + PlayerManager& players = game.playerManager; + + if (isFirstPieceFloor && !players.FirstCollectibleOwner(COLLECTIBLE_KNIFE_PIECE_1, LAZARUS_SHARE_CHECK)) + return true; + return isSecondPieceFloor && !players.FirstCollectibleOwner(COLLECTIBLE_KNIFE_PIECE_2, LAZARUS_SHARE_CHECK); +} + +// Whether something keeps an unopened trapdoor shut: Broken Shovel's floor before Mom's Shovel is dug up, an uncleared +// secret exit, the Ascent, or on Repentance's path a missing knife piece at a secret exit and the Depths' exit on the +// alternate path. +static bool is_held_shut() +{ + Game& game = *g_game; + Room& room = *game.room; + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + int stage = labyrinth_stage_get(false); + + if (!isGreed && game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BROKEN_SHOVEL_1, LAZARUS_SHARE_CHECK) && + room.roomType != ROOM_ERROR && stage == STAGE_DEPTHS_II && + !(game.GetRoomByIdx(ROOM_BOSSRUSH_IDX)->flags & ROOM_DESCRIPTOR_FLAG_CHALLENGE_DONE)) + return true; + if (room.roomType == ROOM_SECRET_EXIT && !room_is_cleared(room)) return true; + if (game.IsAscent()) return true; + if (game.GetChallengeParams().pathType != PATH_TYPE_REPENTANCE) return false; + + bool isAlt = game.IsAltPath(); + if (room.roomType == ROOM_SECRET_EXIT) + { + bool isLabyrinth = game.filter_curses(CURSE_OF_LABYRINTH); + bool isFirstPieceFloor = stage == 2 || (isLabyrinth && stage == 1); + bool isSecondPieceFloor = stage == 4 || (isLabyrinth && stage == 3); + PlayerManager& players = game.playerManager; + if (isFirstPieceFloor && isAlt && + !players.FirstCollectibleOwner(COLLECTIBLE_KNIFE_PIECE_1, LAZARUS_SHARE_CHECK)) + return true; + return isSecondPieceFloor && isAlt && + !players.FirstCollectibleOwner(COLLECTIBLE_KNIFE_PIECE_2, LAZARUS_SHARE_CHECK); + } + bool isDepthsExit = stage == STAGE_DEPTHS_II || (game.filter_curses(CURSE_OF_LABYRINTH) && stage == STAGE_DEPTHS_I); + return isDepthsExit && isAlt && !game.IsMausoleumHeartStage() && room.roomType != ROOM_ISAACS && + room.roomType != ROOM_ERROR; +} + +// Opens an unopened trapdoor (not in Backasswards), its plain sprite scraping as it starts, and marks it open once the +// animation ends. +static void trapdoor_open_update(GridEntity_TrapDoor& trapDoor) +{ + ANM2& sprite = trapDoor.sprite; + if (g_game->challenge == CHALLENGE_BACKASSWARDS) return; + + if (!sprite.animState.animData || sprite.animState.animData->name != ANIM_OPENING) + sprite.Play(ANIM_OPENING, PLAY_FORCED); + bool isPlainSheet = + strncasecmp(sprite.filename.c_str(), TRAPDOOR_SHEET_PREFIX.data(), TRAPDOOR_SHEET_PREFIX.size()) == 0; + if (sprite.IsPlaying(ANIM_OPENING) && (int)std::floor(sprite.animState.animFrame) == 1 && isPlainSheet) + grid_sound_play(SOUND_SHOVEL_HOLE_OPEN); + if (!sprite.animState.animData || !sprite.animState.isPlaying) trapDoor.state = 1; +} + +// Every main player drops into the hole: the trapdoor animation, aimed at its center. +static void players_fall(const Vector& position) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0) continue; + player->PlayExtraAnimation(ANIM_PLAYER_FALL); + player->moveToTarget = position; + } +} + +// Where an open trapdoor takes the player who falls in: Mother's hole to the Corpse's secret exit, the Lil Portal +// room's back, the knife's start room when a piece is missing on Repentance's path, else the next floor (the same one +// again in the endless basement, the Void through its portal). A secret exit or the Mausoleum's heart floor marks the +// secret path, and the Ascent's with the photo door. +static void trapdoor_enter(GridEntity_TrapDoor& trapDoor, Entity_Player& player, const Vector& position) +{ + Game& game = *g_game; + + if (is_mother_hole(trapDoor)) + { + grid_sound_play(SOUND_TRAP_DOOR_LEVEL); + game.leaveDoor = -1; + game.StartRoomTransition({.player = &player, + .animation = TRANSITION_TRAPDOOR, + .direction = DIRECTION_NONE, + .roomIndex = ROOM_SECRET_EXIT_IDX}); + return players_fall(position); + } + + if (game.currentRoomIdx == ROOM_LIL_PORTAL_IDX) + game.StartRoomTransition({.player = &player, + .animation = TRANSITION_PIXELATION, + .direction = DIRECTION_NONE, + .roomIndex = ROOM_ERROR_IDX}); + else + { + grid_sound_play(SOUND_TRAP_DOOR_LEVEL); + if (game.room->roomType == ROOM_SECRET_EXIT || game.IsMausoleumHeartStage()) + { + game.gameStateFlags |= 1ull << GAME_STATE_SECRET_PATH; + if (game.HasPhotoDoor()) game.gameStateFlags |= 1ull << GAME_STATE_BACKWARDS_PATH_INIT; + } + + bool isRepentancePath = + game.GetChallengeParams().pathType == PATH_TYPE_REPENTANCE && game.challenge != CHALLENGE_RED_REDEMPTION; + if (game.seedEffects.HasSeedEffect(SEED_INFINITE_BASEMENT)) + game.stageTransition.start({.type = STAGE_TRANSITION_NEXT, .isSameStage = true}); + else + { + if ((int)game.stage > STAGE_LAST_CHAPTER) + game.seedEffects.ForgetStageSeed((int)game.stage + (game.IsAltPath() ? 1 : 0)); + if (trapDoor.varData == TRAPDOOR_VOID_PORTAL) game.stageTransition.start({.type = STAGE_TRANSITION_VOID}); + else if (!isRepentancePath || !is_knife_piece_missing()) + game.stageTransition.start({.type = STAGE_TRANSITION_NEXT}); + else + { + game.StartRoomTransition({.player = &player, + .animation = TRANSITION_TRAPDOOR, + .direction = DIRECTION_NONE, + .dimension = 0, + .roomIndex = game.startingRoomIdx}); + players_fall(position); + } + } + } + player.PlayExtraAnimation(ANIM_PLAYER_FALL); + player.moveToTarget = position; +} + +// 00703770 Game::MakeShockwave: starts the next of the room's two ripples at a position. +void shockwave_make(const Vector& position, float amplitude, float speed, int duration) +{ + Room& room = *g_game->room; + Shockwave& wave = roomShockwaves[++room.unknown70fc % SHOCKWAVE_COUNT]; + + wave = {.position = position, .amplitude = amplitude, .speed = speed, .duration = duration}; +} + +// The Void's portal (and the Blue Womb's way to it) ripples the room every 15 frames, faintly while shut. +static void void_portal_ripple(GridEntity_TrapDoor& trapDoor) +{ + Game& game = *g_game; + Room& room = *game.room; + bool isVoidRoom = game.stage == STAGE_BLUE_WOMB && game.currentRoomIdx == ROOM_THE_VOID_IDX; + + if (!room.isInitialized || (game.frameCount - room.enterFrame) % VOID_SHOCKWAVE_FRAMES != 0) return; + if (!isVoidRoom && trapDoor.varData != TRAPDOOR_VOID_PORTAL) return; + + bool isMegaSatan = game.currentRoomIdx == ROOM_MEGA_SATAN_IDX; + float amplitude = isMegaSatan ? MEGA_SATAN_SHOCKWAVE_AMPLITUDE : VOID_SHOCKWAVE_AMPLITUDE; + if (trapDoor.state != 1) amplitude *= CLOSED_SHOCKWAVE_SCALE; + shockwave_make(trapDoor.Position(), amplitude, SHOCKWAVE_SPEED, + isMegaSatan ? MEGA_SATAN_SHOCKWAVE_DURATION : VOID_SHOCKWAVE_DURATION); +} + +// 0071fef0 Stays shut while the nearest player stands within 50 of it (or something else holds it shut), opens once +// they step off, and takes the nearest player who walks onto the open hole. Greed shuts it again in an uncleared wave. +// The original also opened it for a netplay boss room's late joiners, which the offline game never has. void GridEntity_TrapDoor::Update() { - reconstruction_missing("GridEntity_TrapDoor::Update 0071fef0"); + Game& game = *g_game; + Room& room = *game.room; + Vector position = Position(); + Entity_Player* player = main_player_nearest(position); + float distance = player ? vector_length(vector_sub(position, player->pos)) : PLAYER_FAR; + float reach = is_mother_hole(*this) ? MOTHER_HOLE_REACH : REACH; + bool isShut = (player && distance < PLAYER_CLEARANCE) || is_forgotten_body_on(position) || is_held_shut(); + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + + frameCount++; + if (isShut && state == 0) sprite.Play(ANIM_CLOSED); + else if (state != 1) trapdoor_open_update(*this); + + if (isGreed && !room_is_cleared(room) && spawnFrame <= room.enterFrame) + { + sprite.Play(ANIM_CLOSED); + state = 0; + } + if (state == 1) + { + if (!game.IsMausoleumHeartStage() || varData != 0) sprite.Play(ANIM_OPENED); + else sprite.SetFrame(ANIM_OPENED, 0); + } + + bool isBusy = player && (player->isPlayingExtraAnimation || player->isPlayingItemAnimation); + bool isHoldingTwin = player && player->heldEntity && player->heldEntity == player->twinPlayer.get(); + if (player && distance < reach && state == 1 && (!isBusy || isHoldingTwin)) + trapdoor_enter(*this, *player, position); + + void_portal_ripple(*this); + sprite.Update(); } // 00714750 Water lies flat over the trapdoor. diff --git a/src/grid_entity_trap_door.h b/src/grid_entity_trap_door.h index 192338d..262b53e 100644 --- a/src/grid_entity_trap_door.h +++ b/src/grid_entity_trap_door.h @@ -2,13 +2,19 @@ #include "grid_entity.h" +// A trapdoor's varData: the Void's portal, which leads to the Void and shakes the room. +constexpr int TRAPDOOR_VOID_PORTAL = 1; + // Destruction (0070bdd0) is the default. -// A trapdoor to the next floor (Lua's GRID_TRAPDOOR), or the heavenly light up. +// A trapdoor to the next floor (Lua's GRID_TRAPDOOR), or the Void's portal: closed while a player stands on it, opening +// once they step off, taking a player who falls in to the next floor. frameCount counts its updates. struct GridEntity_TrapDoor : GridEntity { - int openFrames = 0; + int frameCount = 0; void subclass_init() override; void Update() override; WaterClipInfo GetWaterClipInfo() override; }; + +void shockwave_make(const Vector& position, float amplitude, float speed, int duration); diff --git a/src/item_pool.cpp b/src/item_pool.cpp index 2cbc9fa..da7a59d 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -390,12 +390,6 @@ void ItemPool::StoreGameState(GameStateItemPool& state) state.remainingGenesisItems = remainingGenesisItems; } -// Not reconstructed yet: it stops the game where it is reached. -void ItemPool::RestoreGameState(const GameStateItemPool&) -{ - reconstruction_missing("ItemPool::RestoreGameState 00736530"); -} - // 00732c70 ItemPool_Item& ItemPool::GetPool(ItemPoolType poolType) { diff --git a/src/level.cpp b/src/level.cpp index ba9f1dc..c051793 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -17,6 +17,7 @@ #include #include #include +#include // Where GetEnterPosition puts the players: a crawlspace's ladder down and its ladder back up, the Black Market's // stairs, and the spots of the secret shop and the two off-map rooms between it and the Black Market. @@ -2661,40 +2662,93 @@ void Level::DEBUG_goto_room(RoomConfig_Room*) reconstruction_missing("Level::DEBUG_goto_room 0073fa20"); } -// 00748860 Reveals the map. +// The floor's state flags the map effects keep, by bit, so they apply again. +enum MapEffectFlag : int +{ + MAP_EFFECT_COMPASS = 7, + MAP_EFFECT_MAP = 8, + MAP_EFFECT_BLUE_MAP = 9, + MAP_EFFECT_FULL_MAP = 10, + MAP_EFFECT_BOSS_ROOM = 18, + MAP_EFFECT_SECRET_ROOM = 20 +}; + +// Marks the floor's rooms whose type a map effect shows with display flags, redraws the map and keeps the effect in a +// floor state flag (none for -1). +// The original reads the config of a room without one after logging it. Here that room is skipped. +template +static void map_effect_apply(Level& level, uint32_t display, Shows isShown, int stateFlag) +{ + for (int i = 0; i < level.nbRooms; i++) + { + RoomDescriptor& room = level.roomList[i]; + if (!room.data) log_printf(LOG_ERROR, "[error] Room %d is not initialized\n", i); + else if (isShown(room.data->type)) room.displayFlags |= display; + } + g_game->minimap.Refresh(); + if (stateFlag >= 0) level.levelStateFlags |= 1u << stateFlag; +} + +// Whether a room type is one of the secret rooms. +static bool is_secret_type(int type) +{ + return type == ROOM_SECRET || type == ROOM_SUPERSECRET || type == ROOM_ULTRASECRET; +} + +// 00748860 The map: every room but the secret ones shows its outline. void Level::ApplyMapEffect() { - reconstruction_missing("Level::ApplyMapEffect 00748860"); + map_effect_apply(*this, ROOM_DISPLAY_BOX, [](int type) { return !is_secret_type(type); }, MAP_EFFECT_MAP); } -// 007488d0 Reveals the secret rooms. +// 007488d0 The Blue Map: the secret and super secret rooms show their icons. void Level::ApplyBlueMapEffect() { - reconstruction_missing("Level::ApplyBlueMapEffect 007488d0"); + auto isShown = [](int type) { return type == ROOM_SECRET || type == ROOM_SUPERSECRET; }; + map_effect_apply(*this, ROOM_DISPLAY_ICON, isShown, MAP_EFFECT_BLUE_MAP); } -// 00748940 Reveals the special rooms. -void Level::ApplyCompassEffect(bool) +// 00748940 The Compass: the special rooms (not the normal or secret ones) show their icons, kept for the floor when +// persistent. +void Level::ApplyCompassEffect(bool isPersistent) { - reconstruction_missing("Level::ApplyCompassEffect 00748940"); + auto isShown = [](int type) { return type != ROOM_DEFAULT && !is_secret_type(type); }; + map_effect_apply(*this, ROOM_DISPLAY_ICON, isShown, isPersistent ? MAP_EFFECT_COMPASS : -1); } -// 00748ae0 Hides the special rooms again. -void Level::RemoveCompassEffect() -{ - reconstruction_missing("Level::RemoveCompassEffect 00748ae0"); -} - -// 007489c0 Reveals every room. +// 007489c0 The whole map: every room but the super and ultra secret ones shows its outline and icon. void Level::ShowMap() { - reconstruction_missing("Level::ShowMap 007489c0"); + auto isShown = [](int type) { return type != ROOM_SUPERSECRET && type != ROOM_ULTRASECRET; }; + map_effect_apply(*this, ROOM_DISPLAY_BOX | ROOM_DISPLAY_ICON, isShown, MAP_EFFECT_FULL_MAP); } -// 00748a70 Reveals the secret room. +// 00748a70 Luna's reveal: the first secret room shows its icon. void Level::reveal_secret_room() { - reconstruction_missing("Level::reveal_secret_room 00748a70"); + bool isRevealed = false; + auto isShown = [&](int type) { return type == ROOM_SECRET && !std::exchange(isRevealed, true); }; + map_effect_apply(*this, ROOM_DISPLAY_ICON, isShown, MAP_EFFECT_SECRET_ROOM); +} + +// 00748ae0 Hides the rooms only a temporary compass showed, then applies again the map effects the floor keeps: the +// map, the Blue Map, the Compass, the whole map, the boss room's icon and the secret room's. +void Level::RemoveCompassEffect() +{ + for (int i = 0; i < nbRooms; i++) + if (roomList[i].displayFlags == ROOM_DISPLAY_ICON) roomList[i].displayFlags = 0; + + if (levelStateFlags & 1u << MAP_EFFECT_MAP) ApplyMapEffect(); + if (levelStateFlags & 1u << MAP_EFFECT_BLUE_MAP) ApplyBlueMapEffect(); + if (levelStateFlags & 1u << MAP_EFFECT_COMPASS) ApplyCompassEffect(true); + if (levelStateFlags & 1u << MAP_EFFECT_FULL_MAP) ShowMap(); + if (levelStateFlags & 1u << MAP_EFFECT_BOSS_ROOM) + { + if (lastBossRoomListIdx >= 0) roomList[lastBossRoomListIdx].displayFlags |= ROOM_DISPLAY_ICON; + g_game->minimap.Refresh(); + } + if (levelStateFlags & 1u << MAP_EFFECT_SECRET_ROOM) reveal_secret_room(); + g_game->minimap.Refresh(); } // 00740860 A random room index. @@ -3088,15 +3142,3 @@ void Level::ShowName(bool isSticky) } g_game->hud.messageMain.Show(name.c_str(), curse.c_str(), !isSticky, !curse.empty()); } - -// 007475b0 Restores the floor from a save. -void Level::RestoreGameState(GameState&) -{ - reconstruction_missing("Level::RestoreGameState 007475b0"); -} - -// 007474a0 The room config a saved id names. -RoomConfig_Room* Level::get_room_config_from_saved_id(uint32_t*, void*) -{ - reconstruction_missing("Level::get_room_config_from_saved_id 007474a0"); -} diff --git a/src/level.h b/src/level.h index 74f22bd..8835794 100644 --- a/src/level.h +++ b/src/level.h @@ -259,5 +259,4 @@ public: void ShowName(bool isSticky); void RestoreGameState(GameState& state); void store_game_state(GameState& state); - static RoomConfig_Room* get_room_config_from_saved_id(uint32_t* savedId, void* mergeTable); }; diff --git a/src/manager.cpp b/src/manager.cpp index e275591..56dfb04 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -1234,6 +1234,27 @@ static void nightmare_scene_restart(NightmareScene& scene) scene.order_shuffle(); } +// Continues the saved run, as start_pending_game does inline: the HUD's graphics, the run rebuilt from the save, the +// controllers handed out again, the players entering the floor and their room, which updates once behind a fade in. +static void continue_game() +{ + constexpr float CONTINUE_FADE_SPEED = 0.04f; + Game& game = *g_game; + + game.isStarted = true; + game.isStartingFromState = true; + game.hud.LoadGraphics(); + game.restore_game_state(g_manager->gamestate, RESTORE_CONTINUE); + game.playerManager.restore_controller_assignment(); + game.playerManager.enter_level(); + game.playerManager.trigger_new_room_effects(); + game.room->Update(); + game.Fadein(CONTINUE_FADE_SPEED, FADE_ICON_SHOW, kcolor_rgba(0, 0, 0, 1)); + game.framesSinceRoomTransition = 0; + lua_engine_get().PostGameStart(true); + game.isStartingFromState = false; +} + // 00959720 Starts the queued run on an even frame: unloads the menus, makes the game the first time, readies the // nightmares, then continues the saved run, starts the rerun, the daily, the debug run or a new run, and leaves the run // to save on exit. @@ -1261,7 +1282,7 @@ void Manager::start_pending_game() if (isRerunAvailable) { isRerunAvailable = false; - reconstruction_missing("Game::restore_game_state 006f8140, continuing the saved run"); + continue_game(); } else { diff --git a/src/manager_input.cpp b/src/manager_input.cpp index 95657f8..d090443 100644 --- a/src/manager_input.cpp +++ b/src/manager_input.cpp @@ -111,7 +111,7 @@ void Manager::update_ingame_input() if (transition.mode != TRANSITION_NONE) return; if (game.genericPrompt.IsActive()) return game.genericPrompt.handle_input(); - bool isRunShown = game.fadeInColor._alpha <= 0 && game.stageTransition._state == 0 && !game.onlineStatsScreen.isActive; + bool isRunShown = game.fadeInColor._alpha <= 0 && game.stageTransition.state == 0 && !game.onlineStatsScreen.isActive; if (isRunShown) { game.pauseScreen.Update(); diff --git a/src/menu_game.cpp b/src/menu_game.cpp index 916956a..98629f9 100644 --- a/src/menu_game.cpp +++ b/src/menu_game.cpp @@ -1,8 +1,14 @@ #include "menu_game.h" +#include "game.h" +#include "game_state_player.h" #include "log.h" #include "manager.h" #include "menu_manager.h" #include "render_passes.h" +#include +#include +#include +#include constexpr const char* GAME_MENU_ANM2 = "gfx/ui/main menu/GameMenu.anm2"; constexpr const char* CONTINUE_WIDGET_ANM2 = "gfx/ui/main menu/ContinueProgress_Widget.anm2"; @@ -27,6 +33,23 @@ constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr uint32_t WHITE_ARGB = 0xffffffff; constexpr uint32_t CLEAR_ARGB = 0; +constexpr const char* ANIMATION_CHARACTER = "Character"; +constexpr const char* TIME_NULL = "Time"; +constexpr const char* STAGE_NULL = "Stage"; +constexpr int CHARACTER_LAYER = 0; +constexpr int DIFFICULTY_LAYER = 2; +constexpr int CHARACTER_ALT_LAYER = 3; +constexpr int FRAMES_PER_SECOND = 30; +constexpr int SECONDS_PER_MINUTE = 60; +constexpr int SECONDS_PER_HOUR = 3600; +constexpr int TIME_TEXT_SIZE = 9; +constexpr int STAGE_LINE_WIDTH = 88; +constexpr size_t SHORT_WORD_LENGTH = 2; +constexpr float TEXT_RAISE = 6; +constexpr float SECOND_LINE_SHIFT_X = 4; +constexpr float SECOND_LINE_SHIFT_Y = 14; +constexpr uint32_t INK_ARGB = 0xff372b2d; + // Whether the saved run, or the run to rerun, can be continued. static bool is_continue_available() { @@ -76,10 +99,100 @@ void Menu_Game::Reset() keyDownTimer = 0; } -// 00982100 Draws the saved run into the continue surface: its character, difficulty, time and floor. +// The stage name in at most two lines: whole when it fits the widget, else split at its spaces, a word of up to two +// letters joined to the one before. The first line then takes words while it stays under half the name, and the +// second takes the rest. +static std::vector stage_lines_split(const std::string& name, Font& font) +{ + if (font.GetStringWidth(name) < STAGE_LINE_WIDTH) return {name}; + + std::vector lines; + for (auto word : std::views::split(name, ' ')) lines.emplace_back(word.begin(), word.end()); + + // Joins the line at index into the one before it. + auto lines_join = [&lines](size_t index) + { + lines[index - 1] += " " + lines[index]; + lines.erase(lines.begin() + (long)index); + }; + for (size_t i = 1; i < lines.size();) + if (lines[i].size() > SHORT_WORD_LENGTH) i++; + else lines_join(i); + if (lines.size() <= 2) return lines; + + while (lines.size() > 1 && lines[0].size() + 1 + lines[1].size() < name.size() / 2) lines_join(1); + while (lines.size() > 2) lines_join(2); + return lines; +} + +// 00982100 Draws the saved run into the continue surface: its character (a modded one's portrait) and difficulty, the +// time played at the Time null and the floor's name at the Stage null, in one or two lines. void Menu_Game::PreRenderContinueImg() { - reconstruction_missing("Menu_Game::PreRenderContinueImg 00982100: needs GameState's player, time and level fields"); + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + GameState& state = g_manager->gamestate; + Font& font = g_manager->font2_TeamMeatEx12; + ANM2& widget = continueWidgetSprite; + + graphics.render_target_push(continueImage.get(), KAGE::Graphics::TARGET_OWN_SIZE, KAGE::Graphics::PRESENT_FLUSH); + graphics.Clear(); + if (state.isSaveAvailable) + { + Vector center = vector_make((float)continueImage->width * 0.5f, (float)continueImage->height * 0.5f); + int playerType = state.players.empty() ? 0 : state.players[0].playerType; + bool isVanilla = playerType >= 0 && playerType < PLAYER_TYPE_COUNT; + FontSettings settings; + KColor ink = kcolor_argb(INK_ARGB); + + widget.Play(ANIMATION_CHARACTER); + for (int layer : {CHARACTER_LAYER, CHARACTER_ALT_LAYER}) + { + if (isVanilla) widget.SetLayerFrame(layer, playerType); + widget.GetLayer(layer)->isVisible = isVanilla; + } + widget.SetLayerFrame(DIFFICULTY_LAYER, state.difficulty); + widget.Render({center}); + if (!isVanilla) + { + ModSpriteDraw draw{.position = center}; + g_manager->modManager.RenderCustomCharacterPortraits(playerType, draw); + } + + if (const NullFrame* time = widget.GetNullFrame(TIME_NULL)) + { + int seconds = state.timeCounter / FRAMES_PER_SECOND; + int hours = seconds / SECONDS_PER_HOUR; + int minutes = seconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE; + char text[TIME_TEXT_SIZE]; + + std::snprintf(text, sizeof(text), "%02d:%02d:%02d", hours, minutes, seconds % SECONDS_PER_MINUTE); + Vector at = vector_make(center.x + time->pos.x - (float)(font.GetStringWidth(text) / 2), + center.y + time->pos.y - TEXT_RAISE); + font.DrawString(text, at, time->scale, ink, settings); + } + + if (const NullFrame* stage = widget.GetNullFrame(STAGE_NULL)) + { + bool isGreed = state.difficulty == DIFFICULTY_GREED || state.difficulty == DIFFICULTY_GREEDIER; + bool isNumbered = state.seeds.HasSeedEffect(SEED_INFINITE_BASEMENT); + std::string name = Level::get_stage_display_name({.stage = (int)state.stage, + .stageType = (int)state.stageType, + .curses = state.curses, + .numeral = isNumbered ? state.stageNameNumeral : 0, + .isScrambled = state.seeds.HasSeedEffect(SEED_DYSLEXIA), + .mode = isGreed ? ROOM_MODE_GREED : ROOM_MODE_NORMAL}); + Vector at = vector_make(center.x + stage->pos.x, center.y + stage->pos.y - TEXT_RAISE); + + for (const std::string& line : stage_lines_split(name, font)) + { + font.DrawString(line, vector_make(at.x - (float)((unsigned)font.GetStringWidth(line) >> 1), at.y), + stage->scale, ink, settings); + at = vector_make(at.x + SECOND_LINE_SHIFT_X, at.y + SECOND_LINE_SHIFT_Y); + } + } + } + graphics.Present(KAGE::Graphics::PRESENT_FINISH); + graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); } // Starts the run once the menus faded out, every other frame: the saved run, or a fresh run with a rerun to come. diff --git a/src/minimap.cpp b/src/minimap.cpp index 8473571..66c1a37 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -1,4 +1,5 @@ #include "minimap.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" #include "hud.h" @@ -168,12 +169,62 @@ struct MapIcon const char* animation; }; -constexpr MapIcon MAP_ICONS[] = {{0, "IconHeart"}, {6, "IconItem"}, {10, "IconTrinket"}, {9, "IconChest"}, - {12, "IconRune"}, {5, "IconCard"}, {7, "IconPill"}, {3, "IconKey"}, - {4, "IconBomb"}, {2, "IconPoop"}, {1, "IconCoin"}, {8, "IconBattery"}, - {13, "IconBeggar"}, {11, "IconSlot"}, {14, "IconLadder"}, {15, "IconPortal"}}; -constexpr int MAP_ICON_LADDER = 14; -constexpr int MAP_ICON_COUNT = 16; +// The bits of RoomIcons::shown. +enum MapIconBit : int +{ + MAP_ICON_HEART, + MAP_ICON_COIN, + MAP_ICON_POOP, + MAP_ICON_KEY, + MAP_ICON_BOMB, + MAP_ICON_CARD, + MAP_ICON_ITEM, + MAP_ICON_PILL, + MAP_ICON_BATTERY, + MAP_ICON_CHEST, + MAP_ICON_TRINKET, + MAP_ICON_SLOT, + MAP_ICON_RUNE, + MAP_ICON_BEGGAR, + MAP_ICON_LADDER, + MAP_ICON_PORTAL, + MAP_ICON_COUNT +}; + +constexpr MapIcon MAP_ICONS[] = { + {MAP_ICON_HEART, "IconHeart"}, {MAP_ICON_ITEM, "IconItem"}, {MAP_ICON_TRINKET, "IconTrinket"}, + {MAP_ICON_CHEST, "IconChest"}, {MAP_ICON_RUNE, "IconRune"}, {MAP_ICON_CARD, "IconCard"}, + {MAP_ICON_PILL, "IconPill"}, {MAP_ICON_KEY, "IconKey"}, {MAP_ICON_BOMB, "IconBomb"}, + {MAP_ICON_POOP, "IconPoop"}, {MAP_ICON_COIN, "IconCoin"}, {MAP_ICON_BATTERY, "IconBattery"}, + {MAP_ICON_BEGGAR, "IconBeggar"}, {MAP_ICON_SLOT, "IconSlot"}, {MAP_ICON_LADDER, "IconLadder"}, + {MAP_ICON_PORTAL, "IconPortal"}}; + +// An icon and its frame, as a saved slot or beggar shows it. +struct SlotIcon +{ + MapIconBit bit; + int frame; +}; + +// The frame of the icon a saved heart or coin shows, by subtype, and the icon a slot or beggar shows, by variant. +// A heart past its table shows the full heart's, a coin the penny's and a slot the first's. +constexpr int HEART_ICON_FRAMES[] = {1, 1, 0, 5, 9, 1, 6, 8, 3, 1, 4, 7, 2}; +constexpr int COIN_ICON_FRAMES[] = {0, 0, 1, 2, 0, 0, 1, 3}; +constexpr SlotIcon SLOT_ICONS[] = { + {MAP_ICON_SLOT, 2}, {MAP_ICON_SLOT, 2}, {MAP_ICON_SLOT, 3}, {MAP_ICON_SLOT, 4}, {MAP_ICON_BEGGAR, 0}, + {MAP_ICON_BEGGAR, 2}, {MAP_ICON_BEGGAR, 0}, {MAP_ICON_BEGGAR, 3}, {MAP_ICON_SLOT, 1}, {MAP_ICON_BEGGAR, 4}, + {MAP_ICON_SLOT, 6}, {MAP_ICON_SLOT, 1}, {MAP_ICON_SLOT, 0}, {MAP_ICON_BEGGAR, 5}, {MAP_ICON_SLOT, 2}, + {MAP_ICON_BEGGAR, 2}, {MAP_ICON_SLOT, 5}, {MAP_ICON_SLOT, 7}, {MAP_ICON_BEGGAR, 1}, {MAP_ICON_SLOT, 8}}; +constexpr int SLOT_VARIANT_NO_ICON = 14; +constexpr int EFFECT_PORTAL_VARIANT = 161; +constexpr int EFFECT_PORTAL_SUBTYPE = 980; +constexpr int GOLDEN_BOMB_SUBTYPE = 4; +constexpr int GOLDEN_KEY_SUBTYPE = 2; +constexpr int CHARGED_KEY_SUBTYPE = 4; +constexpr int MEGA_BATTERY_SUBTYPE = 4; +constexpr int GOLD_PILL = 14; +constexpr int PILL_COLOR_MASK = 0x7ff; +constexpr int GRAB_BAG_SACK = 2; // What refresh's passes share: the current room, the first cell drawn and the step from one cell to the next. struct MapWindow @@ -397,20 +448,108 @@ static const char* room_icon_get(const RoomDescriptor& room) } } -// The pickups and objects a shown room holds, from what it saved when left, and its crawlspace ladder. +// Shows an icon once, counting it. +static void room_icon_show(RoomIcons& icons, MapIconBit bit) +{ + if (icons.shown & 1u << bit) return; + icons.shown |= 1u << bit; + icons.count++; +} + +// Shows an icon, raising its frame to at least frame. +static void room_icon_raise(RoomIcons& icons, MapIconBit bit, int frame) +{ + room_icon_show(icons, bit); + icons.frames[bit] = std::max(icons.frames[bit], frame); +} + +// The chest icon's frame a chest or sack shows, or -1 for the spiked chest, which leaves it. +static int chest_icon_frame(const EntitySaveState& saved) +{ + switch (saved.variant) + { + case PICKUP_BOMBCHEST: return 1; + case PICKUP_SPIKEDCHEST: return -1; + case PICKUP_ETERNALCHEST: return 7; + case PICKUP_WOODENCHEST: return 6; + case PICKUP_MEGACHEST: return 9; + case PICKUP_LOCKEDCHEST: return 8; + case PICKUP_GRAB_BAG: return saved.subtype == GRAB_BAG_SACK ? 3 : 2; + case PICKUP_REDCHEST: return 5; + default: return 4; + } +} + +// The icon a saved pickup shows, by its variant: hearts, coins, keys, bombs, pills and batteries by the best one's +// frame, cards and runes, collectibles, trinkets and poop, and chests and sacks. A pickup another one holds or one +// saved at the origin shows none. +static void pickup_icon_add(RoomIcons& icons, const EntitySaveState& saved) +{ + int subtype = saved.subtype; + if (saved.intStorage3 != 0 || (saved.targetPosition.x == 0 && saved.targetPosition.y == 0)) return; + + switch (saved.variant) + { + case PICKUP_HEART: + { + bool isListed = subtype >= 0 && subtype < (int)std::size(HEART_ICON_FRAMES); + room_icon_raise(icons, MAP_ICON_HEART, isListed ? HEART_ICON_FRAMES[subtype] : 1); + return; + } + case PICKUP_COIN: + { + bool isListed = subtype >= 0 && subtype < (int)std::size(COIN_ICON_FRAMES); + room_icon_raise(icons, MAP_ICON_COIN, isListed ? COIN_ICON_FRAMES[subtype] : 0); + return; + } + case PICKUP_POOP: room_icon_show(icons, MAP_ICON_POOP); return; + case PICKUP_BOMB: room_icon_raise(icons, MAP_ICON_BOMB, subtype == GOLDEN_BOMB_SUBTYPE); return; + case PICKUP_KEY: + { + int frame = subtype == GOLDEN_KEY_SUBTYPE ? 1 : subtype == CHARGED_KEY_SUBTYPE ? 2 : 0; + room_icon_raise(icons, MAP_ICON_KEY, frame); + return; + } + case PICKUP_TAROTCARD: + { + ItemConfig_Card* card = g_manager->itemConfig.GetCard(subtype); + room_icon_show(icons, card && card->cardType == CARD_RUNE ? MAP_ICON_RUNE : MAP_ICON_CARD); + return; + } + case PICKUP_LIL_BATTERY: room_icon_raise(icons, MAP_ICON_BATTERY, subtype == MEGA_BATTERY_SUBTYPE); return; + case PICKUP_PILL: room_icon_raise(icons, MAP_ICON_PILL, (subtype & PILL_COLOR_MASK) == GOLD_PILL); return; + case PICKUP_COLLECTIBLE: room_icon_show(icons, MAP_ICON_ITEM); return; + case PICKUP_TRINKET: room_icon_show(icons, MAP_ICON_TRINKET); return; + default: break; + } + if (!Entity_Pickup::IsChest(saved.variant) && saved.variant != PICKUP_GRAB_BAG) return; + + room_icon_show(icons, MAP_ICON_CHEST); + if (int frame = chest_icon_frame(saved); frame >= 0) room_icon_raise(icons, MAP_ICON_CHEST, frame); +} + +// The pickups and objects a shown room holds, from what it saved when left (pickups, slots and beggars, and the +// portal of a Delirium room), and its crawlspace ladder. static RoomIcons room_icons_find(const RoomDescriptor& room, int cell) { RoomIcons icons; if (room.displayFlags == 0) return icons; - if (!g_game->GetRoomByIdx(cell)->savedEntities.empty()) - reconstruction_missing("MinimapConfig::refresh 0098b5e0: a room's saved pickups need EntitySaveState's fields"); - for (const GridEntityDesc& grid : room.savedGridEntities) + for (const EntitySaveState& saved : g_game->GetRoomByIdx(cell)->savedEntities) { - if (grid._type != MAP_GRID_STAIRS || icons.shown & 1u << MAP_ICON_LADDER) continue; - icons.shown |= 1u << MAP_ICON_LADDER; - icons.count++; + if (saved.type == ENTITY_PICKUP) pickup_icon_add(icons, saved); + else if (saved.type == ENTITY_SLOT && saved.variant != SLOT_VARIANT_NO_ICON) + { + bool isListed = saved.variant >= 0 && saved.variant < (int)std::size(SLOT_ICONS); + SlotIcon icon = isListed ? SLOT_ICONS[saved.variant] : SLOT_ICONS[0]; + room_icon_raise(icons, icon.bit, icon.frame); + } + else if (saved.type == ENTITY_EFFECT && saved.variant == EFFECT_PORTAL_VARIANT && + saved.subtype == EFFECT_PORTAL_SUBTYPE) + room_icon_show(icons, MAP_ICON_PORTAL); } + for (const GridEntityDesc& grid : room.savedGridEntities) + if (grid._type == MAP_GRID_STAIRS) room_icon_show(icons, MAP_ICON_LADDER); return icons; } diff --git a/src/nightmare_scene.cpp b/src/nightmare_scene.cpp index b8f72f2..d56bb41 100644 --- a/src/nightmare_scene.cpp +++ b/src/nightmare_scene.cpp @@ -6,10 +6,16 @@ #include "music_manager.h" #include "persistent_game_data.h" #include "manager.h" +#include "entity_config.h" +#include "entity_player.h" +#include "render_passes.h" #include "menu_manager.h" #include "seeds.h" #include "texture_cache.h" #include +#include +#include +#include constexpr std::string_view BACKGROUND_DEFAULT = "nightmare_bg.anm2"; constexpr std::string_view SCENE_ANIM = "Scene"; @@ -22,7 +28,6 @@ constexpr int BACKGROUND_STATIC_LAYER = 7; constexpr int BUBBLE_STATIC_LAYER = 9; constexpr unsigned int STATIC_LAYER_FLAGS = ANIM_RENDER_STATIC | ANIM_RENDER_IGNORE_GAME_TIME; -constexpr int COLLECTIBLE_DREAM_CATCHER = 566; constexpr uint32_t STAGE_ID_HOME = 26; constexpr uint32_t STAGE_LAST_WITH_DREAM_CATCHER = 6; // A Game state flag set once Dream Catcher showed this chapter, letting its nightmare be skipped. @@ -86,8 +91,268 @@ void NightmareScene::order_shuffle() std::swap(nightmareOrder[i], nightmareOrder[Random() % (uint32_t)(i + 1)]); } -void NightmareScene::Show(bool) { reconstruction_missing("NightmareScene::Show 00921ce0"); } -void NightmareScene::Render() { reconstruction_missing("NightmareScene::Render 00920940"); } +// The characters whose portrait floats on the background's alternate layer: ???, Keeper, The Forgotten and The Soul, +// and the tainted ???, Keeper and Forgotten. +constexpr std::array ALT_PORTRAIT_PLAYERS = {4, 16, 17, 14, 25, 35, 33}; +constexpr int PORTRAIT_LAYER = 2; +constexpr int PORTRAIT_ALT_LAYER = 6; +constexpr int BOSS_SPOT_LAYER = 3; +constexpr std::string_view NIGHTMARE_PREFIX = "gfx/ui/stage/nightmare"; +constexpr std::string_view G_FUEL_PREFIX = "gfx/promo/gfuel/ui/stage/nightmareg"; +constexpr std::string_view DREAM_CATCHER_ANM2 = "gfx/ui/stage/nightmare_dc.anm2"; +constexpr std::string_view DOGMA_ANM2 = "gfx/ui/stage/nightmare_dogma.anm2"; +constexpr std::string_view INTRO_ANIM = "Intro"; +constexpr int MUSIC_JINGLE_NIGHTMARE = 96; +constexpr int MUSIC_DOGMA_NIGHTMARE = 65; +constexpr int STAGE_VOID_INDEX = 9; +constexpr float DEGREES_TO_RADIANS = std::numbers::pi_v / 180; + +// The stage bar: its icons 27 apart on row 24, Isaac walking a slot over the scene's frames 10 to 40, and the clock's +// span of five slots. Icon 17 is a stage not reached. +constexpr float BAR_ROW = 24; +constexpr float BAR_SLOT = 27; +constexpr float BAR_START_OFFSET = 11.5f; +constexpr float BAR_CONNECTOR_OFFSET = 13.5f; +constexpr float BAR_SLOT_PADDING = 4; +constexpr float CLOCK_SPAN = 135; +constexpr int WALK_FIRST = 10; +constexpr int WALK_LAST = 40; +constexpr int WALK_DELAY = 30; +constexpr int ICON_UNKNOWN = 17; +constexpr int ICON_HIDDEN = -1; +constexpr int STAGE_BAR_LAST = 6; +constexpr int STAGE_BAR_LAST_WOMB = 8; +constexpr int STAGE_BAR_LAST_GREED = 7; +constexpr int STAGE_BLUE_WOMB = 9; +constexpr int STAGE_HOME_SLOT = 13; +constexpr int ACHIEVEMENT_WOMB = 4; +constexpr int CLOCK_LAST_STAGE = 6; + +// 00921ce0 Starts the nightmare: the next one in the order (G FUEL's own with its seed, Dogma's at Home, Dream +// Catcher's showing the next floor), the player's portrait (an animated one too) on the floor's boss spot, the stage +// bar's position before the new floor, and the nightmare jingle. Netplay's input sync is left out, as the game is +// offline. +void NightmareScene::Show(bool isSameStageShown) +{ + Game& game = *g_game; + Entity_Player* player = game.GetPlayer(0); + // The original indexed an empty nightmare list. This shows no scene. + std::string scenePath = nightmarePaths.empty() ? "" : nightmarePaths[nightmareOrder[nightmareIndex]]; + + if (game.seedEffects.HasSeedEffect(SEED_G_FUEL) && scenePath.starts_with(NIGHTMARE_PREFIX)) + { + std::string promoPath = std::string(G_FUEL_PREFIX) + scenePath.substr(NIGHTMARE_PREFIX.size()); + ANM2 promo; + promo.Load(promoPath, GRAPHICS_LOAD); + if (promo.isLoaded) scenePath = promoPath; + } + dreamCatcherAnims.clear(); + if (isDogma) scenePath = DOGMA_ANM2; + else if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_DREAM_CATCHER, LAZARUS_SHARE_CHECK) && + game.stage != STAGE_HOME) + { + reconstruction_missing("NightmareScene::Show 00921ce0: Dream Catcher's diary of the next floor's items and bosses"); + scenePath = DREAM_CATCHER_ANM2; + } + + EntityConfig_Player* config = g_manager->entityConfig.GetPlayer(player->playerType); + if (config) + { + backgroundSprite.ReplaceSpritesheet(PORTRAIT_LAYER, config->portraitPath); + backgroundSprite.ReplaceSpritesheet(PORTRAIT_ALT_LAYER, config->portraitPath); + } + else log_printf(LOG_INFO, "[warn] could not load player config for type %d.\n", player->playerType); + playerExtraPortraitSprite.Reset(); + // The original read a missing character's animated portrait through a null pointer. This shows none. + if (config && !config->extraPortraitPath.empty()) + { + playerExtraPortraitSprite.Load(config->extraPortraitPath, GRAPHICS_LOAD); + playerExtraPortraitSprite.Play(playerExtraPortraitSprite.GetDefaultAnimationName()); + } + backgroundSprite.ReplaceSpritesheet(BOSS_SPOT_LAYER, game.roomConfig.stages[game.GetStageID()].bossSpot); + backgroundSprite.LoadGraphics(); + backgroundSprite.Play(INTRO_ANIM, PLAY_FORCED); + bubbleSprite.Reset(); + bubbleSprite.Load(scenePath, GRAPHICS_LOAD); + bubbleSprite.SetFrame(SCENE_ANIM, 0); + + bool isAlt = config && std::ranges::find(ALT_PORTRAIT_PLAYERS, config->id) != ALT_PORTRAIT_PLAYERS.end(); + backgroundSprite.GetLayer(PORTRAIT_LAYER)->isVisible = !isAlt; + backgroundSprite.GetLayer(PORTRAIT_ALT_LAYER)->isVisible = isAlt; + + Vector center = vector_make(g_screenWidth * 0.5f, g_screenHeight * 0.5f); + isActive = true; + frame = 0; + backgroundSprite.offset = center; + bubbleSprite.offset = center; + if (!nightmarePaths.empty()) nightmareIndex = (nightmareIndex + 1) % (int)nightmarePaths.size(); + bool isAltPath = game.stageType == STAGE_TYPE_REPENTANCE || game.stageType == STAGE_TYPE_REPENTANCE_B; + stageIndex = isAltPath ? (int)game.stage : (int)game.stage - 1; + isSameStage = isSameStageShown; + g_manager->musicManager.Play(isDogma ? MUSIC_DOGMA_NIGHTMARE : MUSIC_JINGLE_NIGHTMARE, + g_manager->optionsConfig.musicVolume); + if (game.stage == STAGE_VOID) stageIndex = STAGE_VOID_INDEX; +} + +// Draws the background's layers about the screen's middle, the animated portrait over the portrait layers following +// their keyframes. +static void background_render(NightmareScene& scene) +{ + const ANM2& background = scene.backgroundSprite; + const AnimationState& state = background.animState; + ANM2& extra = scene.playerExtraPortraitSprite; + if (!state.animData) return; + + for (const AnimationLayer& layer : state.animData->animLayers) + { + const AnimationFrame* keyframe = state.GetLayerFrame(layer.layerId); + if (!scene.backgroundSprite.GetLayer(layer.layerId)->isVisible || !keyframe || !keyframe->isVisible) continue; + layer.RenderFrame({}, state.GetLayerFrameIdx(layer.layerId), background); + if (!extra.isLoaded || (layer.layerId != PORTRAIT_LAYER && layer.layerId != PORTRAIT_ALT_LAYER)) continue; + + float angle = keyframe->rotation * DEGREES_TO_RADIANS; + float pivotX = -keyframe->pivot.x * keyframe->scale.x; + float pivotY = -keyframe->pivot.y * keyframe->scale.y; + extra.color = keyframe->color; + extra.rotation = keyframe->rotation; + extra.scale = keyframe->scale; + extra.offset.x = pivotX * std::cos(angle) - pivotY * std::sin(angle) + background.offset.x + keyframe->pos.x; + extra.offset.y = pivotY * std::cos(angle) + pivotX * std::sin(angle) + background.offset.y + keyframe->pos.y; + extra.Render({}); + } +} + +// The stage bar's slots: an icon per stage from the first to the further of the floor reached and the chapter's last +// (the Womb's once it was beaten or a daily or debug run goes there), the boss's slot on that last stage, and Isaac's +// slot with the way he walks into it. +struct StageBar +{ + std::vector icons; + int bossSlot = -1; + int current = 0; + int lastSlot = -1; + int playerSlot = -1; + int walk = 0; +}; + +static StageBar stage_bar_get(NightmareScene& scene) +{ + Game& game = *g_game; + Manager& manager = *g_manager; + StageBar bar; + int current = (int)game.stage + (game.IsAltPath() ? 1 : 0); + int last = STAGE_BAR_LAST; + + if (game.IsGreedMode()) last = STAGE_BAR_LAST_GREED; + else + { + bool isDailyOrDebug = manager.state == MANAGER_STATE_GAME && (game.dailyChallenge._id != 0 || game.isDebug); + if (manager.persistentGameData.achievements[ACHIEVEMENT_WOMB] || isDailyOrDebug || + scene.stageIndex > STAGE_BAR_LAST_GREED || (scene.stageIndex == STAGE_BAR_LAST && !scene.isSameStage)) + last = STAGE_BAR_LAST_WOMB; + ChallengeParam& challenge = game.GetChallengeParams(); + if (challenge.isPathTypeSet && challenge.endStage == STAGE_BAR_LAST) last = STAGE_BAR_LAST; + else if (challenge.isPathTypeSet && challenge.endStage > STAGE_BAR_LAST_GREED) last = STAGE_BAR_LAST_WOMB; + if (current == STAGE_BLUE_WOMB) last = current; + } + if (current == STAGE_HOME_SLOT) + { + last = 0; + current = 0; + } + bar.current = current; + + for (int stage = 0; stage <= std::max(current, last); stage++) + { + if (stage == 0 && current != 0) continue; + if (stage == STAGE_BLUE_WOMB && scene.stageIcons[STAGE_BLUE_WOMB] == ICON_UNKNOWN) continue; + + int slot = (int)bar.icons.size(); + bar.icons.push_back(stage == 0 ? scene.stageIcons[STAGE_HOME_SLOT] : scene.stageIcons[stage]); + if (stage == last && scene.stageIndex != last) bar.bossSlot = slot; + if (stage == std::max(current, last) && scene.stageIndex != bar.lastSlot) bar.lastSlot = slot; + if (stage != current) continue; + + bar.playerSlot = slot; + bar.walk = scene.isSameStage ? 0 : game.challenge == CHALLENGE_BACKASSWARDS || current == 0 ? -1 : 1; + } + for (int slot = bar.lastSlot; slot >= 0 && bar.icons[slot] == ICON_UNKNOWN; slot--) bar.icons[slot] = ICON_HIDDEN; + return bar; +} + +// Draws the stage bar's sprite at an x on the bar's row. +static void bar_render_at(ANM2& sprite, float x) +{ + sprite.Render({.position = vector_make(x, BAR_ROW)}); +} + +// The stage bar across the top: connectors, the stages' icons with the passed ones cleared and the unreached ones +// marked, the boss (Greed's) indicator on the chapter's last stage, the Boss Rush clock before the Womb, and Isaac +// walking into the floor reached. +static void stage_bar_render(NightmareScene& scene) +{ + Game& game = *g_game; + ANM2& sprite = scene.progressBarSprite; + StageBar bar = stage_bar_get(scene); + int count = (int)bar.icons.size(); + float startX = g_screenWidth * 0.5f - (float)(count * (int)BAR_SLOT - (int)BAR_SLOT_PADDING) * 0.5f + BAR_START_OFFSET; + auto slotX = [&](int slot) { return (float)slot * BAR_SLOT + startX; }; + + sprite.Play("Connector"); + for (int slot = 0; slot < count - 1; slot++) bar_render_at(sprite, slotX(slot) + BAR_CONNECTOR_OFFSET); + sprite.Play("Levels"); + for (int slot = 0; slot < count; slot++) + { + if (bar.icons[slot] < 0) continue; + if (sprite.animState.animData) sprite.animState.SetFrameFloat((float)bar.icons[slot]); + bar_render_at(sprite, slotX(slot)); + } + sprite.Play("ClearFloor"); + for (int slot = 0; slot < count; slot++) + if (bar.icons[slot] >= 0 && slot != bar.playerSlot) bar_render_at(sprite, slotX(slot)); + sprite.Play("NotClearFloor"); + for (int slot = 0; slot < count; slot++) + if (bar.icons[slot] < 0) bar_render_at(sprite, slotX(slot)); + if (bar.bossSlot >= 0 && bar.lastSlot <= bar.bossSlot) + { + sprite.Play(game.IsGreedMode() ? "GreedIndicator" : "BossIndicator"); + bar_render_at(sprite, slotX(bar.bossSlot)); + } + + bool isClockShown = !game.IsGreedMode() && game.challenge != CHALLENGE_BACKASSWARDS && scene.stageIndex < CLOCK_LAST_STAGE; + if (isClockShown && game.timeCounter <= game.bossRushParTime && bar.current != 0) + { + sprite.Play("Clock"); + bar_render_at(sprite, (float)game.timeCounter / (float)game.bossRushParTime * CLOCK_SPAN + startX); + } + + sprite.SetAnimation("IsaacIndicator"); + if (sprite.animState.animData) + sprite.animState.SetFrameFloat((float)((scene.frame >> 1) % (uint32_t)sprite.animState.animData->length)); + int walkFrame = std::clamp((int)(scene.frame >> 1) - WALK_DELAY, WALK_FIRST, WALK_LAST); + float walked = 1 - (float)(walkFrame - WALK_FIRST) / (float)(WALK_LAST - WALK_FIRST); + bar_render_at(sprite, slotX(bar.playerSlot) - walked * (float)bar.walk * BAR_SLOT); +} + +// 00920940 Draws the nightmare over a cleared screen: the background with the portrait, the bubble (Dream Catcher's +// diary of the next floor), the stage bar but at Dogma's, and the fade. +void NightmareScene::Render() +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + + graphics.Clear(); + if (!isActive) return; + + background_render(*this); + if (isDreamCatcher) reconstruction_missing("NightmareScene::Render 00920940: Dream Catcher's diary"); + else if (bubbleSprite.isLoaded) bubbleSprite.Render({}); + if (!isDogma) stage_bar_render(*this); + if (fadeAlpha <= 0) return; + + graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); + render_color_shader_pass(KAGE::Graphics::color_quad_rect( + {}, vector_make(g_screenWidth, g_screenHeight), kcolor_rgba(0, 0, 0, fadeAlpha))); +} // Whether Dream Catcher's queued animations all played, or else the nightmare's scene stopped. static bool is_scene_finished(NightmareScene& scene) diff --git a/src/nightmare_scene.h b/src/nightmare_scene.h index 4cc2cb5..ede6e97 100644 --- a/src/nightmare_scene.h +++ b/src/nightmare_scene.h @@ -13,7 +13,9 @@ constexpr int STAGE_ICON_COUNT = 14; // Destruction (00950f10) is the default. // The nightmare between floors (g_manager->nightmareScene): a nightmare of nightmares.xml in its bubble over the -// background, the stage bar of the floors so far, and with Dream Catcher the next floor's items and bosses. +// background (the player's portrait on the floor's spot), the stage bar of the floors so far with Isaac walking to the +// next, and with Dream Catcher the next floor's items and bosses. nightmareIndex is the next nightmare in the order, +// stageIndex the bar's stage before the floor reached, and isSameStage whether Isaac stays on it. struct NightmareScene { std::array stageIcons{}; @@ -26,15 +28,18 @@ struct NightmareScene ANM2 playerExtraPortraitSprite; ANM2 progressBarSprite; float fadeAlpha = 0; + int nightmareIndex = 0; int sceneDelay = 0; + int stageIndex = 0; uint32_t frame = 0; bool isActive = false; bool isDogma = false; bool isDreamCatcher = false; + bool isSameStage = false; bool load_nightmares_xml(std::string_view path); void order_shuffle(); - void Show(bool unk); + void Show(bool isSameStageShown); void Update(); void Render(); void record_stage(int stage, int stageType); diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index e9c4cfa..80d0400 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -1,4 +1,6 @@ #include "npc_ai.h" +#include "boss_ai.h" +#include "npc_basement.h" #include "game.h" #include "manager.h" #include "npc_fireplace.h" @@ -85,7 +87,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 211: case 238: case 280: - return (void)NpcAI::ENTITY_GUSHER(&npc); + return npc_gusher_update(npc); case 12: case 248: return npc_horf_update(npc); @@ -101,9 +103,9 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 15: case 282: case 872: - return (void)NpcAI::ENTITY_CLOTTY(&npc); + return npc_clotty_update(npc); case 16: - return (void)NpcAI::ENTITY_MULLIGAN(&npc); + return npc_mulligan_update(npc); case 17: return (void)NpcAI::ENTITY_SHOPKEEPER(&npc); case 19: @@ -234,7 +236,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 78: return (void)NpcAI::ENTITY_MOMS_HEART(&npc); case 79: - reconstruction_missing("npc_ai_update 006c2990: Gemini's parts and death shots"); + return boss_gemini_update(npc); case 81: return (void)NpcAI::ENTITY_FALLEN(&npc); case 82: diff --git a/src/npc_ai.h b/src/npc_ai.h index 24f8a41..5615703 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -11,6 +11,7 @@ constexpr float PI_F = 3.1415927f; constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; constexpr float RANDOM_HALF_TURN = 3.14f; constexpr float DEGREES_TO_RADIANS = 0.017453292f; +constexpr float RADIANS_TO_DEGREES = 57.295776f; // The sound ids the common enemies play (Lua's SoundEffect). enum NpcSound : int @@ -73,6 +74,18 @@ inline Vector vector_resized(Vector v, float length) return current > 0 ? vector_scale(v, length / current) : v; } +// Vector::FromAngle 00a10350: the unit vector at an angle in degrees. +inline Vector vector_from_angle(float degrees) +{ + return vector_make(std::cos(degrees * DEGREES_TO_RADIANS), std::sin(degrees * DEGREES_TO_RADIANS)); +} + +// Vector::GetAngleDegrees 00a10390: a vector's angle in degrees. +inline float vector_angle(Vector v) +{ + return std::atan2(v.y, v.x) * RADIANS_TO_DEGREES; +} + // random_float: a random fraction of one from the global generator. inline float random_unit() { diff --git a/src/npc_basement.h b/src/npc_basement.h new file mode 100644 index 0000000..d7abf7a --- /dev/null +++ b/src/npc_basement.h @@ -0,0 +1,19 @@ +#pragma once + +#include "npc_ai.h" + +// The basement enemies' AIs the dispatcher (npc_ai_update) runs by type. +void npc_gusher_update(Entity_NPC& npc); +void npc_clotty_update(Entity_NPC& npc); +void npc_mulligan_update(Entity_NPC& npc); + +// Keeps an overlay animation playing, restarting it once it ends or another shows. +inline void npc_overlay_loop(ANM2& sprite, std::string_view name) +{ + const AnimationData* data = sprite.overlayAnimState.animData; + bool isShown = data && data->name == name && (!data->isLooping || sprite.overlayAnimState.isPlaying); + if (isShown || !sprite.SetOverlayAnimation(name, SWITCH_KEEP_FRAME)) return; + + sprite.overlayAnimState.Rewind(); + sprite.overlayAnimState.isPlaying = true; +} diff --git a/src/npc_clotty.cpp b/src/npc_clotty.cpp new file mode 100644 index 0000000..f21d42f --- /dev/null +++ b/src/npc_clotty.cpp @@ -0,0 +1,320 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "room_grid.h" + +// The clotties this AI runs: the Clotty with its Clot, I.Blob and Grilled variants, the Mega Clotty and the Cloggy. +constexpr int ENTITY_CLOTTY = 15; +constexpr int ENTITY_GLOBIN_SPAWN = 24; +constexpr int ENTITY_MEGA_CLOTTY = 282; +constexpr int ENTITY_CLOGGY = 872; +constexpr int CLOT = 1; +constexpr int I_BLOB = 2; +constexpr int GRILLED_CLOTTY = 3; + +constexpr int SOUND_FORESTBOSS_STOMPS = 48; +constexpr int SOUND_ANIMAL_SQUISH = 166; +constexpr int CONTROLLER_ACTION_SHOOT = 9; +constexpr int PROJECTILE_PUKE = 3; +constexpr uint64_t PROJECTILE_CURVE_LEFT = 1ull << 18; +constexpr uint64_t PROJECTILE_CURVE_RIGHT = 1ull << 19; +constexpr int BLOOD_EXPLOSION_SPURT = 2; + +// They hop around (a Mega Clotty wading through more friction) and attack once a hop ends while the target is in +// range, waiting 30 frames between (45 for the Mega Clotty, 15 for the Grilled Clotty, who rests after three). +constexpr float CLOTTY_FRICTION = 0.9f; +constexpr float FLEE_FRICTION = 0.8f; +constexpr float MEGA_CLOTTY_FRICTION = 0.85f; +constexpr float CLOTTY_WAIT = 30; +constexpr float MEGA_CLOTTY_WAIT = 45; +constexpr float GRILLED_WAIT = 15; +constexpr int GRILLED_ATTACKS = 3; +constexpr uint32_t CLOTTY_LINGER_ODDS = 30; +constexpr float CLOTTY_RANGE = 1000; +constexpr int CLOTTY_RANGE_FRAMES = 7; +constexpr float HOP_THRESHOLD = 0.5f; +constexpr float CLOTTY_DEADZONE = 0.1f; +constexpr uint64_t FLAG_STUNNED = FLAG_FREEZE | FLAG_CHARM | FLAG_CONFUSION | FLAG_MIDAS_FREEZE; + +// They bleed every 5 frames. Clotties shoot a plus (Clots a black cross, I.Blobs eight ways) at 7 (10 in hard mode), +// the Grilled Clotty a ring of four at 7 (8), the Cloggy a curving ring of four puke shots. +constexpr float BLEED_TICKS = 5; +constexpr float SPLAT_MIN = 0.5f; +constexpr float SPLAT_RANGE = 0.7f; +constexpr float SPURT_RISE = -20; +constexpr float CLOTTY_SHOT_SPEED = 7; +constexpr float CLOTTY_SHOT_SPEED_HARD = 10; +constexpr float GRILLED_SHOT_SPEED_HARD = 8; +constexpr float RING_SHOTS = 4; +constexpr float GRILLED_FALL = 0.02f; +constexpr float GRILLED_SPIN = 0.05f; +constexpr float CLOGGY_SHOT_SPEED = 8; +constexpr float CLOGGY_CURVE = 0.012f; +constexpr float CLOGGY_FALL = -0.02f; +constexpr float CLOGGY_ANGLE = 0.9424779f; + +// The Mega Clotty shoots a ring of six at 10 three times in four, else spawns a Clotty or Globin (while fewer than +// five enemies are left) or spreads four pools of creep within 40, lasting 210 frames. It splits in two Clotties. +constexpr float MEGA_RING_SPEED = 10; +constexpr float MEGA_RING_SHOTS = 6; +constexpr float HALF_TURN_DEGREES = 180; +constexpr float FULL_TURN_DEGREES_CLOTTY = 360; +constexpr float MEGA_SOUND_VOLUME = 0.8f; +constexpr int MEGA_SPAWN_LIMIT = 5; +constexpr float MEGA_SPAWN_STEP = 40; +constexpr int MEGA_CREEPS = 4; +constexpr float MEGA_CREEP_SPREAD = 40; +constexpr float MEGA_CREEP_SCALE_MIN = 1; +constexpr float MEGA_CREEP_SCALE_RANGE = 0.5f; +constexpr int MEGA_CREEP_FRAMES = 210; +constexpr int MEGA_SPLIT = 2; +constexpr float MEGA_SPLIT_SPREAD = 20; + +// A Clotty in a room with little water grills in fire, a Grilled Clotty in water cools down. +constexpr float GRILL_WATER_MAX = 0.2f; +constexpr uint64_t DAMAGE_FIRE_CLOTTY = 1ull << 1; + +constexpr ColorMod CLOGGY_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; +constexpr ColorMod CLOT_SPLAT_COLOR = {{0.02f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod GRILLED_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.14117648f, 0.12156863f, 0.10980392f}}; +constexpr ColorMod CLOT_SHOT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; + +static bool is_grilled(Entity_NPC& npc) +{ + return npc.type == ENTITY_CLOTTY && npc.variant == GRILLED_CLOTTY; +} + +// Keeps a main animation playing, restarting it once it ends or another shows. +static void anim_loop(ANM2& sprite, std::string_view name) +{ + const AnimationData* data = sprite.animState.animData; + bool isShown = data && data->name == name && (!data->isLooping || sprite.animState.isPlaying); + if (isShown || !sprite.SetAnimation(name, SWITCH_KEEP_FRAME)) return; + + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; +} + +// The first frame's blood: the Cloggy's brown (and which way its shots curve first), the Clot's black, the Grilled +// Clotty's burnt. +static void clotty_init(Entity_NPC& npc) +{ + if (npc.type == ENTITY_CLOGGY) + { + npc.splatColor = CLOGGY_SPLAT_COLOR; + npc.i1 = (int)(npc.dropRNG.Next() & 1); + } + else if (npc.variant == CLOT) npc.splatColor = CLOT_SPLAT_COLOR; + else if (npc.variant == GRILLED_CLOTTY) npc.splatColor = GRILLED_SPLAT_COLOR; +} + +// A dead Mega Clotty splits into two Clotties (fewer for a regenerating champion). +static void mega_clotty_split(Entity_NPC& npc) +{ + for (int i = std::max(0, MEGA_SPLIT - npc.championRegenCount); i > 0; i--) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector at = vector_make(std::cos(angle) * MEGA_SPLIT_SPREAD + npc.pos.x, + std::sin(angle) * MEGA_SPLIT_SPREAD + npc.pos.y); + g_game->Spawn({.position = at, .spawner = &npc, .type = ENTITY_CLOTTY, .seed = seed}); + } +} + +// Hopping: the hop (idle when its player holds still), wandering until a hop lands in range and an attack starts, +// fleeing while feared or shrunk. +static void clotty_hop_update(Entity_NPC& npc) +{ + bool isControlled = npc.controllerID != -1; + npc.v1.x = npc.type == ENTITY_MEGA_CLOTTY ? MEGA_CLOTTY_WAIT : is_grilled(npc) ? GRILLED_WAIT : CLOTTY_WAIT; + if (!isControlled || vector_length(npc.velocity) >= HOP_THRESHOLD || + !vector_is_zero(npc.GetControllerInput(CLOTTY_DEADZONE))) + npc.AnimWalkFrame("Hop", "Hop", HOP_THRESHOLD); + else anim_loop(npc.sprite, "Idle"); + + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && !npc.HasEntityFlags(FLAG_STUNNED) && !isControlled) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= FLEE_FRICTION; + } + else if (npc.pathfinder.MoveRandomly(STATUS_OBEYED) && !npc.HasEntityFlags(FLAG_CONFUSION) && + (!isControlled || npc.IsTargetInAttackRange(CLOTTY_RANGE, CLOTTY_RANGE_FRAMES, false) || + npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT))) + { + if (is_grilled(npc) && npc.i2 >= GRILLED_ATTACKS) npc.i2 = 0; + else + { + npc.state = NPC_STATE_ATTACK; + npc.i2++; + npc.controllerMovement = isControlled ? npc.GetControllerMovementInput(CLOTTY_DEADZONE) : vector_make(0, 0); + anim_loop(npc.sprite, "Attack"); + } + } + if (npc.type == ENTITY_MEGA_CLOTTY) npc.friction *= MEGA_CLOTTY_FRICTION; +} + +// The Mega Clotty's way to attack: its ring (three times in four, or its player aiming sideways), else a spawn (one +// time in three, or aiming up for a Globin) or creep. +static bool mega_clotty_ring_get(Entity_NPC& npc, Direction aim) +{ + if (npc.controllerID == -1) return (Random() & 3) != 0; + return aim == DIRECTION_LEFT || aim == DIRECTION_RIGHT; +} + +// The Mega Clotty's "Shoot": a ring of six, a Clotty or Globin from a free spot near it, or four pools of creep. +static void mega_clotty_shoot(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, MEGA_SOUND_VOLUME, 2, false, 1); + bool isControlled = npc.controllerID != -1; + Vector movement = npc.controllerMovement; + Direction aim = vector_is_zero(movement) ? DIRECTION_NONE : vector_to_direction(movement); + if (mega_clotty_ring_get(npc, aim)) + { + ProjectileParams params; + params.circleAngle = random_unit() * FULL_TURN_DEGREES_CLOTTY - HALF_TURN_DEGREES; + npc.FireProjectiles(npc.pos, vector_make(MEGA_RING_SPEED, MEGA_RING_SHOTS), PROJECTILES_RING, params); + return; + } + + bool isSpawning = isControlled ? aim != DIRECTION_NONE : Random() % 3 == 0; + if (isSpawning && npc.GetAliveEnemyCount() < MEGA_SPAWN_LIMIT) + { + bool isGlobin = isControlled ? aim == DIRECTION_UP : Random() % 3 == 0; + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = MEGA_SPAWN_STEP}); + Entity* spawned = g_game->Spawn({.position = spot, .spawner = &npc, + .type = isGlobin ? ENTITY_GLOBIN_SPAWN : ENTITY_CLOTTY, .seed = seed}); + if (!isGlobin) return; + + auto* globin = static_cast(spawned); + globin->sprite.Play("ReGen"); + globin->state = NPC_STATE_IDLE; + globin->Update(); + return; + } + + for (int i = 0; i < MEGA_CREEPS; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float distance = random_unit() * MEGA_CREEP_SPREAD; + Vector at = vector_make(std::cos(angle) * distance + npc.pos.x, std::sin(angle) * distance + npc.pos.y); + auto* creep = static_cast(g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = seed})); + float scale = random_unit() * MEGA_CREEP_SCALE_RANGE + MEGA_CREEP_SCALE_MIN; + creep->timeout = MEGA_CREEP_FRAMES; + creep->sprite.scale = vector_make(scale, scale); + creep->lifespan = MEGA_CREEP_FRAMES; + } +} + +// The spurt of blood and squish a Clotty or Cloggy shoots with. +static void clotty_spurt(Entity_NPC& npc) +{ + Vector rise = vector_make(0, SPURT_RISE); + blood_explosion_spawn(BLOOD_EXPLOSION_SPURT, npc.pos, rise, npc.splatColor, vector_make(0, 0)); + npc_sound_play(SOUND_ANIMAL_SQUISH, 1, 2, 1); +} + +// The Cloggy's "Shoot": a ring of four puke shots curving one way, then the other. +static void cloggy_shoot(Entity_NPC& npc) +{ + clotty_spurt(npc); + ProjectileParams params; + params.variant = PROJECTILE_PUKE; + params.curvingStrength = CLOGGY_CURVE; + params.fallingAccelModifier = CLOGGY_FALL; + params.bulletFlags = npc.i1 == 0 ? PROJECTILE_CURVE_RIGHT : PROJECTILE_CURVE_LEFT; + params.circleAngle = npc.i1 == 0 ? -CLOGGY_ANGLE : CLOGGY_ANGLE; + npc.FireProjectiles(npc.pos, vector_make(CLOGGY_SHOT_SPEED, RING_SHOTS), PROJECTILES_RING, params); + npc.i1 = 1 - npc.i1; +} + +// A Clotty's "Shoot": the Grilled Clotty's slowly turning ring, else a plus, a Clot's black cross or an I.Blob's eight. +// A variant past the I.Blob shoots a plus where the original reads a stale register. +static void clotty_shoot(Entity_NPC& npc) +{ + clotty_spurt(npc); + ProjectileParams params; + if (npc.variant == GRILLED_CLOTTY) + { + params.fallingAccelModifier = GRILLED_FALL; + params.circleAngle = random_unit() * PI_F * GRILLED_SPIN; + float speed = game_is_hard_mode() ? GRILLED_SHOT_SPEED_HARD : CLOTTY_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, RING_SHOTS), PROJECTILES_RING, params); + return; + } + + ProjectilesMode mode = npc.variant == CLOT ? PROJECTILES_CROSS : npc.variant == I_BLOB ? PROJECTILES_EIGHT + : PROJECTILES_PLUS; + if (npc.variant == CLOT) params.color = CLOT_SHOT_COLOR; + float speed = game_is_hard_mode() ? CLOTTY_SHOT_SPEED_HARD : CLOTTY_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), mode, params); +} + +// Attacking: once the attack ends (or one time in 30 after the wait) it hops again, else it plays the attack and +// shoots on its "Shoot". The wait runs down by the speed it moves at. +static void clotty_attack_update(Entity_NPC& npc) +{ + AnimationState& animation = npc.sprite.animState; + if (!animation.animData || !animation.isPlaying || (Random() % CLOTTY_LINGER_ODDS != 0 && npc.v1.x <= 0)) + npc.state = NPC_STATE_MOVE; + else + { + anim_loop(npc.sprite, "Attack"); + bool isShooting = animation.animData && animation.IsEventTriggered("Shoot"); + if (isShooting && npc.type == ENTITY_MEGA_CLOTTY) mega_clotty_shoot(npc); + else if (isShooting && npc.type == ENTITY_CLOGGY) cloggy_shoot(npc); + else if (isShooting) clotty_shoot(npc); + } + npc.v1.x -= npc.speedMultiplier; +} + +// A Clotty grills when fire hits it in a dry room (the hit does no damage), and a Grilled Clotty cools in water. +static void clotty_grill_update(Entity_NPC& npc) +{ + if (g_game->room->waterAmount > GRILL_WATER_MAX) + { + if (npc.variant == GRILLED_CLOTTY) npc.Morph(ENTITY_CLOTTY, 0, 0, -1); + return; + } + if (npc.variant != 0 && npc.variant != GRILLED_CLOTTY) return; + + for (DamageEvent& event : npc.damageEvents) + { + if (!(event.damageFlags & DAMAGE_FIRE_CLOTTY)) continue; + + npc.pendingDamage -= event.damage; + event.damage = 0; + if (npc.variant != 0) continue; + + npc.Morph(ENTITY_CLOTTY, GRILLED_CLOTTY, 0, -1); + npc.splatColor = GRILLED_SPLAT_COLOR; + } +} + +// 0050d370 The clotties' AI: they bleed, hop about at random and stop to shoot, the Mega Clotty spawning and splitting, +// the Cloggy curving its shots, a Clotty grilling in fire. +void npc_clotty_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) clotty_init(npc); + if (npc.GetIntervalTicks(BLEED_TICKS, (float)(npc.index % (uint32_t)BLEED_TICKS))) + npc.MakeSplat(random_unit() * SPLAT_RANGE + SPLAT_MIN) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (npc.isDead && npc.type == ENTITY_MEGA_CLOTTY) mega_clotty_split(npc); + + npc.friction *= CLOTTY_FRICTION; + if (npc.state == NPC_STATE_IDLE || npc.state == NPC_STATE_MOVE) clotty_hop_update(npc); + else if (npc.state == NPC_STATE_ATTACK) clotty_attack_update(npc); + else + { + npc.state = (Random() & 1) == 0 ? NPC_STATE_ATTACK : NPC_STATE_MOVE; + npc.v1.x = is_grilled(npc) ? GRILLED_WAIT : CLOTTY_WAIT; + anim_loop(npc.sprite, "Hop"); + } + + if (npc.type == ENTITY_CLOTTY) clotty_grill_update(npc); +} diff --git a/src/npc_gusher.cpp b/src/npc_gusher.cpp new file mode 100644 index 0000000..fee38dc --- /dev/null +++ b/src/npc_gusher.cpp @@ -0,0 +1,271 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "level.h" + +// The headless enemies this AI runs: the Gusher and Pacer, Blubber and Half Sack, Splasher and the Black Globin's body. +constexpr int ENTITY_GUSHER = 11; +constexpr int ENTITY_BLUBBER = 210; +constexpr int ENTITY_HALF_SACK = 211; +constexpr int ENTITY_SPLASHER = 238; +constexpr int ENTITY_BLACK_GLOBIN_BODY = 280; + +constexpr int SOUND_BLOBBY_WIGGLE = 3; +constexpr int SOUND_BLOODSHOOT = 178; +constexpr int SOUND_BOIL_HATCH = 181; +constexpr int CONTROLLER_ACTION_SHOOT = 9; +constexpr uint64_t PROJECTILE_EXPLODE = 1ull << 1; +constexpr uint64_t FLAG_DISTRACTED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; +constexpr uint64_t DAMAGE_TNT = 1ull << 12; +constexpr float WALK_THRESHOLD_GUSHER = 0.1f; +constexpr float GUSHER_DEADZONE = 0.1f; + +// The flooded floors' shots are tears, the Dross's puke. +constexpr int STAGE_ID_FLOODED_CAVES = 6; +constexpr int STAGE_ID_DOWNPOUR = 27; +constexpr int STAGE_ID_DROSS = 28; +constexpr int PROJECTILE_TEAR = 4; +constexpr int PROJECTILE_PUKE = 3; + +// Gushers wait 20 to 39 frames to start, 40 to 59 between shots (Splashers 60 to 89), shooting at 5 along their walk +// at targets within 1000. Blubbers wait 30 to 59 between bursts of three to five. +constexpr int GUSHER_START_MIN = 20; +constexpr int GUSHER_START_RANGE = 20; +constexpr int GUSHER_COOLDOWN = 40; +constexpr int GUSHER_COOLDOWN_RANGE = 20; +constexpr int SPLASHER_COOLDOWN = 60; +constexpr int SPLASHER_COOLDOWN_RANGE = 30; +constexpr int BLUBBER_COOLDOWN = 30; +constexpr int BLUBBER_COOLDOWN_RANGE = 30; +constexpr float GUSHER_RANGE = 1000; +constexpr int GUSHER_RANGE_FRAMES = 7; +constexpr float GUSHER_SHOT_SPEED = 5; +constexpr float GUSHER_SHOT_FALL_SPEED = -5; +constexpr float GUSHER_SHOT_FALL_ACCEL = 0.3f; +constexpr float BLUBBER_SHOT_HEIGHT = -15; +constexpr float BLUBBER_SHOT_FALL_SPEED = 5; +constexpr float BLUBBER_SHOT_DROP = 5; +constexpr float BLUBBER_SHOT_TRAJECTORY = 10; +constexpr int BLUBBER_SHOTS_MIN = 3; +constexpr int BLUBBER_SHOTS_RANGE = 3; + +// They wander, slowed to three quarters (and more while fleeing), bleeding every 10 frames. +constexpr float GUSHER_FRICTION = 0.75f; +constexpr float FLEE_FRICTION = 0.8f; +constexpr float BLEED_TICKS = 10; +constexpr float SPLAT_MIN = 0.2f; +constexpr float SPLAT_RANGE = 0.3f; +constexpr float BLUBBER_SPLAT_MIN = 0.4f; +constexpr float BLUBBER_SPLAT_RANGE = 0.4f; +constexpr float WIGGLE_TICKS = 50; +constexpr float WIGGLE_VOLUME = 0.7f; +constexpr float GUSHER_OVERKILL = -25; + +// The Black Globin's body throws a spider every 90 or 180 frames while fewer than five enemies are left. +constexpr int SPIDER_ENEMY_LIMIT = 5; +constexpr int SPIDER_COOLDOWN = 90; +constexpr float SPIDER_AIM_REACH = 80; +constexpr float SPIDER_THROW_HEIGHT = -30; +constexpr float SPIDER_SOUND_VOLUME = 0.5f; +constexpr float SPIDER_BLOOD_RISE = -10; + +constexpr ColorMod SPLASHER_SPLAT_COLOR = {{0.5f, 0.5f, 0.5f, 1}, + {0, 0, 0, 0}, + {-0.19607845f, 0.50980395f, 0.19607845f}}; +constexpr ColorMod SPLASHER_CREEP_COLOR = {{0, 1, 0, 1}, {0, 0, 0, 0}, {0, 0.5f, 0}}; +constexpr ColorMod SPLASHER_SHOT_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; + +static bool is_bleeding_gusher(Entity_NPC& npc) +{ + return (npc.type == ENTITY_GUSHER && npc.variant == 0) || npc.type == ENTITY_SPLASHER; +} + +// The first frame: wandering, a shot 20 to 39 frames away, and the blood overlay of a Gusher or Splasher (whose +// splats are green). +static void gusher_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + if (npc.type == ENTITY_SPLASHER) npc.splatColor = SPLASHER_SPLAT_COLOR; + npc.projectileCooldown = (int)(Random() % GUSHER_START_RANGE) + GUSHER_START_MIN; + if (is_bleeding_gusher(npc)) npc.sprite.PlayOverlay("Blood"); +} + +// A Splasher ignores explosions but the players' own, friendly ones' and TNT's. +static void splasher_explosions_ignore(Entity_NPC& npc) +{ + for (DamageEvent& event : npc.damageEvents) + { + bool isPlayerMade = event.source.type == ENTITY_PLAYER || event.source.spawnerType == ENTITY_PLAYER || + event.source.spawnerType == ENTITY_FAMILIAR; + if ((event.damageFlags & DAMAGE_EXPLOSION) && !(event.source.flags & ENTITY_REF_FRIENDLY) && !isPlayerMade && + !(event.damageFlags & DAMAGE_TNT)) + event.damage = 0; + } +} + +// The shot's look: the flooded floors' tears and the Dross's puke. +static void stage_projectile_apply(ProjectileParams& params) +{ + uint32_t stage = Level::GetStageID(); + if (stage == STAGE_ID_FLOODED_CAVES || stage == STAGE_ID_DOWNPOUR) params.variant = PROJECTILE_TEAR; + else if (stage == STAGE_ID_DROSS) params.variant = PROJECTILE_PUKE; +} + +// A Gusher or Splasher spurts a shot the way it walks (or its player steers) off cooldown. The Splasher's explode +// green. +static void gusher_shoot_update(Entity_NPC& npc) +{ + if (npc.projectileCooldown >= 1 || npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return; + } + bool isControlled = npc.controllerID != -1; + if (isControlled && !npc.IsTargetInAttackRange(GUSHER_RANGE, GUSHER_RANGE_FRAMES, false)) return; + + float speed = vector_length(npc.velocity); + Vector aim = vector_make(0, 0); + if (isControlled) aim = npc.GetControllerMovementInput(GUSHER_DEADZONE); + else if (speed > 0) aim = vector_make(npc.velocity.x / speed, npc.velocity.y / speed); + if (vector_is_zero(aim)) return; + + if (npc.type == ENTITY_GUSHER) + npc.projectileCooldown = (isControlled ? 0 : (int)(Random() % GUSHER_COOLDOWN_RANGE)) + GUSHER_COOLDOWN; + ProjectileParams params; + params.fallingAccelModifier = GUSHER_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = GUSHER_SHOT_FALL_SPEED; + if (npc.type == ENTITY_SPLASHER) + { + npc.projectileCooldown = (isControlled ? 0 : (int)(Random() % SPLASHER_COOLDOWN_RANGE)) + SPLASHER_COOLDOWN; + params.bulletFlags |= PROJECTILE_EXPLODE; + params.color = SPLASHER_SHOT_COLOR; + } + stage_projectile_apply(params); + npc.FireProjectiles(npc.pos, vector_scale(aim, GUSHER_SHOT_SPEED), PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); +} + +// A moving Blubber bursts three to five arcing shots off cooldown. +static void blubber_shoot_update(Entity_NPC& npc) +{ + bool isControlled = npc.controllerID != -1; + bool isReady = npc.projectileCooldown < 1 && !npc.HasEntityFlags(FLAG_DISTRACTED) && + (!isControlled || npc.IsTargetInAttackRange(GUSHER_RANGE, GUSHER_RANGE_FRAMES, false) || + npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)); + if (!isReady) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return; + } + if (vector_length(npc.velocity) <= 0) return; + + npc.projectileCooldown = (isControlled ? 0 : (int)(Random() % BLUBBER_COOLDOWN_RANGE)) + BLUBBER_COOLDOWN; + ProjectileParams params; + params.heightModifier += BLUBBER_SHOT_HEIGHT; + params.fallingSpeedModifier = BLUBBER_SHOT_FALL_SPEED; + params.positionOffset = vector_make(0, BLUBBER_SHOT_DROP); + int count = (int)(Random() % BLUBBER_SHOTS_RANGE) + BLUBBER_SHOTS_MIN; + npc.FireBossProjectiles(count, vector_make(0, 0), BLUBBER_SHOT_TRAJECTORY, params); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); +} + +// Wanders, or flees its target while feared or shrunk. +static void gusher_wander(Entity_NPC& npc) +{ + npc.friction *= GUSHER_FRICTION; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= FLEE_FRICTION; +} + +// Every 10 frames it bleeds: a Half Sack red creep (unless shrunk), the others splats, a Blubber a big one besides, +// a Splasher a green one. +static void gusher_bleed(Entity_NPC& npc) +{ + if (!npc.GetIntervalTicks(BLEED_TICKS, 0)) return; + + if (npc.type == ENTITY_HALF_SACK) + { + if (npc.HasEntityFlags(FLAG_SHRINK)) return; + + Entity* creep = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, + .seed = Random()}); + float scale = random_unit() * SPLAT_RANGE + SPLAT_MIN; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + return; + } + if (npc.type == ENTITY_BLUBBER) npc.MakeSplat(random_unit() * BLUBBER_SPLAT_RANGE + BLUBBER_SPLAT_MIN); + Entity_Effect* splat = npc.MakeSplat(random_unit() * SPLAT_RANGE + SPLAT_MIN); + if (npc.type == ENTITY_SPLASHER) splat->SetColor(SPLASHER_CREEP_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// The Black Globin's body throws a spider (where its player aims) with a burst of blood, while few enemies are left. +// True when it waited instead. +static bool globin_body_spiders_update(Entity_NPC& npc) +{ + if (npc.projectileCooldown > 0) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return true; + } + bool isControlled = npc.controllerID != -1; + if (npc.GetAliveEnemyCount() >= SPIDER_ENEMY_LIMIT || + (isControlled && !npc.IsTargetInAttackRange(GUSHER_RANGE, GUSHER_RANGE_FRAMES, false))) + return false; + + Vector target = vector_make(0, 0); + Vector aim = isControlled ? npc.GetControllerMovementInput(GUSHER_DEADZONE) : vector_make(0, 0); + if (!vector_is_zero(aim)) target = vector_add(vector_scale(aim, SPIDER_AIM_REACH), npc.pos); + Entity_NPC::ThrowSpider(npc.pos, &npc, target, false, SPIDER_THROW_HEIGHT); + npc.PlaySound(SOUND_BOIL_HATCH, SPIDER_SOUND_VOLUME, 2, false, 1); + + Vector rise = vector_make(0, SPIDER_BLOOD_RISE); + Entity* blood = blood_explosion_spawn(1, npc.pos, rise, COLOR_DEFAULT, vector_make(0, 0)); + blood->renderDepthOffset = 1; + static_cast(blood)->FollowParent(&npc); + npc.projectileCooldown = isControlled ? SPIDER_COOLDOWN : (int)((Random() & 1) + 1) * SPIDER_COOLDOWN; + return false; +} + +// 0050af90 The headless enemies' AI: they wander bleeding. Gushers and Splashers spurt shots along their walk, +// Blubbers burst arcs and get up as Half Sacks one time in two, the Black Globin's body throws spiders, and the fat +// ones wiggle audibly. +void npc_gusher_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return gusher_init(npc); + if (npc.isDead && npc.type == ENTITY_BLUBBER) + { + if (npc.health <= GUSHER_OVERKILL || (Random() & 1) != 0) return; + + npc.Morph(ENTITY_HALF_SACK, 0, 0, -1); + npc.isDead = false; + npc.health = npc.maxHitPoints; + return; + } + if (npc.type == ENTITY_SPLASHER && npc.pendingDamage > 0) splasher_explosions_ignore(npc); + + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD_GUSHER); + if (is_bleeding_gusher(npc)) + { + npc_overlay_loop(npc.sprite, "Blood"); + gusher_shoot_update(npc); + } + else if (npc.type == ENTITY_BLUBBER) blubber_shoot_update(npc); + else if (npc.type == ENTITY_BLACK_GLOBIN_BODY) npc_overlay_loop(npc.sprite, "Spiders"); + + gusher_wander(npc); + gusher_bleed(npc); + if (npc.type == ENTITY_BLACK_GLOBIN_BODY && globin_body_spiders_update(npc)) return; + + bool isFat = npc.type == ENTITY_BLUBBER || npc.type == ENTITY_HALF_SACK; + if (isFat && npc.GetIntervalTicks(WIGGLE_TICKS, (float)(npc.index % (uint32_t)WIGGLE_TICKS)) && (Random() & 1) == 0) + npc.PlaySound(SOUND_BLOBBY_WIGGLE, WIGGLE_VOLUME, 2, false, 1); +} diff --git a/src/npc_mulligan.cpp b/src/npc_mulligan.cpp new file mode 100644 index 0000000..9a2b70e --- /dev/null +++ b/src/npc_mulligan.cpp @@ -0,0 +1,174 @@ +#include "npc_basement.h" +#include "active_items.h" +#include "entity_bomb.h" +#include "game.h" +#include "menu_manager.h" + +constexpr int MULLIGOON = 1; +constexpr int MULLIBOOM = 2; +constexpr int ENTITY_FLY = 13; +constexpr int ENTITY_POOTER = 14; +constexpr int ENTITY_ATTACKFLY = 18; +constexpr int EFFECT_BOMB_EXPLOSION = 1; +constexpr int EFFECT_BOMB_CRATER = 18; +constexpr int SOUND_SCARED_WHIMPER = 143; +constexpr int CONTROLLER_ACTION_ITEM = 9; +constexpr int CONTROLLER_ACTION_WHIMPER = 10; + +// Mulligans flee whimpering (45 to 144 frames later) once 10 frames old, slowed to 0.8. A Mulliboom chases at 1.2, +// slowed to 0.9, and blows up within 40 of its target, checked every 5 frames. +constexpr float MULLIGAN_FRICTION = 0.8f; +constexpr float MULLIBOOM_FRICTION = 0.9f; +constexpr float MULLIBOOM_SPEED = 1.2f; +constexpr float MULLIBOOM_REACH_SQUARED = 1600; +constexpr float MULLIBOOM_CHECK_TICKS = 5; +constexpr int WHIMPER_AGE = 10; +constexpr int WHIMPER_DELAY_MIN = 45; +constexpr int WHIMPER_DELAY_RANGE = 100; +constexpr float WALK_THRESHOLD_MULLIGAN = 0.1f; + +// One in 300 frames a Mulligan touching a wall starts to burst. The burst deals 40 within 60 and shoots a plus (a +// Mulligoon a cross) at 7, 10 in hard mode. +constexpr int BURST_ODDS = 300; +constexpr float BURST_DAMAGE = 40; +constexpr float BURST_RADIUS = 60; +constexpr float BURST_SHOT_SPEED = 7; +constexpr float BURST_SHOT_SPEED_HARD = 10; + +// A dead Mulligan lets out four flies (fewer for a regenerating champion) within 6, unless torn apart: flies seven +// times in 11, a pooter one, attack flies three. +constexpr float MULLIGAN_OVERKILL = -10; +constexpr int MULLIGAN_FLIES = 4; +constexpr uint32_t MULLIGAN_FLY_ROLLS = 11; +constexpr uint32_t MULLIGAN_POOTER_ROLL = 7; +constexpr float MULLIGAN_FLY_SPREAD = 6; + +// A burst: explosion damage around it, the explosion and its crater. +static void mulligan_explode(Entity_NPC& npc) +{ + explosion_damage({.position = npc.pos, + .source = &npc, + .damage = BURST_DAMAGE, + .radius = BURST_RADIUS}); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_CRATER, .seed = Random()}) + ->Update(); +} + +static float burst_shot_speed() +{ + return game_is_hard_mode() ? BURST_SHOT_SPEED_HARD : BURST_SHOT_SPEED; +} + +// A Mulliboom runs at its target and blows up near it (or when its player uses the item button). +static void mulliboom_chase(Entity_NPC& npc, const Vector& target) +{ + npc.pathfinder.FindGridPath(target, MULLIBOOM_SPEED, 0, DIRECT_PATH_FAR); + bool isBlowing = npc.controllerID == -1 + ? npc.GetIntervalTicks(MULLIBOOM_CHECK_TICKS, 0) && + vector_length_squared(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)) < + MULLIBOOM_REACH_SQUARED + : npc.IsControllerActionPressed(CONTROLLER_ACTION_ITEM); + if (isBlowing) npc.Kill(EntityRef()); + npc.friction *= MULLIBOOM_FRICTION; +} + +// A Mulligan flees a hostile target whimpering (or wanders), its eye open while it runs. +static void mulligan_flee(Entity_NPC& npc, const Vector& target) +{ + bool isControlled = npc.controllerID != -1; + if (!isControlled && !npc.IsHostileTo(npc.GetPlayerTarget())) npc.pathfinder.MoveRandomly(STATUS_IGNORED); + else + { + npc.pathfinder.EvadeTarget(target, STATUS_OBEYED); + bool isWhimpering = isControlled ? npc.IsControllerActionTriggered(CONTROLLER_ACTION_WHIMPER) + : npc.pathfinder.evadeMovementCountdown > 0 && + g_game->frameCount - npc.spawnFrame > WHIMPER_AGE; + if (isWhimpering) + npc.PlaySound(SOUND_SCARED_WHIMPER, 1, (int)(Random() % WHIMPER_DELAY_RANGE) + WHIMPER_DELAY_MIN, false, 1); + } + npc.friction *= MULLIGAN_FRICTION; +} + +// Walking: the chase or the flight, the walk, the head overlay, and now and then the start of a burst. +static void mulligan_move(Entity_NPC& npc, const Vector& target) +{ + if (npc.variant == MULLIBOOM) mulliboom_chase(npc, target); + else mulligan_flee(npc, target); + + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD_MULLIGAN); + bool isEyeOpen = npc.pathfinder.evadeMovementCountdown >= 1 && npc.variant != MULLIBOOM; + std::string_view head = isEyeOpen ? "WalkOpenEye" : "Walk"; + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) npc.sprite.PlayOverlay(head); + else if (npc.sprite.SetOverlayAnimation(head, SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + + bool isBursting = npc.controllerID == -1 + ? npc.isCollidesWithGrid && Random() % BURST_ODDS == 0 + : input_is_action_pressed(ACTION_ITEM, npc.controllerID, &npc); + if (!isBursting || npc.variant == MULLIBOOM) return; + + npc.sprite.PlayOverlay("Explode"); + npc.state = NPC_STATE_SUICIDE; +} + +// Once its burst overlay ends it explodes, shooting a plus, and dies. +static void mulligan_burst_update(Entity_NPC& npc) +{ + npc.friction *= MULLIGAN_FRICTION; + if (npc.sprite.overlayAnimState.animData && npc.sprite.overlayAnimState.isPlaying) return; + + mulligan_explode(npc); + npc.FireProjectiles(npc.pos, vector_make(burst_shot_speed(), 0), PROJECTILES_PLUS, ProjectileParams()); + npc.Kill(EntityRef()); +} + +// What its death lets out: the Mulliboom's explosion (none when shrunk), the Mulligoon's cross and troll bomb, a +// Mulligan's flies. +static void mulligan_death(Entity_NPC& npc) +{ + if (npc.variant == MULLIBOOM) + { + if (!npc.HasEntityFlags(FLAG_SHRINK)) mulligan_explode(npc); + return; + } + if (npc.variant == MULLIGOON) + { + npc.FireProjectiles(npc.pos, vector_make(burst_shot_speed(), 0), PROJECTILES_CROSS, ProjectileParams()); + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BOMB, .variant = BOMB_TROLL, + .seed = Random()}); + return; + } + if (npc.health <= MULLIGAN_OVERKILL) return; + + for (int i = std::max(0, MULLIGAN_FLIES - npc.championRegenCount); i > 0; i--) + { + uint32_t roll = Random() % MULLIGAN_FLY_ROLLS; + int type = roll < MULLIGAN_POOTER_ROLL ? ENTITY_FLY + : roll == MULLIGAN_POOTER_ROLL ? ENTITY_POOTER + : ENTITY_ATTACKFLY; + float angle = random_unit() * PI_F; + angle += angle; + float distance = random_unit() * MULLIGAN_FLY_SPREAD; + uint32_t seed = Random(); + Vector at = vector_make(std::cos(angle) * distance + npc.pos.x, std::sin(angle) * distance + npc.pos.y); + Entity* fly = g_game->Spawn({.position = at, .spawner = &npc, .type = type, .seed = seed}); + fly->ClearEntityFlags(FLAG_APPEAR); + } +} + +// 0050bbe0 The Mulligan's AI (Mulligoon and Mulliboom with it): it flees its target and may burst against a wall, the +// Mulliboom chases and blows up. Dying, each lets out what it holds. +void npc_mulligan_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + return; + } + + Vector target = npc.CalcTargetPosition(0); + if (npc.state == NPC_STATE_MOVE) mulligan_move(npc, target); + else if (npc.state == NPC_STATE_SUICIDE) mulligan_burst_update(npc); + if (npc.isDead) mulligan_death(npc); +} diff --git a/src/player_hud.cpp b/src/player_hud.cpp index 51a7771..11311e9 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -146,21 +146,6 @@ constexpr const char* BOOK_OF_VIRTUES_BELIAL_PNG = "gfx/ui/hud_BookOfVirtuesWith constexpr int PICKUP_PILL = 70; constexpr int PICKUP_TAROTCARD = 300; -// Multiplies a color by another, as Color's *= does: tints multiply, offsets add and colorizes average. -static void color_multiply(ColorMod& color, const ColorMod& other) -{ - for (int i = 0; i < 4; i++) color._tint[i] = other._tint[i] * color._tint[i]; - - if (other._colorize[0] + other._colorize[1] + other._colorize[2] != 0) - { - bool isColorized = color._colorize[0] + color._colorize[1] + color._colorize[2] != 0; - for (int i = 0; i < 4; i++) - color._colorize[i] = isColorized ? (color._colorize[i] + other._colorize[i]) * 0.5f : other._colorize[i]; - } - - for (int i = 0; i < 3; i++) color._offset[i] = other._offset[i] + color._offset[i]; -} - // A color that only tints by an alpha and adds a red offset. static ColorMod heart_color(float alpha, float redOffset) { diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 708cf0c..10de4ff 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -813,10 +813,6 @@ Entity_Player* PlayerManager::get_player_by_user_id(uint64_t) reconstruction_missing("PlayerManager::get_player_by_user_id 0090abf0"); } void PlayerManager::add_lost_curse(int) { reconstruction_missing("PlayerManager::add_lost_curse 009be850"); } -void PlayerManager::restore_controller_assignment() -{ - reconstruction_missing("PlayerManager::restore_controller_assignment 009bf530"); -} void PlayerManager::spawn_coop_baby_for_join(int) { reconstruction_missing("PlayerManager::spawn_coop_baby_for_join 009bd3b0"); @@ -987,7 +983,7 @@ void PlayerManager::Update() { Game& game = *g_game; - if (game.roomTransition.mode == TRANSITION_NONE && game.stageTransition._state == 0) + if (game.roomTransition.mode == TRANSITION_NONE && game.stageTransition.state == 0) for (size_t i = 0; i < game.playerManager.playerList.size(); i++) { Entity_Player* player = GetPlayer((int)i); @@ -1016,7 +1012,6 @@ void PlayerManager::Update() sfx.AdjustPitch(SOUND_STATIC_BUILDUP, 1); } -void PlayerManager::trigger_room_clear() { reconstruction_missing("PlayerManager::trigger_room_clear 009bb840"); } Vector PlayerManager::find_safe_spawn_position(Vector) { reconstruction_missing("PlayerManager::find_safe_spawn_position 009bc280"); @@ -1029,12 +1024,3 @@ void PlayerManager::remove_coplayer_slot(int*, Entity_Player*) { reconstruction_missing("PlayerManager::remove_coplayer_slot 0083bc50"); } -void PlayerManager::RestoreGameState(GameState*) { reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0"); } -void PlayerManager::RestoreGameState_PostLevelInit(GameState*) -{ - reconstruction_missing("PlayerManager::RestoreGameState_PostLevelInit 009bd010"); -} -int* PlayerManager::match_saved_players(int*, int, bool) -{ - reconstruction_missing("PlayerManager::match_saved_players 009bc790"); -} diff --git a/src/player_manager.h b/src/player_manager.h index 2263e69..740aa37 100644 --- a/src/player_manager.h +++ b/src/player_manager.h @@ -19,6 +19,14 @@ enum LazarusShare LAZARUS_SHARE_CHECK }; +// Whether match_saved_players only finds the saved players' room players, or also removes the unmatched ones and spawns +// the missing ones. +enum PlayerMatch +{ + MATCH_FIND, + MATCH_SPAWN +}; + // Whether check_full_health needs every player at full health or any one. enum HealthCheck { @@ -132,8 +140,8 @@ public: static void unlock_completion_mark(int completionType); static void remove_coplayer_slot(int* hudSlots, Entity_Player* player); - void RestoreGameState(GameState* state); - void RestoreGameState_PostLevelInit(GameState* state); + void RestoreGameState(GameState& state); + void RestoreGameState_PostLevelInit(GameState& state); void store_game_state(GameState* state); - static int* match_saved_players(int* matches, int savedCount, bool isRestoring); + std::vector match_saved_players(GameState& state, PlayerMatch match); }; diff --git a/src/room_clear.cpp b/src/room_clear.cpp new file mode 100644 index 0000000..46ee0d1 --- /dev/null +++ b/src/room_clear.cpp @@ -0,0 +1,1108 @@ +#include "room_clear.h" +#include "challenge_params.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_list.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_pit.h" +#include "item_config.h" +#include "item_pool.h" +#include "lua_callbacks.h" +#include "manager.h" +#include "npc_ai.h" +#include "persistent_game_data.h" +#include "player_manager.h" +#include "room.h" +#include "room_grid.h" +#include "score_sheet.h" +#include "seeds.h" +#include +#include +#include + +constexpr int COLLECTIBLE_LUCKY_FOOT_CLEAR = 46; +constexpr int COLLECTIBLE_GUPPYS_TAIL = 134; +constexpr int COLLECTIBLE_CONTRACT_FROM_BELOW = 241; +constexpr int COLLECTIBLE_THERES_OPTIONS = 249; +constexpr int COLLECTIBLE_DEEP_POCKETS_CLEAR = 416; +constexpr int COLLECTIBLE_GLYPH_OF_BALANCE = 464; +constexpr int COLLECTIBLE_SMELTER = 479; +constexpr int COLLECTIBLE_BROKEN_MODEM = 514; +constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; +constexpr int COLLECTIBLE_BROKEN_SHOVEL_2 = 551; +constexpr int COLLECTIBLE_4_5_VOLT = 647; +constexpr int COLLECTIBLE_OPTIONS = 670; +constexpr int COLLECTIBLE_SWARM = 693; +constexpr int COLLECTIBLE_AZAZELS_RAGE = 699; +constexpr int COLLECTIBLE_WHITE_PONY = 181; +constexpr int COLLECTIBLE_PONY = 130; +constexpr int COLLECTIBLE_LITTLE_CHAD = 96; +constexpr int COLLECTIBLE_LITTLE_GISH = 99; +constexpr int COLLECTIBLE_STEVEN = 50; +constexpr int COLLECTIBLE_LITTLE_STEVEN = 100; +constexpr int COLLECTIBLE_CUBE_OF_MEAT = 73; +constexpr int COLLECTIBLE_BALL_OF_BANDAGES = 207; +constexpr int TRINKET_AAA_BATTERY_CLEAR = 3; +constexpr int TRINKET_DAEMONS_TAIL = 22; +constexpr int TRINKET_RUSTED_KEY = 36; +constexpr int TRINKET_MATCH_STICK = 41; +constexpr int TRINKET_LUCKY_TOE = 42; +constexpr int TRINKET_SAFETY_CAP = 44; +constexpr int TRINKET_ACE_OF_SPADES = 45; +constexpr int TRINKET_ISAACS_FORK = 46; +constexpr int TRINKET_LOUSE = 70; +constexpr int TRINKET_WATCH_BATTERY = 72; +constexpr int TRINKET_RIB_OF_GREED = 84; +constexpr int TRINKET_OLD_CAPACITOR = 143; +constexpr int TRINKET_BLUE_KEY = 150; +constexpr int TRINKET_GILDED_KEY = 159; +constexpr int TRINKET_AZAZELS_STUMP = 162; +constexpr int TRINKET_DINGLE_BERRY = 163; +constexpr int TRINKET_POLISHED_BONE = 167; +constexpr int TRINKET_CRYSTAL_KEY = 170; +constexpr int TRINKET_TEMPORARY_TATTOO = 177; +constexpr int NULLITEM_WAVY_CAP = 71; +constexpr int NULLITEM_AZAZELS_RAGE_1 = 96; +constexpr int FAMILIAR_BLUE_FLY_CLEAR = 43; +constexpr int ENTITY_ETERNALFLY_CLEAR = 96; +constexpr int GRID_PATH_TRODDEN = 900; +constexpr int BABY_SKIN_WISP = 64; +constexpr int EFFECT_HEART_CLEAR = 49; +constexpr int SOUND_DOOR_HEAVY_OPEN = 36; +constexpr int SOUND_VAMP_GULP_CLEAR = 157; +constexpr int SOUND_VAMP_DOUBLE_CLEAR = 614; +constexpr int SOUND_BATTERYCHARGE = 170; +constexpr int ACHIEVEMENT_LITTLE_CHAD = 25; +constexpr int ACHIEVEMENT_LITTLE_GISH = 23; +constexpr int ACHIEVEMENT_LITTLE_STEVEN = 24; +constexpr int ACHIEVEMENT_BOOK_OF_REVELATIONS = 7; +constexpr int EVENT_COUNTER_LAMB_KILLS = 25; +constexpr int EVENT_COUNTER_BOSSRUSHS_CLEARED = 111; +constexpr int ULTRA_GREED_BOSS = 62; +constexpr int BABY_PLUM_BOSS = 84; +constexpr int STAGE_HOME_ID = 35; +constexpr int STAGE_WOMB_2 = 8; +constexpr int STAGE_HOME_END = 13; +constexpr int GREED_WAVES = 10; +constexpr int LEVEL_STATE_SHOVEL_QUEST_TRIGGERED = 16; +constexpr int LEVEL_STATE_SATANIC_BIBLE_USED = 17; +constexpr int ACHIEVEMENT_MONSTROS_LUNG = 13; +constexpr int ACHIEVEMENT_LIL_CHUBBY = 14; +constexpr int ACHIEVEMENT_STEVEN = 16; +constexpr int ACHIEVEMENT_CHAD = 17; +constexpr int ACHIEVEMENT_GISH = 18; +constexpr int ACHIEVEMENT_ANGELS = 155; + +// The unlocks of reaching a floor's last boss without damage since a floor: Basement Boy and Sprinkler, Spelunker Boy +// and Telekinesis, Dark Boy and Leprosy, Mama's Boy and Pop!, and Dead Boy. +struct NoDamageUnlock +{ + int stage; + int damagedLevelBound; + int achievement; + int secondAchievement; +}; +constexpr std::array NO_DAMAGE_UNLOCKS = { + {{2, 1, 37, 351}, {4, 3, 38, 365}, {6, 5, 39, 368}, {8, 7, 40, 374}, {11, 11, 83, 0}}}; +constexpr int STAGE_DEPTHS_2 = 6; + +// The room clear award's generator shifts (5, 9, 7), and Deep Pockets' (2, 21, 9). +constexpr uint32_t AWARD_RNG_SHIFT = 35; +constexpr uint32_t DEEP_POCKETS_RNG_SHIFT = 19; + +// The pickup roll: Lucky Foot and Lucky Toe lift it, luck adds up to a tenth, and cards, pills and trinkets lie below +// 0.3, coins below 0.45, hearts below 0.6, keys below 0.8, bombs below 0.95 and chests above. +constexpr float LUCKY_FOOT_SCALE = 0.9f; +constexpr float LUCKY_FOOT_FLOOR = 0.1f; +constexpr float LUCKY_TOE_SCALE = 0.98f; +constexpr float LUCKY_TOE_FLOOR = 0.02f; +constexpr float AWARD_LUCK_MAX = 10; +constexpr float AWARD_LUCK_SCALE = 0.1f; +constexpr float AWARD_NOTHING = 0.22f; +constexpr float AWARD_OPTIONS_LOW = 0.06f; +constexpr float AWARD_OPTIONS_SPREAD = 0.78f; +constexpr float AWARD_FORCED_SPREAD = 0.7799f; +constexpr float AWARD_FORCED_FLOOR = 0.2201f; +constexpr float AWARD_CONSUMABLE = 0.3f; +constexpr float AWARD_COIN = 0.45f; +constexpr float AWARD_COIN_RIB = 0.5f; +constexpr float AWARD_HEART = 0.6f; +constexpr float AWARD_KEY = 0.8f; +constexpr float AWARD_BOMB = 0.95f; + +// The trinkets that turn a room's award into their own pickup, one roll in 10 (20 doubled, 50 tripled). +constexpr std::array, 5> AWARD_TRINKETS = {{{TRINKET_ACE_OF_SPADES, PICKUP_TAROTCARD}, + {TRINKET_SAFETY_CAP, PICKUP_PILL}, + {TRINKET_CHILDS_HEART, PICKUP_HEART}, + {TRINKET_MATCH_STICK, PICKUP_BOMB}, + {TRINKET_RUSTED_KEY, PICKUP_KEY}}}; +constexpr uint32_t AWARD_TRINKET_ODDS = 10; +constexpr uint32_t AWARD_TRINKET_ODDS_DOUBLE = 20; +constexpr uint32_t AWARD_TRINKET_ODDS_TRIPLE = 50; + +// Contract From Below's extra pickups fail by 0.666 a copy, Rib of Greed's coin upgrade is 666 in 10000 (1300 at +// three), Old Capacitor's battery chance is 0.2 plus 0.03 a luck up to 0.33. +constexpr float CONTRACT_FAIL_BASE = 0.666f; +constexpr float CONTRACT_FAIL_SCALE = 0.5f; +constexpr int HARD_HEART_PERCENT = 66; +constexpr int RIB_OF_GREED_ODDS = 666; +constexpr int RIB_OF_GREED_ODDS_TRIPLE = 1300; +constexpr std::array RIB_OF_GREED_COINS = {4, 2, 3, 5, 7}; +constexpr float OLD_CAPACITOR_BASE = 0.2f; +constexpr float OLD_CAPACITOR_LUCK = 0.03f; +constexpr float OLD_CAPACITOR_MAX = 0.33f; + +// Where the room clear puts its rewards around the room's center: the trapdoor 80 above, the items 80 below in a row +// 40 and 80 to the sides, or 40 below for a Satanic Bible's deal. +constexpr float AWARD_ITEM_DROP = 80; +constexpr float AWARD_ITEM_DROP_DEAL = 40; +constexpr float AWARD_ITEM_SPACING = 40; +constexpr float AWARD_TRAPDOOR_RISE = 80; + +// Shovel quest: the Basement's boss beaten within a minute, once the Lamb has died. +constexpr int SHOVEL_QUEST_FRAMES = 1801; + +// The boss rooms whose layout fills its pits from the middle out once cleared. +constexpr std::array PIT_FILL_BOSS_ROOMS = {1057, 1087, 2025, 2064, 3265, 3266, 3704, 3707, + 3710, 3714, 3760, 3765, 3819, 4022, 4041, 5103, + 5144, 5174, 5180, 5181, 5222, 5229, 5361}; +constexpr float PIT_FILL_CENTER = 0.5f; + +// A clear's active charge: one, two in the big rooms, Watch Battery's extra roll one in 20 per copy, AAA Battery's +// overcharge by up to three. +constexpr int WATCH_BATTERY_MAX_ROLLS = 16; +constexpr uint32_t WATCH_BATTERY_ODDS = 20; +constexpr int AAA_BATTERY_MAX = 3; +constexpr float HEART_EFFECT_RISE_CLEAR = -24; + +// Isaac's Fork heals one clear in 10 minus half the luck, at least one in one. +constexpr int ISAACS_FORK_ODDS = 10; +constexpr float ISAACS_FORK_LUCK = 0.5f; + +// Azazel's Rage stacks four rooms, darkening the player for 6 frames each time. +constexpr int AZAZELS_RAGE_ROOMS = 5; +constexpr int AZAZELS_RAGE_FLASH_FRAMES = 6; +constexpr int COLOR_PRIORITY_FULL = 255; + +// The heart that rises above a player on a heal or a battery's overcharge. +static void clear_heart_spawn(Entity_Player& player, int subType) +{ + Entity* heart = g_game->Spawn({.position = player.pos, .subType = subType, .type = ENTITY_EFFECT, + .variant = EFFECT_HEART_CLEAR, .seed = Random()}); + heart->sprite.offset = vector_make(0, HEART_EFFECT_RISE_CLEAR); + heart->renderDepthOffset = 1; +} + +// A free spot near a position, searched from the position itself. +static Vector free_spot_get(Vector position) +{ + return room_free_pickup_position_find({.position = position}); +} + +// Destroys the grid entity on a cell to make room for a spawn, a bombable rock as a plain one. +static void spawn_cell_destroy(int gridIndex) +{ + room_grid_destroy({.gridIndex = gridIndex, .isImmediate = true, .isDefuseBombRock = true}); +} + +// 007fa360 Clears a cell for a spawn: a pit there is removed (its neighbors redrawn), anything else destroyed, a +// blocked cell traded for a free one, and the colliding grid entities around it destroyed or, for pits, filled. +// Neighbors off the grid are skipped where the original reads before the grid. +void room_spawn_cell_clear(Room& room, int& gridIndex) +{ + if (gridIndex < 0) return; + + if (GridEntity* grid = room.gridEntities[gridIndex]; grid && grid->type == GRID_PIT) + { + int column = gridIndex % room.gridWidth; + int row = gridIndex / room.gridWidth; + room.gridPaths[grid->gridIndex] = 0; + room.gridEntities[grid->gridIndex] = nullptr; + delete grid; + for (int dx = -1; dx <= 1; dx++) + for (int dy = -1; dy <= 1; dy++) + { + int neighborIndex = room.GetGridIndexByTile(column + dx, row + dy); + GridEntity* neighbor = neighborIndex >= 0 ? room.gridEntities[neighborIndex] : nullptr; + if (neighbor && neighbor->type == GRID_PIT) neighbor->PostInit(); + } + } + else if (grid) + { + if (grid->type == GRID_POOP) + for (Entity* entity : room.entityList.updateEL) + if (entity->type == ENTITY_ETERNALFLY_CLEAR && room.GetGridIndex(entity->pos) == gridIndex) + reconstruction_missing("Room::remove_grid_entity_for_spawn 007fa360: an Eternal Fly on the poop"); + spawn_cell_destroy(gridIndex); + } + + if (room.GetGridCollision(gridIndex) != COLLISION_NONE) + gridIndex = room.GetGridIndex(free_spot_get(room.GetGridPosition(gridIndex))); + + RoomConfig_Room* data = room.descriptor->data; + bool isHomeCloset = data && data->type == ROOM_DUNGEON && data->stageId == STAGE_HOME_ID; + int column = gridIndex % room.gridWidth; + int row = gridIndex / room.gridWidth; + for (int x = column - 1; x <= column + 1; x++) + for (int y = row - 1; y <= row + 1; y++) + { + int neighborIndex = room.GetGridIndexByTile(x, y); + GridEntity* neighbor = neighborIndex >= 0 ? room.gridEntities[neighborIndex] : nullptr; + if (!neighbor || isHomeCloset || neighbor->collisionClass == COLLISION_NONE) continue; + if (neighbor->type != GRID_PIT) spawn_cell_destroy(neighborIndex); + else if (neighbor->state == 0) + { + neighbor->state = PIT_STATE_FILLED; + static_cast(neighbor)->UpdateCollision(); + } + } +} + +// 007f9ee0 Clears the spot of a big reward: a pit under it gets a bridge, anything else is destroyed (a destroyed poop +// still standing marks its cell trodden and is taken away next update), and a cell that still collides gives way to a +// free spot. +static void reward_spot_clear(Room& room, Vector& position) +{ + int index = room.GetGridIndex(position); + GridEntity* grid = (uint32_t)index < ROOM_GRID_CELLS ? room.gridEntities[index] : nullptr; + if (grid && grid->type == GRID_PIT) room_bridge_make(grid, nullptr); + else if (grid) + { + spawn_cell_destroy(index); + GridEntity* standing = room.gridEntities[index]; + if (grid->type == GRID_POOP && standing && standing->type != GRID_DECORATION) + { + room.gridPaths[index] = GRID_PATH_TRODDEN; + room.pendingGridRemovals.insert(index); + } + } + + if (room.GetGridCollision(room.GetGridIndex(position)) != COLLISION_NONE) position = free_spot_get(position); +} + +// 007fa2a0 Snaps a reward's spot to the center of its cell, cleared for the spawn. +static void reward_spot_snap(Room& room, Vector& position) +{ + int index = room.GetGridIndex(position); + room_spawn_cell_clear(room, index); + position = room.GetGridPosition(index); +} + +// 00823ec0 The cell a boss room's trapdoor opens on, 80 above the room's center. +static int trapdoor_index_get(Room& room) +{ + Vector center = Room::GetCenterPos(); + return room.GetGridIndex(vector_make(center.x, center.y - AWARD_TRAPDOOR_RISE)); +} + +// 007ed240 Whether this is the last boss of the Depths (a labyrinth's Caves included), where the Home path ends. +static bool is_depths_last_boss() +{ + Game& game = *g_game; + if (game.stage != STAGE_DEPTHS_2 && (game.stage != STAGE_DEPTHS_2 - 1 || !game.filter_curses(CURSE_OF_LABYRINTH))) + return false; + return game.GetRoomByIdx(game.currentRoomIdx)->listIndex == game.lastBossRoomListIdx; +} + +// 007fa7d0 A boss room built over pits starts filling them from the middle out, the farther the later. +static void boss_pits_fill(Room& room) +{ + Vector center = vector_make((float)room.gridWidth * PIT_FILL_CENTER, (float)room.gridHeight * PIT_FILL_CENTER); + for (int column = 0; column <= room.gridWidth; column++) + for (int row = 0; row <= room.gridHeight; row++) + { + int index = room.GetGridIndexByTile(column, row); + auto* pit = index >= 0 ? dynamic_cast(room.gridEntities[index]) : nullptr; + if (!pit || room.GetGridCollision(index) == COLLISION_NONE || pit->state != 0) continue; + + float dx = center.x - (float)column; + float dy = center.y - (float)row; + int delay = (int)(uint32_t)(dx * dx + dy * dy) * 2; + if (delay != 0) + { + pit->varData = delay; + pit->state = PIT_STATE_BRIDGE_PENDING; + continue; + } + pit->state = PIT_STATE_FILLED; + pit->UpdateCollision(); + } +} + +// The total luck of the real players, between 0 and 10. +static float award_luck_get() +{ + float luck = 0; + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && !player->isCoopGhost) luck += player->luck; + return std::clamp(luck, 0.0f, AWARD_LUCK_MAX); +} + +// The pickup roll in [0, 1), lifted by Lucky Foot, luck and Lucky Toe, flipped by Options' low rolls, and kept above +// the empty award when a pickup is forced. +static float award_roll_get(RNG& rng, AwardRoll roll) +{ + PlayerManager& players = g_game->playerManager; + float base = rng.RandomFloat(); + bool isLuckyFoot = players.FirstCollectibleOwner(COLLECTIBLE_LUCKY_FOOT_CLEAR, LAZARUS_SHARE_CHECK); + if (isLuckyFoot) base = base * LUCKY_FOOT_SCALE + LUCKY_FOOT_FLOOR; + + float luck = award_luck_get(); + float pick = rng.RandomFloat() * luck * AWARD_LUCK_SCALE + base; + if (players.AnyoneHasTrinket(TRINKET_LUCKY_TOE)) + { + bool isFootLuck = players.FirstCollectibleOwner(COLLECTIBLE_LUCKY_FOOT_CLEAR, LAZARUS_SHARE_CHECK) && luck > 0; + pick = isFootLuck ? pick * LUCKY_TOE_SCALE + LUCKY_TOE_FLOOR : pick * LUCKY_FOOT_SCALE + LUCKY_FOOT_FLOOR; + } + if (players.FirstCollectibleOwner(COLLECTIBLE_OPTIONS, LAZARUS_SHARE_CHECK) && pick < AWARD_OPTIONS_LOW) + pick = 1 - std::clamp(pick / AWARD_OPTIONS_LOW, 0.0f, 1.0f) * AWARD_OPTIONS_SPREAD; + if (pick <= AWARD_NOTHING && roll == AWARD_ROLL_PICKUP) + pick = std::clamp(pick / AWARD_NOTHING, 0.0f, 1.0f) * AWARD_FORCED_SPREAD + AWARD_FORCED_FLOOR; + return pick; +} + +// The pickup a roll above the empty award gives: a card, pill or trinket, a coin, heart, key, bomb or chest by the +// roll, with Rib of Greed's coins and Daemon's Tail's hearts. +static int award_kind_get(RNG& rng, float pick) +{ + PlayerManager& players = g_game->playerManager; + if (pick < AWARD_CONSUMABLE) + { + if (rng.Next() % 3 == 0) return PICKUP_TAROTCARD; + return (rng.Next() & 1) == 0 ? PICKUP_TRINKET : PICKUP_PILL; + } + if (pick < AWARD_COIN || (pick < AWARD_COIN_RIB && players.AnyoneHasTrinket(TRINKET_RIB_OF_GREED))) + return PICKUP_COIN; + if (pick < AWARD_HEART && !(players.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) && rng.RandomInt(5) != 0)) + return PICKUP_HEART; + if (pick < AWARD_KEY) return PICKUP_KEY; + return pick < AWARD_BOMB ? PICKUP_BOMB : PICKUP_CHEST; +} + +// Watch Battery's batteries and Gilded Key's chests replace the pickup on their rolls. +static int award_battery_chest_apply(RNG& rng, int variant) +{ + PlayerManager& players = g_game->playerManager; + if (rng.Next() % 15 == 0 && players.AnyoneHasTrinket(TRINKET_WATCH_BATTERY)) variant = PICKUP_LIL_BATTERY; + + Entity_Player* owner = players.FirstTrinketOwner(TRINKET_GILDED_KEY); + if (!owner) return variant; + + int multiplier = owner->GetTrinketMultiplier(TRINKET_GILDED_KEY); + if (multiplier == 2) return rng.Next() % 10 == 0 ? PICKUP_CHEST : variant; + if (multiplier >= 3) return rng.RandomInt(4) == 0 ? PICKUP_CHEST : variant; + return variant; +} + +// The first real player holding a trinket, or a dead Lazarus's backup holding a shared one. +static bool is_award_trinket_held(int trinket) +{ + bool isShared = ItemConfig::is_trinket_tagged(trinket, TAG_LAZ_SHARED_GLOBAL); + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER) continue; + if (player->HasTrinket(trinket)) return true; + if (isShared && player->backupPlayer && player->backupPlayer->HasTrinket(trinket)) return true; + } + return false; +} + +// Ace of Spades, Safety Cap, Child's Heart, Match Stick and Rusted Key each get a roll to turn the pickup into +// theirs. Child's Heart rolls only one time in five beside Daemon's Tail. +static int award_trinkets_apply(RNG& rng, int variant) +{ + PlayerManager& players = g_game->playerManager; + for (auto [trinket, pickup] : AWARD_TRINKETS) + { + if (!is_award_trinket_held(trinket)) continue; + if (trinket == TRINKET_CHILDS_HEART && players.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) && rng.Next() % 5 != 0) + continue; + + int multiplier = players.GetTrinketMultiplier(trinket); + uint32_t odds = multiplier == 2 ? AWARD_TRINKET_ODDS_DOUBLE + : multiplier > 2 ? AWARD_TRINKET_ODDS_TRIPLE + : AWARD_TRINKET_ODDS; + if (rng.Next() % 100 < odds) return pickup; + } + return variant; +} + +// 007fa920 RoomClear_PickVariant: the pickup a cleared room drops, or none. Grab bags one time in 50, Smelter's +// trinkets one in 50, and Guppy's Tail's chests one time in three (else it empties a third of the rest). +int clear_award_variant_pick(RNG& rng, AwardRoll roll) +{ + PlayerManager& players = g_game->playerManager; + float pick = award_roll_get(rng, roll); + int variant = PICKUP_NULL; + + if (pick > AWARD_NOTHING) + { + variant = award_battery_chest_apply(rng, award_kind_get(rng, pick)); + if (rng.Next() % 50 == 0) variant = PICKUP_GRAB_BAG; + variant = award_trinkets_apply(rng, variant); + if (players.FirstCollectibleOwner(COLLECTIBLE_SMELTER, LAZARUS_SHARE_CHECK) && rng.Next() % 50 == 0) + variant = PICKUP_TRINKET; + } + + if (!players.FirstCollectibleOwner(COLLECTIBLE_GUPPYS_TAIL, LAZARUS_SHARE_CHECK)) return variant; + if (rng.Next() % 3 == 0) return (rng.Next() & 1) != 0 ? PICKUP_LOCKEDCHEST : PICKUP_CHEST; + if (roll == AWARD_ROLL_ANY) return rng.Next() % 3 != 0 ? variant : PICKUP_NULL; + return variant; +} + +// What one room clear spawns: the pickup, its subtype, how many, and whether Broken Modem doubles the first. +struct ClearAward +{ + RNG rng; + Vector reward{}; + float itemRow = 0; + int count = 1; + int trapdoorIndex = -1; + int subType = 0; + int variant = PICKUP_NULL; + bool isGlitched = false; + bool isShopItems = false; +}; + +// How many pickups the award drops: Contract From Below's copies (that may all fail), hard mode's hearts that fail a +// third of the time, Blue Key's copies in a blue room, and Glyph of Balance's choice of pickup. +static void award_count_roll(Room& room, ClearAward& award) +{ + PlayerManager& players = g_game->playerManager; + if (players.AnyoneHasCollectible(COLLECTIBLE_CONTRACT_FROM_BELOW) && award.variant != PICKUP_TRINKET) + { + award.count = players.GetNumCollectibles(COLLECTIBLE_CONTRACT_FROM_BELOW) + 1; + float roll = award.rng.RandomFloat(); + if (roll < std::pow(CONTRACT_FAIL_BASE, (float)(award.count - 1)) * CONTRACT_FAIL_SCALE) award.count = 0; + } + if (g_game->difficulty == DIFFICULTY_HARD && award.variant == PICKUP_HEART && + award.rng.RandomInt(100) >= (uint32_t)HARD_HEART_PERCENT) + award.count = 0; + + if (!Entity_Pickup::IsChest(award.variant)) + { + Entity_Player* owner = players.RandomCollectibleOwner(COLLECTIBLE_GLYPH_OF_BALANCE, award.rng._seed, nullptr); + if (owner) owner->GetGlyphOfBalanceDrop(&award.variant, &award.subType); + } + + if (room.descriptor->gridIndex == ROOM_BLUE_ROOM_IDX) + if (Entity_Player* owner = players.FirstTrinketOwner(TRINKET_BLUE_KEY)) + award.count *= owner->GetTrinketMultiplier(TRINKET_BLUE_KEY); +} + +// Deep Pockets turns an empty award into coins, and Rib of Greed's doubled copies may upgrade the coins. +static void award_coins_apply(ClearAward& award) +{ + PlayerManager& players = g_game->playerManager; + bool isEmpty = award.variant == PICKUP_COIN || award.variant == PICKUP_NULL || award.count == 0; + if (isEmpty && players.FirstCollectibleOwner(COLLECTIBLE_DEEP_POCKETS_CLEAR, LAZARUS_SHARE_IGNORE)) + { + award.variant = PICKUP_COIN; + RNG pockets; + pockets.game_constructor(award.rng._seed, DEEP_POCKETS_RNG_SHIFT); + award.count = std::max(1u, pockets.RandomInt(3) + (uint32_t)award.count); + } + if (award.variant != PICKUP_COIN || !players.AnyoneHasTrinket(TRINKET_RIB_OF_GREED)) return; + + int multiplier = players.GetTrinketMultiplier(TRINKET_RIB_OF_GREED); + if (multiplier <= 1) return; + + RNG& rng = players.FirstTrinketOwner(TRINKET_RIB_OF_GREED)->GetTrinketRNG(TRINKET_RIB_OF_GREED); + int odds = multiplier > 2 ? RIB_OF_GREED_ODDS_TRIPLE : RIB_OF_GREED_ODDS; + if (rng.RandomInt(10000) < (uint32_t)odds) award.subType = RIB_OF_GREED_COINS[rng.RandomInt(5)]; +} + +// Spawns the award's pickups at free spots near the center. Each keeps the subtype the first got, a spiked or mimic +// chest that cannot open there turns plain, and Broken Modem glitches the first. +static void award_pickups_spawn(ClearAward& award) +{ + PlayerManager& players = g_game->playerManager; + int variant = award.variant; + for (int i = 0; i < award.count; i++) + { + if (variant == PICKUP_NULL) continue; + + Vector spot = free_spot_get(award.reward); + auto* pickup = static_cast(g_game->Spawn({.position = spot, .subType = award.subType, + .type = ENTITY_PICKUP, .variant = variant, + .seed = award.rng.Next()})); + if (!Entity_Pickup::IsChest(pickup->variant)) award.subType = pickup->subtype; + if (pickup->variant == PICKUP_SPIKEDCHEST || pickup->variant == PICKUP_MIMICCHEST) + reconstruction_missing("Room::SpawnClearAward 007fb250: a spiked chest's spot (Room::" + "CanSpawnObstacleAtPosition 00822820)"); + if (award.isGlitched && i == 0) pickup->AddEntityFlags(FLAG_GLITCH); + if (players.FirstCollectibleOwner(COLLECTIBLE_OPTIONS, LAZARUS_SHARE_CHECK)) + reconstruction_missing("Room::SpawnClearAward 007fb250: Options' alternative (Room::" + "spawn_options_alternative 008276e0)"); + } +} + +// Old Capacitor's battery, a chance growing with luck, and Temporary Tattoo's chest or item in a challenge room with +// stat ups for its doubled copies. Cantripped! adds a card. +static void award_extras_spawn(Room& room, ClearAward& award) +{ + Game& game = *g_game; + PlayerManager& players = game.playerManager; + if (players.AnyoneHasTrinket(TRINKET_OLD_CAPACITOR)) + { + float multiplier = (float)players.GetTrinketMultiplier(TRINKET_OLD_CAPACITOR); + float chance = std::min((players.get_total_luck() * OLD_CAPACITOR_LUCK + OLD_CAPACITOR_BASE) * multiplier, + OLD_CAPACITOR_MAX); + if (award.rng.RandomFloat() < chance) + { + Vector spot = free_spot_get(award.reward); + game.Spawn({.position = spot, .subType = 1, .type = ENTITY_PICKUP, .variant = PICKUP_LIL_BATTERY, + .seed = award.rng.Next()}); + if (players.AnyoneHasCollectible(COLLECTIBLE_OPTIONS)) + reconstruction_missing("Room::SpawnClearAward 007fb250: Options' alternative battery"); + } + } + + if (players.AnyoneHasTrinket(TRINKET_TEMPORARY_TATTOO) && room.roomType == ROOM_CHALLENGE) + { + bool isBossChallenge = room.descriptor->data->subtype == 1; + Vector spot = free_spot_get(award.reward); + game.Spawn({.position = spot, .type = ENTITY_PICKUP, + .variant = isBossChallenge ? PICKUP_COLLECTIBLE : PICKUP_CHEST, .seed = award.rng.Next()}); + for (Entity_Player* player : players.playerList) + { + int multiplier = player->GetTrinketMultiplier(TRINKET_TEMPORARY_TATTOO); + if (multiplier > 1) player->add_random_stat_up(&award.rng); + if (multiplier > 2) player->add_random_stat_up(&award.rng); + } + } + + if (game.challenge == CHALLENGE_CANTRIPPED) + { + Vector spot = free_spot_get(award.reward); + game.Spawn({.position = spot, .subType = 1, .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD, + .seed = award.rng.Next()}); + } +} + +// A normal room's award: the rolled pickup in its count, then the extras. +static void room_award_spawn(Room& room, ClearAward& award) +{ + PlayerManager& players = g_game->playerManager; + award.variant = clear_award_variant_pick(award.rng, AWARD_ROLL_ANY); + award_count_roll(room, award); + + bool isModemPickup = award.variant == PICKUP_COIN || award.variant == PICKUP_HEART || + award.variant == PICKUP_KEY || award.variant == PICKUP_GRAB_BAG || + award.variant == PICKUP_BOMB; + award.isGlitched = players.AnyoneHasCollectible(COLLECTIBLE_BROKEN_MODEM) && award.rng.RandomInt(4) == 0 && + award.count >= 1 && isModemPickup; + award_coins_apply(award); + award_pickups_spawn(award); + award_extras_spawn(room, award); +} + +// A boss item spawned at a cleared and snapped spot, a deal when the award is. +static Entity_Pickup* boss_item_spawn(Room& room, ClearAward& award, Vector spot, int item) +{ + reward_spot_clear(room, spot); + reward_spot_snap(room, spot); + auto* pickup = static_cast(g_game->Spawn({.position = spot, .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = award.rng.Next()})); + if (award.isShopItems) pickup->MakeShopItem(-2); + pickup->coopDuplicateIndex = 0; + return pickup; +} + +// The collectible a boss gives: the horsemen's and the sins' own while they are left, a Broken Shovel's second half +// in Boss Rush, else the room's pool. The chosen one leaves the pools. +static int boss_item_pick(Room& room, ClearAward& award) +{ + Game& game = *g_game; + ItemPool& pool = game.itemPool; + PersistentGameData& data = g_manager->persistentGameData; + auto isLeft = [&](int item) { return pool.is_collectible_available(item, UNLOCK_CHECKED); }; + + int item = 0; + if (room.bossId == 38 && isLeft(COLLECTIBLE_WHITE_PONY)) item = COLLECTIBLE_WHITE_PONY; + else if (room.bossId == 22 && isLeft(COLLECTIBLE_PONY)) item = COLLECTIBLE_PONY; + else if (room.bossId == 21 && isLeft(COLLECTIBLE_LITTLE_CHAD)) + { + data.TryUnlock(ACHIEVEMENT_LITTLE_CHAD); + item = COLLECTIBLE_LITTLE_CHAD; + } + else if (room.bossId == 19 && isLeft(COLLECTIBLE_LITTLE_GISH)) + { + data.TryUnlock(ACHIEVEMENT_LITTLE_GISH); + item = COLLECTIBLE_LITTLE_GISH; + } + else if (room.bossId == 20 && (isLeft(COLLECTIBLE_STEVEN) || isLeft(COLLECTIBLE_LITTLE_STEVEN))) + { + data.TryUnlock(ACHIEVEMENT_LITTLE_STEVEN); + bool isLittle = isLeft(COLLECTIBLE_LITTLE_STEVEN) && award.rng.RandomInt(6) != 0; + item = isLittle ? COLLECTIBLE_LITTLE_STEVEN : COLLECTIBLE_STEVEN; + } + else if ((room.bossId >= 9 && room.bossId <= 12) || room.bossId == 38 || room.bossId == 22) + { + data.TryUnlock(ACHIEVEMENT_BOOK_OF_REVELATIONS); + item = award.rng.RandomInt(2) != 0 ? COLLECTIBLE_BALL_OF_BANDAGES : COLLECTIBLE_CUBE_OF_MEAT; + if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_CUBE_OF_MEAT, LAZARUS_SHARE_CHECK)) + item = COLLECTIBLE_CUBE_OF_MEAT; + else if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BALL_OF_BANDAGES, LAZARUS_SHARE_CHECK)) + item = COLLECTIBLE_BALL_OF_BANDAGES; + } + else if (room.roomType == ROOM_BOSSRUSH && + game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BROKEN_SHOVEL_1, LAZARUS_SHARE_CHECK)) + item = COLLECTIBLE_BROKEN_SHOVEL_2; + else if (room.bossId == BABY_PLUM_BOSS) + reconstruction_missing("Room::SpawnClearAward 007fb250: Baby Plum's Plum Flute (Room +0x73f0)"); + + if (!item) return pool.GetSeededCollectible(award.rng.Next(), 0, *room.descriptor); + pool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY); + return item; +} + +// 0080e320 Room::pick_special_clear_award: one boss kill in 100 also gives the boss's own collectible or trinket +// while they are left. Not for a second boss outside a boss room. +static bool special_award_pick(Room& room, RNG& rng, int& item, int& trinket) +{ + static const std::map BOSS_ITEMS = { + {1, 86}, {3, 88}, {4, 384}, {5, 229}, {13, 10}, {14, 578}, {15, 87}, {16, 537}, + {17, 318}, {18, 525}, {23, 646}, {27, 683}, {28, 384}, {29, 148}, {30, 155}, {31, 435}, + {32, 612}, {33, 645}, {34, 211}, {35, 242}, {36, 266}, {41, 170}, {42, 89}, {43, 277}, + {44, 36}, {45, 369}, {46, 375}, {47, 314}, {48, 610}, {49, 384}, {50, 259}, {51, 572}, + {52, 658}, {53, 167}, {56, 384}, {57, 682}, {58, 576}, {59, 545}, {60, 503}, {61, 288}, + {64, 680}, {65, 378}, {66, 549}, {67, 3}, {68, 225}, {69, 503}, {72, 473}, {73, 453}, + {74, 358}, {75, 308}, {76, 270}, {77, 469}, {78, 676}, {80, 663}, {81, 216}, {82, 256}, + {83, 210}, {85, 642}, {86, 729}, {87, 639}, {91, 264}, {92, 291}, {93, 616}, {95, 209}, + {96, 641}, {97, 504}, {102, 677}}; + static const std::map BOSS_TRINKETS = {{9, 115}, {10, 114}, {11, 113}, {12, 116}, + {38, 117}, {79, 141}, {101, 183}}; + constexpr std::array SIN_TRINKETS = {12, 26, 9, 11, 27, 10, 64, 65, 96, 144, 66}; + constexpr int COLLECTIBLE_DAMOCLES_PASSIVE = 639; + + item = 0; + trinket = 0; + if (room.roomType != ROOM_BOSS && room.secondBossId != 0) return false; + if (rng.Next() % 100 != 0) return false; + + bool isSin = room.bossId == 2 || room.bossId == 7 || room.bossId == 26 || room.bossId == 37; + if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED) item = COLLECTIBLE_DAMOCLES_PASSIVE; + else if (isSin) trinket = SIN_TRINKETS[rng.RandomInt(SIN_TRINKETS.size())]; + else if (auto found = BOSS_ITEMS.find(room.bossId); found != BOSS_ITEMS.end()) item = found->second; + else if (auto found = BOSS_TRINKETS.find(room.bossId); found != BOSS_TRINKETS.end()) trinket = found->second; + + if (item && !g_game->itemPool.is_collectible_available(item, UNLOCK_CHECKED)) item = 0; + if (trinket && !g_game->itemPool.RemoveTrinket(trinket)) trinket = 0; + return item || trinket; +} + +// The boss item, There's Options' second choice (left and right of it) and the rare boss award beside them, all one +// pick. The boss's trinket lands where its collectible would. +static void boss_items_spawn(Room& room, ClearAward& award) +{ + Game& game = *g_game; + PlayerManager& players = game.playerManager; + int item = boss_item_pick(room, award); + if (game.challenge == CHALLENGE_CANTRIPPED) + reconstruction_missing("Room::SpawnClearAward 007fb250: Cantripped!'s boss card"); + + int specialItem = 0; + int specialTrinket = 0; + bool isSpecial = special_award_pick(room, award.rng, specialItem, specialTrinket); + float row = award.reward.y + AWARD_ITEM_DROP; + Vector center = vector_make(award.reward.x, award.itemRow); + Vector left = vector_make(award.reward.x - AWARD_ITEM_SPACING, row); + Vector right = vector_make(award.reward.x + AWARD_ITEM_SPACING, row); + Vector farLeft = vector_make(award.reward.x - 2 * AWARD_ITEM_SPACING, row); + Vector farRight = vector_make(award.reward.x + 2 * AWARD_ITEM_SPACING, row); + + bool hasOptions = players.FirstCollectibleOwner(COLLECTIBLE_THERES_OPTIONS, LAZARUS_SHARE_CHECK); + Vector spot = hasOptions && isSpecial ? vector_make(award.reward.x, row) : hasOptions != isSpecial ? left : center; + Entity_Pickup* first = boss_item_spawn(room, award, spot, item); + + int optionsIndex = -1; + if (players.FirstCollectibleOwner(COLLECTIBLE_THERES_OPTIONS, LAZARUS_SHARE_CHECK)) + { + int second = game.itemPool.GetSeededCollectible(award.rng.Next(), 0, *room.descriptor); + game.itemPool.RemoveCollectible(second, REMOVE_ANY, REMOVE_APPLY); + Entity_Pickup* option = boss_item_spawn(room, award, isSpecial ? farLeft : right, second); + optionsIndex = first->AssignOptionsIndex(); + option->optionsPickupIndex = optionsIndex; + } + if (!isSpecial) return; + + spot = players.FirstCollectibleOwner(COLLECTIBLE_THERES_OPTIONS, LAZARUS_SHARE_CHECK) ? farRight : right; + if (specialItem) + { + game.itemPool.RemoveCollectible(specialItem, REMOVE_ANY, REMOVE_APPLY); + reward_spot_clear(room, spot); + reward_spot_snap(room, spot); + auto* special = static_cast(game.Spawn({.position = spot, .subType = specialItem, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = award.rng.Next()})); + if (award.isShopItems) special->MakeShopItem(-2); + if (optionsIndex == -1) optionsIndex = first->AssignOptionsIndex(); + special->optionsPickupIndex = optionsIndex; + special->coopDuplicateIndex = 0; + } + if (specialTrinket) + game.Spawn({.position = spot, .subType = specialTrinket, .type = ENTITY_PICKUP, .variant = PICKUP_TRINKET, + .seed = Random()}); +} + +// The trapdoor down, or a trophy at the challenge's last floor. A Secret path challenge opens it only on the floors +// the alternate path goes down from, a Home one not at the Depths' last boss. +static void boss_exit_spawn(Room& room, ClearAward& award, int stage, bool isContinuing) +{ + Game& game = *g_game; + if (!isContinuing) + { + Vector spot = award.reward; + reward_spot_clear(room, spot); + game.Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_TROPHY, .seed = Random()}); + return; + } + + ChallengeParam& params = game.GetChallengeParams(); + bool isLabyrinth = game.filter_curses(CURSE_OF_LABYRINTH); + bool isHomeEnd = params.pathType == PATH_TYPE_HOME && is_depths_last_boss(); + bool isOddStage = stage == 1 || stage == 3 || stage == 5 || stage == 7; + bool isPathClosed = params.pathType == PATH_TYPE_REPENTANCE && (!game.IsAltPath() || isLabyrinth || !isOddStage); + if (game.challenge != CHALLENGE_RED_REDEMPTION && (isHomeEnd || isPathClosed)) return; + + room_spawn_cell_clear(room, award.trapdoorIndex); + room.SpawnGridEntity(award.trapdoorIndex, GRID_TRAPDOOR, 0, Random(), 0); +} + +// The kill records a boss clear keeps: each floor's boss kills (Steven, Chad and Gish at 40 Basement, 30 Caves and +// 20 Depths kills), the first Monstro's Lung, Lil Chubby and angel unlocks, and the no-damage runs to a last boss. +static void boss_kill_records(int stage, bool isLastBoss) +{ + PersistentGameData& data = g_manager->persistentGameData; + if (!data.isReadOnly && stage >= 0 && stage < LEVEL_COUNTER_COUNT) + { + data.levelCounters[stage]++; + data.isChangesMade = true; + if ((uint32_t)data.levelCounters[2] >= 40) data.TryUnlock(ACHIEVEMENT_STEVEN); + if ((uint32_t)data.levelCounters[4] >= 30) data.TryUnlock(ACHIEVEMENT_CHAD); + if ((uint32_t)data.levelCounters[6] >= 20) data.TryUnlock(ACHIEVEMENT_GISH); + } + if (stage == 2) data.TryUnlock(ACHIEVEMENT_MONSTROS_LUNG); + else if (stage == 4) data.TryUnlock(ACHIEVEMENT_LIL_CHUBBY); + else if (stage == 11) data.TryUnlock(ACHIEVEMENT_ANGELS); + if (!isLastBoss) return; + + int damagedLevel = g_game->lastLevelWithDamage; + for (const NoDamageUnlock& unlock : NO_DAMAGE_UNLOCKS) + { + if (unlock.stage != stage || damagedLevel >= unlock.damagedLevelBound) continue; + data.TryUnlock(unlock.achievement); + if (unlock.secondAchievement) data.TryUnlock(unlock.secondAchievement); + } +} + +// The floor a boss stands for: an extra boss's own, a labyrinth's second floor (Red Redemption counts every boss so). +static int boss_stage_get() +{ + Game& game = *g_game; + int stage = (int)game.stage; + int stageType = (int)game.stageType; + if (game.currentRoomIdx == ROOM_EXTRA_BOSS_IDX) Level::boss_count_adjust(stage, stageType); + else if ((game.filter_curses(CURSE_OF_LABYRINTH) && stage < STAGE_WOMB_2) || + game.challenge == CHALLENGE_RED_REDEMPTION) + stage++; + return stage; +} + +// A boss room's award: Boss Rush's records, the pits some layouts fill, the co-op ghosts revived at the last boss, +// the trapdoor and the boss's items. The final bosses' endings are not reconstructed yet. +static void boss_award_spawn(Room& room, ClearAward& award) +{ + Game& game = *g_game; + PlayerManager& players = game.playerManager; + int stage = boss_stage_get(); + ChallengeParam& params = game.GetChallengeParams(); + bool isContinuing = !params.isPathTypeSet || stage < params.endStage; + + if (room.roomType == ROOM_BOSSRUSH) + { + PlayerManager::unlock_completion_mark(COMPLETION_BOSS_RUSH); + g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_BOSSRUSHS_CLEARED, 1); + game.gameStateFlags |= 1ull << GAME_STATE_BOSSRUSH_DONE; + } + RoomConfig_Room* data = room.descriptor->data; + bool isPitRoom = data && std::ranges::find(PIT_FILL_BOSS_ROOMS, data->variant) != PIT_FILL_BOSS_ROOMS.end(); + if (isPitRoom) boss_pits_fill(room); + + bool isSecretExitBoss = game.currentRoomIdx == ROOM_SECRET_EXIT_IDX && room.roomType == ROOM_BOSS; + bool isLastBoss = Room::IsCurrentRoomLastBoss() || isSecretExitBoss; + if (game.challenge == CHALLENGE_RED_REDEMPTION) + isLastBoss = game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx)->data->type == ROOM_BOSS; + if (players.IsCoopPlay() && isLastBoss) players.revive_player_ghosts(); + + bool isPlainFloor = stage < STAGE_WOMB_2 && stage != STAGE_DEPTHS_2; + bool isMomsFloor = (stage == STAGE_WOMB_2 || stage == STAGE_DEPTHS_2) && !isLastBoss; + bool isBossRush = room.roomType == ROOM_BOSSRUSH || + (game.challenge == CHALLENGE_RED_REDEMPTION && stage < STAGE_WOMB_2); + if (isSecretExitBoss) + reconstruction_missing("Room::SpawnClearAward 007fb250: the secret exit's bosses (Mom, Mother)"); + else if (isPlainFloor || isBossRush) + { + if (isLastBoss) boss_exit_spawn(room, award, stage, isContinuing); + boss_items_spawn(room, award); + } + else if (isMomsFloor) boss_items_spawn(room, award); + else reconstruction_missing("Room::SpawnClearAward 007fb250: the final bosses' endings and chests"); + boss_kill_records(stage, isLastBoss); +} + +// 007fb250 Room::SpawnClearAward: the reward of a cleared room, unless a mod's MC_PRE_SPAWN_CLEAN_AWARD takes it. +// A normal room drops a pickup by the roll (none in crawlspaces and the mineshaft's second dimension), a boss room +// its exit and items. Tainted Keeper and a Satanic Bible's boss turn the boss items into deals. The award's +// generator is kept for the next clear. +void room_clear_award_spawn(Room& room) +{ + Game& game = *g_game; + ClearAward award; + award.rng = rng_make(room.descriptor->awardSeed, AWARD_RNG_SHIFT); + award.reward = Room::GetCenterPos(); + lua_callback_check(MC_PRE_SPAWN_CLEAN_AWARD, "Room::SpawnClearAward 007fb250: MC_PRE_SPAWN_CLEAN_AWARD"); + award.trapdoorIndex = trapdoor_index_get(room); + award.itemRow = award.reward.y + AWARD_ITEM_DROP; + + bool isBibleDeal = (game.levelStateFlags & (1u << LEVEL_STATE_SATANIC_BIBLE_USED)) && room.roomType == ROOM_BOSS; + award.isShopItems = game.playerManager.FirstPlayerByType(PLAYER_KEEPER_B) || isBibleDeal; + if (!game.playerManager.FirstPlayerByType(PLAYER_KEEPER_B) && isBibleDeal) + award.itemRow = award.reward.y + AWARD_ITEM_DROP_DEAL; + + RoomConfig_Room* data = room.descriptor->data; + bool isNormal = room.roomType != ROOM_BOSS && room.roomType != ROOM_BOSSRUSH; + bool isEmpty = room.roomType == ROOM_DUNGEON || (game.HasAbandonedMineshaft() && game.currentDimensionIdx == 1); + if (game.IsGreedMode()) + { + if (room.roomType == ROOM_DEFAULT || (room.roomType == ROOM_BOSS && room.bossId == ULTRA_GREED_BOSS)) + reconstruction_missing("Room::SpawnClearAward 007fb250: Greed mode's wave music and Ultra Greed's coins"); + } + else if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_HOME_ID) + reconstruction_missing("Room::SpawnClearAward 007fb250: Home's ending"); + else if (isNormal && !isEmpty) room_award_spawn(room, award); + else if (!isNormal) boss_award_spawn(room, award); + room.descriptor->awardSeed = award.rng._seed; +} + +// The Broken Shovel quest: Mom's voice when the Basement's boss falls within a minute after the Lamb was killed. +static void shovel_quest_check() +{ + Game& game = *g_game; + bool isQuestBoss = g_manager->persistentGameData.eventCounters[EVENT_COUNTER_LAMB_KILLS] != 0 && + !(game.levelStateFlags & (1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED)) && + Room::IsCurrentRoomLastBoss() && game.stage == 1 && + game.stageType != STAGETYPE_REPENTANCE && game.stageType != STAGETYPE_REPENTANCE_B && + game.frameCount < SHOVEL_QUEST_FRAMES; + if (isQuestBoss) + reconstruction_missing("Room::TriggerClear 008068f0: the Broken Shovel quest (Manager::IsGameplayInputActive " + "009595e0, Room +0x72fc)"); +} + +// 008068f0 Room::TriggerClear: marks and counts the clear, scores it, opens the exits it earns (the secret exit, the +// devil room's, Boss Rush, the Blue Womb, the Void), plays the clear sound unless silent, rewards the players and +// spawns the award (unless the room gives none), revives Greed's co-op ghosts and saves the rewind state. +void room_clear_trigger(Room& room, ClearSound sound) +{ + Game& game = *g_game; + RoomDescriptor& descriptor = *room.descriptor; + descriptor.flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; + descriptor.clearCount++; + game.scoreSheet.add_cleared_room({.clearCount = descriptor.clearCount, + .shape = descriptor.data->shape, + .type = room.roomType, + .isRedRoom = (descriptor.flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM) != 0}); + + ChallengeParam& params = game.GetChallengeParams(); + bool isPathChallenge = game.challenge == CHALLENGE_BACKASSWARDS || params.pathType == PATH_TYPE_HOME || + params.endStage == STAGE_HOME_END; + int nextStage = (int)game.stage + (game.filter_curses(CURSE_OF_LABYRINTH) ? 1 : 0); + if (isPathChallenge && Room::IsCurrentRoomLastBoss() && nextStage == STAGE_DEPTHS_2) + reconstruction_missing("Room::TriggerClear 008068f0: a path challenge's doors (Room::update_door_targets " + "00802670)"); + + bool isGreed = game.IsGreedMode(); + if (!isGreed) room.TrySpawnSecretExit(true, false); + room.TrySpawnDevilRoomDoor(true, false); + if (sound == CLEAR_SOUND_PLAY) sound_play(SOUND_DOOR_HEAVY_OPEN); + if (!isGreed) + { + room.TrySpawnBossRushDoor(false, false); + room.TrySpawnBlueWombDoor(true, false, false); + room.TrySpawnTheVoidDoor(false); + shovel_quest_check(); + } + + if (!(descriptor.flags & ROOM_DESCRIPTOR_FLAG_NO_REWARD)) + { + if (!isGreed || room.roomType != ROOM_DEFAULT) game.playerManager.trigger_room_clear(); + room_clear_award_spawn(room); + } + if (isGreed && room.roomType == ROOM_DEFAULT) + { + int wave = game.greedModeWave; + game.greedLastBeatenWave = wave; + int lastWave = game.difficulty == DIFFICULTY_GREEDIER ? GREED_WAVES + 1 : GREED_WAVES; + if (game.playerManager.IsCoopPlay() && wave == lastWave) game.playerManager.revive_player_ghosts(); + } + else if (isGreed && room.roomType == ROOM_BOSS && room.bossId == ULTRA_GREED_BOSS && + game.playerManager.IsCoopPlay()) + game.playerManager.revive_player_ghosts(); + game.save_rewind_state(-1); +} + +// 009bb840 Every player's room clear effects, then every familiar's in the room. The familiars are gathered first, +// as the original's query does, so what the effects spawn waits for the next clear. +void PlayerManager::trigger_room_clear() +{ + for (size_t i = 0; i < playerList.size(); i++) playerList[i]->TriggerRoomClear(); + + std::vector familiars; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity && entity->type == ENTITY_FAMILIAR) familiars.push_back(static_cast(entity)); + for (Entity_Familiar* familiar : familiars) familiar->TriggerRoomClear(); +} + +// A clear's charge for an active slot: one (two in the big rooms) plus Watch Battery's rolls, overcharged by AAA +// Battery near full with a sound and a heart. Timed actives fill. +static void active_clear_charge(Entity_Player& player, int slot) +{ + ActiveItemDesc& active = player.activeItems[slot]; + if (!g_manager->itemConfig.GetCollectible(active.item)) return; + + ChargeType type = active_charge_type(player, slot); + if (type == CHARGE_TIMED) player.FullCharge(slot, false, false); + if (type != CHARGE_NORMAL) return; + + Room& room = *g_game->room; + RoomConfig_Room* data = room.descriptor ? room.descriptor->data : nullptr; + bool isBig = room.roomType != ROOM_BOSSRUSH && data && data->shape >= ROOMSHAPE_2x2 && data->shape <= ROOMSHAPE_LBR; + int charge = isBig ? 2 : 1; + for (int rolls = std::min(player.GetTrinketMultiplier(TRINKET_WATCH_BATTERY), WATCH_BATTERY_MAX_ROLLS); rolls > 0; + rolls--) + if (player.GetTrinketRNG(TRINKET_WATCH_BATTERY).Next() % WATCH_BATTERY_ODDS == 0) + charge += player.GetTrinketMultiplier(TRINKET_WATCH_BATTERY); + + int maxCharge = player.GetActiveMaxCharge(slot); + int overcharge = std::min(player.GetTrinketMultiplier(TRINKET_AAA_BATTERY_CLEAR), AAA_BATTERY_MAX); + if (overcharge < 1 || active.charge + charge < maxCharge - overcharge) + { + player.AddActiveCharge(charge, slot, false, false, false); + return; + } + + if (player.AddActiveCharge(charge + overcharge, slot, false, false, false) == 0) return; + sound_play(SOUND_BATTERYCHARGE); + clear_heart_spawn(player, 1); +} + +// Isaac's Fork: one clear in 10 less half the luck heals a heart per copy, with a gulp and a heart. +static void isaacs_fork_heal(Entity_Player& player) +{ + int odds = std::max(1, ISAACS_FORK_ODDS - (int)(player.luck * ISAACS_FORK_LUCK)); + if (Random() % (uint32_t)odds != 0) return; + + player.AddHearts(player.GetTrinketMultiplier(TRINKET_ISAACS_FORK), false, false); + sound_play(player.playerType == PLAYER_MAGDALENE_B ? SOUND_VAMP_DOUBLE_CLEAR : SOUND_VAMP_GULP_CLEAR); + clear_heart_spawn(player, 0); +} + +// Rotten hearts keep two blue flies each: the missing ones come back. +static void rotten_flies_restore(Entity_Player& player) +{ + int flies = 0; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity && entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_BLUE_FLY_CLEAR && + static_cast(entity)->player == &player) + flies++; + int missing = player.rottenHearts * 2 - flies; + if (missing > 0) player.AddBlueFlies(missing, player.pos, nullptr); +} + +// Curse of the Lost's last room renews it, on the player and on a dead Lazarus's backup. +static void lost_curse_renew(Entity_Player& player) +{ + TemporaryEffect* curse = player.temporaryEffects.GetNullEffect(NULLITEM_LOST_CURSE); + if (!curse || curse->count != 1) return; + + player.temporaryEffects.AddNullEffect(NULLITEM_LOST_CURSE, true, 1); + Entity_Player* backup = player.backupPlayer; + TemporaryEffect* backupCurse = backup ? backup->temporaryEffects.GetNullEffect(NULLITEM_LOST_CURSE) : nullptr; + if (backupCurse && backupCurse->count == 1) backup->temporaryEffects.AddNullEffect(NULLITEM_LOST_CURSE, true, 1); +} + +// Azazel's Rage gathers a room each clear up to four, its costume growing, with a dark flash. +static void azazels_rage_charge(Entity_Player& player) +{ + ItemConfig& items = g_manager->itemConfig; + TemporaryEffect* rage = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_AZAZELS_RAGE); + int rooms = rage ? rage->count : 0; + if (rooms >= AZAZELS_RAGE_ROOMS) return; + + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_AZAZELS_RAGE, false, 1); + player.RemoveCostume(items.GetCollectible(COLLECTIBLE_AZAZELS_RAGE)); + for (int stage = 0; stage < 4; stage++) player.RemoveCostume(items.GetNullItem(NULLITEM_AZAZELS_RAGE_1 + stage)); + player.AddCostume(items.GetNullItem(NULLITEM_AZAZELS_RAGE_1 + std::min(rooms, 3)), false); + player.SetColor({{0.1f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, AZAZELS_RAGE_FLASH_FRAMES, COLOR_PRIORITY_FULL, + true, true); +} + +// Azazel's Stump: its demon form ends with the room, else one clear in four (three doubled) brings it. +static void azazels_stump_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + if (effects.GetTrinketEffect(TRINKET_AZAZELS_STUMP)) + { + effects.RemoveTrinketEffect(TRINKET_AZAZELS_STUMP, 1); + return; + } + if (!player.HasTrinket(TRINKET_AZAZELS_STUMP)) return; + + uint32_t odds = (uint32_t)std::max(1, 4 - player.GetTrinketMultiplier(TRINKET_AZAZELS_STUMP)); + if (player.trinketRNGs[TRINKET_AZAZELS_STUMP].Next() % odds != 0) return; + if (ItemConfig_Item* stump = g_manager->itemConfig.GetTrinket(TRINKET_AZAZELS_STUMP)) + effects.AddEffect(TemporaryEffect(stump), true, 2); +} + +// 007a8fd0 A cleared room's effects on the player: active charge (none with Old Capacitor or 4.5 Volt), Isaac's +// Fork, Louse, rotten hearts' flies, the end of an astral projection, Curse of the Lost, Swarm, Wavy Cap's fading, +// Azazel's Rage and Stump, and the wisps waiting for a clear. +void Entity_Player::TriggerRoomClear() +{ + if (!HasTrinket(TRINKET_OLD_CAPACITOR) && !HasCollectible(COLLECTIBLE_4_5_VOLT)) + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) active_clear_charge(*this, slot); + if (HasTrinket(TRINKET_ISAACS_FORK)) isaacs_fork_heal(*this); + if (HasTrinket(TRINKET_LOUSE)) AddBlueSpider(pos); + if (rottenHearts > 0) rotten_flies_restore(*this); + try_end_astral_projection(); + lost_curse_renew(*this); + if (HasCollectible(COLLECTIBLE_SWARM)) AddSwarmFlyOrbital(pos); + temporaryEffects.RemoveNullEffect(NULLITEM_WAVY_CAP, 1); + if (HasCollectible(COLLECTIBLE_AZAZELS_RAGE)) azazels_rage_charge(*this); + + if (HasTrinket(TRINKET_DINGLE_BERRY)) + reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Dingle Berry's dip"); + if (HasTrinket(TRINKET_POLISHED_BONE)) + reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Polished Bone's bony"); + if (HasTrinket(TRINKET_CRYSTAL_KEY)) + reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Crystal Key's red room"); + if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_SKIN_WISP) + reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: the wisp baby's wisps"); + bool isTaintedLazarus = playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B; + if (isTaintedLazarus && (backupPlayer || twinPlayer) && controlsCooldown <= 0 && !hasCurseMistEffect) + reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Tainted Lazarus's flip"); + azazels_stump_update(*this); + if (!proceduralItems.empty()) + reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: the TMTRAINER clear triggers " + "(trigger_set_dispatch 009e0680)"); + + for (size_t i = 0; i < pendingWisps.size(); i++) AddWisp(pendingWisps[i], pos, false, false); + pendingWisps.clear(); +} diff --git a/src/room_clear.h b/src/room_clear.h new file mode 100644 index 0000000..5c33029 --- /dev/null +++ b/src/room_clear.h @@ -0,0 +1,22 @@ +#pragma once + +#include "classes.h" + +// Whether a room's clear plays the clear sound (Lua's Room:TriggerClear(silent)). +enum ClearSound +{ + CLEAR_SOUND_PLAY, + CLEAR_SOUND_SILENT +}; + +// Whether the room clear's pickup roll may come up empty, or always gives a pickup. +enum AwardRoll +{ + AWARD_ROLL_ANY, + AWARD_ROLL_PICKUP +}; + +void room_clear_trigger(Room& room, ClearSound sound = CLEAR_SOUND_PLAY); +void room_clear_award_spawn(Room& room); +int clear_award_variant_pick(RNG& rng, AwardRoll roll); +void room_spawn_cell_clear(Room& room, int& gridIndex); diff --git a/src/room_grid.cpp b/src/room_grid.cpp new file mode 100644 index 0000000..b92c42e --- /dev/null +++ b/src/room_grid.cpp @@ -0,0 +1,208 @@ +#include "room_grid.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_pit.h" +#include "grid_entity_rock.h" +#include "log.h" +#include "npc_ai.h" +#include "room.h" +#include + +// The partitions a query bit looks in, in the order QueryRadius goes through them. +struct PartitionQuery +{ + uint32_t bit; + Partition partition; +}; + +constexpr std::array PARTITION_QUERIES = {{{QUERY_FAMILIARS, PARTITION_FAMILIARS}, + {QUERY_TEARS, PARTITION_SHOTS}, + {QUERY_ENEMIES, PARTITION_ENEMIES}, + {QUERY_PROJECTILES, PARTITION_PROJECTILES}, + {QUERY_PICKUPS, PARTITION_PICKUPS}}}; + +// The free spot search: its tries, the grid path each band of tries accepts (pits allow 3000 more), how far it steps +// out each try and where it starts over, the spot a pickup or another entity keeps free, the generator the original +// seeds the same each call, and the doors' reach and retries. +constexpr int SPOT_TRIES = 125; +constexpr int PIT_PATH_EXTRA = 3000; +constexpr float SPOT_STEP = 5; +constexpr float SPOT_STEP_MAX = 500; +constexpr float SPOT_ENTITY_DISTANCE = 20; +constexpr float SPOT_FALLBACK_MARGIN = 20; +constexpr RNG SPOT_RNG = {0x441c1dfd, 1, 9, 29}; +constexpr float DOOR_DISTANCE = 70; +constexpr int DOOR_RETRIES = 20; +constexpr float DOOR_RETRY_STEP = 40; +constexpr float DEGREES_FULL_TURN = 360; + +// The grid path a try accepts, by the tries left below which it does: higher as the search runs out. +struct PathBand +{ + int triesLeft; + int pathLimit; +}; + +constexpr std::array PATH_BANDS = {{{5, 1000}, {20, 900}, {40, 800}, {60, 700}}}; +constexpr int PATH_LIMIT_FIRST = 600; + +// The grid path a try accepts. +static int spot_path_limit(int triesLeft) +{ + for (const PathBand& band : PATH_BANDS) + if (triesLeft < band.triesLeft) return band.pathLimit; + return PATH_LIMIT_FIRST; +} + +// 0041a790 The entities whose size reaches within a radius of a position and that queries may see: those of the +// partitions asked for, then the players, then the effects. +EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t partitions) +{ + EntityList& list = g_game->room->entityList; + EntityList_EL found; + Vector extent = vector_make(radius, radius); + auto isReached = [&](Entity* entity) { + float reach = radius + entity->size; + return !entity->HasEntityFlags(FLAG_NO_QUERY) && vector_length_squared(vector_sub(entity->pos, position)) < reach * reach; + }; + + for (const PartitionQuery& query : PARTITION_QUERIES) + if (partitions & query.bit) list.partitions[query.partition].query_box(found, position, extent); + if (partitions & QUERY_PLAYERS) + for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player); + std::erase_if(found, [&](Entity* entity) { return !isReached(entity); }); + if (partitions & QUERY_EFFECTS) + for (Entity* effect : list.effectEL) + if (isReached(effect)) found.push_back(effect); + return found; +} + +// 00456620 The grid entity on the cell at a position, if any. +GridEntity* room_grid_entity_at(const Vector& position) +{ + int gridIndex = g_game->room->GetGridIndex(position); + return gridIndex < 0 ? nullptr : g_game->room->GetGridEntity((uint32_t)gridIndex); +} + +// Whether a cell takes a pickup: free of grid collision (or a pit, when allowed) and of trapdoors, stairs, pressure +// plates and teleporters. +static bool is_cell_free(Room& room, int gridIndex, const FreeSpotSearch& search) +{ + uint32_t collision = room.GetGridCollision(gridIndex); + bool isPit = search.isAllowPits && collision == COLLISION_PIT; + if (collision != COLLISION_NONE && !isPit) return false; + + GridEntity* grid = room.GetGridEntity((uint32_t)gridIndex); + if (!grid) return true; + GridEntityType type = grid->type; + return type != GRID_TRAPDOOR && type != GRID_STAIRS && type != GRID_PRESSURE_PLATE && type != GRID_TELEPORTER; +} + +// Whether an entity keeps the spot at a cell's center taken: a pickup, bomb or slot, or an enemy or player when the +// search avoids them. +static bool is_spot_taken(const Vector& center, bool isAvoidActiveEntities) +{ + for (Entity* entity : g_game->room->entityList.updateEL) + { + int type = entity->type; + bool isActive = type == ENTITY_PLAYER || Entity::is_enemy_type(type); + bool isKept = type == ENTITY_PICKUP || type == ENTITY_BOMB || type == ENTITY_SLOT || (isAvoidActiveEntities && isActive); + if (isKept && vector_length(vector_sub(entity->pos, center)) < SPOT_ENTITY_DISTANCE) return true; + } + return false; +} + +// Whether a try's cell takes the pickup: trodden less than the try allows (pits up to 3000 more) and free. +static bool is_cell_accepted(Room& room, int gridIndex, int pathLimit, const FreeSpotSearch& search) +{ + int path = room.GetGridPath(gridIndex); + bool isPit = search.isAllowPits && room.GetGridCollision(gridIndex) == COLLISION_PIT; + return (path < pathLimit || (isPit && path < pathLimit + PIT_PATH_EXTRA)) && is_cell_free(room, gridIndex, search); +} + +// 00813520 A free spot for a pickup near a position: tries spiral out at random angles, first only on clear cells, +// then accepting more trodden ones, and fall back to the cell under the position kept off the walls. A spot near a +// door, when doors are avoided, is searched again from there. +// A try outside the room keeps the last cell it checked, and a spot found on the very last try falls back, as in the +// original. +Vector room_free_pickup_position_find(const FreeSpotSearch& search) +{ + Room& room = *g_game->room; + RNG rng = SPOT_RNG; + Vector spot{}; + float step = search.step; + int gridIndex = -1; + bool isFound = false; + for (int triesLeft = SPOT_TRIES - 1; triesLeft >= 0; triesLeft--) + { + int pathLimit = spot_path_limit(triesLeft); + if (gridIndex >= 0 && is_cell_accepted(room, gridIndex, pathLimit, search)) + { + isFound = triesLeft >= 1; + break; + } + + if (step > SPOT_STEP_MAX) step = 0; + step += SPOT_STEP; + float angle = rng.RandomFloat() * DEGREES_FULL_TURN * DEGREES_TO_RADIANS; + spot = vector_make(std::cos(angle) * step + search.position.x, std::sin(angle) * step + search.position.y); + Vector clamped = room.GetClampedPositionImpl(spot, 0, 0, 0, 0); + if (clamped.x != spot.x || clamped.y != spot.y) continue; + + gridIndex = room.GetGridIndex(spot); + if (gridIndex < 0 || room.GetGridPath(gridIndex) >= pathLimit) continue; + spot = room.GetGridPosition(gridIndex); + if (is_spot_taken(spot, search.isAvoidActiveEntities)) gridIndex = -1; + } + if (!isFound) + { + Vector clamped = room.GetClampedPositionImpl(search.position, SPOT_FALLBACK_MARGIN, SPOT_FALLBACK_MARGIN, + SPOT_FALLBACK_MARGIN, SPOT_FALLBACK_MARGIN); + spot = room.GetGridPosition(room.GetGridIndex(clamped)); + } + if (!search.isAvoidDoors) return spot; + + for (GridEntity_Door* door : room.doors) + { + if (!door) continue; + + Vector doorCenter = room.GetGridPosition(door->gridIndex); + if (vector_length(vector_sub(doorCenter, spot)) >= DOOR_DISTANCE) continue; + for (int retry = 0; retry < DOOR_RETRIES && vector_length(vector_sub(doorCenter, spot)) < DOOR_DISTANCE; retry++) + spot = room_free_pickup_position_find({.position = spot, .step = DOOR_RETRY_STEP}); + return spot; + } + return spot; +} + +// 00813bf0, 00813c40 Destroys the grid entity on a cell, a bomb rock first made a plain rock when it is to be defused. +// False for an empty cell or one that did not break. +bool room_grid_destroy(const GridDestroy& destroy) +{ + GridEntity* grid = g_game->room->GetGridEntity((uint32_t)destroy.gridIndex); + if (!grid) return false; + + if (destroy.isDefuseBombRock && grid->type == GRID_ROCK_BOMB) grid->type = GRID_ROCK; + return grid->Destroy(destroy.isImmediate, destroy.source); +} + +// 0081e6e0 Fills a pit with a broken rock (spiked for a spiked rock that stood), unless the pit is part of a corner of +// pits. False when there is no pit to fill. +bool room_bridge_make(GridEntity* pit, GridEntity* rock) +{ + if (!pit || pit->type != GRID_PIT) return false; + + Vector center = pit->Position(); + auto isPitAt = [&](float x, float y) { + GridEntity* grid = room_grid_entity_at(vector_make(center.x + x, center.y + y)); + return grid && grid->type == GRID_PIT; + }; + bool isRowPit = isPitAt(GRID_CELL_SIZE, 0) || isPitAt(-GRID_CELL_SIZE, 0); + bool isColumnPit = isPitAt(0, -GRID_CELL_SIZE) || isPitAt(0, GRID_CELL_SIZE); + if (isRowPit && isColumnPit) return false; + + bool isRock = rock && rock->type == GRID_ROCK_SPIKED; + static_cast(pit)->MakeBridge(isRock ? static_cast(rock) : nullptr, 0); + return true; +} diff --git a/src/room_grid.h b/src/room_grid.h new file mode 100644 index 0000000..36797b9 --- /dev/null +++ b/src/room_grid.h @@ -0,0 +1,43 @@ +#pragma once + +#include "entity_list.h" +#include "grid_entity.h" + +// The groups EntityList::QueryRadius looks in (Lua's EntityPartition), by bit. +enum QueryPartition : uint32_t +{ + QUERY_FAMILIARS = 1 << 0, + QUERY_PROJECTILES = 1 << 1, + QUERY_TEARS = 1 << 2, + QUERY_ENEMIES = 1 << 3, + QUERY_PICKUPS = 1 << 4, + QUERY_PLAYERS = 1 << 5, + QUERY_EFFECTS = 1 << 6, + QUERY_ALL = 0xffffffff +}; + +// A search for a free spot for a pickup (Room::FindFreePickupSpawnPosition's arguments): around a position, first +// this far out, kept off spots near enemies and players, maybe over pits, and maybe away from the doors. +struct FreeSpotSearch +{ + Vector position{}; + float step = 0; + bool isAvoidActiveEntities = false; + bool isAllowPits = false; + bool isAvoidDoors = false; +}; + +// A grid entity destroyed through the room (Room::DestroyGrid's arguments): a bomb rock may be defused into a rock. +struct GridDestroy +{ + EntityRef source{}; + int gridIndex = 0; + bool isImmediate = false; + bool isDefuseBombRock = false; +}; + +EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t partitions); +GridEntity* room_grid_entity_at(const Vector& position); +Vector room_free_pickup_position_find(const FreeSpotSearch& search); +bool room_grid_destroy(const GridDestroy& destroy); +bool room_bridge_make(GridEntity* pit, GridEntity* rock); diff --git a/src/room_state.cpp b/src/room_state.cpp index a2c3e02..8e53a0c 100644 --- a/src/room_state.cpp +++ b/src/room_state.cpp @@ -5,10 +5,12 @@ #include "entity_pickup.h" #include "entity_player.h" #include "entity_slot.h" +#include "entity_tear.h" #include "game.h" #include "log.h" #include "npc_ai.h" #include "room.h" +#include "room_clear.h" #include #include #include @@ -41,11 +43,9 @@ constexpr int SLOT_STATE_GONE = 4; constexpr int CHEST_RECLOSED_SUBTYPE = 1; constexpr int SHOP_ITEM_ID_MIN = -2; constexpr int SHOP_ITEM_ID_MAX = 7; -constexpr int TEAR_HYDROBOUNCE = 61; constexpr int TEAR_FLAG_WORDS = 4; constexpr int TEAR_FLAG_WORD_BITS = 32; constexpr uint8_t BOMB_NO_PLAYER = 0xff; -constexpr float RADIANS_TO_DEGREES = 57.2957763671875f; constexpr RNG DROP_RNG_SAVED = {0, 4, 3, 17}; // The pickups whose save keeps where they were heading rather than where they are. @@ -378,7 +378,7 @@ void Room::on_leave() game.scoreSheet.add_cleared_room({descriptor->clearCount, descriptor->data->shape, roomType, (descriptor->flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM) != 0}); if (!isGreedWave) game.playerManager.trigger_room_clear(); - reconstruction_missing("Room::SpawnClearAward 007fb250"); + room_clear_award_spawn(*this); if (isGreedWave) game.greedLastBeatenWave = game.greedModeWave; } diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 6a08242..8f6f85d 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -99,7 +99,7 @@ void RoomTransition::start(const RoomTransitionRequest& request) log_printf(LOG_INFO, "[Frame %d] Starting room transition (type %d) \n", game.frameCount, request.animation); if (!versusScreenANM2.isLoaded) versusScreenANM2.Load(VERSUS_SCREEN_ANM2, GRAPHICS_LOAD); - if (game.stageTransition._state != 0 && request.animation != TRANSITION_BOSS_FORCED) return; + if (game.stageTransition.state != 0 && request.animation != TRANSITION_BOSS_FORCED) return; bool isCurrentRoom = request.roomIndex == game.currentRoomIdx && request.dimension == game.currentDimensionIdx; roomIndex = request.roomIndex; @@ -135,11 +135,6 @@ void RoomTransition::start(const RoomTransitionRequest& request) g_manager->sfxManager.Play(sound); } -void RoomTransition::StartBossIntro(uint32_t, uint32_t) -{ - reconstruction_missing("RoomTransition::StartBossIntro 0082f1c0"); -} - // The distance between two rooms in screen pixels, mirrored in the mirror world: from their map cells when both lie on // the map of one dimension, else the size of the room on the side left through (the target's for left and up). static Vector room_distance_get(RoomDescriptor& current, RoomDescriptor& target, bool isOnMap, Direction direction) diff --git a/src/room_update.cpp b/src/room_update.cpp index 8ddfcf7..f9e3862 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -8,6 +8,7 @@ #include "log.h" #include "manager.h" #include "room.h" +#include "room_clear.h" #include "room_render.h" #include "seeds.h" #include @@ -387,14 +388,6 @@ static void output_trigger(Room& room, int group) if (!room.outputGroupCallbacks[group].empty()) reconstruction_missing("Room::TriggerOutput 00823080: callbacks"); } -// 008068f0 Clears the room: marks and counts it, scores it, opens the exits the clear earns (the secret exit, the -// devil room's, Boss Rush, the Blue Womb, the Void), plays the clear jingle, rewards the players, and saves the -// rewind state. Not reconstructed yet. -static void room_clear_trigger(Room&) -{ - reconstruction_missing("Room::TriggerClear 008068f0"); -} - // The clear check: while enemies or Greed's wave are left (or an ambush runs) the room holds off clearing; once the // delay is out the doors open and the room clears, or a crawlspace's exit room sends the players back. static void clear_update(Room& room) diff --git a/src/stage_transition.cpp b/src/stage_transition.cpp new file mode 100644 index 0000000..e52a81d --- /dev/null +++ b/src/stage_transition.cpp @@ -0,0 +1,507 @@ +#include "stage_transition.h" +#include "entity_effect.h" +#include "entity_list.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "level.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "render_passes.h" +#include "room.h" +#include "seeds.h" +#include + +constexpr int START_DURATION = 50; +constexpr int ASCENT_DURATION = 8; +constexpr int ASCENT_FADE_IN_DURATION = 15; +constexpr int EXIT_WAIT_FRAMES = 20; +constexpr int FORGET_ME_NOW_WAIT_FRAMES = 5; +constexpr int CATCH_UP_FRAME = 6; +constexpr int EXIT_FRAME_UNSET = 1000; +constexpr int MUSIC_FRAME = 2; +constexpr int FIRST_ASCENT_STAGE = 1; +constexpr int LAST_ASCENT_STAGE = 6; +constexpr int STAGE_SHEOL = 11; +constexpr int STAGE_VOID = 12; +constexpr int STAGE_HOME = 13; +constexpr int STAGE_WOMB_I = 7; +constexpr int GRID_COLUMN_OFFSET = 40; +constexpr int GRID_ROW_OFFSET = 120; +constexpr float GRID_CELL = 40; + +constexpr int COLLECTIBLE_FORGET_ME_NOW = 127; +constexpr int SOUND_ASCENT_START = 615; +constexpr int ACHIEVEMENT_NO_HEARTS_STAGES = 42; +constexpr int ACHIEVEMENT_NO_DAMAGE_STAGES = 67; +constexpr int ACHIEVEMENT_ALT_WOMB = 411; +constexpr uint32_t LEVEL_STATE_DAMAGED = 1 << 5; + +constexpr int EFFECT_POOF01 = 15; +constexpr int EFFECT_DUST_CLOUD = 99; +constexpr int POOF_SMALL = 2; +constexpr int DUST_SPLASH = 1; +constexpr float DRY_WATER_LIMIT = 0.2f; +constexpr float EXIT_POOF_ALPHA = 0.5f; +constexpr float EXIT_EFFECT_SPEED = 2; +constexpr float EXIT_POOF_DEPTH = 4; +constexpr int SPLASH_COUNT_MIN = 3; +constexpr int SPLASH_COUNT_SPREAD = 5; +constexpr float SPLASH_SPEED = 8; +constexpr float SPLASH_FALL = 1; +constexpr float SPLASH_LIFT = -8; +constexpr float SPLASH_LIFT_SPREAD = 4; +constexpr float RANDOM_UNIT = 2.3283064e-10f; +constexpr float RANDOM_PI = 3.14f; + +constexpr float LIGHT_SCALE_LIMIT = 2; +constexpr float LIGHT_SCALE_TARGET = 1.5f; +constexpr float LIGHT_EASE_UPDATE = 1; +constexpr float LIGHT_EASE_INTERPOLATE = 1.5f; +constexpr float LIGHT_OFFSET_BASE = -32; +constexpr float LIGHT_OFFSET_PER_SCALE = 11; +constexpr float LIGHT_OFFSET_EASE = 0.15f; + +constexpr std::string_view ANIM_TRAPDOOR = "Trapdoor"; +constexpr std::string_view ANIM_TRAPDOOR_EXIT = "Player Exit"; +constexpr std::string_view ANIM_APPEAR = "Appear"; +constexpr std::string_view EVENT_EXIT = "Poof"; + +// The room's ambient loops, which a boss intro and a floor change silence. +constexpr std::array AMBIENT_LOOP_SOUNDS = {269, 4, 279, 281, 163, 473, 476, 480, + 161, 505, 580, 535, 558, 553, 555, 612}; + +// (007ea5d0) Stops the room's ambient loops that play. The original also zeroed their last volumes, which +// update_ambient_sounds keeps in room_update.cpp. +void room_ambient_sounds_stop() +{ + SFXManager& sfx = g_manager->sfxManager; + + for (int sound : AMBIENT_LOOP_SOUNDS) + if (sfx.IsPlaying(sound)) sfx.Stop(sound); +} + +// Whether the run climbs the Ascent on one of its floors. +static bool is_ascent_floor() +{ + Game& game = *g_game; + return (int)game.stage >= FIRST_ASCENT_STAGE && (int)game.stage <= LAST_ASCENT_STAGE && + game.GetStateFlag(GAME_STATE_BACKWARDS_PATH); +} + +// The main players: not babies, nor the slots co-op ghosts hold. +template static void main_players_visit(Visit visit) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + if (player && player->variant == 0) visit(*player); +} + +// 006fdc10 Game::StartStageTransition: scores the floor left (a replayed one apart), stops the players and their Dead +// Bird, leaves the room and starts the players' fall. A run on the Ascent's floors fades fast, and the Ascent's start +// skips straight to the fade out on its stage. The daily's leaderboard and the online stats are left out, as the game +// is offline. +void StageTransition::start(const StageTransitionRequest& request) +{ + Game& game = *g_game; + if ((uint32_t)request.type >= STAGE_TRANSITION_TYPE_COUNT) + return log_printf(LOG_ERROR, "Invalid animation passed to Game::StartStageTransition()\n"); + + if (request.type != STAGE_TRANSITION_ASCENT) game.save_rewind_state(-1); + log_printf(LOG_INFO, "[Frame %d] Starting stage transition (transition type: %d) \n", game.frameCount, + request.type); + bool isBackwards = game.GetStateFlag(GAME_STATE_BACKWARDS_PATH); + StageVisit visit = {(int)game.stage, (int)game.stageType, isBackwards}; + if (request.isSameStage) game.scoreSheet.replayedStages.push_back(visit); + else + { + game.scoreSheet.AddFinishedStage(visit, game.timeCounter); + if (game.filter_curses(CURSE_OF_LABYRINTH)) + game.scoreSheet.AddFinishedStage({visit.stage + 1, visit.stageType, isBackwards}, game.timeCounter); + } + + game.playerManager.stageTransitionPlayer = request.player ? request.player : game.GetPlayer(0); + state = STAGE_TRANSITION_START; + frame = 0; + isSameStage = request.isSameStage; + type = request.type; + isDreamCatcher = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_DREAM_CATCHER, LAZARUS_SHARE_CHECK); + duration = START_DURATION; + exitPosition = {}; + main_players_visit([](Entity_Player& player) { + player.velocity = {}; + player.isControlsEnabled = false; + player.ThrowHeldEntity(vector_make(0, 0)); + }); + + int stage = (int)game.stage + (game.IsAltPath() ? 1 : 0); + if (is_ascent_floor() && stage != FIRST_ASCENT_STAGE) duration = ASCENT_DURATION; + else if (type == STAGE_TRANSITION_ASCENT) + { + isDreamCatcher = false; + frame = duration; + state = STAGE_TRANSITION_OUT; + game.room->on_leave(); + game.SetStage((int)game.stage, STAGETYPE_REPENTANCE); + } + + game.isRoomRespawned = false; + game.room->on_leave(); + main_players_visit([](Entity_Player& player) { + player.room_exit(false); + TemporaryEffects& effects = player.temporaryEffects; + while (!effects.isDisabled && effects.HasCollectibleEffect(COLLECTIBLE_DEAD_BIRD)) + effects.RemoveCollectibleEffect(COLLECTIBLE_DEAD_BIRD, 1); + }); + if (game.seedEffects.HasSeedEffect(SEED_INFINITE_BASEMENT)) game.stageNameNumeral++; +} + +// The trapdoor under the falling players, if a plain one is there. +static GridEntity* exit_trapdoor_get(const Vector& position) +{ + Room& room = *g_game->room; + int column = (int)((position.x - GRID_COLUMN_OFFSET) / GRID_CELL + 0.5f); + int row = (int)((position.y - GRID_ROW_OFFSET) / GRID_CELL + 0.5f); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return nullptr; + + uint32_t index = (uint32_t)(row * room.gridWidth + column); + if (index >= ROOM_GRID_CELLS) return nullptr; + GridEntity* grid = room.gridEntities[index]; + return grid && grid->type == GRID_TRAPDOOR && grid->variant == 0 ? grid : nullptr; +} + +// Spawns an exit effect that keeps playing through the transition. +static Entity* exit_effect_spawn(const EntitySpawn& spawn) +{ + Entity* effect = g_game->Spawn(spawn); + effect->flags |= FLAG_TRANSITION_UPDATE; + effect->sprite.playbackSpeed = EXIT_EFFECT_SPEED; + return effect; +} + +// The trapdoor swallows the players: its exit animation with a puff of dust, or on a flooded floor a splash and drops +// flying out. +static void trapdoor_splash(GridEntity& trapDoor) +{ + Room& room = *g_game->room; + Vector position = trapDoor.Position(); + + trapDoor.sprite.Play(ANIM_TRAPDOOR_EXIT, PLAY_FORCED); + if (room.waterAmount <= DRY_WATER_LIMIT) + { + Entity* poof = exit_effect_spawn({.position = position, + .subType = POOF_SMALL, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = Random()}); + poof->sprite.color._tint[3] = EXIT_POOF_ALPHA; + poof->renderDepthOffset = EXIT_POOF_DEPTH; + return poof->Update(); + } + + Entity* splash = exit_effect_spawn( + {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = Random()}); + splash->sprite.scale = vector_scale(splash->sprite.scale, 2); + splash->Update(); + + int drops = (int)(Random() % SPLASH_COUNT_SPREAD) + SPLASH_COUNT_MIN; + for (int i = 0; i < drops; i++) + { + uint32_t seed = Random(); + float angle = (float)Random() * RANDOM_UNIT * RANDOM_PI; + angle += angle; + float speed = (float)Random() * RANDOM_UNIT * SPLASH_SPEED; + auto* drop = static_cast( + exit_effect_spawn({.position = room.GetGridPosition(trapDoor.gridIndex), + .velocity = vector_make(std::cos(angle) * speed, speed * std::sin(angle)), + .subType = DUST_SPLASH, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + drop->fallingAcceleration = SPLASH_FALL; + drop->sprite.scale = vector_scale(drop->sprite.scale, 2); + drop->fallingSpeed = SPLASH_LIFT - (float)Random() * RANDOM_UNIT * SPLASH_LIFT_SPREAD; + drop->Update(); + } +} + +// The players falling in: each one done falling hides, the slowest one still falling marks where the trapdoor is, and a +// player left standing catches up by playing the faller's animation. Once nobody falls (or Forget Me Now's pickup +// started) the fade out starts after 20 frames (5 for Forget Me Now). A chest's ending ends the run there. +static void start_update(StageTransition& transition) +{ + Game& game = *g_game; + Entity_Player* exiting = nullptr; + Entity_Player* waiting = nullptr; + int minExitFrame = EXIT_FRAME_UNSET; + bool isExitEvent = false; + bool isAnyFalling = false; + + game.room->entityList.Update(UPDATE_TRANSITION); + Entity_Player* starter = game.playerManager.stageTransitionPlayer; + if (transition.type == STAGE_TRANSITION_ENDING && vector_is_zero(starter->moveToTarget)) + return main_players_visit([](Entity_Player& player) { player.Update(); }); + + main_players_visit([&](Entity_Player& player) { + AnimationState& animation = player.sprite.animState; + bool isDoneFalling = + player.isPlayingExtraAnimation && + (!animation.animData || (int)std::floor(animation.animFrame) == animation.animData->length - 1); + player.Update(); + if (player.isDead || transition.type == STAGE_TRANSITION_FORGET_ME_NOW) return; + + bool isAtTarget = player.isCoopGhost && vector_length_squared(vector_sub(player.moveToTarget, player.pos)) <= 1; + if ((!player.isPlayingExtraAnimation && !player.isPlayingItemAnimation) || isAtTarget) + { + if (isDoneFalling) player.isVisible = false; + else if (player.isVisible && !waiting) waiting = &player; + return; + } + + isAnyFalling = true; + int exitFrame = animation.animData ? (int)std::floor(animation.animFrame) : -1; + if (exitFrame < minExitFrame) + { + minExitFrame = exitFrame; + exiting = &player; + } + transition.update_player_trapdoor_scale(player, TRAPDOOR_SCALE_UPDATE); + if (animation.animData && animation.IsEventTriggered(EVENT_EXIT)) isExitEvent = true; + }); + if (exiting) transition.exitPosition = exiting->moveToTarget; + + bool isWaiting = !isAnyFalling; + if (GridEntity* trapDoor = exit_trapdoor_get(transition.exitPosition)) + { + if (isExitEvent) trapdoor_splash(*trapDoor); + if (trapDoor->sprite.IsPlaying()) + { + trapDoor->sprite.Update(); + isWaiting = false; + } + } + + if (exiting && waiting && minExitFrame >= CATCH_UP_FRAME) + { + waiting->PlayExtraAnimation(exiting->sprite.GetAnimation()); + waiting->moveToTarget = exiting->moveToTarget; + if (transition.type != STAGE_TRANSITION_FORGET_ME_NOW) return; + } + else if (!isWaiting && transition.type != STAGE_TRANSITION_FORGET_ME_NOW) return; + + main_players_visit([](Entity_Player& player) { player.sprite.offset = {}; }); + bool isForgetMeNow = transition.type == STAGE_TRANSITION_FORGET_ME_NOW; + if (transition.frame <= EXIT_WAIT_FRAMES && !(isForgetMeNow && transition.frame > FORGET_ME_NOW_WAIT_FRAMES)) + return; + + transition.frame = 0; + transition.state = STAGE_TRANSITION_OUT; + room_ambient_sounds_stop(); + g_manager->sfxManager.StopLoopingSounds(); + if (transition.type == STAGE_TRANSITION_ENDING) + reconstruction_missing("StageTransition::Update 0092f1c0: " + "get_stage_ending_id 006f9d20 and the run's ending"); +} + +// The floor changes two frames before the fade out ends: to the type's stage, or the next one (the endless basement's +// same floor alternates between its two). The nightmare shows on the last frame unless Dream Catcher moves it after the +// new floor or it is the Ascent. +static void out_update(StageTransition& transition) +{ + Game& game = *g_game; + if (transition.frame == transition.duration - 2) + { + if (!transition.isSameStage) + { + if (transition.type == STAGE_TRANSITION_SHEOL) game.SetStage(STAGE_SHEOL, STAGETYPE_ORIGINAL); + else if (transition.type == STAGE_TRANSITION_VOID) game.SetStage(STAGE_VOID, STAGETYPE_ORIGINAL); + else if (transition.type == STAGE_TRANSITION_HOME) game.SetStage(STAGE_HOME, STAGETYPE_ORIGINAL); + else game.SetNextStage(); + } + else if (game.seedEffects.HasSeedEffect(SEED_INFINITE_BASEMENT)) + { + game.SetStage(game.IsGreedMode() ? 1 : (~game.stageNameNumeral & 1) + 1, STAGETYPE_ORIGINAL); + game.seedEffects.ForgetStageSeed((int)game.stage); + } + return; + } + if (transition.frame != transition.duration - 1 || transition.isDreamCatcher || game.IsAscent()) return; + + g_manager->isNightmarePending = true; + g_manager->pendingNightmareId = transition.isSameStage; +} + +// The players' records of the floor left: the floors in a row without a heart picked up or without damage, each +// unlocking its achievement at two, and the alternate Womb on Hard. +static void floor_records_update() +{ + Game& game = *g_game; + PersistentGameData& persistent = g_manager->persistentGameData; + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + + if (game.isHeartPicked) game.stagesWithoutHeartsPicked = 0; + else if (++game.stagesWithoutHeartsPicked > 1) persistent.TryUnlock(ACHIEVEMENT_NO_HEARTS_STAGES); + if (game.levelStateFlags & LEVEL_STATE_DAMAGED) game.stagesWithoutDamage = 0; + else if (++game.stagesWithoutDamage > 1) persistent.TryUnlock(ACHIEVEMENT_NO_DAMAGE_STAGES); + if (!isGreed && (int)game.stage == STAGE_WOMB_I && game.IsAltPath()) persistent.TryUnlock(ACHIEVEMENT_ALT_WOMB); +} + +// The fade out ends on the new floor: the players appear (Forget Me Now's user holding it up), the records of the floor +// left update, the Ascent's sound plays, and the new floor is laid out, saved and entered. Backasswards starts the +// floor in its boss room. Dream Catcher's nightmare shows now, but on the Ascent. +static void floor_enter(StageTransition& transition) +{ + Game& game = *g_game; + + transition.frame = 0; + transition.state = STAGE_TRANSITION_IN; + if (transition.duration == ASCENT_DURATION) transition.duration = ASCENT_FADE_IN_DURATION; + if (transition.type == STAGE_TRANSITION_FORGET_ME_NOW) + main_players_visit([&](Entity_Player& player) { + if (&player == game.playerManager.stageTransitionPlayer) + player.AnimateCollectible(COLLECTIBLE_FORGET_ME_NOW, "Pickup", "PlayerPickupSparkle"); + else player.PlayExtraAnimation(ANIM_APPEAR); + }); + else if (transition.type != STAGE_TRANSITION_ASCENT && !game.IsAscent()) + main_players_visit([](Entity_Player& player) { player.PlayExtraAnimation(ANIM_APPEAR); }); + + game.room->entityList.Update(UPDATE_TRANSITION); + main_players_visit([](Entity_Player& player) { + player.Update(); + player.isVisible = true; + }); + floor_records_update(); + if (transition.type == STAGE_TRANSITION_ASCENT) game.gameStateFlags |= 1ull << GAME_STATE_BACKWARDS_PATH; + if (transition.type == STAGE_TRANSITION_ASCENT || is_ascent_floor()) + { + int sound = SOUND_ASCENT_START; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + } + + game.Init(false); + game.room->Update(); + Manager::save_game_state(); + game.playerManager.trigger_new_room_effects(); + if (game.challenge == CHALLENGE_BACKASSWARDS && (int)game.stage != STAGE_SHEOL) + { + main_players_visit([](Entity_Player& player) { + player.isPlayingExtraAnimation = false; + player.isPlayingItemAnimation = false; + }); + game.roomTransition.start({.animation = TRANSITION_BOSS_FORCED, + .direction = DIRECTION_NONE, + .roomIndex = game.roomList[game.lastBossRoomListIdx].gridIndex}); + game.roomTransition.Update(); + game.GetRoomByIdx(game.startingRoomIdx)->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; + game.UpdateVisibility(); + transition.state = STAGE_TRANSITION_NONE; + } + if (!transition.isDreamCatcher || is_ascent_floor()) return; + + g_manager->isNightmarePending = true; + g_manager->pendingNightmareId = transition.isSameStage; +} + +// The players land: control comes back to each once its animation ends, and the transition ends when all landed. +static void landing_update(StageTransition& transition) +{ + Game& game = *g_game; + bool isLanded = true; + + game.room->entityList.Update(UPDATE_TRANSITION); + main_players_visit([&](Entity_Player& player) { + player.Update(); + if (player.isPlayingExtraAnimation || player.isPlayingItemAnimation) isLanded = false; + else player.isControlsEnabled = true; + }); + if (isLanded) transition.state = STAGE_TRANSITION_NONE; + game.itemOverlay.Update(0); +} + +// 0092f1c0 Steps the transition a frame, the HUD redrawn in full while the screen fades. +void StageTransition::Update() +{ + Game& game = *g_game; + + switch (state) + { + case STAGE_TRANSITION_START: + start_update(*this); + break; + case STAGE_TRANSITION_OUT: + if (frame < duration) out_update(*this); + else floor_enter(*this); + break; + case STAGE_TRANSITION_IN: + if (frame == MUSIC_FRAME && isDreamCatcher) game.room->PlayMusic(); + if (frame < duration) break; + frame = 0; + state = STAGE_TRANSITION_LANDING; + game.ShowName(false); + break; + case STAGE_TRANSITION_LANDING: + landing_update(*this); + break; + default: + break; + } + + frame++; + if (state != STAGE_TRANSITION_IN && state != STAGE_TRANSITION_OUT) return; + game.hud.hudRefreshType = HUD_REFRESH_FULL; + game.hud.hudRefreshCountdown = 2; +} + +// 0092ffc0 Fades the screen to black over the fade out and back in, to white on the Ascent but leaving its first floor. +void StageTransition::Render() +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + bool isWhite = type == STAGE_TRANSITION_ASCENT || (is_ascent_floor() && state != STAGE_TRANSITION_OUT); + float shade = isWhite ? 1 : 0; + Vector screen = vector_make(g_screenWidth, g_screenHeight); + + graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); + if (state != STAGE_TRANSITION_OUT && state != STAGE_TRANSITION_IN) return; + render_color_shader_pass( + KAGE::Graphics::color_quad_rect({}, screen, kcolor_rgba(shade, shade, shade, get_fade_progress()))); +} + +// 00930160 How far the fade has gone, 0 to 1 dark (or white), -1 outside the fades. +float StageTransition::get_fade_progress() +{ + if (state != STAGE_TRANSITION_OUT && state != STAGE_TRANSITION_IN) return -1; + + float progress = (float)frame / (float)duration; + return state == STAGE_TRANSITION_IN ? 1 - progress : progress; +} + +// 009301d0 Whether the screen pixelates as it fades: always but on the Ascent, whose first floor still pixelates fading +// out. +bool StageTransition::is_pixelated() +{ + Game& game = *g_game; + if (type == STAGE_TRANSITION_ASCENT) return false; + if (!is_ascent_floor()) return true; + return state == STAGE_TRANSITION_OUT && (int)game.stage + (game.IsAltPath() ? 1 : 0) == FIRST_ASCENT_STAGE; +} + +// 0092f050 A player rising into an ending's light shrinks from its huge start back toward 1.5 as the animation goes, +// and floats up the more the larger it is. +void StageTransition::update_player_trapdoor_scale(Entity_Player& player, TrapdoorScaleRate rate) +{ + ANM2& sprite = player.sprite; + if (type != STAGE_TRANSITION_ENDING || !sprite.IsPlaying(ANIM_TRAPDOOR)) return; + + if (sprite.scale.x > LIGHT_SCALE_LIMIT || sprite.scale.y > LIGHT_SCALE_LIMIT) + { + float ease = rate == TRAPDOOR_SCALE_INTERPOLATE ? LIGHT_EASE_INTERPOLATE : LIGHT_EASE_UPDATE; + float progress = 1 - 1 / (ease + sprite.animState.animFrame); + sprite.scale.y += (std::min(sprite.scale.y, LIGHT_SCALE_TARGET) - sprite.scale.y) * progress; + sprite.scale.x += (std::min(sprite.scale.x, LIGHT_SCALE_TARGET) - sprite.scale.x) * progress; + } + Vector flying = player.GetFlyingOffset(); + sprite.offset.x += (-flying.x - sprite.offset.x) * LIGHT_OFFSET_EASE; + sprite.offset.y += + (LIGHT_OFFSET_BASE - sprite.scale.y * LIGHT_OFFSET_PER_SCALE - flying.y - sprite.offset.y) * LIGHT_OFFSET_EASE; +} diff --git a/src/stage_transition.h b/src/stage_transition.h new file mode 100644 index 0000000..1454eb6 --- /dev/null +++ b/src/stage_transition.h @@ -0,0 +1,68 @@ +#pragma once + +#include "classes.h" + +// Where a stage transition is (Game's StageTransition): the players dropping out, the fade out (the floor changes as it +// ends), the fade in, and the players landing. +enum StageTransitionState : int +{ + STAGE_TRANSITION_NONE, + STAGE_TRANSITION_START, + STAGE_TRANSITION_OUT, + STAGE_TRANSITION_IN, + STAGE_TRANSITION_LANDING +}; + +// Where a stage transition leads (Game::StartStageTransition's override): the next floor, the same floor again by +// Forget Me Now, Sheol, the Void, a chest or light's ending, the Ascent, or Home. +enum StageTransitionType : int +{ + STAGE_TRANSITION_NEXT, + STAGE_TRANSITION_FORGET_ME_NOW, + STAGE_TRANSITION_SHEOL, + STAGE_TRANSITION_VOID, + STAGE_TRANSITION_ENDING, + STAGE_TRANSITION_ASCENT, + STAGE_TRANSITION_HOME, + STAGE_TRANSITION_TYPE_COUNT +}; + +// How fast update_player_trapdoor_scale eases a player falling into the light back down: an update's step, or an +// interpolation's faster one. +enum TrapdoorScaleRate +{ + TRAPDOOR_SCALE_UPDATE, + TRAPDOOR_SCALE_INTERPOLATE +}; + +// What Game::StartStageTransition asks for: where it leads, whether the floor is the same one again, and the player who +// started it (the first one by default). +struct StageTransitionRequest +{ + Entity_Player* player = nullptr; + StageTransitionType type = STAGE_TRANSITION_NEXT; + bool isSameStage = false; +}; + +// Moving to the next floor (g_game->stageTransition): the players fall through the trapdoor at exitPosition, the screen +// fades out while the floor changes and in on the new one, with the nightmare between them. Dream Catcher moves the +// nightmare after the new floor is laid out, to show what it holds. +struct StageTransition +{ + Vector exitPosition{}; + StageTransitionState state = STAGE_TRANSITION_NONE; + StageTransitionType type = STAGE_TRANSITION_NEXT; + int duration = 0; + int frame = 0; + bool isDreamCatcher = false; + bool isSameStage = false; + + void start(const StageTransitionRequest& request); + void Update(); + void Render(); + float get_fade_progress(); + bool is_pixelated(); + void update_player_trapdoor_scale(Entity_Player& player, TrapdoorScaleRate rate); +}; + +void room_ambient_sounds_stop();