diff --git a/generated-src/classes.h b/generated-src/classes.h index b4c19e8..f6a5ac4 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -273,6 +273,7 @@ struct GenericPopup; struct GenericPrompt; struct GiantbookEntry; struct GiantbookLayer; +struct GibSpawn; struct Gl; struct GlitchedCollectibleGfx; struct GlitchedItemSet; @@ -377,6 +378,8 @@ struct LobbySettings; struct LocustConfig; struct LocustEffect; struct LootList; +struct LuaCardDraw; +struct LuaCollectibleDraw; struct LuaEngine; struct LuaItemUse; struct LuaMod; @@ -1413,18 +1416,6 @@ struct FriendEntry { }; -struct GameOver { - void RenderItemSprite(int memberIndex); // 008ebfb0 - void Render(); // 00998880 - void Show(); // 009997c0 - - int _state; - uint8_t _pad_0x4[0x118]; - bool _isStopSoundsPending; -}; -LAYOUT32(offsetof(GameOver, _state) == 0x0); -LAYOUT32(offsetof(GameOver, _isStopSoundsPending) == 0x11c); - struct Game_StateSlot { void * operator_assign(void *other); // 006f8a40 }; @@ -3650,12 +3641,6 @@ LAYOUT32(offsetof(PMD, pdisp) == 0x4); LAYOUT32(offsetof(PMD, vdisp) == 0x8); LAYOUT32(sizeof(PMD) == 0xc); -struct PathNode { - PathNode(void *other); // 007e48b0 - PathNode() = default; -}; - - struct PersistentGameDataReader { void read(PersistentGameData *data); // 0091adf0 }; @@ -6268,7 +6253,6 @@ void FUN_004bfd20(); // 004bfd20 void FUN_004c5850(uint8_t *param_1); // 004c5850 void FUN_004c5980(float *param_1, Vector *param_2); // 004c5980 void FUN_004cdce0(); // 004cdce0 -uint32_t FUN_004cdd30(uint32_t param_1, int param_2); // 004cdd30 uint32_t FUN_004ce0f0(); // 004ce0f0 void FUN_004cf0f0(uint8_t param_1); // 004cf0f0 void FUN_004cf380(int *param_1); // 004cf380 @@ -6300,7 +6284,6 @@ void FUN_004e46b0(); // 004e46b0 void FUN_004e46c0(); // 004e46c0 bool FUN_004e47b0(); // 004e47b0 int FUN_004e4840(); // 004e4840 -Entity * find_nearest_enemy(Vector *position, float *outDistance, uint8_t isFriendly); // 004e7d10 void FUN_004f8390(); // 004f8390 void FUN_004f8460(int *param_1, int *param_2); // 004f8460 uint8_t str_ne(std_string *a, uint8_t *b); // 004f84a0 @@ -6647,14 +6630,12 @@ void FUN_0067ae30(int *param_1); // 0067ae30 void FUN_0067af30(); // 0067af30 void tear_flags_area_apply(Vector *position, Entity *source, float radius, float damage, BitSet128 flags); // 0067d430 uint32_t FUN_0067d9b0(); // 0067d9b0 -void FUN_0067da40(); // 0067da40 void FUN_0067dac0(int *param_1); // 0067dac0 uint32_t * FUN_0067ef50(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3); // 0067ef50 uint32_t FUN_0067efb0(); // 0067efb0 uint8_t FUN_0067efd0(); // 0067efd0 float random_float(); // 0067efe0 uint32_t FUN_0067f030(); // 0067f030 -Vector * RandomVector(Vector *out, uint32_t seed); // 0067f0d0 void FUN_0067f2e0(); // 0067f2e0 void * string_split(void *outTokens, std_string *text, uint8_t delimiter); // 0067f420 uint8_t string_to_bool(void *self); // 0067f600 @@ -6816,7 +6797,6 @@ void FUN_006a80d0(); // 006a80d0 void FUN_006a8180(uint32_t param_1); // 006a8180 void FUN_006a8210(int param_1); // 006a8210 uint32_t FUN_006ae7a0(); // 006ae7a0 -void spawn_gibs(Vector *position, int amount, float spread, uint32_t *gibFlags, Entity *spawner, ColorMod *color, Vector *velocity, float scale); // 006b31b0 void FUN_006b5de0(); // 006b5de0 void FUN_006b5f40(); // 006b5f40 void play_sound_with_fart_seed(int soundId, float volume, int frameDelay, uint8_t isLoop, float pitch); // 006b6470 @@ -7082,7 +7062,6 @@ void FUN_00758bd0(); // 00758bd0 int FUN_00759260(); // 00759260 void FUN_0075d9f0(uint32_t param_1); // 0075d9f0 uint32_t FUN_0075ef20(ANM2 *param_1, int param_2); // 0075ef20 -int FUN_0075f020(uint32_t param_1, uint32_t param_2); // 0075f020 void FUN_00763290(); // 00763290 void FUN_00770640(float *param_1); // 00770640 uint8_t is_trinket_unpickable_id(int trinketId); // 007716c0 @@ -7209,11 +7188,8 @@ void FUN_007e2fa0(); // 007e2fa0 uint32_t * FUN_007e3060(uint32_t *param_1); // 007e3060 void FUN_007e3190(); // 007e3190 void FUN_007e3230(); // 007e3230 -void FUN_007e4860(); // 007e4860 void FUN_007e4890(); // 007e4890 uint8_t pathfinder_can_reach_pos(Vector *targetPos, Vector *startPos, Room *room); // 007e7820 -uint32_t FUN_007e7fb0(uint32_t param_1); // 007e7fb0 -void FUN_007e85a0(uint32_t *param_1); // 007e85a0 void FUN_007e8620(); // 007e8620 void FUN_007e86e0(int param_1, int param_2); // 007e86e0 void * vector_PathNode_emplace_reallocate_copy(void *self, void *where, void *value); // 007e8810 @@ -7365,8 +7341,6 @@ uint8_t FUN_0085bd40(uint32_t param_1, int *param_2, int *param_3); // 0085bd40 void FUN_0085be70(); // 0085be70 void FUN_0085bf50(uint32_t param_1); // 0085bf50 void FUN_0085bf90(); // 0085bf90 -void FUN_0085bfd0(); // 0085bfd0 -void FUN_0085bff0(); // 0085bff0 void FUN_0085c010(); // 0085c010 void FUN_0085c030(); // 0085c030 void FUN_0085c050(); // 0085c050 @@ -7374,7 +7348,6 @@ void FUN_0085c1d0(); // 0085c1d0 int * FUN_0085c200(); // 0085c200 void FUN_0085c210(uint8_t param_1); // 0085c210 void FUN_0085c250(); // 0085c250 -void FUN_0085c270(uint32_t param_1); // 0085c270 bool FUN_0085c2d0(); // 0085c2d0 bool FUN_0085c300(); // 0085c300 bool FUN_0085c340(); // 0085c340 @@ -7407,27 +7380,10 @@ uint32_t FUN_0085fcc0(); // 0085fcc0 uint32_t FUN_0085fec0(uint32_t param_1); // 0085fec0 uint32_t FUN_008601f0(uint32_t param_1); // 008601f0 uint32_t FUN_008603d0(uint32_t param_1); // 008603d0 -void FUN_008607a0(); // 008607a0 -uint32_t Catch_00860826(); // 00860826 -void FUN_00860880(int param_1); // 00860880 -uint32_t Catch_0086090e(); // 0086090e -bool FUN_00860960(int param_1); // 00860960 -uint32_t Catch_00860a70(); // 00860a70 -uint32_t Catch_00860b4b(); // 00860b4b -void FUN_00860ba0(int param_1, uint32_t *param_2); // 00860ba0 -uint32_t Catch_00860c36(); // 00860c36 -void FUN_00860c90(int param_1); // 00860c90 -uint32_t Catch_00860d1e(); // 00860d1e void FUN_00860f00(int param_1); // 00860f00 uint32_t Catch_00860f8b(); // 00860f8b void FUN_00860fe0(int param_1, uint32_t *param_2); // 00860fe0 uint32_t Catch_00861076(); // 00861076 -void FUN_00861330(int param_1); // 00861330 -uint32_t Catch_008613bf(); // 008613bf -void FUN_00861410(int param_1); // 00861410 -uint32_t Catch_0086149f(); // 0086149f -void FUN_008614f0(int param_1, uint32_t *param_2); // 008614f0 -uint32_t Catch_00861587(); // 00861587 void FUN_008615e0(int param_1); // 008615e0 uint32_t Catch_0086166f(); // 0086166f void FUN_008616c0(int param_1); // 008616c0 @@ -7454,21 +7410,8 @@ void FUN_00862590(int param_1); // 00862590 uint32_t Catch_0086261f(); // 0086261f void FUN_00862670(int param_1, uint32_t *param_2); // 00862670 uint32_t Catch_00862707(); // 00862707 -void FUN_008629c0(int param_1); // 008629c0 -uint32_t Catch_00862a4c(); // 00862a4c -void FUN_00862aa0(int param_1); // 00862aa0 -uint32_t Catch_00862b2f(); // 00862b2f -void FUN_00862b80(uint32_t param_1, uint32_t *param_2); // 00862b80 -uint32_t Catch_00862cb8(); // 00862cb8 void FUN_00862d0a(); // 00862d0a void FUN_00862d53(); // 00862d53 -void FUN_00862f00(int param_1); // 00862f00 -uint32_t Catch_00862f8c(); // 00862f8c -void FUN_00862fe0(int param_1); // 00862fe0 -uint32_t Catch_0086306c(); // 0086306c -void FUN_008630c0(int param_1, uint32_t *param_2); // 008630c0 -uint32_t Catch_00863154(); // 00863154 -uint32_t Catch_0086354b(); // 0086354b void FUN_008635a0(int param_1); // 008635a0 uint32_t Catch_0086362b(); // 0086362b uint32_t Catch_00863879(); // 00863879 @@ -7476,42 +7419,21 @@ void FUN_00863be0(int param_1); // 00863be0 uint32_t Catch_00863c6e(); // 00863c6e void FUN_00863cc0(uint32_t param_1, uint32_t param_2, uint32_t param_3); // 00863cc0 uint32_t Catch_00863d4e(); // 00863d4e -void lua_callback_run_post_fire_tear(uint32_t param_1); // 00863f70 -uint32_t Catch_00863fff(); // 00863fff void FUN_00864130(int param_1); // 00864130 uint32_t Catch_008641bb(); // 008641bb void FUN_00864210(int param_1, uint32_t *param_2); // 00864210 uint32_t Catch_008642a4(); // 008642a4 uint32_t Catch_00864682(); // 00864682 -uint8_t * Catch_00864a6a(); // 00864a6a -uint32_t FUN_00864ae0(uint32_t param_1); // 00864ae0 -uint8_t * Catch_00864bb8(); // 00864bb8 -uint8_t lua_run_input_action_callback(Entity *entity, int hook, int action, uint8_t *outValue); // 00864c30 -uint8_t * Catch_00864d16(); // 00864d16 uint8_t FUN_00864d80(uint32_t param_1, uint32_t param_2, uint32_t param_3, float *param_4); // 00864d80 uint8_t * Catch_00864e6d(); // 00864e6d void FUN_00864fc0(uint32_t param_1); // 00864fc0 uint32_t Catch_0086504e(); // 0086504e void FUN_008650a0(uint32_t param_1); // 008650a0 uint32_t Catch_0086512e(); // 0086512e -uint32_t Catch_00865209(); // 00865209 -uint32_t Catch_008652e9(); // 008652e9 -int lua_callback_run_get_card(RNG *rng, int card, uint8_t isPlaying, uint8_t isRunes, uint8_t isOnlyRunes); // 00865340 -uint8_t * Catch_00865424(); // 00865424 uint8_t * Catch_008655b7(); // 008655b7 char * FUN_00865660(char *param_1, uint32_t *param_2); // 00865660 -uint32_t FUN_008658c0(uint32_t param_1, uint32_t *param_2); // 008658c0 -uint8_t * Catch_008659a7(); // 008659a7 -uint32_t FUN_00865a04(); // 00865a04 void FUN_00865aad(); // 00865aad void FUN_00865c61(); // 00865c61 -uint32_t FUN_00865c80(uint32_t param_1, uint32_t param_2); // 00865c80 -uint8_t * Catch_00865d53(); // 00865d53 -uint32_t FUN_00865dc0(uint32_t param_1, uint32_t param_2, uint32_t param_3); // 00865dc0 -uint8_t * Catch_00865e99(); // 00865e99 -uint32_t FUN_00865f10(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4); // 00865f10 -uint8_t * Catch_00865fe8(); // 00865fe8 -uint32_t Catch_008660ec(); // 008660ec uint32_t FUN_00866220(uint32_t *param_1, uint32_t *param_2); // 00866220 uint32_t Catch_00866364(); // 00866364 uint8_t FUN_008663b6(); // 008663b6 @@ -7534,18 +7456,14 @@ void FUN_00872780(void *param_1); // 00872780 bool FUN_00872820(); // 00872820 char * FUN_00872860(char *param_1); // 00872860 void FUN_00872a0c(); // 00872a0c -uint32_t * FUN_00872a20(uint32_t *param_1, uint32_t param_2, int param_3); // 00872a20 void FUN_00872af1(); // 00872af1 -int * FUN_00872b10(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5); // 00872b10 void FUN_00872c43(); // 00872c43 void FUN_00872d80(); // 00872d80 uint32_t * FUN_00872da0(uint32_t *param_1, uint32_t param_2, int param_3); // 00872da0 void FUN_00872e71(); // 00872e71 int * FUN_00872e90(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5); // 00872e90 void FUN_00872fc3(); // 00872fc3 -uint32_t * FUN_00872ff0(uint32_t *param_1, uint32_t param_2, int param_3); // 00872ff0 void FUN_008730c1(); // 008730c1 -int * FUN_008730e0(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5); // 008730e0 void FUN_00873213(); // 00873213 uint32_t * FUN_00873230(uint32_t *param_1, uint32_t param_2, int param_3); // 00873230 void FUN_00873301(); // 00873301 @@ -7558,15 +7476,11 @@ uint32_t * FUN_00873650(uint32_t *param_1, uint32_t param_2, int param_3); // 0 void FUN_00873721(); // 00873721 int * FUN_00873740(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5); // 00873740 void FUN_00873873(); // 00873873 -uint32_t * FUN_00873890(uint32_t *param_1, uint32_t param_2, int param_3); // 00873890 void FUN_00873961(); // 00873961 void FUN_00873aa0(); // 00873aa0 -uint32_t * FUN_00873ac0(uint32_t *param_1, uint32_t param_2, int param_3); // 00873ac0 void FUN_00873b91(); // 00873b91 -int * FUN_00873bb0(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5); // 00873bb0 void FUN_00873ce3(); // 00873ce3 void FUN_00873e20(); // 00873e20 -int * FUN_00873e40(int *param_1, uint32_t param_2, int param_3, uint32_t param_4); // 00873e40 void FUN_00873f26(); // 00873f26 void FUN_00874103(); // 00874103 void FUN_008741f1(); // 008741f1 @@ -7577,19 +7491,14 @@ void FUN_00874533(); // 00874533 int * FUN_00874550(int *param_1, uint32_t param_2, int param_3, float param_4, uint32_t param_5, uint32_t param_6, int param_7); // 00874550 void FUN_0087469a(); // 0087469a void FUN_00874846(); // 00874846 -uint32_t * FUN_00874860(uint32_t *param_1); // 00874860 void FUN_008748f6(); // 008748f6 void FUN_008749f7(); // 008749f7 void FUN_00874aa8(); // 00874aa8 -int * FUN_00874ac0(int *param_1, uint32_t param_2, int param_3, int param_4, uint8_t param_5, uint8_t param_6, uint8_t param_7); // 00874ac0 void FUN_00874bbb(); // 00874bbb uint32_t * FUN_00874bd0(uint32_t *param_1, uint32_t param_2, void *param_3); // 00874bd0 void FUN_00874d0a(); // 00874d0a -uint32_t * FUN_00874d20(uint32_t *param_1); // 00874d20 void FUN_00874db6(); // 00874db6 -uint32_t * FUN_00874dd0(uint32_t *param_1, uint32_t param_2, int param_3, uint8_t param_4); // 00874dd0 void FUN_00874e7e(); // 00874e7e -uint32_t * FUN_00874e90(uint32_t *param_1, uint32_t param_2, int param_3, int param_4, uint8_t param_5); // 00874e90 void FUN_00874f4a(); // 00874f4a uint32_t * FUN_00875050(uint32_t *param_1, uint32_t param_2, uint32_t param_3, uint16_t param_4, uint16_t param_5, uint32_t param_6); // 00875050 void FUN_00875116(); // 00875116 @@ -9627,7 +9536,6 @@ uint8_t * FUN_009587e0(StringTable *param_1, uint8_t *param_2, uint8_t *param_3) uint8_t * FUN_00958840(StringTable *param_1, uint8_t *param_2, int param_3, uint8_t *param_4); // 00958840 void save_rerun_to_steam_cloud(); // 00959180 void FUN_00959500(); // 00959500 -void persistent_game_data_set_writable(); // 0095a680 void unlock_completion_mark_for_player_type(int markIndex, int playerType, int difficulty); // 0095aa30 void render_online_icon(int frame, Vector position, float scaleX, float scaleY); // 0095ae60 void FUN_0095be60(int param_1, int param_2); // 0095be60 @@ -9736,13 +9644,11 @@ void Catch_All_009c7256(); // 009c7256 char * FUN_009c7280(void *param_1, void *param_2, char *param_3); // 009c7280 void FUN_009c7320(); // 009c7320 void FUN_009c7340(); // 009c7340 -uint8_t is_valid_item_config_id(int itemKind, int id); // 009c7350 void FUN_009c7750(); // 009c7750 void FUN_009c7780(); // 009c7780 void FUN_009c77f0(); // 009c77f0 void FUN_009cad40(); // 009cad40 uint32_t FUN_009caea0(); // 009caea0 -uint8_t read_entity_save_state_tree(void *saveState, void *stream); // 009cb020 uint32_t Catch_All_009cc16c(); // 009cc16c uint32_t Catch_All_009cc172(); // 009cc172 uint32_t FUN_009ce5a0(); // 009ce5a0 @@ -9754,7 +9660,6 @@ uint8_t * Catch_All_009d2bd4(); // 009d2bd4 uint32_t Catch_All_009d396e(); // 009d396e uint8_t FUN_009d459a(); // 009d459a void FUN_009d8470(uint16_t *param_1); // 009d8470 -void FUN_009d84a0(uint32_t *param_1); // 009d84a0 void FUN_009d8550(uint8_t *param_1); // 009d8550 void FUN_009d8820(uint32_t *param_1, int param_2); // 009d8820 void FUN_009d88a0(uint32_t param_1); // 009d88a0 @@ -21570,10 +21475,6 @@ void wisp_mine_crafter_update(Entity_Familiar *wisp); // 0043d850 Entity_Laser * sprinkler_fire_laser(Entity_Familiar *familiar, float angle, float distance); // 0063acf0 void fly_head_pathfind_move(Entity_Familiar *familiar); // 0063d570 } -namespace GameStateReader { -void read_bool_vector(void *reader, void *bits, uint32_t minSize); // 009c84c0 -void read_int_vector(void *reader, int *values); // 009d8580 -} namespace Input { void IsButtonTriggered(uint32_t param_1, uint32_t param_2); // 0086fc70 void IsButtonPressed(uint32_t param_1, uint32_t param_2); // 0086fca0 @@ -21656,9 +21557,6 @@ void heap_free(uint32_t heapId, void *ptr); // 00a23160 namespace LobbySteam { void * find_by_id_string(void *outLobby); // 00a54150 } -namespace LuaCallbackCaller { -int * CallInputAction(int *param_1, uint32_t param_2, int param_3, int param_4); // 00874910 -} namespace Math { void abs(); // 0041d510 float clamp(float min, float max, float value); // 0042f2a0 @@ -21964,7 +21862,6 @@ void ENTITY_WORMWOOD_segment_follow(Entity_NPC *npc); // 005ae840 void wormwood_pick_emerge_position(Entity_NPC *npc); // 005aef20 void ENTITY_WORMWOOD_main(Entity_NPC *npc); // 005af800 void ENTITY_SHOPKEEPER(Entity_NPC *npc); // 006c2220 -void ENTITY_FIREPLACE(Entity_NPC *npc); // 006d18d0 void ENTITY_MOVABLE_TNT(Entity_NPC *npc); // 006d6690 } namespace OnlinePlayerInfo { @@ -22021,9 +21918,6 @@ void readTheoraVorbisHeaders(); // 00a8e530 namespace _Entity { int GetAncestorField(uint32_t param_1); // 006b7d20 } -namespace _Entity_NPC { -float * GetColorWithFlash(float *param_1); // 00505b80 -} namespace _Entity_Player { uint32_t SpawnTrinketRandomPickup(); // 007dc2d0 } diff --git a/generated-src/game_over.cpp b/generated-src/game_over.cpp deleted file mode 100644 index 05f7bff..0000000 --- a/generated-src/game_over.cpp +++ /dev/null @@ -1,1792 +0,0 @@ -#include "classes.h" - -// 008ebfb0 -void GameOver::RenderItemSprite(int memberIndex) -{ - ColorMod color; - ColorMod color_00; - Vector position; - Vector position_00; - Vector position_01; - Vector pos; - Vector pos_00; - GameOver *pGVar1; - char cVar2; - ANM2 *memberSprite; - int *user; - int iVar3; - std_string *right; - uint8_t *******pppppppbVar4; - float *nullFrame; - LayerState *pLVar5; - float fVar6; - void *settings; - KColor *color_01; - uint8_t unk; - void *pvVar7; - KColor *color_02; - int *size; - uint32_t uVar8; - uint8_t *portraitSprite; - bool isKeyboardInput; - float fVar9; - float fVar10; - float fVar11; - Color aCStackY_173c [128]; - uint8_t in_stack_fffffef0 [28]; - uint32_t in_stack_ffffff0c; - int in_stack_ffffff10; - KColor *in_stack_ffffff14; - KColor *pos_01; - char *nullLayerName; - FontSettings fontSettings [6]; - uint32_t local_b8; - uint32_t local_b4; - uint8_t **local_b0; - Font *local_ac; - int *savedUser; - KColor local_a4; - GameOver *local_90; - float local_8c; - int cursorPlayerNumber; - float slotY; - float slotX; - int playerNumber; - uint8_t local_76; - char isSwapAllowed; - uint8_t local_74; - char isKeyboard; - char isLocalMember; - uint8_t isVisible; - uint8_t local_70 [8]; - char local_68 [8]; - uint32_t local_60; - uint32_t local_5c; - uint8_t *******local_58; - KColor local_54; - void *numberText [3]; - uint8_t **local_34; - KColor local_30; - void *local_1c; - uint8_t *puStack_18; - void *local_14; - Manager *manager; - - local_30._unk = GHIDRA_INT((numberText + 0xf)); - puStack_18 = &LAB_00b07173; - local_1c = ExceptionList; - local_30._alpha = (float)(__security_cookie ^ GHIDRA_UINT((numberText + 0xc))); - ExceptionList = &local_1c; - local_a4._green = (float)memberIndex; - local_34 = KAGE::Network::Multiplayer::ConstLobby::vftable; - local_30._red = 0.0; - local_30._green = 0.0; - local_14 = (void *)0x0; - local_90 = this; - (GHIDRA_CAST((&local_30)))->msvc::shared_ptr::assign(&g_multiplayerLobbyPtr); - local_34 = KAGE::Network::Multiplayer::Lobby::vftable; - local_14 = (void *)0x1; - if (GHIDRA_CAST(local_30._red) == GHIDRA_CAST(0x0)) { -LAB_008ec04c: - local_74 = '\x01'; - } - else { - cVar2 = (**(code **)(*GHIDRA_CAST(local_30._red) + 0xc))(); - local_74 = '\0'; - if (cVar2 == '\0') goto LAB_008ec04c; - } - local_34 = KAGE::Network::Multiplayer::ConstLobby::vftable; - local_14 = (void *)0x2; - if (((GHIDRA_CAST(local_30._green) != GHIDRA_CAST(0x0)) && - (cVar2 = (**(code **)(*GHIDRA_CAST(local_30._green) + 0xc))(), cVar2 != '\0')) && - (g_lobbyReleaseFn != (void *)0x0)) { - (*g_lobbyReleaseFn)(); - } - local_14 = (void *)0xffffffff; - if (local_74 != '\0') { - ExceptionList = local_1c; - return; - } - isKeyboard = g_menuControllerIndex == 0; - slotX = (g_menuManager->_ViewPosition).x + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))); - slotY = (g_menuManager->_ViewPosition).y + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - local_8c = g_vectorZero.x; - local_a4._unk = GHIDRA_INT(g_vectorZero.y); - memberSprite = lobby_member_sprite_get(this,memberIndex); - if (memberSprite == GHIDRA_CAST(0x0)) { - ExceptionList = local_1c; - return; - } - local_a4._blue = (float)memberSprite; - user = lobby_get_member_info(this,GHIDRA_INT(local_a4._green)); - savedUser = user; - playerNumber = FUN_008edde0(); - playerNumber = playerNumber + 1; - cursorPlayerNumber = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_90[8])) + 0x6c)))); - local_74 = playerNumber == cursorPlayerNumber; - if (user == GHIDRA_CAST(0x0)) { -LAB_008ec144: - isLocalMember = '\0'; - } - else { - cVar2 = (**(code **)(*user + 0x14))(); - isLocalMember = '\x01'; - if (cVar2 == '\0') goto LAB_008ec144; - } - local_54._blue = (float)KAGE::Network::Multiplayer::ConstLobby::vftable; - local_54._alpha = 0.0; - local_54._unk = 0; - local_14 = (void *)0x3; - (GHIDRA_CAST((&local_54._alpha)))->msvc::shared_ptr::assign(&g_multiplayerLobbyPtr); - local_54._blue = (float)KAGE::Network::Multiplayer::Lobby::vftable; - local_14 = (void *)0x4; - if (GHIDRA_CAST(local_54._alpha) == GHIDRA_CAST(0x0)) { - local_30._green = 0.0; - } - else { - iVar3 = (**(code **)(*GHIDRA_CAST(local_54._alpha) + 0x20))(); - local_30._green = *GHIDRA_CAST((iVar3 + 4)); - local_b0 = KAGE::System::UserProfileBase::vftable; - } - local_30._red = (float)KAGE::System::UserProfile::vftable; - local_14 = (void *)CONCAT31((*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))),5); - local_76 = (GHIDRA_CAST((&local_30)))->KAGE::System::UserProfile::is_local_user(); - local_30._red = (float)KAGE::System::UserProfileBase::vftable; - local_54._blue = (float)KAGE::Network::Multiplayer::ConstLobby::vftable; - local_14 = (void *)0x6; - if (((GHIDRA_CAST(local_54._unk) != GHIDRA_CAST(0x0)) && - (cVar2 = (**(code **)(*GHIDRA_CAST(local_54._unk) + 0xc))(), cVar2 != '\0')) && - (g_lobbyReleaseFn != (void *)0x0)) { - (*g_lobbyReleaseFn)(); - } - local_54._blue = (float)KAGE::Network::Multiplayer::ConstLobby::vftable; - local_54._alpha = 0.0; - local_54._unk = 0; - local_14 = (void *)0x7; - (GHIDRA_CAST((&local_54._alpha)))->msvc::shared_ptr::assign(&g_multiplayerLobbyPtr); - local_54._blue = (float)KAGE::Network::Multiplayer::Lobby::vftable; - local_14 = (void *)0x8; - if (GHIDRA_CAST(local_54._alpha) == GHIDRA_CAST(0x0)) { - local_ac = GHIDRA_CAST(0x0); - } - else { - local_ac = GHIDRA_CAST((**(code **)(*GHIDRA_CAST(local_54._alpha) + 0x1c))()); - } - local_54._blue = (float)KAGE::Network::Multiplayer::ConstLobby::vftable; - local_14 = (void *)0x9; - if (((GHIDRA_CAST(local_54._unk) != GHIDRA_CAST(0x0)) && - (cVar2 = (**(code **)(*GHIDRA_CAST(local_54._unk) + 0xc))(), cVar2 != '\0')) && - (g_lobbyReleaseFn != (void *)0x0)) { - (*g_lobbyReleaseFn)(); - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 0xff; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))) = 0xffffff; - iVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_manager->_lobbySettings))) + 0x4)))); - if ((((iVar3 == 4) || (iVar3 == 5)) || (playerNumber != cursorPlayerNumber)) || - (isSwapAllowed = '\x01', isLocalMember == '\0')) { - isSwapAllowed = '\0'; - } - if ((user == GHIDRA_CAST(0x0)) || (cVar2 = (**(code **)(*user + 0x14))(), cVar2 == '\0')) { - right = int_to_string(GHIDRA_CAST(numberText),playerNumber); - builtin_strncpy(local_68,"Player",7); - local_5c = 0xf; - local_60 = 0xe; - local_70 = (uint8_t [8])0x6e6f697469736f50; - local_14 = (void *)0xb; - (GHIDRA_CAST((GHIDRA_CAST(&local_58))))->msvc::string::concat_move(GHIDRA_INT(local_30._green),local_70,right); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 0xc; - pppppppbVar4 = GHIDRA_CAST(&local_58); - if (&DAT_0000000f < GHIDRA_UINT(local_54._unk)) { - pppppppbVar4 = local_58; - } - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_90)) + 0x44)))) == 0) { - nullFrame = GHIDRA_CAST(0x0); - } - else { - nullFrame = AnimationState::GetNullFrame - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_90)) + 0x40)))),GHIDRA_CAST(pppppppbVar4)); - } - memberSprite = GHIDRA_CAST(local_a4._blue); - local_8c = *nullFrame; - local_a4._unk = GHIDRA_INT(nullFrame[1]); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 0xb; - if (&DAT_0000000f < GHIDRA_UINT(local_54._unk)) { - size = GHIDRA_CAST((local_54._unk + 1)); - pppppppbVar4 = local_58; - if (GHIDRA_CAST(0xfff) < size) { - pppppppbVar4 = GHIDRA_CAST(local_58[-1]); - size = GHIDRA_CAST((local_54._unk + 0x24)); - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(local_58) + (-4 - GHIDRA_INT(pppppppbVar4))))) goto LAB_008ec408; - } - operator_delete(pppppppbVar4,GHIDRA_UINT(size)); - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 10; - if (0xf < local_5c) { - uVar8 = local_5c + 1; - pvVar7 = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)local_70)) + 0x0))); - if (0xfff < uVar8) { - pvVar7 = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(local_70)) + 0x0))) + -4); - uVar8 = local_5c + 0x24; - if (0x1f < GHIDRA_UINT(((*GHIDRA_CAST((GHIDRA_CAST(&(local_70)) + 0x0))) + (-4 - GHIDRA_INT(pvVar7))))) goto LAB_008ec408; - } - operator_delete(pvVar7,uVar8); - } - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 0xff; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))) = 0xffffff; - if (0xf < GHIDRA_UINT(local_30._green)) { - uVar8 = GHIDRA_INT(local_30._green) + 1; - pvVar7 = numberText[0]; - if (0xfff < uVar8) { - pvVar7 = *(void **)(GHIDRA_INT(numberText[0]) + -4); - uVar8 = GHIDRA_INT(local_30._green) + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(numberText[0]) + (-4 - GHIDRA_INT(pvVar7))))) { -LAB_008ec408: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar7,uVar8); - } - local_30._green = slotY + (float)local_a4._unk; - local_30._red = slotX + local_8c; - in_stack_ffffff14 = GHIDRA_CAST(0x8ec44e); - ANM2::Render(memberSprite,GHIDRA_CAST(&local_30),&g_vectorZero,&g_vectorZero); - } - if ((memberSprite->_animState)._animData == (void *)0x0) { - slotX = slotX + local_8c; - slotY = slotY + (float)local_a4._unk; - local_a4._alpha = slotX; - local_8c = slotY; - } - else { - nullFrame = AnimationState::GetNullFrame(&memberSprite->_animState,GHIDRA_CAST("Player_Info")); - slotX = slotX + local_8c; - slotY = slotY + (float)local_a4._unk; - local_a4._alpha = slotX; - local_8c = slotY; - if (nullFrame != GHIDRA_CAST(0x0)) { - local_a4._alpha = slotX + *nullFrame; - local_8c = slotY + nullFrame[1]; - } - } - local_a4._unk = GHIDRA_INT(slotX); - local_30._green = slotY; - if (GHIDRA_UINT(local_a4._green) < local_ac) { - FUN_0040a860(); - if (((user == GHIDRA_CAST(0x0)) || (isLocalMember == '\0')) || - ((*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\0' || (isKeyboard == '\0')))) { - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Ready_Button")); - pLVar5->_visible = 0; - if ((user != GHIDRA_CAST(0x0)) && (isLocalMember != '\0')) goto LAB_008ec54e; -LAB_008ec56c: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Unready_Button")); - pLVar5->_visible = 0; - if ((user != GHIDRA_CAST(0x0)) || (isVisible = 1, (*GHIDRA_CAST((GHIDRA_CAST(&(local_90[6])) + 0x20))) != '\0')) - goto LAB_008ec590; - } - else { - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Ready_Button")); - pLVar5->_visible = 1; -LAB_008ec54e: - if ((*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\x01') || (isKeyboard == '\0')) goto LAB_008ec56c; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Unready_Button")); - pLVar5->_visible = 1; -LAB_008ec590: - isVisible = 0; - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Invite_Player")); - pLVar5->_visible = isVisible; - FUN_0040a860(); - if (((user == GHIDRA_CAST(0x0)) && ((*GHIDRA_CAST((GHIDRA_CAST(&(local_90[6])) + 0x20))) == '\0')) && (isKeyboard != '\0')) { - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Invite_Player_Button")); - pLVar5->_visible = 1; -LAB_008ec5da: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Swap_Button")); - pLVar5->_visible = 0; - if ((user != GHIDRA_CAST(0x0)) && (isLocalMember != '\0')) goto LAB_008ec5f4; -LAB_008ec667: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_ArrowLeft")); - pLVar5->_visible = 0; - if ((user != GHIDRA_CAST(0x0)) && (isLocalMember != '\0')) goto LAB_008ec681; -LAB_008ec69f: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_ArrowRight")); - pLVar5->_visible = 0; - if (user != GHIDRA_CAST(0x0)) goto LAB_008ec6b3; -LAB_008ec6e0: - isVisible = 0; - } - else { - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Invite_Player_Button")); - pLVar5->_visible = 0; - if (((((user == GHIDRA_CAST(0x0)) || (playerNumber != cursorPlayerNumber)) || - ((isLocalMember == '\0' || - ((*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\0' || ((char)user[3] != '\0')))))) || - (cVar2 = FUN_008ed2e0(), cVar2 == '\0')) || - ((isKeyboard == '\0' || (isSwapAllowed == '\0')))) goto LAB_008ec5da; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Swap_Button")); - pLVar5->_visible = 1; -LAB_008ec5f4: - if ((*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\0') || (isSwapAllowed == '\0')) goto LAB_008ec667; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_ArrowLeft")); - pLVar5->_visible = 1; -LAB_008ec681: - if ((*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\0') || (isSwapAllowed == '\0')) goto LAB_008ec69f; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_ArrowRight")); - pLVar5->_visible = 1; -LAB_008ec6b3: - if ((((playerNumber != cursorPlayerNumber) || (isLocalMember == '\0')) || - (*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\0')) || - ((((char)user[3] != '\0' || (cVar2 = FUN_008ed2e0(), cVar2 == '\0')) || - (isVisible = 1, isSwapAllowed == '\0')))) goto LAB_008ec6e0; - } - pLVar5 = ANM2::GetLayer(memberSprite,&DAT_00b6d168); - pLVar5->_visible = isVisible; - isVisible = user != GHIDRA_CAST(0x0); - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Number")); - pLVar5->_visible = isVisible; - if (user == GHIDRA_CAST(0x0)) { - FUN_0040a860(); -LAB_008ec78b: - fVar9 = slotY; - fVar10 = slotX; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Character")); - pLVar5->_visible = 0; - if (user != GHIDRA_CAST(0x0)) goto LAB_008ec79f; -LAB_008ec7cb: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Ready")); - pLVar5->_visible = 0; - if (user != GHIDRA_CAST(0x0)) goto LAB_008ec7df; -LAB_008ec803: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Unready")); - pLVar5->_visible = 0; - if ((user != GHIDRA_CAST(0x0)) && - ((slotY = fVar9, slotX = fVar10, isLocalMember != '\0' || - (playerNumber != cursorPlayerNumber)))) goto LAB_008ec839; -LAB_008ec851: - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_InProgress")); - pLVar5->_visible = 0; - if (user != GHIDRA_CAST(0x0)) goto LAB_008ec865; -LAB_008ec879: - isVisible = 0; - } - else { - online_lobby_find_member_index(user); - FUN_0040a860(); - if (isLocalMember == '\0') { - slotX = (float)local_a4._unk; - slotY = local_30._green; - if (playerNumber == cursorPlayerNumber) goto LAB_008ec78b; - } - fVar10 = (float)local_a4._unk; - fVar9 = local_30._green; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Character")); - pLVar5->_visible = 1; - slotY = fVar9; - slotX = fVar10; -LAB_008ec79f: - if (((isLocalMember == '\0') && - ((playerNumber == cursorPlayerNumber || (*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\x01')))) || - ((char)user[3] != '\0')) goto LAB_008ec7cb; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Ready")); - pLVar5->_visible = 1; -LAB_008ec7df: - if (((isLocalMember == '\0') || (*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\x01')) || - ((char)user[3] != '\0')) goto LAB_008ec803; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Unready")); - pLVar5->_visible = 1; -LAB_008ec839: - if ((char)user[3] == '\0') goto LAB_008ec851; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_InProgress")); - pLVar5->_visible = 1; -LAB_008ec865: - if ((isLocalMember == '\0') && (playerNumber == cursorPlayerNumber)) goto LAB_008ec879; - isVisible = 1; - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Completion")); - pLVar5->_visible = isVisible; - FUN_0040a860(); - } - else { - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Ready_Button")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Unready_Button")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Invite_Player")); - pLVar5->_visible = 1; - FUN_0040a860(); - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Invite_Player_Button")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Swap_Button")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Number")); - pLVar5->_visible = 0; - FUN_0040a860(); - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Character")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Ready")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Unready")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_InProgress")); - pLVar5->_visible = 0; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Completion")); - pLVar5->_visible = 0; - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Next_Right")); - pLVar5->_visible = local_74; - if ((playerNumber != cursorPlayerNumber) || (isVisible = 1, isKeyboard == '\0')) { - isVisible = 0; - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Right_Next_Button")); - pLVar5->_visible = isVisible; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Next_Left")); - pLVar5->_visible = local_74; - if ((playerNumber != cursorPlayerNumber) || (isVisible = 1, isKeyboard == '\0')) { - isVisible = 0; - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Left_Next_Button")); - pLVar5->_visible = isVisible; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Options")); - pLVar5->_visible = local_74; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Options_Cursor")); - pLVar5->_visible = local_74; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Options")); - if (pLVar5 == GHIDRA_CAST(0x0)) { - in_stack_ffffff14 = GHIDRA_CAST(0x8eca3e); - KAGE_LogMessage(4,GHIDRA_CAST("[warn] no layer named %s\n")); - } - else { - ANM2::SetLayerFrame(memberSprite,*GHIDRA_CAST(pLVar5->_layerData),GHIDRA_UINT((local_76 == 0))); - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Player_Options_Cursor")); - if (pLVar5 == GHIDRA_CAST(0x0)) { - pos_01 = GHIDRA_CAST(&DAT_00000004); - in_stack_ffffff14 = GHIDRA_CAST(0x8eca78); - KAGE_LogMessage(4,GHIDRA_CAST("[warn] no layer named %s\n")); - } - else { - pos_01 = GHIDRA_CAST(0x8eca91); - ANM2::SetLayerFrame(memberSprite,*GHIDRA_CAST(pLVar5->_layerData),*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_90[8])) + 0x70))))); - } - if ((isKeyboard == '\0') && (playerNumber == cursorPlayerNumber)) { - if ((memberSprite->_animState)._animData == (void *)0x0) { - nullFrame = GHIDRA_CAST(0x0); - } - else { - nullFrame = AnimationState::GetNullFrame - (&memberSprite->_animState,GHIDRA_CAST("PlayerNextRightButton")); - } - local_30._green = slotY + nullFrame[1]; - local_30._red = slotX + *nullFrame; - position_00.y = slotY + nullFrame[1]; - position_00.x = slotX + *nullFrame; - Manager::render_button_sprite(0xd,position_00); - if ((memberSprite->_animState)._animData == (void *)0x0) { - nullFrame = GHIDRA_CAST(0x0); - } - else { - nullFrame = AnimationState::GetNullFrame - (&memberSprite->_animState,GHIDRA_CAST("PlayerNextLeftButton")); - } - local_30._green = slotY + nullFrame[1]; - local_30._red = slotX + *nullFrame; - pos_01 = GHIDRA_CAST(0xc); - in_stack_ffffff14 = GHIDRA_CAST(0x8ecb29); - position_01.y = local_30._green; - position_01.x = local_30._red; - Manager::render_button_sprite(0xc,position_01); - } - if (user == GHIDRA_CAST(0x0)) { - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Connection_Bar")); - isKeyboardInput = g_menuControllerIndex == 0; - pLVar5->_visible = 0; - if (isKeyboardInput) { - ExceptionList = local_1c; - return; - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_90[6])) + 0x20))) != '\0') { - ExceptionList = local_1c; - return; - } - if (local_ac <= GHIDRA_UINT(local_a4._green)) { - ExceptionList = local_1c; - return; - } - nullFrame = (GHIDRA_CAST((GHIDRA_CAST(memberSprite))))->Sprite::GetNullFrame(GHIDRA_CAST("InviteButton")); - fVar10 = local_8c + nullFrame[1]; - fVar9 = local_a4._alpha + *nullFrame; - local_30._green = fVar10; - local_30._red = fVar9; - (GHIDRA_CAST((aCStackY_173c + 0x81)))->Color::Color(1.0,1.0,1.0,1.0); - iVar3 = 0x18; - goto LAB_008ed064; - } - cVar2 = (**(code **)(*user + 0x14))(); - pGVar1 = local_90; - if (cVar2 != '\0') { - if ((char)user[2] == '\0') { - pLVar5 = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_90)) + 0x10)))),GHIDRA_CAST("Player_Portrait_Random")); - pLVar5->_visible = 1; - pLVar5 = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((pGVar1)) + 0x10)))),GHIDRA_CAST("Player_Portrait")); - pLVar5->_visible = 0; - } - else { - FUN_00949b90(); - local_30._green = (float)FUN_0069bd10(); - if (local_30._green == 0.0) goto LAB_008ecbd8; - portraitSprite = &(*GHIDRA_CAST((GHIDRA_CAST((local_90)) + 0x10))); - pLVar5 = ANM2::GetLayer(GHIDRA_CAST(portraitSprite),GHIDRA_CAST("Player_Portrait")); - pLVar5->_visible = 1; - pLVar5 = ANM2::GetLayer(GHIDRA_CAST(portraitSprite),GHIDRA_CAST("Player_Portrait_Random")); - pLVar5->_visible = 0; - Sprite::ReplaceSpritesheet - (GHIDRA_CAST(portraitSprite),0x2a,GHIDRA_CAST((GHIDRA_INT(local_30._green) + 0x4c))); - ANM2::LoadGraphics(GHIDRA_CAST(portraitSprite),unk); - } - memberSprite = GHIDRA_CAST(local_a4._blue); - } -LAB_008ecbd8: - iVar3 = user[1]; - local_ac = &g_manager->_font1_TeamMeatEx10; - if (iVar3 == 0) { - local_30._red = 0.0; - fVar9 = local_30._red; - local_30._green = 0.0; - fVar10 = local_30._green; - local_30._green = 0.0; - local_30._red = 0.0; - fVar6 = local_30._green; - fVar11 = local_30._red; - local_30._red = fVar9; - local_30._green = fVar10; - } - else { - fVar6 = *GHIDRA_CAST((iVar3 + 0xc)); - fVar11 = *GHIDRA_CAST((iVar3 + 8)); - } - local_30._green = (float)user_profile_format_display_name(CONCAT44(fVar6,fVar11),local_ac,0x46); - if ((memberSprite->_animState)._animData == (void *)0x0) { - nullFrame = GHIDRA_CAST(0x0); - } - else { - nullFrame = AnimationState::GetNullFrame(&memberSprite->_animState,GHIDRA_CAST("PlayerName")); - } - local_a4._red = slotX + *nullFrame; - local_a4._green = slotY + nullFrame[1]; - if ((playerNumber == cursorPlayerNumber) && (isLocalMember == '\0')) { - local_a4._green = local_a4._green + 10.0; - } - FUN_00a1a580(); - local_14 = (void *)0xd; - (GHIDRA_CAST((&local_54)))->KColor::SetFromARGB(0xff362f2d); - pos_01 = &local_a4; - in_stack_ffffff10 = 0x8eccac; - in_stack_ffffff14 = GHIDRA_CAST(local_30._green); - Font::DrawStringScaled(local_ac,GHIDRA_CAST(local_30._green),GHIDRA_CAST(pos_01),color_02,fontSettings); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 0xff; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))) = 0xffffff; - iVar3 = (g_manager->_optionsConfig)._eosCrossplay; - if ((iVar3 == 2) || (iVar3 == 3)) { - cVar2 = (**(code **)(*user + 0x14))(); - fVar10 = g_vectorOne.y; - fVar9 = g_vectorOne.x; - if (cVar2 == '\0') { - fVar6 = 8.0; - fVar11 = 18.0; - } - else { - fVar6 = 58.0; - fVar11 = 30.0; - } - local_30._red = local_a4._alpha + fVar6; - local_30._green = local_8c + fVar11; - in_stack_ffffff10 = (**(code **)(*savedUser + 0xc))(); - in_stack_ffffff0c = 0x8ecd41; - position.y = local_30._green; - position.x = local_30._red; - in_stack_ffffff14 = GHIDRA_CAST(local_30._red); - pos_01 = GHIDRA_CAST(local_30._green); - render_online_icon(in_stack_ffffff10,position,fVar9,fVar10); - memberSprite = GHIDRA_CAST(local_a4._blue); - user = savedUser; - } - cVar2 = (**(code **)(*user + 0x14))(); - if (cVar2 == '\0') { - FUN_00a29fd0(); - local_14 = (void *)0xe; - if ((GHIDRA_CAST(local_30._red) == GHIDRA_CAST(0x0)) || - (0x77 < *GHIDRA_CAST(&(GHIDRA_CAST((GHIDRA_INT(local_30._red) + 0x14)))->_red))) { - iVar3 = 0; - } - else { - iVar3 = 2; - if (0x3c < *GHIDRA_CAST(&(GHIDRA_CAST((GHIDRA_INT(local_30._red) + 0x14)))->_red)) { - iVar3 = 1; - } - } - local_76 = playerNumber != cursorPlayerNumber; - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Connection_Bar")); - pLVar5->_visible = local_76; - ANM2::SetLayerFrame(memberSprite,0x21,iVar3); - FUN_008eee70(); - ExceptionList = local_1c; - return; - } - pLVar5 = ANM2::GetLayer(memberSprite,GHIDRA_CAST("Connection_Bar")); - pLVar5->_visible = 0; - if (((char)user[2] == '\n') && (*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) == '\0')) { - sprintf_s(GHIDRA_CAST(&local_54),0x14,GHIDRA_CAST("Tokens: %d")); - nullFrame = (GHIDRA_CAST((GHIDRA_CAST(memberSprite))))->Sprite::GetNullFrame(GHIDRA_CAST("EdenTokenCounter")); - manager = g_manager; - local_30._green = slotY + nullFrame[1]; - fVar9 = slotX + *nullFrame; - iVar3 = Font::get_string_width_n(&g_manager->_font1_TeamMeatEx10,GHIDRA_CAST(&local_54),-1); - local_30._red = fVar9 - (float)((double)iVar3 + __uint_to_double_fixup[-(iVar3 >> 0x1f)]) * 0.5; - FontSettings::constructor(fontSettings); - local_14 = (void *)0xf; - (GHIDRA_CAST((GHIDRA_CAST((local_70 + 4)))))->KColor::SetFromARGB(0xff362f2d); - pos_01 = &local_30; - in_stack_ffffff14 = &local_54; - in_stack_ffffff10 = 0x8ece9e; - Font::DrawStringScaled - (&manager->_font1_TeamMeatEx10,GHIDRA_CAST(in_stack_ffffff14),GHIDRA_CAST(pos_01),color_01, - settings); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 0xff; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))) = 0xffffff; - local_b8 = 0; - local_b4 = 0; - memberSprite = GHIDRA_CAST(local_a4._blue); - user = savedUser; - } - if (g_menuControllerIndex == 0) { - ExceptionList = local_1c; - return; - } - if (*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) == '\0') { - nullLayerName = "ReadyButton"; - } - else { - nullLayerName = "UnreadyButton"; - } - nullFrame = (GHIDRA_CAST((GHIDRA_CAST(memberSprite))))->Sprite::GetNullFrame(GHIDRA_CAST(nullLayerName)); - fVar10 = local_a4._alpha + *nullFrame; - fVar9 = local_8c + nullFrame[1]; - local_30._green = fVar9; - local_30._red = fVar10; - (GHIDRA_CAST((aCStackY_173c + 0x81)))->Color::Color(1.0,1.0,1.0,1.0); - color._colorize[3] = (float)in_stack_ffffff0c; - color._tint[0] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x0))); - color._tint[1] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x4))); - color._tint[2] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x8))); - color._tint[3] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0xc))); - color._colorize[0] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x10))); - color._colorize[1] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x14))); - color._colorize[2] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x18))); - color._offset[0] = (float)in_stack_ffffff10; - color._offset[1] = (float)in_stack_ffffff14; - color._offset[2] = (float)pos_01; - pos.y = fVar9; - pos.x = fVar10; - render_input_button_icon(g_menuControllerIndex,0x1c,0,1,color,pos); - if (isSwapAllowed == '\0') { - ExceptionList = local_1c; - return; - } - if (*GHIDRA_CAST((GHIDRA_CAST(user) + 10)) != '\0') { - ExceptionList = local_1c; - return; - } - if (playerNumber != cursorPlayerNumber) { - ExceptionList = local_1c; - return; - } - if ((*GHIDRA_CAST((GHIDRA_CAST(user) + 9)) == '\0') && (cVar2 = FUN_008ed2e0(), cVar2 == '\0')) { - ExceptionList = local_1c; - return; - } - nullFrame = (GHIDRA_CAST((GHIDRA_CAST(memberSprite))))->Sprite::GetNullFrame(GHIDRA_CAST("SwapButton")); - fVar10 = local_8c + nullFrame[1]; - fVar9 = local_a4._alpha + *nullFrame; - local_30._green = fVar10; - local_30._red = fVar9; - (GHIDRA_CAST((aCStackY_173c + 0x81)))->Color::Color(1.0,1.0,1.0,1.0); - iVar3 = 0x19; -LAB_008ed064: - color_00._colorize[3] = (float)in_stack_ffffff0c; - color_00._tint[0] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x0))); - color_00._tint[1] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x4))); - color_00._tint[2] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x8))); - color_00._tint[3] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0xc))); - color_00._colorize[0] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x10))); - color_00._colorize[1] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x14))); - color_00._colorize[2] = (*GHIDRA_CAST((GHIDRA_CAST(&((float)in_stack_fffffef0)) + 0x18))); - color_00._offset[0] = (float)in_stack_ffffff10; - color_00._offset[1] = (float)in_stack_ffffff14; - color_00._offset[2] = (float)pos_01; - pos_00.y = fVar10; - pos_00.x = fVar9; - render_input_button_icon(g_menuControllerIndex,iVar3,0,1,color_00,pos_00); - ExceptionList = local_1c; - return; -} - -// 00998880 -void GameOver::Render() -{ - GameOver *smallFont = this; - uint8_t bVar1; - Manager *pMVar2; - char cVar3; - uint32_t uVar4; - void *pvVar5; - LayerState *pLVar6; - int iVar7; - Entity_Player *netplayPlayer; - ItemConfig_Item *itemConfig; - float extraout_EAX; - float *nullFrame; - char *text; - Font *smallFont; - uint8_t *translatedText; - uint8_t *******pppppppbVar8; - size_t copyLen; - AnimationLayer *animLayer; - int iVar9; - uint8_t *pbVar10; - KColor *color; - KColor *color_00; - std_string *ptr; - int layerEntry; - uint32_t uVar11; - ANM2 *pAVar12; - char *memberEntry; - uint8_t *deedName; - KColor tmpColor; - Vector drawPos; - float local_124; - Vector local_120; - Vector screenCenter; - float local_110; - float local_10c; - std_string *local_108; - uint32_t local_104; - float local_100; - Entity_Player *local_fc; - uint32_t local_f8; - std_string *local_f4; - char local_f0 [12]; - uint32_t local_e4; - uint32_t local_e0; - uint8_t *******deedText [2]; - uint8_t seedHalf [12]; - uint32_t uStack_c8; - ColorMod tmpColorMod; - uint8_t quad [48]; - uint8_t nullName [68]; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - void *collectibleConfigs; - Game *game; - - puStack_20 = nullName + 100; - local_14 = 0xffffffff; - puStack_18 = &LAB_00b0d7dd; - local_1c = ExceptionList; - uVar4 = __security_cookie ^ GHIDRA_UINT((nullName + 0x58)); - ExceptionList = &local_1c; - local_124 = 0.0; - if (*GHIDRA_CAST(smallFont) != 0) { - tmpColor._red = 0.0; - tmpColor._green = 0.0; - tmpColor._blue = 0.0; - tmpColor._alpha = 0.5019608; - tmpColor._unk = 0; - local_24 = uVar4; - pvVar5 = render_quad_set_uniform_color(quad,0.0,0.0,g_screenWidth,g_screenHeight,&tmpColor); - render_color_shader_pass(pvVar5); - screenCenter.x = g_screenWidth * 0.5 + 16.0; - screenCenter.y = g_screenHeight * 0.5 + 16.0; - if (g_manager->_netplayManager != *GHIDRA_CAST((g_manager + 1))) { - screenCenter.x = screenCenter.x - 112.0; - } - pLVar6 = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),&DAT_00000006); - pLVar6->_visible = 0; - local_fc = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_playerManager))) + 0x7c)))); - if (local_fc == GHIDRA_CAST(0x0)) { - local_fc = Game::GetPlayer(g_game,0); - } - if (local_fc->_playerType == 0x28) { - local_fc = GHIDRA_CAST(local_fc->_twinPlayer); - } - if ((g_manager->_netplayManager != *GHIDRA_CAST((g_manager + 1))) && - (iVar7 = FUN_0090b070(uVar4), iVar7 != 0)) { - FUN_0090b070(); - netplayPlayer = GHIDRA_CAST(FUN_004253d0()); - if (netplayPlayer != GHIDRA_CAST(0x0)) { - local_fc = netplayPlayer; - } - } - local_108 = GHIDRA_CAST(local_fc->_playerType); - if (GHIDRA_INT(local_108) < 0x29) { - ANM2::Render(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),&screenCenter,&g_vectorZero,&g_vectorZero); - } - else { - pLVar6 = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),&DAT_00000004); - pLVar6->_visible = 0; - ANM2::Render(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),&screenCenter,&g_vectorZero,&g_vectorZero); - ModManager::RenderCustomGameOver(GHIDRA_INT(local_108),&screenCenter); - } - local_10c = g_vectorZero.x; - local_110 = g_vectorZero.y; - pLVar6 = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),&DAT_00000006); - local_104 = 0x10; - pLVar6->_visible = 1; - pvVar5 = (local_fc->_history)._historyItems._begin; - if (pvVar5 != (local_fc->_history)._historyItems._end) { - do { - if (local_104 == 0) break; - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 4)) == '\0') { - local_100 = *GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 8)); - } - else { - local_100 = 0.0; - } - if (g_game == GHIDRA_CAST(0x0)) { - if (-1 < GHIDRA_INT(local_100)) goto LAB_00998b3f; - } - else { - if (GHIDRA_INT(local_100) < 0) { - if ((GHIDRA_INT(local_100) < 0) && - (local_108 = (g_game->_proceduralItemManager)._proceduralItems._begin, - GHIDRA_INT(~GHIDRA_UINT(local_100)) < - GHIDRA_INT((g_game->_proceduralItemManager)._proceduralItems._end) - GHIDRA_INT(local_108) >> 2)) { - itemConfig = (ItemConfig_Item *) - **GHIDRA_CAST((GHIDRA_CAST(local_108) + ~GHIDRA_UINT(local_100) * 4)); - } - else { - itemConfig = GHIDRA_CAST(0x0); - } - } - else { -LAB_00998b3f: - collectibleConfigs = (g_manager->_itemConfig)._collectibles._begin; - if (GHIDRA_INT((g_manager->_itemConfig)._collectibles._end) - GHIDRA_INT(collectibleConfigs) >> 2 <= - GHIDRA_INT(local_100)) goto LAB_00998f1b; - itemConfig = *GHIDRA_CAST((GHIDRA_CAST(collectibleConfigs) + GHIDRA_INT(local_100) * 4)); - } - if ((itemConfig != GHIDRA_CAST(0x0)) && - ((itemConfig->type != 3 || (itemConfig->id == local_fc->_activeDesc[0]._item)))) { - if (GHIDRA_INT(local_100) < 0x2dd) { - if (GHIDRA_INT(local_100) < 1) { - local_100 = 1.02715e-42; - } - else { - local_100 = (float)(GHIDRA_INT(local_100) - 1); - } - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))) != 0) && - ((6 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 6 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)))))) { - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))); - local_108 = *GHIDRA_CAST((iVar7 + 0x50)); - if ((iVar7 == 0) || - ((GHIDRA_INT(local_108) < 0 || (*GHIDRA_CAST((iVar7 + 0x1c)) <= GHIDRA_INT(local_108))))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x40)))) + GHIDRA_INT(local_108) * 4)) = 0; - AnimationState::AdvanceLayerPosition - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))),GHIDRA_INT(local_108),(float)GHIDRA_INT(local_100)) - ; - } - local_120.x = local_10c + screenCenter.x; - local_120.y = local_110 + screenCenter.y; - if ((*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x111))) != '\0') { - if ((*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x78))) == '\0') { - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))); - if (((iVar7 != 0) && (6 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)))) && - (iVar9 = *GHIDRA_CAST((iVar7 + 0x50)), -1 < iVar9)) { - AnimationLayer::RenderFrame - (GHIDRA_CAST((iVar9 * 0x10 + *GHIDRA_CAST((iVar7 + 0x18)))),&local_120, - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x40)))) + iVar9 * 4)),&g_vectorZero, - &g_vectorZero,*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38))))); - } - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x5c)))); - if (((iVar7 != 0) && (6 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x58)))) + 0x80)))) && - (iVar9 = *GHIDRA_CAST((iVar7 + 0x50)), -1 < iVar9)) { - pAVar12 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x58)))); - animLayer = GHIDRA_CAST((iVar9 * 0x10 + *GHIDRA_CAST((iVar7 + 0x18)))); - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x60)))); - goto LAB_00998e94; - } - } - else { - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x5c)))); - if (((iVar7 != 0) && (6 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x58)))) + 0x80)))) && - (iVar9 = *GHIDRA_CAST((iVar7 + 0x50)), -1 < iVar9)) { - AnimationLayer::RenderFrame - (GHIDRA_CAST((iVar9 * 0x10 + *GHIDRA_CAST((iVar7 + 0x18)))),&local_120, - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x60)))) + iVar9 * 4)),&g_vectorZero, - &g_vectorZero,*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x58))))); - } - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))); - if (((iVar7 != 0) && (6 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)))) && - (iVar9 = *GHIDRA_CAST((iVar7 + 0x50)), -1 < iVar9)) { - pAVar12 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))); - animLayer = GHIDRA_CAST((iVar9 * 0x10 + *GHIDRA_CAST((iVar7 + 0x18)))); - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x40)))); -LAB_00998e94: - AnimationLayer::RenderFrame - (animLayer,&local_120,*GHIDRA_CAST((iVar7 + iVar9 * 4)),&g_vectorZero, - &g_vectorZero,pAVar12); - } - } - } - } - else { - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))) == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("AnimationData is NULL\n")); - } - if (*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)) < 7) { - KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")); - } - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))); - if (((iVar7 == 0) || (*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)) < 6)) || - ((iVar9 = *GHIDRA_CAST((iVar7 + 0x50)), iVar9 < 0 || (*GHIDRA_CAST((iVar7 + 0x1c)) <= iVar9)))) - { -LAB_00998bff: - iVar7 = 0; - } - else { - layerEntry = iVar9 * 0x10 + *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))) + 0x18)); - iVar7 = *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x40)))) + iVar9 * 4)); - if ((iVar7 < 0) || (*GHIDRA_CAST((layerEntry + 8)) <= iVar7)) goto LAB_00998bff; - iVar7 = iVar7 * 0x6c + *GHIDRA_CAST((layerEntry + 4)); - } - if (iVar7 != 0) { - tmpColor._unk = 7; - if (((uint8_t)g_graphicsManager_flags & 4) == 0) { - tmpColor._green = 8.40779e-45; - } - else { - tmpColor._green = 1.4013e-45; - } - tmpColor._red = 0.0; - tmpColor._blue = 9.80909e-45; - tmpColor._alpha = 1.4013e-45; - tmpColorMod._offset[0] = 0.0; - tmpColorMod._tint[0] = 1.0; - tmpColorMod._tint[1] = 1.0; - tmpColorMod._tint[2] = 1.0; - tmpColorMod._tint[3] = 1.0; - tmpColorMod._offset[1] = 0.0; - drawPos.x = screenCenter.x + *GHIDRA_CAST((iVar7 + 0x10)) + local_10c; - tmpColorMod._offset[2] = 0.0; - tmpColorMod._colorize[0] = 0.0; - tmpColorMod._colorize[1] = 0.0; - tmpColorMod._colorize[2] = 0.0; - tmpColorMod._colorize[3] = 0.0; - drawPos.y = screenCenter.y + *GHIDRA_CAST((iVar7 + 0x14)) + local_110; - ModManager::RenderCustomCollectionItem - (GHIDRA_CAST(&g_manager->_modManager),GHIDRA_UINT(local_100),&drawPos, - &g_vectorOne,&tmpColorMod,&tmpColor); - } - } - local_10c = local_10c + 16.0; - local_110 = local_110 + 2.5; - if (128.0 <= local_10c) { - local_10c = local_10c - 132.0; - local_110 = local_110 - 4.0; - } - local_104 = local_104 - 1; - } - } -LAB_00998f1b: - pvVar5 = (void *)(GHIDRA_INT(pvVar5) + 0x1c); - } while (pvVar5 != (local_fc->_history)._historyItems._end); - } - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(smallFont[1])) + 0x10)))) != 0) { - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))) == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("AnimationData is NULL\n")); - } - if (*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)) < 6) { - KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")); - } - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))); - if ((((iVar7 != 0) && (4 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))) + 0x80)))) && - (iVar9 = *GHIDRA_CAST((iVar7 + 0x4c)), -1 < iVar9)) && (iVar9 < *GHIDRA_CAST((iVar7 + 0x1c)))) { - layerEntry = iVar9 * 0x10 + *GHIDRA_CAST((iVar7 + 0x18)); - iVar7 = *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x40)))) + iVar9 * 4)); - if (((-1 < iVar7) && (iVar7 < *GHIDRA_CAST((layerEntry + 8)))) && - (iVar7 = iVar7 * 0x6c + *GHIDRA_CAST((layerEntry + 4)), iVar7 != 0)) { - drawPos.x = screenCenter.x + *GHIDRA_CAST((iVar7 + 0x10)); - iVar9 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(smallFont[1])) + 0x10)))); - tmpColorMod._offset[0] = 0.0; - tmpColorMod._offset[1] = 0.0; - tmpColorMod._offset[2] = 0.0; - tmpColorMod._tint[0] = 1.0; - tmpColorMod._tint[1] = 1.0; - tmpColorMod._tint[2] = 1.0; - tmpColorMod._tint[3] = 1.0; - tmpColorMod._colorize[0] = 0.0; - tmpColorMod._colorize[1] = 0.0; - tmpColorMod._colorize[2] = 0.0; - tmpColorMod._colorize[3] = 0.0; - drawPos.y = screenCenter.y + *GHIDRA_CAST((iVar7 + 0x14)); - if (((iVar9 != 0) && (iVar7 = *GHIDRA_CAST((iVar9 + 0x160)), iVar7 != 0)) && - (pAVar12 = GHIDRA_CAST((iVar7 + 0xdf0)), *GHIDRA_CAST((iVar7 + 0xef9)) != '\0')) { - ANM2::SetFrame(pAVar12,GHIDRA_CAST((iVar7 + 0xe08)),*GHIDRA_CAST((iVar9 + 100))); - (GHIDRA_CAST((GHIDRA_CAST(pAVar12))))->Sprite::SetColor(&tmpColorMod); - *GHIDRA_CAST((iVar7 + 0xe8c)) = g_vectorOne.x; - *GHIDRA_CAST((iVar7 + 0xe90)) = g_vectorOne.y; - ANM2::Render(pAVar12,&drawPos,&g_vectorZero,&g_vectorZero); - } - } - } - } - game = g_game; - if (g_manager->_netplayManager == *GHIDRA_CAST((g_manager + 1))) { - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_seedEffects))) + 0x4)))); - if (uVar4 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("Error: Game Start Seed was not set.\n")); - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((game->_seedEffects))) + 0x4)))); - } - Seeds::Seed2String(GHIDRA_CAST(&local_f4),uVar4); - uVar4 = local_e0; - local_14 = 5; - local_108 = GHIDRA_CAST(&local_f4); - if (0xf < local_e0) { - local_108 = local_f4; - } - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))) != 0) { - nullFrame = AnimationState::GetNullFrame - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))),GHIDRA_CAST("SeedPos")); - uVar11 = local_e4; - if (nullFrame != GHIDRA_CAST(0x0)) { - local_124 = g_screenHeight * 0.5 + nullFrame[1]; - local_100 = g_screenWidth * 0.5 + *nullFrame; - copyLen = 4; - if (local_e4 < 4) { - copyLen = local_e4; - } - seedHalf[0] = 0; - seedHalf[1] = 0; - seedHalf[2] = 0; - seedHalf[3] = 0; - seedHalf[4] = 0; - seedHalf[5] = 0; - seedHalf[6] = 0; - seedHalf[7] = 0; - seedHalf[8] = 0; - seedHalf[9] = 0; - seedHalf[10] = 0; - seedHalf[0xb] = 0; - uStack_c8 = 0; - memcpy(seedHalf,local_108,copyLen); - pMVar2 = g_manager; - tmpColorMod._colorize[0] = 0.0; - tmpColorMod._colorize[1] = 9.18341e-41; - tmpColorMod._colorize[2] = 0.0; - tmpColorMod._colorize[3] = 1.0; - tmpColorMod._offset[0] = -NAN; - tmpColorMod._offset[1] = 0.0; - tmpColorMod._offset[2] = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 6; - (GHIDRA_CAST((&tmpColor)))->KColor::SetFromARGB(0xff362f2d); - local_100 = local_100 - 4.0; - Font::DrawString(&pMVar2->_font2_TeamMeatEx12,seedHalf,color,tmpColorMod._colorize, - local_100,local_124 + 2.0); - seedHalf[0] = 0; - seedHalf[1] = 0; - seedHalf[2] = 0; - seedHalf[3] = 0; - seedHalf[4] = 0; - seedHalf[5] = 0; - seedHalf[6] = 0; - seedHalf[7] = 0; - seedHalf[8] = 0; - seedHalf[9] = 0; - seedHalf[10] = 0; - seedHalf[0xb] = 0; - uStack_c8 = 0; - copyLen = 4; - if (uVar11 - 4 < 4) { - copyLen = uVar11 - 4; - } - memcpy(seedHalf,local_108->_buf + 5,copyLen); - pMVar2 = g_manager; - tmpColorMod._colorize[0] = 0.0; - tmpColorMod._colorize[1] = 9.18341e-41; - tmpColorMod._colorize[2] = 0.0; - tmpColorMod._colorize[3] = 1.0; - tmpColorMod._offset[0] = -NAN; - tmpColorMod._offset[1] = 0.0; - tmpColorMod._offset[2] = 0.0; - local_14 = CONCAT31((*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))),7); - (GHIDRA_CAST((&tmpColor)))->KColor::SetFromARGB(0xff362f2d); - Font::DrawString(&pMVar2->_font2_TeamMeatEx12,seedHalf,color_00,tmpColorMod._colorize, - local_100,local_124 + 17.0); - uVar4 = local_e0; - } - } - if (0xf < uVar4) { - uVar11 = uVar4 + 1; - ptr = local_f4; - if (0xfff < uVar11) { - ptr = GHIDRA_CAST(local_f4[-1]._capacity); - uVar11 = uVar4 + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_f4) + (-4 - GHIDRA_INT(ptr))))) { -LAB_0099978e: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ptr,uVar11); - } - } - else { - local_108 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(smallFont[1])) + 0x4)))); - iVar9 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(smallFont[1])) + 0x8)))) - GHIDRA_INT(local_108); - local_104 = 0; - iVar7 = iVar9 >> 0x1f; - if (iVar9 / 0x38 + iVar7 != iVar7) { - local_fc = GHIDRA_CAST(0x0); - do { - if (GHIDRA_CAST(0xdf) < local_fc) { - ExceptionList = local_1c; - return; - } - memberEntry = local_108->_buf + GHIDRA_INT(local_fc); - local_120.x = (float)KAGE::System::UserProfileBase::vftable; - (GHIDRA_CAST((memberEntry)))->UserProfile::find_or_create(); - local_14 = 0; - local_120.x = (float)KAGE::System::UserProfile::vftable; - local_120.y = extraout_EAX; - if (((extraout_EAX != 0.0) && - (*GHIDRA_CAST((GHIDRA_CAST(extraout_EAX) + 8)) != 0 || *GHIDRA_CAST((GHIDRA_CAST(extraout_EAX) + 0xc)) != 0)) && - (*GHIDRA_CAST((GHIDRA_CAST(extraout_EAX) + 0x14)) == 0)) { - (GHIDRA_CAST((&local_120)))->KAGE::System::UserProfile::load_steam_avatar(); - } - local_14 = 1; - cVar3 = (**(code **)(GHIDRA_CAST(local_120.x) + 0x14))(); - local_14 = 0xffffffff; - local_120.x = (float)KAGE::System::UserProfileBase::vftable; - if (cVar3 != '\0') { - pLVar6 = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),GHIDRA_CAST("DeedsMe")); - if (pLVar6 == GHIDRA_CAST(0x0)) { - KAGE_LogMessage(4,GHIDRA_CAST("[warn] no layer named %s\n")); - } - else { - ANM2::SetLayerFrame(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x8)))),*GHIDRA_CAST(pLVar6->_layerData),local_104); - } - } - local_104 = local_104 + 1; - sprintf_s(nullName,0x40,GHIDRA_CAST("Player%d Text")); - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x3c)))) == 0) { - nullFrame = GHIDRA_CAST(0x0); - } - else { - nullFrame = AnimationState::GetNullFrame(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((smallFont)) + 0x38)))),nullName); - } - drawPos.y = screenCenter.y + nullFrame[1]; - drawPos.x = screenCenter.x + *nullFrame; - local_f4 = GHIDRA_CAST(0x55ffff); - local_f0[4] = '\0'; - local_f0[5] = '\0'; - local_f0[6] = -0x80; - local_f0[7] = '?'; - local_f0[8] = -1; - local_f0[9] = -1; - local_f0[10] = -1; - local_f0[0xb] = -1; - local_e4 = 0; - local_e0 = 0; - local_14 = 2; - text = memberEntry + 8; - local_f8 = 1; - local_f0[0] = '\x02'; - local_f0[1] = '\0'; - local_f0[2] = '\0'; - local_f0[3] = '\0'; - tmpColor._unk = 0; - tmpColor._red = 0.21176471; - tmpColor._green = 0.18431373; - tmpColor._blue = 0.1764706; - tmpColor._alpha = 1.0; - if (0xf < *GHIDRA_CAST((memberEntry + 0x1c))) { - text = *GHIDRA_CAST(text); - } - local_110 = drawPos.y; - Font::DrawStringScaled - (&g_manager->_font2_TeamMeatEx12,GHIDRA_CAST(text),&drawPos,&tmpColor,&local_f8); - deedName = GHIDRA_CAST(&DAT_00c78f08); - drawPos.y = local_110 + 18.0; - smallFont = &g_manager->_font1_TeamMeatEx10; - local_10c = 0.0; - local_100 = 0.0; - local_110 = drawPos.y; - do { - if (2 < GHIDRA_INT(local_10c)) break; - cVar3 = FUN_008ca1d0(*(uint32_t *) - (GHIDRA_INT((local_fc->_sprite)._filename._buf) + GHIDRA_INT((local_108 + -3))), - *GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST((local_fc)) + 0x4))) + GHIDRA_INT(local_108))),local_100); - if (cVar3 != '\0') { - pbVar10 = deedName; - if (0xf < *GHIDRA_CAST((deedName + 0x14))) { - pbVar10 = *GHIDRA_CAST(deedName); - } - translatedText = string_table_translate(&g_manager->_stringTable,pbVar10); - seedHalf[8] = 0; - seedHalf[9] = 0; - seedHalf[10] = 0; - seedHalf[0xb] = 0; - uStack_c8 = 0xf; - deedText[0] = GHIDRA_CAST(0x0); - pbVar10 = translatedText; - do { - bVar1 = *pbVar10; - pbVar10 = pbVar10 + 1; - } while (bVar1 != 0); - (GHIDRA_CAST((GHIDRA_CAST(deedText))))->msvc::string::assign(translatedText, - GHIDRA_INT(pbVar10) - GHIDRA_INT((translatedText + 1))); - local_124 = (float)(GHIDRA_UINT(local_124) | 1); - tmpColorMod._colorize[0] = 1.4013e-45; - tmpColorMod._colorize[1] = 9.18341e-41; - tmpColorMod._colorize[2] = 0.0; - tmpColorMod._colorize[3] = 1.0; - tmpColorMod._offset[0] = -NAN; - tmpColorMod._offset[1] = 0.0; - tmpColorMod._offset[2] = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 4; - pppppppbVar8 = GHIDRA_CAST(deedText); - if (0xf < uStack_c8) { - pppppppbVar8 = deedText[0]; - } - tmpColor._unk = 0; - tmpColor._red = 0.21176471; - tmpColor._green = 0.18431373; - tmpColor._blue = 0.1764706; - tmpColor._alpha = 1.0; - Font::DrawStringScaled - (smallFont,GHIDRA_CAST(pppppppbVar8),&drawPos,&tmpColor,tmpColorMod._colorize); - drawPos.y = local_110 + 15.0; - local_10c = (float)(GHIDRA_INT(local_10c) + 1); - local_14 = CONCAT31((*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))),2); - local_110 = drawPos.y; - if (0xf < uStack_c8) { - uVar4 = uStack_c8 + 1; - pppppppbVar8 = deedText[0]; - if (0xfff < uVar4) { - pppppppbVar8 = GHIDRA_CAST(deedText[0][-1]); - uVar4 = uStack_c8 + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(deedText[0]) + (-4 - GHIDRA_INT(pppppppbVar8))))) - goto LAB_0099978e; - } - operator_delete(pppppppbVar8,uVar4); - } - } - deedName = deedName + 0x18; - local_100 = (float)(GHIDRA_INT(local_100) + 1); - } while (GHIDRA_INT(deedName) < 0xc79100); - local_fc = GHIDRA_CAST(&local_fc->_spawnerVariant); - local_14 = 0xffffffff; - local_108 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(smallFont[1])) + 0x4)))); - } while (local_104 < GHIDRA_UINT(((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(smallFont[1])) + 0x8)))) - GHIDRA_INT(local_108)) / 0x38))); - } - } - } - ExceptionList = local_1c; - return; -} - -// 009997c0 -void GameOver::Show() -{ - uint64_t qVar1; - uint8_t bVar2; - uint32_t uVar3; - Entity_Player *deadPlayer; - LayerState *layer; - int extraout_ECX; - uint8_t *pbVar4; - int layerId; - void *pvVar5; - int extraout_EDX; - uint32_t uVar6; - uint8_t *nameEnd; - char *anm2Path; - int iVar7; - int layerId; - Game *game; - uint32_t uStack_88; - EntityConfig_Entity *pEStack_84; - int stageFrame; - uint64_t uStack_74; - void *pvStack_6c; - uint32_t uStack_5c; - uint32_t uStack_58; - uint32_t uStack_54; - uint32_t uStack_50; - uint32_t uStack_4c; - uint32_t uStack_48; - uint32_t uStack_44; - uint32_t uStack_40; - std_string anm2File; - uint8_t playerLabel [12]; - int playerType; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - bool isBossKiller; - Manager *manager; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b0d825; - local_10 = ExceptionList; - local_14 = __security_cookie ^ GHIDRA_UINT((playerLabel + 0x20)); - ExceptionList = &local_10; - if ((g_game->_pauseScreen)._state != 0) { - (GHIDRA_CAST((&g_game->_pauseScreen)))->PopupWindow::hide(); - } - manager = g_manager; - *GHIDRA_CAST(this) = 2; - *GHIDRA_CAST((this + 1)) = 1; - PopupButtons::reset(&manager->_popupButtons,1); - if (*GHIDRA_CAST((extraout_EDX + 0x4b3d8)) == *GHIDRA_CAST((extraout_EDX + 0x4b3dc))) { - *GHIDRA_CAST((extraout_ECX + 0x11c)) = 3; - uVar3 = 2; - } - else { - *(code **)(extraout_ECX + 0x264) = FUN_008cb190; - uVar3 = 6; - *GHIDRA_CAST((extraout_ECX + 0x268)) = this; - *GHIDRA_CAST((extraout_ECX + 0x118)) = 0x42c00000; - *GHIDRA_CAST((extraout_ECX + 0x114)) = 0x42c00000; - } - *GHIDRA_CAST((extraout_ECX + 0x24c)) = uVar3; - anm2Path = "gfx/ui/DeedsDeathScreen.anm2"; - if (*GHIDRA_CAST((extraout_EDX + 0x4b3d8)) == *GHIDRA_CAST((extraout_EDX + 0x4b3dc))) { - anm2Path = "gfx/ui/Death Screen.anm2"; - } - anm2File._size = 0; - anm2File._capacity = 0xf; - (*GHIDRA_CAST((GHIDRA_CAST(&(anm2File._buf)) + 0x0))) = (void *)0x0; - pbVar4 = GHIDRA_CAST(anm2Path); - do { - bVar2 = *pbVar4; - pbVar4 = pbVar4 + 1; - } while (bVar2 != 0); - (GHIDRA_CAST((anm2File._buf)))->msvc::string::assign(GHIDRA_CAST(anm2Path),GHIDRA_INT(pbVar4) - GHIDRA_INT((anm2Path + 1))); - local_8 = 0; - ANM2::Load(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),&anm2File,1); - local_8 = 0xffffffff; - if (0xf < anm2File._capacity) { - uVar6 = anm2File._capacity + 1; - pvVar5 = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)anm2File._buf)) + 0x0))); - if (0xfff < uVar6) { - pvVar5 = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(anm2File._buf)) + 0x0))) + -4); - uVar6 = anm2File._capacity + 0x24; - if (0x1f < GHIDRA_UINT(((*GHIDRA_CAST((GHIDRA_CAST(&(anm2File._buf)) + 0x0))) + (-4 - GHIDRA_INT(pvVar5))))) { -LAB_009998fd: - local_8 = 0xffffffff; - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar5,uVar6); - } - anm2File._size = 0; - anm2File._capacity = 0xf; - (*GHIDRA_CAST((GHIDRA_CAST(&(anm2File._buf)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST(&(anm2File._buf)) + 0x0))) & 0xffffff00; - iVar7 = g_game->_stage; - if ((g_game->_difficulty == 2) || (layerId = iVar7, g_game->_difficulty == 3)) { - if (iVar7 < 5) { - layerId = iVar7 * 2 + -1; - } - else { - layerId = 0; - if (iVar7 == 5) { - layerId = 10; - } - } - } - bVar2 = ANM2::SetAnimation(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),GHIDRA_CAST("Diary"),1); - if (((bVar2 != 0) && (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0)) && - (AnimationState::SetFrameFloat(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),0.0), - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0)) { - (*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4c))) = 0; - } - if ((layerId < 9) && ((g_game->_stageType == 4 || (g_game->_stageType == 5)))) { - switch(layerId) { - case 1: - case 2: - stageFrame = 7; - break; - case 3: - case 4: - stageFrame = 8; - break; - case 5: - case 6: - stageFrame = 9; - break; - case 7: - case 8: - stageFrame = 10; - break; - default: - goto code_r0x009999d4; - } - } - else { -code_r0x009999d4: - switch(layerId) { - case 1: - case 2: - stageFrame = 0; - break; - case 3: - case 4: - stageFrame = 1; - break; - case 5: - case 6: - stageFrame = 2; - break; - case 7: - case 8: - stageFrame = 3; - break; - case 9: - stageFrame = 5; - break; - default: - stageFrame = 4; - break; - case 0xc: - stageFrame = 6; - break; - case 0xd: - stageFrame = 0xb; - } - } - if (((0 < g_game->_stage) && (g_game->_stage < 7)) && - ((g_game->_gameStateFlags & 0x1000000000000) != 0)) { - stageFrame = 0xc; - } - deadPlayer = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_playerManager))) + 0x7c)))); - if (deadPlayer == GHIDRA_CAST(0x0)) { - deadPlayer = Game::GetPlayer(g_game,0); - } - if (deadPlayer->_playerType == 0x28) { - deadPlayer = GHIDRA_CAST(deadPlayer->_twinPlayer); - } - KAGE_LogMessage(1,GHIDRA_CAST("Game Over. Killed by (%d.%d) spawned by (%d.%d) damage flags (%d)\n")); - layerId = (deadPlayer->_lastDamageSource)._type; - pEStack_84 = GHIDRA_CAST(0x0); - iVar7 = -1; - if ((((layerId == 0) || - (pEStack_84 = EntityConfig::GetEntity - (&g_manager->_entityConfig,layerId, - (deadPlayer->_lastDamageSource)._variant,0), - pEStack_84 == GHIDRA_CAST(0x0))) || (iVar7 = pEStack_84->portrait, iVar7 == -1)) && - (((layerId = (deadPlayer->_lastDamageSource)._spawnerType, layerId == 0 || - (pEStack_84 = EntityConfig::GetEntity - (&g_manager->_entityConfig,layerId, - (deadPlayer->_lastDamageSource)._spawnerVariant,0), - pEStack_84 == GHIDRA_CAST(0x0))) || (iVar7 = pEStack_84->portrait, iVar7 == -1)))) - { - layerId = (deadPlayer->_lastDamageSource)._type; - if (layerId == 4) { - iVar7 = 0x41; - } - else if ((layerId == 0) && ((deadPlayer->_lastDamageSource)._variant != 0)) { - layerId = (deadPlayer->_lastDamageSource)._variant; -LAB_00999b62: - if (layerId == 0x19) { - iVar7 = 0xca; - } - else if (layerId == 10000) { - iVar7 = 0xe5; - } - else if (layerId == 0x2711) { - iVar7 = 0xeb; - } - else if (layerId == 0x2712) { - iVar7 = 0xef; - } - else { - if (layerId != 0x2713) goto LAB_00999bb5; - iVar7 = 0xfd; - } - } - else { - if (((deadPlayer->_lastDamageSource)._spawnerType == 0) && - ((deadPlayer->_lastDamageSource)._spawnerVariant != 0)) { - if ((layerId != 0) || (layerId = (deadPlayer->_lastDamageSource)._variant, layerId == 0)) { - layerId = (deadPlayer->_lastDamageSource)._spawnerVariant; - } - goto LAB_00999b62; - } -LAB_00999bb5: - qVar1 = deadPlayer->_lastDamageFlags; - if ((qVar1 & 0x80) == 0) { - if ((qVar1 & 0x10000) == 0) { - if ((qVar1 & 0x200) == 0) { - if ((qVar1 & 0x1000) == 0) { - if ((qVar1 & 2) == 0) { - if ((qVar1 & 0x400) == 0) { - if ((qVar1 & 4) == 0) { - if ((qVar1 & 0x20000) == 0) { - if ((qVar1 & 0x40000) != 0) { - iVar7 = 0x72; - } - } - else { - iVar7 = 0x70; - } - } - else { - iVar7 = 0x41; - } - } - else { - iVar7 = 0x6e; - } - } - else { - iVar7 = 0x44; - } - } - else { - iVar7 = 0x71; - } - } - else { - iVar7 = 0x43; - } - } - else { - iVar7 = 0x75; - } - } - else { - iVar7 = 0x42; - } - } - if (pEStack_84 != GHIDRA_CAST(0x0)) goto LAB_00999c6f; -LAB_00999c79: - isBossKiller = false; - } - else { -LAB_00999c6f: - isBossKiller = true; - if (pEStack_84->isBoss == 0) goto LAB_00999c79; - } - game = g_game; - playerType = deadPlayer->_playerType; - if (iVar7 < 0) { - iVar7 = 0x95; - } - uStack_88 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_seedEffects))) + 0x4)))); - if (uStack_88 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("Error: Game Start Seed was not set.\n")); - uStack_88 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((game->_seedEffects))) + 0x4)))); - } - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0) && - ((1 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 1 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)))))) { - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((layerId + 0x3c)); - if ((layerId == 0) || ((layerId < 0 || (*GHIDRA_CAST((layerId + 0x1c)) <= layerId)))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x40)))) + layerId * 4)) = 0; - AnimationState::AdvanceLayerPosition - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),layerId,(float)(uStack_88 % 0xc)); - } - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0) && - ((2 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 2 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)))))) { - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((layerId + 0x40)); - if ((layerId == 0) || ((layerId < 0 || (*GHIDRA_CAST((layerId + 0x1c)) <= layerId)))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x40)))) + layerId * 4)) = 0; - AnimationState::AdvanceLayerPosition - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),layerId,(float)stageFrame); - } - if (((8 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x88))))) && (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0)) && - ((8 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 8 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)))))) { - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((layerId + 0x58)); - if (((layerId == 0) || (layerId < 0)) || (*GHIDRA_CAST((layerId + 0x1c)) <= layerId)) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x40)))) + layerId * 4)) = 0; - AnimationState::AdvanceLayerPosition - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),layerId,(float)stageFrame); - } - layer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),GHIDRA_CAST(0x3)); - layer->_visible = 0; - layer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),&DAT_00000005); - layer->_visible = 0; - if (isBossKiller) { - layer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),GHIDRA_CAST(0x3)); - layer->_visible = 1; - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) == 0) || - ((*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) < 4 && - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) < 4)))) goto LAB_00999f34; - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((layerId + 0x44)); - } - else { - layer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),&DAT_00000005); - layer->_visible = 1; - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) == 0) || - ((*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) < 6 && - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) < 6)))) goto LAB_00999f34; - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((layerId + 0x4c)); - } - if (((layerId == 0) || (layerId < 0)) || (*GHIDRA_CAST((layerId + 0x1c)) <= layerId)) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x40)))) + layerId * 4)) = 0; - AnimationState::AdvanceLayerPosition(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),layerId,(float)iVar7); -LAB_00999f34: - if (((pEStack_84 != GHIDRA_CAST(0x0)) && (pEStack_84->modEntry != (void *)0x0)) && - (pEStack_84->isPortraitModded != 0)) { - layer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),GHIDRA_CAST(0x3)); - layer->_visible = 0; - layer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))),&DAT_00000005); - layer->_visible = 0; - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0) && - ((5 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 5 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)))))) { - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((iVar7 + 0x4c)); - if ((iVar7 == 0) || ((layerId < 0 || (*GHIDRA_CAST((iVar7 + 0x1c)) <= layerId)))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x40)))) + layerId * 4)) = 0; - AnimationState::AdvanceLayerPosition(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),layerId,0.0); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x10)))) = pEStack_84; - } - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))) != 0) && - ((4 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 4 < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))) + 0x80)))))) { - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x3c)))); - layerId = *GHIDRA_CAST((iVar7 + 0x48)); - if ((iVar7 == 0) || ((layerId < 0 || (*GHIDRA_CAST((iVar7 + 0x1c)) <= layerId)))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x40)))) + layerId * 4)) = 0; - AnimationState::AdvanceLayerPosition - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x38)))),layerId,(float)playerType); - } - if (g_manager->_netplayManager != *GHIDRA_CAST((g_manager + 1))) { - online_vote_start(this,0,1); - } - if (g_manager->_netplayManager != *GHIDRA_CAST((g_manager + 1))) { - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))); - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))); - if (layerId != iVar7) { - do { - (GHIDRA_CAST((GHIDRA_CAST((layerId + 8)))))->msvc::string::_Tidy_deallocate(); - layerId = layerId + 0x38; - } while (layerId != iVar7); - layerId = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) = layerId; - pEStack_84 = GHIDRA_CAST(0x0); - layerId = GHIDRA_INT((g_game->_onlinePlayerStats)._end) - GHIDRA_INT((g_game->_onlinePlayerStats)._begin); - iVar7 = layerId >> 0x1f; - if (layerId / 0x68 + iVar7 != iVar7) { - uStack_88 = 0; - do { - game = g_game; - uStack_74 = 0; - uStack_5c = 0; - uStack_58 = 0xf; - pvStack_6c = (void *)0x0; - uStack_44 = 0; - uStack_54 = 0x3f800000; - uStack_50 = 0x3f800000; - uStack_4c = 0x3f800000; - uStack_48 = 0x3f800000; - uStack_40 = 1; - local_8 = 1; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) == *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0xc))))) { - msvc::vector<56byte>::_Emplace_reallocate(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))),&uStack_74); - game = g_game; - } - else { - FUN_008cb3a0(); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) + 0x38; - } - local_8 = 0xffffffff; - if (0xf < uStack_58) { - uVar6 = uStack_58 + 1; - pvVar5 = pvStack_6c; - if (0xfff < uVar6) { - pvVar5 = *(void **)(GHIDRA_CAST(pvStack_6c) + -4); - uVar6 = uStack_58 + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvStack_6c) + (-4 - GHIDRA_INT(pvVar5))))) goto LAB_009998fd; - } - operator_delete(pvVar5,uVar6); - game = g_game; - } - pvVar5 = (game->_onlinePlayerStats)._begin; - uVar3 = *GHIDRA_CAST((uStack_88 + 4 + GHIDRA_INT(pvVar5))); - iVar7 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))); - *GHIDRA_CAST((iVar7 + -0x38)) = *GHIDRA_CAST((uStack_88 + GHIDRA_INT(pvVar5))); - manager = g_manager; - *GHIDRA_CAST((iVar7 + -0x34)) = uVar3; - if (manager->_netplayManager == *GHIDRA_CAST((manager + 1))) { - PlayerManager::GetPlayerSlotFromController - (&game->_playerManager,*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) + -0x38))); - sprintf_s(playerLabel,0x10,GHIDRA_CAST("Player %d")); - pbVar4 = playerLabel; - do { - bVar2 = *pbVar4; - pbVar4 = pbVar4 + 1; - } while (bVar2 != 0); - uVar6 = GHIDRA_INT(pbVar4) - GHIDRA_INT((playerLabel + 1)); - pbVar4 = playerLabel; - } - else { - pbVar4 = user_profile_format_display_name - (*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) + -0x38)), - &manager->_font1_TeamMeatEx10,0x50); - nameEnd = pbVar4; - do { - bVar2 = *nameEnd; - nameEnd = nameEnd + 1; - } while (bVar2 != 0); - uVar6 = GHIDRA_INT(nameEnd) - GHIDRA_INT((pbVar4 + 1)); - } - (GHIDRA_CAST((GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) + -0x30)))))->msvc::string::assign(pbVar4,uVar6); - pEStack_84 = GHIDRA_CAST((GHIDRA_INT(pEStack_84) + 1)); - uStack_88 = uStack_88 + 0x68; - } while (pEStack_84 < - GHIDRA_UINT(((GHIDRA_INT((g_game->_onlinePlayerStats)._end) - - GHIDRA_INT((g_game->_onlinePlayerStats)._begin)) / 0x68))); - } - } - ExceptionList = local_10; - return; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 715892e..456d418 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -13170,32 +13170,6 @@ LAB_006d1556: return; } -// 00860ac0 -void NpcHelper::default_case_lua_callback(Entity_NPC *npc) -{ - int in_stack_00000004; - uint32_t uStack_40; - uint32_t luaState; - uint32_t callbackRef; - uint8_t *local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - puStack_c = &LAB_00b03ce0; - local_10 = ExceptionList; - uStack_40 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - local_14 = GHIDRA_CAST(&uStack_40); - ExceptionList = &local_10; - if ((**GHIDRA_CAST(g_luaEngine) & 1) != 0) { - local_8 = 0; - FUN_00872a20(&luaState,*GHIDRA_CAST((in_stack_00000004 + 0x28)),in_stack_00000004); - luaL_unref(luaState,0xfff0b9d8,callbackRef); - } - ExceptionList = local_10; - return; -} - // 009be990 uint32_t NpcHelper::big_horn_is_any_hole_busy() { diff --git a/generated-src/path_node.cpp b/generated-src/path_node.cpp deleted file mode 100644 index 4588589..0000000 --- a/generated-src/path_node.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "classes.h" - -// 007e48b0 -PathNode::PathNode(void *other) -{ - size_t srcBytes; - uint32_t uVar1; - void *buffer; - void *srcBegin; - - *GHIDRA_CAST(this) = *GHIDRA_CAST(other); - *GHIDRA_CAST((GHIDRA_CAST(this) + 4)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 4)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 8)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 0; - srcBegin = *(void **)(GHIDRA_CAST(other) + 8); - if (srcBegin != *(void **)(GHIDRA_CAST(other) + 0xc)) { - srcBytes = GHIDRA_INT(*(void **)(GHIDRA_CAST(other) + 0xc)) - GHIDRA_INT(srcBegin); - uVar1 = GHIDRA_INT(srcBytes) >> 2; - if (0x3fffffff < uVar1) { - /* WARNING: Subroutine does not return */ - FUN_0040cee0(); - } - uVar1 = uVar1 * 4; - buffer = msvc::_Allocate(uVar1); - *(void **)(GHIDRA_CAST(this) + 8) = buffer; - *(void **)(GHIDRA_CAST(this) + 0xc) = buffer; - *(void **)(GHIDRA_CAST(this) + 0x10) = (void *)(GHIDRA_INT(buffer) + uVar1); - buffer = *(void **)(GHIDRA_CAST(this) + 8); - memmove(buffer,srcBegin,srcBytes); - *(void **)(GHIDRA_CAST(this) + 0xc) = (void *)(uVar1 + GHIDRA_INT(buffer)); - } - return this; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 33ccc5e..adc6b56 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8398,9 +8398,6 @@ uint8_t FileSystem::open_disk_file(uint8_t *path, void **outFile) { generated_st uint8_t FileSystem::open_archive_file(uint8_t *path, void **outFile) { generated_stub("FileSystem::open_archive_file 00a17f40"); } void FrameQueue::setSize(int count) { generated_stub("FrameQueue::setSize 00aaa500"); } FriendEntry::~FriendEntry() { generated_stub("FriendEntry::~FriendEntry 008e1f30"); } -void GameOver::RenderItemSprite(int memberIndex) { generated_stub("GameOver::RenderItemSprite 008ebfb0"); } -void GameOver::Render() { generated_stub("GameOver::Render 00998880"); } -void GameOver::Show() { generated_stub("GameOver::Show 009997c0"); } void * GlitchedCollectibleGfx::constructor() { generated_stub("GlitchedCollectibleGfx::constructor 009dc6e0"); } void GlitchedItemSet::recalculate() { generated_stub("GlitchedItemSet::recalculate 009e0500"); } void HallucinationOverlay::Render(Vector *offset) { generated_stub("HallucinationOverlay::Render 00839550"); } @@ -9366,7 +9363,6 @@ Entity * NpcHelper::wormwood_spawn_splash(Entity_NPC *npc) { generated_stub("Npc uint8_t NpcHelper::is_target_valid(Entity *target) { generated_stub("NpcHelper::is_target_valid 006be7e0"); } void NpcHelper::ChampionDrop(Entity_NPC *npc) { generated_stub("NpcHelper::ChampionDrop 006bf120"); } void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } -void NpcHelper::default_case_lua_callback(Entity_NPC *npc) { generated_stub("NpcHelper::default_case_lua_callback 00860ac0"); } uint32_t NpcHelper::big_horn_is_any_hole_busy() { generated_stub("NpcHelper::big_horn_is_any_hole_busy 009be990"); } float * NpcHelper::hush_fly_shape_build(float *outPath, int shape, float radius) { generated_stub("NpcHelper::hush_fly_shape_build 009bfd40"); } void NpcHelper::path_point_at(void *path, Vector *outPoint, float share) { generated_stub("NpcHelper::path_point_at 009bffb0"); } @@ -9377,7 +9373,6 @@ void OnlineChat::broadcast_message(std_string *text) { generated_stub("OnlineCha uint8_t OnlineChat::is_key_repeating(int keyCode) { generated_stub("OnlineChat::is_key_repeating 0091ee00"); } void OnlineChat::apply_roll_command(std_string *message) { generated_stub("OnlineChat::apply_roll_command 0091f5d0"); } void OnlineChatMessage::constructor() { generated_stub("OnlineChatMessage::constructor 0091cec0"); } -PathNode::PathNode(void *other) { generated_stub("PathNode::PathNode 007e48b0"); } void PersistentGameDataReader::read(PersistentGameData *data) { generated_stub("PersistentGameDataReader::read 0091adf0"); } void * PersistentGameDataWriter::compress(uint32_t *outSize) { generated_stub("PersistentGameDataWriter::compress 0091acc0"); } void PersistentGameDataWriter::write(PersistentGameData *data, void *header) { generated_stub("PersistentGameDataWriter::write 0091b130"); } @@ -10367,7 +10362,6 @@ void NpcAI::ENTITY_MATRIARCH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MA void NpcAI::ENTITY_MEGA_SATAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEGA_SATAN 004c8090"); } void NpcAI::ENTITY_MEGA_SATAN_hand(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEGA_SATAN_hand 004cca10"); } void FUN_004cdce0() { generated_stub("FUN_004cdce0 004cdce0"); } -uint32_t FUN_004cdd30(uint32_t param_1, int param_2) { generated_stub("FUN_004cdd30 004cdd30"); } uint32_t FUN_004ce0f0() { generated_stub("FUN_004ce0f0 004ce0f0"); } void NpcAI::ENTITY_MINECART(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MINECART 004ce8a0"); } void FUN_004cf0f0(uint8_t param_1) { generated_stub("FUN_004cf0f0 004cf0f0"); } @@ -10421,7 +10415,6 @@ int FUN_004e4840() { generated_stub("FUN_004e4840 004e4840"); } void NpcAI::ENTITY_CANDLER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CANDLER 004e4970"); } void NpcAI::ENTITY_WHIPPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WHIPPER 004e5170"); } void NpcAI::ENTITY_GRUDGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GRUDGE 004e6570"); } -Entity * find_nearest_enemy(Vector *position, float *outDistance, uint8_t isFriendly) { generated_stub("find_nearest_enemy 004e7d10"); } uint32_t NpcAI::ENTITY_BISHOP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BISHOP 004e7ea0"); } uint8_t * NpcAI::ENTITY_BABY_BEGOTTEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY_BEGOTTEN 004e8380"); } void NpcAI::ENTITY_VIS_FATTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS_FATTY 004ea3d0"); } @@ -10463,7 +10456,6 @@ void NpcAI::ENTITY_DUSTY_DEATHS_HEAD(Entity_NPC *npc) { generated_stub("NpcAI::E void NpcAI::ENTITY_NECRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_NECRO 005052a0"); } void pow_wrapper() { generated_stub("pow_wrapper 00505b40"); } void set_byte_0x101(void *self, uint8_t value) { generated_stub("set_byte_0x101 00505b50"); } -float * _Entity_NPC::GetColorWithFlash(float *param_1) { generated_stub("_Entity_NPC::GetColorWithFlash 00505b80"); } int FUN_00505ca0() { generated_stub("FUN_00505ca0 00505ca0"); } uint32_t * FUN_00505ce0() { generated_stub("FUN_00505ce0 00505ce0"); } void NpcAI::ENTITY_STONE_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_STONE_EYE 00505d00"); } @@ -10976,7 +10968,6 @@ void FUN_0067ae30(int *param_1) { generated_stub("FUN_0067ae30 0067ae30"); } void FUN_0067af30() { generated_stub("FUN_0067af30 0067af30"); } void tear_flags_area_apply(Vector *position, Entity *source, float radius, float damage, BitSet128 flags) { generated_stub("tear_flags_area_apply 0067d430"); } uint32_t FUN_0067d9b0() { generated_stub("FUN_0067d9b0 0067d9b0"); } -void FUN_0067da40() { generated_stub("FUN_0067da40 0067da40"); } void FUN_0067dac0(int *param_1) { generated_stub("FUN_0067dac0 0067dac0"); } uint32_t * FUN_0067ef50(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_0067ef50 0067ef50"); } uint32_t FUN_0067efb0() { generated_stub("FUN_0067efb0 0067efb0"); } @@ -10984,7 +10975,6 @@ uint8_t FUN_0067efd0() { generated_stub("FUN_0067efd0 0067efd0"); } float random_float() { generated_stub("random_float 0067efe0"); } int Isaac::Random(int Max) { generated_stub("Isaac::Random 0067f010"); } uint32_t FUN_0067f030() { generated_stub("FUN_0067f030 0067f030"); } -Vector * RandomVector(Vector *out, uint32_t seed) { generated_stub("RandomVector 0067f0d0"); } Vector * Isaac::GetAxisAlignedUnitVectorFromDir(Vector *outVector, int direction) { generated_stub("Isaac::GetAxisAlignedUnitVectorFromDir 0067f1d0"); } void FUN_0067f2e0() { generated_stub("FUN_0067f2e0 0067f2e0"); } void * string_split(void *outTokens, std_string *text, uint8_t delimiter) { generated_stub("string_split 0067f420"); } @@ -11148,7 +11138,6 @@ void FUN_006a80d0() { generated_stub("FUN_006a80d0 006a80d0"); } void FUN_006a8180(uint32_t param_1) { generated_stub("FUN_006a8180 006a8180"); } void FUN_006a8210(int param_1) { generated_stub("FUN_006a8210 006a8210"); } uint32_t FUN_006ae7a0() { generated_stub("FUN_006ae7a0 006ae7a0"); } -void spawn_gibs(Vector *position, int amount, float spread, uint32_t *gibFlags, Entity *spawner, ColorMod *color, Vector *velocity, float scale) { generated_stub("spawn_gibs 006b31b0"); } void FUN_006b5de0() { generated_stub("FUN_006b5de0 006b5de0"); } void FUN_006b5f40() { generated_stub("FUN_006b5f40 006b5f40"); } void play_sound_with_fart_seed(int soundId, float volume, int frameDelay, uint8_t isLoop, float pitch) { generated_stub("play_sound_with_fart_seed 006b6470"); } @@ -11168,7 +11157,6 @@ Entity * spawn_gfuel_explosion() { generated_stub("spawn_gfuel_explosion 006b945 uint32_t _NpcHelper::spider_load_graphics(uint8_t *param_1) { generated_stub("_NpcHelper::spider_load_graphics 006baa70"); } void NpcAI::ENTITY_SHOPKEEPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SHOPKEEPER 006c2220"); } int FUN_006c4a90() { generated_stub("FUN_006c4a90 006c4a90"); } -void NpcAI::ENTITY_FIREPLACE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FIREPLACE 006d18d0"); } void FUN_006d6650() { generated_stub("FUN_006d6650 006d6650"); } void NpcAI::ENTITY_MOVABLE_TNT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOVABLE_TNT 006d6690"); } uint8_t is_local_player_owned(void *self) { generated_stub("is_local_player_owned 006d8e10"); } @@ -11421,7 +11409,6 @@ void FUN_00758bd0() { generated_stub("FUN_00758bd0 00758bd0"); } int FUN_00759260() { generated_stub("FUN_00759260 00759260"); } void FUN_0075d9f0(uint32_t param_1) { generated_stub("FUN_0075d9f0 0075d9f0"); } uint32_t FUN_0075ef20(ANM2 *param_1, int param_2) { generated_stub("FUN_0075ef20 0075ef20"); } -int FUN_0075f020(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_0075f020 0075f020"); } void FUN_00763290() { generated_stub("FUN_00763290 00763290"); } void FUN_00770640(float *param_1) { generated_stub("FUN_00770640 00770640"); } uint8_t is_trinket_unpickable_id(int trinketId) { generated_stub("is_trinket_unpickable_id 007716c0"); } @@ -11549,11 +11536,8 @@ void FUN_007e2fa0() { generated_stub("FUN_007e2fa0 007e2fa0"); } uint32_t * FUN_007e3060(uint32_t *param_1) { generated_stub("FUN_007e3060 007e3060"); } void FUN_007e3190() { generated_stub("FUN_007e3190 007e3190"); } void FUN_007e3230() { generated_stub("FUN_007e3230 007e3230"); } -void FUN_007e4860() { generated_stub("FUN_007e4860 007e4860"); } void FUN_007e4890() { generated_stub("FUN_007e4890 007e4890"); } uint8_t pathfinder_can_reach_pos(Vector *targetPos, Vector *startPos, Room *room) { generated_stub("pathfinder_can_reach_pos 007e7820"); } -uint32_t FUN_007e7fb0(uint32_t param_1) { generated_stub("FUN_007e7fb0 007e7fb0"); } -void FUN_007e85a0(uint32_t *param_1) { generated_stub("FUN_007e85a0 007e85a0"); } void FUN_007e8620() { generated_stub("FUN_007e8620 007e8620"); } void FUN_007e86e0(int param_1, int param_2) { generated_stub("FUN_007e86e0 007e86e0"); } void * vector_PathNode_emplace_reallocate_copy(void *self, void *where, void *value) { generated_stub("vector_PathNode_emplace_reallocate_copy 007e8810"); } @@ -11713,8 +11697,6 @@ uint8_t FUN_0085bd40(uint32_t param_1, int *param_2, int *param_3) { generated_s void FUN_0085be70() { generated_stub("FUN_0085be70 0085be70"); } void FUN_0085bf50(uint32_t param_1) { generated_stub("FUN_0085bf50 0085bf50"); } void FUN_0085bf90() { generated_stub("FUN_0085bf90 0085bf90"); } -void FUN_0085bfd0() { generated_stub("FUN_0085bfd0 0085bfd0"); } -void FUN_0085bff0() { generated_stub("FUN_0085bff0 0085bff0"); } void FUN_0085c010() { generated_stub("FUN_0085c010 0085c010"); } void FUN_0085c030() { generated_stub("FUN_0085c030 0085c030"); } void FUN_0085c050() { generated_stub("FUN_0085c050 0085c050"); } @@ -11722,7 +11704,6 @@ void FUN_0085c1d0() { generated_stub("FUN_0085c1d0 0085c1d0"); } int * FUN_0085c200() { generated_stub("FUN_0085c200 0085c200"); } void FUN_0085c210(uint8_t param_1) { generated_stub("FUN_0085c210 0085c210"); } void FUN_0085c250() { generated_stub("FUN_0085c250 0085c250"); } -void FUN_0085c270(uint32_t param_1) { generated_stub("FUN_0085c270 0085c270"); } bool FUN_0085c2d0() { generated_stub("FUN_0085c2d0 0085c2d0"); } bool FUN_0085c300() { generated_stub("FUN_0085c300 0085c300"); } bool FUN_0085c340() { generated_stub("FUN_0085c340 0085c340"); } @@ -11756,27 +11737,10 @@ uint32_t FUN_0085fcc0() { generated_stub("FUN_0085fcc0 0085fcc0"); } uint32_t FUN_0085fec0(uint32_t param_1) { generated_stub("FUN_0085fec0 0085fec0"); } uint32_t FUN_008601f0(uint32_t param_1) { generated_stub("FUN_008601f0 008601f0"); } uint32_t FUN_008603d0(uint32_t param_1) { generated_stub("FUN_008603d0 008603d0"); } -void FUN_008607a0() { generated_stub("FUN_008607a0 008607a0"); } -uint32_t Catch_00860826() { generated_stub("Catch_00860826 00860826"); } -void FUN_00860880(int param_1) { generated_stub("FUN_00860880 00860880"); } -uint32_t Catch_0086090e() { generated_stub("Catch_0086090e 0086090e"); } -bool FUN_00860960(int param_1) { generated_stub("FUN_00860960 00860960"); } -uint32_t Catch_00860a70() { generated_stub("Catch_00860a70 00860a70"); } -uint32_t Catch_00860b4b() { generated_stub("Catch_00860b4b 00860b4b"); } -void FUN_00860ba0(int param_1, uint32_t *param_2) { generated_stub("FUN_00860ba0 00860ba0"); } -uint32_t Catch_00860c36() { generated_stub("Catch_00860c36 00860c36"); } -void FUN_00860c90(int param_1) { generated_stub("FUN_00860c90 00860c90"); } -uint32_t Catch_00860d1e() { generated_stub("Catch_00860d1e 00860d1e"); } void FUN_00860f00(int param_1) { generated_stub("FUN_00860f00 00860f00"); } uint32_t Catch_00860f8b() { generated_stub("Catch_00860f8b 00860f8b"); } void FUN_00860fe0(int param_1, uint32_t *param_2) { generated_stub("FUN_00860fe0 00860fe0"); } uint32_t Catch_00861076() { generated_stub("Catch_00861076 00861076"); } -void FUN_00861330(int param_1) { generated_stub("FUN_00861330 00861330"); } -uint32_t Catch_008613bf() { generated_stub("Catch_008613bf 008613bf"); } -void FUN_00861410(int param_1) { generated_stub("FUN_00861410 00861410"); } -uint32_t Catch_0086149f() { generated_stub("Catch_0086149f 0086149f"); } -void FUN_008614f0(int param_1, uint32_t *param_2) { generated_stub("FUN_008614f0 008614f0"); } -uint32_t Catch_00861587() { generated_stub("Catch_00861587 00861587"); } void FUN_008615e0(int param_1) { generated_stub("FUN_008615e0 008615e0"); } uint32_t Catch_0086166f() { generated_stub("Catch_0086166f 0086166f"); } void FUN_008616c0(int param_1) { generated_stub("FUN_008616c0 008616c0"); } @@ -11803,21 +11767,8 @@ void FUN_00862590(int param_1) { generated_stub("FUN_00862590 00862590"); } uint32_t Catch_0086261f() { generated_stub("Catch_0086261f 0086261f"); } void FUN_00862670(int param_1, uint32_t *param_2) { generated_stub("FUN_00862670 00862670"); } uint32_t Catch_00862707() { generated_stub("Catch_00862707 00862707"); } -void FUN_008629c0(int param_1) { generated_stub("FUN_008629c0 008629c0"); } -uint32_t Catch_00862a4c() { generated_stub("Catch_00862a4c 00862a4c"); } -void FUN_00862aa0(int param_1) { generated_stub("FUN_00862aa0 00862aa0"); } -uint32_t Catch_00862b2f() { generated_stub("Catch_00862b2f 00862b2f"); } -void FUN_00862b80(uint32_t param_1, uint32_t *param_2) { generated_stub("FUN_00862b80 00862b80"); } -uint32_t Catch_00862cb8() { generated_stub("Catch_00862cb8 00862cb8"); } void FUN_00862d0a() { generated_stub("FUN_00862d0a 00862d0a"); } void FUN_00862d53() { generated_stub("FUN_00862d53 00862d53"); } -void FUN_00862f00(int param_1) { generated_stub("FUN_00862f00 00862f00"); } -uint32_t Catch_00862f8c() { generated_stub("Catch_00862f8c 00862f8c"); } -void FUN_00862fe0(int param_1) { generated_stub("FUN_00862fe0 00862fe0"); } -uint32_t Catch_0086306c() { generated_stub("Catch_0086306c 0086306c"); } -void FUN_008630c0(int param_1, uint32_t *param_2) { generated_stub("FUN_008630c0 008630c0"); } -uint32_t Catch_00863154() { generated_stub("Catch_00863154 00863154"); } -uint32_t Catch_0086354b() { generated_stub("Catch_0086354b 0086354b"); } void FUN_008635a0(int param_1) { generated_stub("FUN_008635a0 008635a0"); } uint32_t Catch_0086362b() { generated_stub("Catch_0086362b 0086362b"); } uint32_t Catch_00863879() { generated_stub("Catch_00863879 00863879"); } @@ -11825,42 +11776,21 @@ void FUN_00863be0(int param_1) { generated_stub("FUN_00863be0 00863be0"); } uint32_t Catch_00863c6e() { generated_stub("Catch_00863c6e 00863c6e"); } void FUN_00863cc0(uint32_t param_1, uint32_t param_2, uint32_t param_3) { generated_stub("FUN_00863cc0 00863cc0"); } uint32_t Catch_00863d4e() { generated_stub("Catch_00863d4e 00863d4e"); } -void lua_callback_run_post_fire_tear(uint32_t param_1) { generated_stub("lua_callback_run_post_fire_tear 00863f70"); } -uint32_t Catch_00863fff() { generated_stub("Catch_00863fff 00863fff"); } void FUN_00864130(int param_1) { generated_stub("FUN_00864130 00864130"); } uint32_t Catch_008641bb() { generated_stub("Catch_008641bb 008641bb"); } void FUN_00864210(int param_1, uint32_t *param_2) { generated_stub("FUN_00864210 00864210"); } uint32_t Catch_008642a4() { generated_stub("Catch_008642a4 008642a4"); } uint32_t Catch_00864682() { generated_stub("Catch_00864682 00864682"); } -uint8_t * Catch_00864a6a() { generated_stub("Catch_00864a6a 00864a6a"); } -uint32_t FUN_00864ae0(uint32_t param_1) { generated_stub("FUN_00864ae0 00864ae0"); } -uint8_t * Catch_00864bb8() { generated_stub("Catch_00864bb8 00864bb8"); } -uint8_t lua_run_input_action_callback(Entity *entity, int hook, int action, uint8_t *outValue) { generated_stub("lua_run_input_action_callback 00864c30"); } -uint8_t * Catch_00864d16() { generated_stub("Catch_00864d16 00864d16"); } uint8_t FUN_00864d80(uint32_t param_1, uint32_t param_2, uint32_t param_3, float *param_4) { generated_stub("FUN_00864d80 00864d80"); } uint8_t * Catch_00864e6d() { generated_stub("Catch_00864e6d 00864e6d"); } void FUN_00864fc0(uint32_t param_1) { generated_stub("FUN_00864fc0 00864fc0"); } uint32_t Catch_0086504e() { generated_stub("Catch_0086504e 0086504e"); } void FUN_008650a0(uint32_t param_1) { generated_stub("FUN_008650a0 008650a0"); } uint32_t Catch_0086512e() { generated_stub("Catch_0086512e 0086512e"); } -uint32_t Catch_00865209() { generated_stub("Catch_00865209 00865209"); } -uint32_t Catch_008652e9() { generated_stub("Catch_008652e9 008652e9"); } -int lua_callback_run_get_card(RNG *rng, int card, uint8_t isPlaying, uint8_t isRunes, uint8_t isOnlyRunes) { generated_stub("lua_callback_run_get_card 00865340"); } -uint8_t * Catch_00865424() { generated_stub("Catch_00865424 00865424"); } uint8_t * Catch_008655b7() { generated_stub("Catch_008655b7 008655b7"); } char * FUN_00865660(char *param_1, uint32_t *param_2) { generated_stub("FUN_00865660 00865660"); } -uint32_t FUN_008658c0(uint32_t param_1, uint32_t *param_2) { generated_stub("FUN_008658c0 008658c0"); } -uint8_t * Catch_008659a7() { generated_stub("Catch_008659a7 008659a7"); } -uint32_t FUN_00865a04() { generated_stub("FUN_00865a04 00865a04"); } void FUN_00865aad() { generated_stub("FUN_00865aad 00865aad"); } void FUN_00865c61() { generated_stub("FUN_00865c61 00865c61"); } -uint32_t FUN_00865c80(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_00865c80 00865c80"); } -uint8_t * Catch_00865d53() { generated_stub("Catch_00865d53 00865d53"); } -uint32_t FUN_00865dc0(uint32_t param_1, uint32_t param_2, uint32_t param_3) { generated_stub("FUN_00865dc0 00865dc0"); } -uint8_t * Catch_00865e99() { generated_stub("Catch_00865e99 00865e99"); } -uint32_t FUN_00865f10(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4) { generated_stub("FUN_00865f10 00865f10"); } -uint8_t * Catch_00865fe8() { generated_stub("Catch_00865fe8 00865fe8"); } -uint32_t Catch_008660ec() { generated_stub("Catch_008660ec 008660ec"); } uint32_t FUN_00866220(uint32_t *param_1, uint32_t *param_2) { generated_stub("FUN_00866220 00866220"); } uint32_t Catch_00866364() { generated_stub("Catch_00866364 00866364"); } uint8_t FUN_008663b6() { generated_stub("FUN_008663b6 008663b6"); } @@ -11938,18 +11868,14 @@ void FUN_00872780(void *param_1) { generated_stub("FUN_00872780 00872780"); } bool FUN_00872820() { generated_stub("FUN_00872820 00872820"); } char * FUN_00872860(char *param_1) { generated_stub("FUN_00872860 00872860"); } void FUN_00872a0c() { generated_stub("FUN_00872a0c 00872a0c"); } -uint32_t * FUN_00872a20(uint32_t *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00872a20 00872a20"); } void FUN_00872af1() { generated_stub("FUN_00872af1 00872af1"); } -int * FUN_00872b10(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5) { generated_stub("FUN_00872b10 00872b10"); } void FUN_00872c43() { generated_stub("FUN_00872c43 00872c43"); } void FUN_00872d80() { generated_stub("FUN_00872d80 00872d80"); } uint32_t * FUN_00872da0(uint32_t *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00872da0 00872da0"); } void FUN_00872e71() { generated_stub("FUN_00872e71 00872e71"); } int * FUN_00872e90(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5) { generated_stub("FUN_00872e90 00872e90"); } void FUN_00872fc3() { generated_stub("FUN_00872fc3 00872fc3"); } -uint32_t * FUN_00872ff0(uint32_t *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00872ff0 00872ff0"); } void FUN_008730c1() { generated_stub("FUN_008730c1 008730c1"); } -int * FUN_008730e0(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5) { generated_stub("FUN_008730e0 008730e0"); } void FUN_00873213() { generated_stub("FUN_00873213 00873213"); } uint32_t * FUN_00873230(uint32_t *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00873230 00873230"); } void FUN_00873301() { generated_stub("FUN_00873301 00873301"); } @@ -11962,15 +11888,11 @@ uint32_t * FUN_00873650(uint32_t *param_1, uint32_t param_2, int param_3) { gene void FUN_00873721() { generated_stub("FUN_00873721 00873721"); } int * FUN_00873740(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5) { generated_stub("FUN_00873740 00873740"); } void FUN_00873873() { generated_stub("FUN_00873873 00873873"); } -uint32_t * FUN_00873890(uint32_t *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00873890 00873890"); } void FUN_00873961() { generated_stub("FUN_00873961 00873961"); } void FUN_00873aa0() { generated_stub("FUN_00873aa0 00873aa0"); } -uint32_t * FUN_00873ac0(uint32_t *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00873ac0 00873ac0"); } void FUN_00873b91() { generated_stub("FUN_00873b91 00873b91"); } -int * FUN_00873bb0(int *param_1, uint32_t param_2, int param_3, uint32_t param_4, uint32_t param_5) { generated_stub("FUN_00873bb0 00873bb0"); } void FUN_00873ce3() { generated_stub("FUN_00873ce3 00873ce3"); } void FUN_00873e20() { generated_stub("FUN_00873e20 00873e20"); } -int * FUN_00873e40(int *param_1, uint32_t param_2, int param_3, uint32_t param_4) { generated_stub("FUN_00873e40 00873e40"); } void FUN_00873f26() { generated_stub("FUN_00873f26 00873f26"); } void FUN_00874103() { generated_stub("FUN_00874103 00874103"); } void FUN_008741f1() { generated_stub("FUN_008741f1 008741f1"); } @@ -11981,20 +11903,14 @@ void FUN_00874533() { generated_stub("FUN_00874533 00874533"); } int * FUN_00874550(int *param_1, uint32_t param_2, int param_3, float param_4, uint32_t param_5, uint32_t param_6, int param_7) { generated_stub("FUN_00874550 00874550"); } void FUN_0087469a() { generated_stub("FUN_0087469a 0087469a"); } void FUN_00874846() { generated_stub("FUN_00874846 00874846"); } -uint32_t * FUN_00874860(uint32_t *param_1) { generated_stub("FUN_00874860 00874860"); } void FUN_008748f6() { generated_stub("FUN_008748f6 008748f6"); } -int * LuaCallbackCaller::CallInputAction(int *param_1, uint32_t param_2, int param_3, int param_4) { generated_stub("LuaCallbackCaller::CallInputAction 00874910"); } void FUN_008749f7() { generated_stub("FUN_008749f7 008749f7"); } void FUN_00874aa8() { generated_stub("FUN_00874aa8 00874aa8"); } -int * FUN_00874ac0(int *param_1, uint32_t param_2, int param_3, int param_4, uint8_t param_5, uint8_t param_6, uint8_t param_7) { generated_stub("FUN_00874ac0 00874ac0"); } void FUN_00874bbb() { generated_stub("FUN_00874bbb 00874bbb"); } uint32_t * FUN_00874bd0(uint32_t *param_1, uint32_t param_2, void *param_3) { generated_stub("FUN_00874bd0 00874bd0"); } void FUN_00874d0a() { generated_stub("FUN_00874d0a 00874d0a"); } -uint32_t * FUN_00874d20(uint32_t *param_1) { generated_stub("FUN_00874d20 00874d20"); } void FUN_00874db6() { generated_stub("FUN_00874db6 00874db6"); } -uint32_t * FUN_00874dd0(uint32_t *param_1, uint32_t param_2, int param_3, uint8_t param_4) { generated_stub("FUN_00874dd0 00874dd0"); } void FUN_00874e7e() { generated_stub("FUN_00874e7e 00874e7e"); } -uint32_t * FUN_00874e90(uint32_t *param_1, uint32_t param_2, int param_3, int param_4, uint8_t param_5) { generated_stub("FUN_00874e90 00874e90"); } void FUN_00874f4a() { generated_stub("FUN_00874f4a 00874f4a"); } uint32_t * FUN_00875050(uint32_t *param_1, uint32_t param_2, uint32_t param_3, uint16_t param_4, uint16_t param_5, uint32_t param_6) { generated_stub("FUN_00875050 00875050"); } void FUN_00875116() { generated_stub("FUN_00875116 00875116"); } @@ -14063,7 +13979,6 @@ uint8_t * FUN_009587e0(StringTable *param_1, uint8_t *param_2, uint8_t *param_3) uint8_t * FUN_00958840(StringTable *param_1, uint8_t *param_2, int param_3, uint8_t *param_4) { generated_stub("FUN_00958840 00958840"); } void save_rerun_to_steam_cloud() { generated_stub("save_rerun_to_steam_cloud 00959180"); } void FUN_00959500() { generated_stub("FUN_00959500 00959500"); } -void persistent_game_data_set_writable() { generated_stub("persistent_game_data_set_writable 0095a680"); } void unlock_completion_mark_for_player_type(int markIndex, int playerType, int difficulty) { generated_stub("unlock_completion_mark_for_player_type 0095aa30"); } void render_online_icon(int frame, Vector position, float scaleX, float scaleY) { generated_stub("render_online_icon 0095ae60"); } void FUN_0095be60(int param_1, int param_2) { generated_stub("FUN_0095be60 0095be60"); } @@ -14173,14 +14088,11 @@ void Catch_All_009c7256() { generated_stub("Catch_All_009c7256 009c7256"); } char * FUN_009c7280(void *param_1, void *param_2, char *param_3) { generated_stub("FUN_009c7280 009c7280"); } void FUN_009c7320() { generated_stub("FUN_009c7320 009c7320"); } void FUN_009c7340() { generated_stub("FUN_009c7340 009c7340"); } -uint8_t is_valid_item_config_id(int itemKind, int id) { generated_stub("is_valid_item_config_id 009c7350"); } void FUN_009c7750() { generated_stub("FUN_009c7750 009c7750"); } void FUN_009c7780() { generated_stub("FUN_009c7780 009c7780"); } void FUN_009c77f0() { generated_stub("FUN_009c77f0 009c77f0"); } -void GameStateReader::read_bool_vector(void *reader, void *bits, uint32_t minSize) { generated_stub("GameStateReader::read_bool_vector 009c84c0"); } void FUN_009cad40() { generated_stub("FUN_009cad40 009cad40"); } uint32_t FUN_009caea0() { generated_stub("FUN_009caea0 009caea0"); } -uint8_t read_entity_save_state_tree(void *saveState, void *stream) { generated_stub("read_entity_save_state_tree 009cb020"); } uint32_t Catch_All_009cc16c() { generated_stub("Catch_All_009cc16c 009cc16c"); } uint32_t Catch_All_009cc172() { generated_stub("Catch_All_009cc172 009cc172"); } uint32_t FUN_009ce5a0() { generated_stub("FUN_009ce5a0 009ce5a0"); } @@ -14192,9 +14104,7 @@ uint8_t * Catch_All_009d2bd4() { generated_stub("Catch_All_009d2bd4 009d2bd4"); uint32_t Catch_All_009d396e() { generated_stub("Catch_All_009d396e 009d396e"); } uint8_t FUN_009d459a() { generated_stub("FUN_009d459a 009d459a"); } void FUN_009d8470(uint16_t *param_1) { generated_stub("FUN_009d8470 009d8470"); } -void FUN_009d84a0(uint32_t *param_1) { generated_stub("FUN_009d84a0 009d84a0"); } void FUN_009d8550(uint8_t *param_1) { generated_stub("FUN_009d8550 009d8550"); } -void GameStateReader::read_int_vector(void *reader, int *values) { generated_stub("GameStateReader::read_int_vector 009d8580"); } void FUN_009d8820(uint32_t *param_1, int param_2) { generated_stub("FUN_009d8820 009d8820"); } void FUN_009d88a0(uint32_t param_1) { generated_stub("FUN_009d88a0 009d88a0"); } void FUN_009d8a20(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_009d8a20 009d8a20"); } diff --git a/src/console.cpp b/src/console.cpp index a4c0f41..30f8bc4 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -4,6 +4,7 @@ #include "game.h" #include "kage_graphics.h" #include "kage_input.h" +#include "lua_engine.h" #include "manager.h" #include "menu_manager.h" #include "platform.h" @@ -51,7 +52,6 @@ constexpr size_t HISTORY_LOAD_MAX = 64; constexpr int INPUT_HOOK_TRIGGERED = 1; constexpr int ACTION_CONSOLE = 33; constexpr int COLLECTIBLE_GLITCHED_CROWN = 689; -constexpr unsigned int PICKUP_COLLECTIBLE = 100; constexpr int SLIDE_FRAMES = 14; constexpr int BLINK_FRAMES = 30; @@ -127,11 +127,11 @@ static bool is_key(int key, ActionTest test) // Whether the console key was pressed: in a game a mod's input callback for it may decide, else the ` key does. static bool is_open_pressed() { - uint8_t isPressed = 0; - bool isModDecided = g_manager->state == MANAGER_STATE_GAME && g_luaEngine && - lua_run_input_action_callback(nullptr, INPUT_HOOK_TRIGGERED, ACTION_CONSOLE, &isPressed); + std::optional isModPressed; + if (g_manager->state == MANAGER_STATE_GAME && g_luaEngine) + isModPressed = lua_engine_get().InputAction(nullptr, INPUT_HOOK_TRIGGERED, ACTION_CONSOLE); - return isModDecided ? isPressed : is_key(KEY_GRAVE_ACCENT, ACTION_TRIGGERED); + return isModPressed ? *isModPressed : is_key(KEY_GRAVE_ACCENT, ACTION_TRIGGERED); } // A 0xAARRGGBB color's channels with another alpha. diff --git a/src/entity.cpp b/src/entity.cpp index d9ac440..6b45bad 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -82,18 +82,7 @@ constexpr int HIT_FLASH_DIVISOR = 3; constexpr int HIT_FLASH_MIN = 1; constexpr int HIT_FLASH_MAX = 6; constexpr int SOUND_FIREDEATH_HISS = 43; -constexpr int COLLECTIBLE_BLACK_POWDER = 420; constexpr float POSITION_LIMIT = 10000; -// The extra fire Black Powder makes a fireplace burst with. -constexpr int FIREPLACE_NORMAL = 0; -constexpr int FIREPLACE_RED = 1; -constexpr int FIREPLACE_MOVEABLE = 10; -// The Lua callback a removal runs (MC_POST_ENTITY_REMOVE). -constexpr int LUA_CALLBACK_POST_ENTITY_REMOVE = 67; -// The online stats a kill counts toward (kills, boss kills, and kills as a co-op ghost). -constexpr uint32_t STAT_KILLS = 17; -constexpr uint32_t STAT_BOSS_KILLS = 20; -constexpr uint32_t STAT_GHOST_BOSS_KILLS = 21; // The debug flags PostRender draws for: entity positions, collision shapes and grid collision points. constexpr uint32_t DEBUG_ENTITY_POSITIONS = 1 << 0; constexpr uint32_t DEBUG_HITSPHERES = 1 << 5; @@ -1164,35 +1153,6 @@ bool Entity::IsValidTarget(Entity* other) return type != ENTITY_RING_OF_FLIES || other->type != ENTITY_RING_OF_FLIES; } -// 006ac920 Kills it once: counts the kill for the player behind the source, bursts it, and runs the Lua callback. -void Entity::Kill(const EntityRef& source) -{ - if (isDead) return; - isDead = true; - - Entity* killer = source.entity ? source.entity->GetPlayerAncestor() : nullptr; - bool isScored = type > ENTITY_PROJECTILE && type != ENTITY_EFFECT; - if (killer && type == ENTITY_FIREPLACE) - { - bool isPowderable = variant == FIREPLACE_NORMAL || variant == FIREPLACE_RED || variant == FIREPLACE_MOVEABLE; - if (static_cast(killer)->HasCollectible(COLLECTIBLE_BLACK_POWDER) && - isPowderable) - reconstruction_missing("Entity::Kill 006ac920: Black Powder's fireplace blast (BombExplosionEffects)"); - } - else if (killer && isScored) - { - Entity_Player* player = static_cast(killer); - Player_stats_add(&g_game->onlinePlayerStats, STAT_KILLS, player, 1); - if (IsBoss()) - { - Player_stats_add(&g_game->onlinePlayerStats, STAT_BOSS_KILLS, player, 1); - if (player->isCoopGhost) Player_stats_add(&g_game->onlinePlayerStats, STAT_GHOST_BOSS_KILLS, player, 1); - } - } - if (!IsBoss() && type != ENTITY_FAMILIAR) BloodExplode(); - static_cast(g_luaEngine)->PostEntityKill(this); -} - // 006acb00 Takes it out of the game: it stops existing and counts as dead, and Lua forgets it. void Entity::Remove() { @@ -1226,11 +1186,9 @@ void Entity::ClearReferences() } // 00866060 Runs MC_POST_ENTITY_REMOVE for it, which also lets Lua forget it. -void Entity::ReleaseLuaRef(Entity*) +void Entity::ReleaseLuaRef(Entity* entity) { - LuaEngine& lua = *static_cast(g_luaEngine); - if (lua.enabledCallbacks[LUA_CALLBACK_POST_ENTITY_REMOVE]) - reconstruction_missing("Entity::ReleaseLuaRef 00866060: MC_POST_ENTITY_REMOVE"); + lua_engine_get().PostEntityRemove(entity); } // 006b6af0 Where its sprite's null layer sits from its position, scaled, flipped and turned with the sprite, or zero @@ -1284,12 +1242,6 @@ void Entity::convert_shot_for_enemy_owner(Entity*) reconstruction_missing("Entity::convert_shot_for_enemy_owner 0064bb70"); } -// 006ace60 -bool Entity::TakeDamage(float, uint64_t, const EntityRef&, int) -{ - reconstruction_missing("Entity::TakeDamage 006ace60"); -} - // 006ad350 int Entity::apply_second_hand_duration(int, const EntityRef&) { @@ -1356,12 +1308,6 @@ void Entity::RemoveStatusEffects() reconstruction_missing("Entity::RemoveStatusEffects 006ae630"); } -// 006b45c0 -void Entity::BloodExplode() -{ - reconstruction_missing("Entity::BloodExplode 006b45c0"); -} - // 006b5c10 void Entity::AddShrink(const EntityRef&, int, bool) { diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp new file mode 100644 index 0000000..83645e9 --- /dev/null +++ b/src/entity_combat.cpp @@ -0,0 +1,1181 @@ +#include "entity_combat.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_list.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "fx_layers.h" +#include "game.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "platform.h" +#include "room.h" +#include "room_render.h" +#include "sfx_manager.h" +#include +#include +#include +#include + +constexpr float HALF_F = 0.5f; + +// The entities the combat code tells apart (Lua's EntityType). +constexpr int ENTITY_POOTER = 14; +constexpr int ENTITY_ATTACKFLY = 18; +constexpr int ENTITY_SINS_FIRST = 46; +constexpr int ENTITY_SINS_LAST = 52; +constexpr int ENTITY_SUCKER = 61; +constexpr int ENTITY_KNIGHT = 41; +constexpr int ENTITY_SELFLESS_KNIGHT = 254; +constexpr int ENTITY_FLOATING_KNIGHT = 283; +constexpr int ENTITY_CHARGER = 23; +constexpr int ENTITY_IGNORED_BY_TEARS = 291; +constexpr int ENTITY_BIG_HORN = 411; +constexpr int ENTITY_DELIRIUM = 412; +constexpr int ENTITY_BISHOP = 805; +constexpr int ENTITY_REFLECTING_ENEMY = 822; +constexpr int ENTITY_SHIELDED_SPAWN = 832; +constexpr int ENTITY_SHIELDED_PART = 889; +constexpr int ENTITY_FACING_SHIELD = 903; +constexpr int ENTITY_SHIELD_SPAWNER = 905; +constexpr int ENTITY_CHAOS_REMOVED = 907; +constexpr int ENTITY_SHIELD_PARENT = 921; +constexpr int ENTITY_DOGMA = 950; +constexpr int ENTITY_SCOURGE_TYPE = 830; +constexpr int ENTITY_GURDY = 36; +constexpr int ENTITY_SATAN = 84; +constexpr int SUCKER_BULB = 5; +constexpr int SCOURGE_BONE_VARIANT = 10; +constexpr int CHARGER_MY_SHADOW = 3; +constexpr int FACING_SHIELD_VARIANT = 1; +constexpr float DIAGONAL = 0.70710677f; +constexpr int FIREPLACE_NORMAL = 0; +constexpr int FIREPLACE_RED = 1; +constexpr int FIREPLACE_MOVEABLE = 10; +constexpr int FIREPLACE_VARIANT_LAST = 10; +constexpr int FAMILIAR_INCUBUS = 80; +constexpr int FAMILIAR_TEAR_DEFLECTOR = 239; +constexpr int BEAST_BACKGROUND_FIRST = 102; +constexpr int BEAST_BACKGROUND_COUNT = 3; +constexpr int BEAST_CHEER_MIN = 2; +constexpr uint32_t BEAST_CHEER_RANGE = 15; + +// The obstacles a spectral or piercing tear treats as solid (Entity 006ac660): a lit fireplace, movable TNT, poop and +// the stone enemies. +constexpr std::array STATIC_OBSTACLE_TYPES = {292, 245, 302, 42, 201, 203, 235}; +constexpr int STATIC_OBSTACLE_EXTRA = 202; + +// The items, trinkets and player kinds the combat code reads (Lua's ids). +constexpr int COLLECTIBLE_VIRUS = 13; +constexpr int COLLECTIBLE_MOMS_HEELS = 30; +constexpr int COLLECTIBLE_THE_NAIL = 83; +constexpr int COLLECTIBLE_MULLIGAN = 151; +constexpr int COLLECTIBLE_MIDAS_TOUCH = 202; +constexpr int COLLECTIBLE_INFAMY = 242; +constexpr int COLLECTIBLE_ISAACS_HEART = 276; +constexpr int COLLECTIBLE_ARIES = 300; +constexpr int COLLECTIBLE_BREATH_OF_LIFE = 326; +constexpr int COLLECTIBLE_DEAD_EYE = 373; +constexpr int COLLECTIBLE_SERPENTS_KISS = 393; +constexpr int COLLECTIBLE_BLACK_POWDER = 420; +constexpr int COLLECTIBLE_LITTLE_HORN = 503; +constexpr int COLLECTIBLE_RECALL = 714; +constexpr int NULLITEM_TOOTH_AND_NAIL = 59; +constexpr int PLAYER_FORM_GUPPY = 0; +constexpr int PLAYER_FORM_COUNT_NEEDED = 3; +constexpr int BABY_CROW = 12; +constexpr int BLUE_FLY_MAX = 30; +constexpr int MAGGY_SWING_READY = 3; + +// Lua's DamageFlag bits beyond entity.h's. +constexpr uint64_t DAMAGE_COUNTDOWN = 1ull << 6; +constexpr uint64_t DAMAGE_INVINCIBLE = 1ull << 13; +constexpr uint64_t DAMAGE_SPAWN_FLY = 1ull << 14; +constexpr uint64_t DAMAGE_BOOGER = 1ull << 22; +constexpr uint64_t DAMAGE_CRUSH = 1ull << 24; +constexpr uint64_t DAMAGE_THROUGH_COOLDOWN = 1ull << 35; + +// The effects the combat code spawns (Lua's EffectVariant). +constexpr int EFFECT_ROCK_PARTICLE = 4; +constexpr int EFFECT_BLOOD_PARTICLE = 5; +constexpr int EFFECT_BLOOD_SPLAT = 7; +constexpr int EFFECT_TOOTH_PARTICLE = 35; +constexpr int EFFECT_POOP_PARTICLE = 58; +constexpr int EFFECT_DUST_CLOUD = 59; +constexpr int EFFECT_WORM = 63; +constexpr int EFFECT_BRIMSTONE_BALL = 113; +constexpr int EFFECT_BISHOP_SHIELD = 160; +constexpr int EFFECT_CHAIN_GIB = 163; +constexpr int ROCK_PARTICLE_SUBTYPE = 0x10001; + +// The sounds the combat code plays (Lua's SoundEffect). +constexpr int SOUND_DEATH_BURST_BONE = 27; +constexpr int SOUND_DEATH_BURST_LARGE = 28; +constexpr int SOUND_DEATH_BURST_SMALL = 30; +constexpr int SOUND_ROCK_CRUMBLE = 137; +constexpr int SOUND_ROCKET_BLAST_DEATH = 141; +constexpr int SOUND_GOODEATH = 207; +constexpr int SOUND_BONE_BREAK = 500; +constexpr int SOUND_BISHOP_HIT = 501; +constexpr int SOUND_CHAIN_BREAK = 504; +constexpr int BISHOP_HIT_DELAY = 10; +constexpr float SOUND_LARGE_VOLUME = 1.25f; +constexpr float SOUND_BABY_VOLUME = 1.8f; +constexpr float SOUND_SMALL_VOLUME = 0.8f; + +// Entity::TakeDamage: a fire hit's cooldown, the share of a boss's hits co-op lets through, and the Bishop's shield. +constexpr int FIRE_DAMAGE_COOLDOWN = 10; +constexpr float COOP_BOSS_DAMAGE = 0.8f; +constexpr float BISHOP_SHIELD_HEIGHT = -24; +constexpr float BISHOP_SHIELD_NULL_Y = 4; +constexpr float NULL_OFFSET_SCALE = 0.5f / 0.65f; + +// Entity_Tear::HandleCollision: the hit countdown, the tears' push, the bounce of a just fired tear off a bomb, and +// the burning tear's explosion chance from luck. +constexpr int TEAR_HIT_COUNTDOWN = 30; +constexpr float TEAR_PUSH_MIN_DISTANCE = 0.0001f; +constexpr float TEAR_DEFLECTOR_MASS_SCALE = 0.1f; +constexpr int BOMB_GRACE_FRAMES = 3; +constexpr float FLY_PUSH = 0.5f; +constexpr int BURN_EXPLODE_CHANCE = 10; +constexpr float BURN_EXPLODE_LUCK = 0.7f; +constexpr float TEAR_HIT_MOVE = 0.8f; +constexpr uint32_t TEAR_BOUNCE_PIERCE_MASK = 3; +constexpr int INFAMY_CHANCE = 2; +constexpr int INFAMY_CHANCE_VERSUS = 4; +constexpr int INFAMY_FLASH_FRAMES = 15; +constexpr int COLOR_PRIORITY_TOP = 255; +constexpr ColorMod INFAMY_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {64 / 255.0f, 64 / 255.0f, 128 / 255.0f}}; +constexpr float MULLIGAN_FLY_CHANCE = 0.166f; +constexpr float GUPPY_FLY_CHANCE = 0.66f; +constexpr float LASTING_BEAM_FLY_SCALE = 0.1f; + +// Entity_Player::HandleCollision: the contact damage the items deal. +constexpr int CONTACT_COUNTDOWN = 15; +constexpr int SUPLEX_STATE_PASSING = 3; +constexpr float HEELS_DAMAGE = 12; +constexpr float HEELS_DAMAGE_VERSUS = 2; +constexpr float VIRUS_DAMAGE = 12; +constexpr float VIRUS_DAMAGE_VERSUS = 1; +constexpr float BABY_CONTACT_DAMAGE = 10; +constexpr float HORN_DAMAGE = 3.5f; +constexpr float ARIES_DAMAGE = 25; +constexpr float ARIES_DAMAGE_VERSUS = 10; +constexpr float ARIES_SPEED = 4; +constexpr float ARIES_MASS = 1000; +constexpr int ARIES_COOLDOWN = 2; +constexpr float NULL_CONTACT_DAMAGE = 40; +constexpr float NULL_CONTACT_DAMAGE_VERSUS = 15; +constexpr float THROWN_DAMAGE_SCALE = 3; +constexpr float THROWN_DAMAGE_BONUS = 5; +constexpr float SLOW_ON_CONTACT = 0.5f; +constexpr float ICE_KNOCKBACK_SPEED_SQUARED = 0.001f; + +// Entity::BloodExplode and gibs_spawn: the bursts' gibs and blood drops. +constexpr int EXTRA_BLOOD_GIBS = 8; +constexpr int GIB_KINDS = 14; +constexpr int GIB_KIND_BONE = 1; +constexpr int GIB_KIND_EYE = 3; +constexpr int GIB_KIND_POOP = 5; +constexpr int GIB_KIND_WORM = 6; +constexpr int GIB_KIND_ROCK = 7; +constexpr int GIB_KIND_ROCK_SMALL = 8; +constexpr int GIB_KIND_CHAIN = 11; +constexpr int GIB_EYES_MAX = 3; +constexpr int GIB_TIMEOUT_MIN = 15; +constexpr int GIB_TIMEOUT_RANGE = 15; +constexpr int GIB_HUGE_TIMEOUT_MIN = 20; +constexpr int GIB_HUGE_TIMEOUT_RANGE = 30; +constexpr int GIB_ROCK_DISCARDED_DRAWS = 4; +constexpr uint32_t GIB_COUNTED_KINDS = GIB_FLAG_BLOOD | GIB_FLAG_BONE | GIB_FLAG_GUT | GIB_FLAG_POOP | GIB_FLAG_ROCK | + GIB_FLAG_ROCK_SMALL | GIB_FLAG_CHAIN; +constexpr float GIB_SPEED_MIN = 2; +constexpr float GIB_SPEED_RANGE = 4; +constexpr float GIB_LIFT = 0.5f; +constexpr float GIB_WORM_HEIGHT = -40; +constexpr float DUST_SPEED = 5; +constexpr float DUST_RADIUS = 20; +constexpr float DUST_ALPHA_MIN = 0.2f; +constexpr float DUST_ALPHA_RANGE = 0.5f; +constexpr float DROP_SPEED = 10; +constexpr float DROP_SPIN_MIN = 2; +constexpr float DROP_SPIN_RANGE = 10; +constexpr float DROP_ALPHA_MIN = 0.1f; +constexpr float DROP_ALPHA_RANGE = 0.25f; +constexpr float HUGE_GIB_SCALE_MIN = 2; +constexpr float HUGE_DROP_SCALE_RANGE = 2; +constexpr float HUGE_DROP_SPEED = 4; +constexpr int BURST_DROPS_MIN_GIBS = 6; +constexpr int BURST_SHAKE_MIN_GIBS = 8; +constexpr int BURST_SHAKE = 6; +constexpr int HUGE_BURST_SHAKE = 24; +constexpr float BURST_SPEED = 2; +constexpr float HUGE_BURST_SPEED = 4; +constexpr float BURST_PUSH = 16; +constexpr int REDUCED_GIBS_DIVISOR = 4; +constexpr float EXTRA_BLOOD_SPLAT_SCALE = 2; +constexpr KColor BLOOD_BASE_COLOR = kcolor_rgba(0.61960787f, 0.043137256f, 0.05882353f, 1); +constexpr ColorMod POISON_GIB_TINT = {{1, 1, 1, 1}, {0.3f, 1.6f, 0, 1}, {0, 0, 0}}; +constexpr ColorMod TOOTH_COLOR = {{0.54902f, 0.482353f, 0.482353f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Sorted insertion into a hit list, as the entities keep them. +static void hit_list_add(std::vector& hitList, Entity& entity) +{ + uint32_t index = entity.GetHitListIndex(); + auto at = std::lower_bound(hitList.begin(), hitList.end(), index); + if (at == hitList.end() || *at != index) hitList.insert(at, index); +} + +// Spawns an effect with a seed drawn by the caller. +static Entity_Effect* effect_spawn(int variant, int subType, Vector position, Vector velocity, Entity* spawner, + uint32_t seed) +{ + Entity* effect = g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = spawner, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = variant, + .seed = seed}); + 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() +{ + float angle = random_unit() * RANDOM_HALF_TURN; + return angle + angle; +} + +// Which way a spawned gib spins: against the side of its flight it landed on. +static float spin_side(Entity& gib, Vector origin, Vector velocity) +{ + return (gib.pos.y - origin.y) * -velocity.x + (gib.pos.x - origin.x) * velocity.y < 0 ? -1.0f : 1.0f; +} + +// 006ac660 Whether it stands like a block: a collidable fireplace, movable TNT, poop or stone enemy. +static bool is_static_obstacle(Entity& entity) +{ + if (entity.entityCollisionClass == ENTCOLL_NONE) return false; + if (entity.type == ENTITY_FIREPLACE) return entity.variant < FIREPLACE_VARIANT_LAST; + return entity.type == STATIC_OBSTACLE_EXTRA || std::ranges::find(STATIC_OBSTACLE_TYPES, entity.type) != + STATIC_OBSTACLE_TYPES.end(); +} + +// 004e7d10 The Bishop nearest a position whose charm matches, in the room's update order. A frozen one does not count, +// a confused, feared or shrunk one half the time. +Entity* bishop_nearest_find(const Vector& position, bool isCharmed) +{ + Entity* nearest = nullptr; + float nearestDistance = 1e6f; + + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type != ENTITY_BISHOP || entity->HasEntityFlags(FLAG_FREEZE)) continue; + bool isDistracted = entity->HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK); + if ((isDistracted && (Random() & 1)) || entity->HasEntityFlags(FLAG_CHARM) != isCharmed) continue; + + float distance = vector_length(vector_sub(position, entity->pos)); + if (distance >= nearestDistance) continue; + nearest = entity; + nearestDistance = distance; + } + return nearest; +} + +// Part of 006ace60: a Bishop takes the hit for it, its shield effect flashing over it. +static bool bishop_shield(Entity& entity, Entity& bishop) +{ + npc_sound_play(SOUND_BISHOP_HIT, 1, BISHOP_HIT_DELAY, 1); + if (entity.hitEffect) entity.hitEffect->Remove(); + + Entity_Effect* shield = effect_spawn(EFFECT_BISHOP_SHIELD, 0, entity.pos, {}, &bishop, Random()); + shield->parent = &bishop; + shield->target = &entity; + shield->parentOffset = vector_make(0, BISHOP_SHIELD_HEIGHT); + const NullFrame* overlay = + entity.sprite.animState.animData ? entity.sprite.animState.GetNullFrame("OverlayEffect") : nullptr; + if (overlay) + shield->posOffset = vector_make(overlay->pos.x * NULL_OFFSET_SCALE + entity.posOffset.x, + (overlay->pos.y - BISHOP_SHIELD_NULL_Y) * NULL_OFFSET_SCALE + entity.posOffset.y); + shield->Update(); + entity.hitEffect = shield; + return false; +} + +// Part of 006ace60: the boss parts whose own shield may take the hit, none written yet. +static void shielded_part_check(Entity& entity) +{ + Entity* spawner = entity.spawnerEntity; + Entity* parent = entity.parent; + bool isShieldedSpawn = entity.type == ENTITY_SHIELDED_SPAWN && entity.variant == 1 && spawner && + spawner->type == ENTITY_SHIELD_SPAWNER; + bool isShieldedPart = entity.type == ENTITY_SHIELDED_PART && parent && parent->type == ENTITY_SHIELD_PARENT; + bool isDogmaPart = entity.type == ENTITY_DOGMA && entity.variant == 0 && parent; + if (isShieldedSpawn || isShieldedPart || isDogmaPart) + reconstruction_missing("Entity::TakeDamage 006ace60: a boss part's own shield"); +} + +// The players a co-op boss fight counts: one for each pair of twins and none for a player's attachments. +static int coop_player_count() +{ + int count = 0; + for (Entity_Player* player : g_game->playerManager.playerList) + { + Entity_Player* twin = player->twin_get(); + bool isMainTwin = !twin || twin->playerIndex == -1 || player->playerIndex <= twin->playerIndex || player == twin; + if (isMainTwin && !player->parent) count++; + } + return count; +} + +// 006ace60 Queues a hit for the next update: nothing from a friendly source, nothing from a fire or countdown hit +// while its cooldown runs, and nothing a Bishop shields. A boss takes less in co-op, a weakened entity double, and a +// mod's MC_ENTITY_TAKE_DMG may cancel it. Whether the hit was queued. +bool Entity::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int countdown) +{ + if (type == ENTITY_PLAYER) log_printf(LOG_ASSERT, "Entity TakeDamage should not be called for Entity Player!"); + if (!(damageFlags & DAMAGE_INVINCIBLE) && IsDamageSourceFriendly(source)) return false; + + if (damage > 0) + { + bool isVulnerable = IsVulnerableEnemy(nullptr); + if (isVulnerable || type == ENTITY_DOGMA) shielded_part_check(*this); + if ((isVulnerable && type != ENTITY_BISHOP) || (!isVulnerable && type == ENTITY_DOGMA)) + { + Entity* bishop = bishop_nearest_find(pos, IsFriendly()); + if (bishop) return bishop_shield(*this, *bishop); + } + } + + if ((damageFlags & DAMAGE_FIRE) && damage > 0) + { + if (fireDamageCountdown > 0) return false; + fireDamageCountdown = FIRE_DAMAGE_COOLDOWN; + } + if (damageFlags & DAMAGE_COUNTDOWN) + { + if (damageCountdown > 0) return false; + damageCountdown = countdown; + } + if (!(damageFlags & DAMAGE_INVINCIBLE) && IsBoss() && g_game->playerManager.playerList.size() > 1 && + coop_player_count() > 1) + damage *= COOP_BOSS_DAMAGE; + if (HasEntityFlags(FLAG_WEAKNESS)) damage += damage; + if (maxHitPoints <= 0) return false; + + lua_callback_check(MC_ENTITY_TAKE_DMG, "Entity::TakeDamage 006ace60: MC_ENTITY_TAKE_DMG"); + damageEvents.push_back({.source = source, .damage = damage, .damageFlags = damageFlags}); + pendingDamageFlags |= damageFlags; + pendingDamage += damage; + // The damage the attacking player dealt is tallied only for the online stats screen, which is not written yet. + return true; +} + +// 006ac920 Kills it once: Black Powder blasts a fireplace its player put out, anything not a boss or familiar bursts +// into gibs, and MC_POST_ENTITY_KILL runs. The online kill tally of the stats screen is not written yet. +void Entity::Kill(const EntityRef& source) +{ + if (isDead) return; + isDead = true; + + Entity* killer = source.entity ? source.entity->GetPlayerAncestor() : nullptr; + if (killer && type == ENTITY_FIREPLACE) + { + bool isPowderable = variant == FIREPLACE_NORMAL || variant == FIREPLACE_RED || variant == FIREPLACE_MOVEABLE; + if (static_cast(killer)->HasCollectible(COLLECTIBLE_BLACK_POWDER) && isPowderable) + reconstruction_missing("Entity::Kill 006ac920: Black Powder's fireplace blast (BombExplosionEffects)"); + } + if (!IsBoss() && type != ENTITY_FAMILIAR) BloodExplode(); + lua_engine_get().PostEntityKill(this); +} + +// Part of 006b45c0: the burst's sound, by what its config says it is made of. +static void burst_sound_play(Entity& entity) +{ + uint32_t gibFlags = entity.config->gibFlags; + int gibsAmount = entity.config->gibsAmount; + bool isSin = entity.type >= ENTITY_SINS_FIRST && entity.type <= ENTITY_SINS_LAST; + bool isLargeBurst = !entity.isDead || !entity.config->isBoss || isSin; + Entity_NPC* npc = entity.IsEnemy() ? dynamic_cast(&entity) : nullptr; + bool isDarkRed = npc && npc->championColorIdx == CHAMPION_DARK_RED; + + if (entity.type == ENTITY_SCOURGE_TYPE && entity.variant == SCOURGE_BONE_VARIANT) npc_sound_play(SOUND_BONE_BREAK, 1, 2, 1); + else if (gibFlags & GIB_FLAG_CHAIN) npc_sound_play(SOUND_CHAIN_BREAK, 1, 2, 1); + else if (entity.freezeCountdown > 0 || (gibFlags & (GIB_FLAG_ROCK | GIB_FLAG_ROCK_SMALL))) + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, 1); + else if (isDarkRed) npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + else if (gibFlags & GIB_FLAG_SOUND_BABY) npc_sound_play(SOUND_GOODEATH, SOUND_BABY_VOLUME, 2, 1); + else if (gibFlags & GIB_FLAG_SOUND_BONE) npc_sound_play(SOUND_DEATH_BURST_BONE, 1, 2, 1); + else if (gibFlags & GIB_FLAG_HUGE) npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, 1); + else if (gibFlags & GIB_FLAG_LARGE) + { + if (isLargeBurst) npc_sound_play(SOUND_DEATH_BURST_LARGE, SOUND_LARGE_VOLUME, 2, 1); + else npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, 1); + } + else if (entity.HasEntityFlags(FLAG_EXTRA_GORE) && gibsAmount > 0 && (gibFlags & GIB_FLAG_BLOOD)) + npc_sound_play(SOUND_DEATH_BURST_LARGE, SOUND_LARGE_VOLUME, 2, 1); + else npc_sound_play(SOUND_DEATH_BURST_SMALL, gibsAmount > 0 ? 1 : SOUND_SMALL_VOLUME, 2, 1); +} + +// Part of 006b45c0: a big burst's blood drops, dust clouds in the blood's color flung around it. +static void burst_drops_spawn(Entity& entity, int gibsAmount) +{ + int half = gibsAmount / 2; + int count = half + random_below(half); + KColor blood = kcolor_apply(entity.splatColor, BLOOD_BASE_COLOR); + bool isHuge = entity.config->gibFlags & GIB_FLAG_HUGE; + + for (int i = 0; i < count; i++) + { + float angle = random_angle(); + float speed = random_unit() * DROP_SPEED; + Vector velocity = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); + uint32_t seed = Random(); + float placeAngle = random_angle(); + float radius = random_unit() * DUST_RADIUS; + Vector position = vector_add(entity.pos, vector_make(std::cos(placeAngle) * radius, std::sin(placeAngle) * radius)); + + Entity_Effect* drop = effect_spawn(EFFECT_DUST_CLOUD, 0, position, velocity, &entity, seed); + float side = spin_side(*drop, entity.pos, velocity); + drop->rotation = (random_unit() * DROP_SPIN_RANGE + DROP_SPIN_MIN) * side; + float alpha = (random_unit() * DROP_ALPHA_RANGE + DROP_ALPHA_MIN) * blood._alpha; + drop->SetColor({{blood._red, blood._green, blood._blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, -1, + COLOR_PRIORITY_TOP, false, true); + if (!isHuge) drop->SetTimeout((int)(Random() % GIB_TIMEOUT_RANGE) + GIB_TIMEOUT_MIN); + else + { + float scale = random_unit() * HUGE_DROP_SCALE_RANGE + HUGE_GIB_SCALE_MIN; + drop->sprite.scale = vector_make(scale, scale); + drop->SetTimeout((int)(Random() % GIB_HUGE_TIMEOUT_RANGE) + GIB_HUGE_TIMEOUT_MIN); + drop->velocity = vector_scale(drop->velocity, HUGE_DROP_SPEED); + } + drop->Update(); + } +} + +// 006b45c0 Bursts it: an iced enemy shatters, anything else plays its burst sound and throws its config's gibs, a big +// burst (extra gore, or a huge config) shaking the screen, pushed away from the first hit and with blood drops. It +// leaves a blood splat unless it is a bomb, a pickup or splashes no blood. +void Entity::BloodExplode() +{ + if (HasEntityFlags(FLAG_ICE) && !IsBoss() && !config->isBoss) + reconstruction_missing("Entity::BloodExplode 006b45c0: an iced enemy shattering (Game::SpawnParticles)"); + if (HasEntityFlags(FLAG_ICE_FROZEN)) + reconstruction_missing("Entity::BloodExplode 006b45c0: a frozen enemy shattering (Game::SpawnParticles)"); + + burst_sound_play(*this); + if (type == ENTITY_SUCKER && variant == SUCKER_BULB) + reconstruction_missing("Entity::BloodExplode 006b45c0: the bulb's death flash"); + + int gibsAmount = config->gibsAmount; + if (gibsAmount >= 1 && HasEntityFlags(FLAG_REDUCE_GIBS)) gibsAmount = std::max(gibsAmount / REDUCED_GIBS_DIVISOR, 1); + else if (HasEntityFlags(FLAG_EXTRA_GORE)) gibsAmount *= 2; + + bool isHuge = config->gibFlags & GIB_FLAG_HUGE; + GibSpawn gibs = {.color = splatColor, .position = pos, .spawner = this, .spread = size, .amount = gibsAmount, + .gibFlags = config->gibFlags}; + if (HasEntityFlags(FLAG_EXTRA_GORE) || isHuge) + { + gibs.speed = isHuge ? HUGE_BURST_SPEED : BURST_SPEED; + if (isHuge) game_shake_screen(HUGE_BURST_SHAKE); + else if (gibsAmount > BURST_SHAKE_MIN_GIBS) game_shake_screen(BURST_SHAKE); + if (!damageEvents.empty()) + gibs.velocity = vector_scale(vector_normalized(vector_sub(pos, damageEvents.front().source.position)), + BURST_PUSH); + if (gibsAmount > BURST_DROPS_MIN_GIBS && (config->gibFlags & GIB_FLAG_BLOOD)) burst_drops_spawn(*this, gibsAmount); + } + gibs_spawn(gibs); + + if (type == ENTITY_BOMB || type == ENTITY_PICKUP || HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) return; + Entity_Effect* splat = effect_spawn(EFFECT_BLOOD_SPLAT, 0, pos, {}, nullptr, Random()); + splat->SetColor(splatColor, -1, COLOR_PRIORITY_TOP, false, true); + if (g_game->seedEffects.HasSeedEffect(SEED_EXTRA_BLOOD)) + splat->sprite.scale = vector_make(EXTRA_BLOOD_SPLAT_SCALE, EXTRA_BLOOD_SPLAT_SCALE); + splat->Update(); +} + +// Part of 006b31b0: how many gibs of each kind a burst throws. +static std::array gib_counts_get(uint32_t gibFlags, int each) +{ + std::array counts{}; + int half = each / 2; + + if (gibFlags & GIB_FLAG_BLOOD) + { + int first = random_below(each); + counts[0] = first + random_below(each); + } + if (gibFlags & GIB_FLAG_BONE) counts[GIB_KIND_BONE] = half + random_below(half); + if (gibFlags & GIB_FLAG_GUT) counts[2] = random_below(each); + if (gibFlags & GIB_FLAG_EYE) counts[GIB_KIND_EYE] = random_below(std::min(each, GIB_EYES_MAX)); + if (gibFlags & GIB_FLAG_POOP) counts[GIB_KIND_POOP] = random_below(each); + if (gibFlags & GIB_FLAG_WORM) counts[GIB_KIND_WORM] = random_below(each); + if (gibFlags & GIB_FLAG_ROCK) counts[GIB_KIND_ROCK] = half + random_below(half); + if (gibFlags & GIB_FLAG_ROCK_SMALL) counts[GIB_KIND_ROCK_SMALL] = half + random_below(half); + if (gibFlags & GIB_FLAG_CHAIN) counts[GIB_KIND_CHAIN] = half + random_below(half); + return counts; +} + +// Part of 006b31b0: a dusty burst's clouds, from half to all of a share. +static void gib_dust_spawn(const GibSpawn& gibs, int half) +{ + int count = (int)(Random() % (uint32_t)half) + half; + for (int i = 0; i < count; i++) + { + float angle = random_angle(); + float speed = random_unit() * DUST_SPEED; + Vector velocity = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); + uint32_t seed = Random(); + float placeAngle = random_angle(); + float radius = random_unit() * DUST_RADIUS; + Vector position = vector_add(gibs.position, vector_make(std::cos(placeAngle) * radius, std::sin(placeAngle) * radius)); + + Entity_Effect* dust = effect_spawn(EFFECT_DUST_CLOUD, 0, position, velocity, gibs.spawner, seed); + dust->rotation = (random_unit() * DROP_SPIN_RANGE + DROP_SPIN_MIN) * spin_side(*dust, gibs.position, velocity); + dust->SetTimeout((int)(Random() % GIB_TIMEOUT_RANGE) + GIB_TIMEOUT_MIN); + float alpha = random_unit() * DUST_ALPHA_RANGE + DUST_ALPHA_MIN; + dust->SetColor({{1, 1, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, -1, COLOR_PRIORITY_TOP, false, true); + dust->Update(); + } +} + +// Part of 006b31b0: a gib flung up from within half the spread, at its speed plus a random share of the push. +static Entity_Effect* gib_fling(const GibSpawn& gibs, int variant, int subType, uint32_t seed, float speed) +{ + float angle = random_angle(); + float push = random_unit(); + Vector velocity = vector_make(std::cos(angle) * speed + push * gibs.velocity.x, + std::sin(angle) * GIB_LIFT * speed + push * gibs.velocity.y); + float placeAngle = random_angle(); + Vector position = vector_add(gibs.position, vector_make(std::cos(placeAngle) * HALF_F * gibs.spread, + std::sin(placeAngle) * HALF_F * gibs.spread)); + return effect_spawn(variant, subType, position, velocity, gibs.spawner, seed); +} + +// Part of 006b31b0: a tooth or chain gib, scattered within half the spread and flung at its own speed. +static Entity_Effect* gib_scatter(const GibSpawn& gibs, int variant, uint32_t angleDraw) +{ + float angle = (float)angleDraw * RANDOM_UNIT_SCALE * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit(); + Vector position = vector_add(gibs.position, vector_make(std::cos(angle) * reach * HALF_F * gibs.spread, + std::sin(angle) * reach * HALF_F * gibs.spread)); + float flingAngle = random_angle(); + float speed = random_unit() * GIB_SPEED_RANGE + GIB_SPEED_MIN; + float push = random_unit(); + Vector velocity = vector_make(push * gibs.velocity.x + std::cos(flingAngle) * speed, + push * gibs.velocity.y + std::sin(flingAngle) * speed); + return effect_spawn(variant, 0, position, velocity, gibs.spawner, Random()); +} + +// Part of 006b31b0: a blood, bone, gut or eye gib in the burst's color, tinted green for a poisoned spawner. +static Entity_Effect* gib_blood_spawn(const GibSpawn& gibs, int kind, uint32_t seed, float speed) +{ + Entity_Effect* gib = gib_fling(gibs, EFFECT_BLOOD_PARTICLE, kind, seed, speed); + if (!gibs.spawner || !gibs.spawner->HasEntityFlags(FLAG_POISON)) + { + gib->SetColor(gibs.color, -1, COLOR_PRIORITY_TOP, false, true); + gib->splatColor = gibs.color; + } + else + { + ColorMod tinted = color_multiply(gibs.color, POISON_GIB_TINT); + gib->SetColor(kind == 0 ? tinted : gibs.color, -1, COLOR_PRIORITY_TOP, false, true); + gib->splatColor = tinted; + } + if (kind == GIB_KIND_BONE) gib->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + return gib; +} + +// Part of 006b31b0: one gib of a kind. +static Entity_Effect* gib_spawn(const GibSpawn& gibs, int kind) +{ + float speed = (random_unit() * GIB_SPEED_RANGE + GIB_SPEED_MIN) * gibs.speed; + switch (kind) + { + case GIB_KIND_POOP: + { + uint32_t seed = Random(); + return gib_fling(gibs, EFFECT_POOP_PARTICLE, 0, seed, speed); + } + case GIB_KIND_WORM: + { + uint32_t seed = Random(); + int subType = (int)(Random() & 1); + Entity_Effect* worm = gib_fling(gibs, EFFECT_WORM, subType, seed, speed); + worm->posOffset = vector_make(0, random_unit() * GIB_WORM_HEIGHT); + return worm; + } + case GIB_KIND_ROCK: + { + for (int i = 0; i < GIB_ROCK_DISCARDED_DRAWS; i++) Random(); + uint32_t seed = Random(); + Entity_Effect* rock = gib_fling(gibs, EFFECT_ROCK_PARTICLE, ROCK_PARTICLE_SUBTYPE, seed, speed); + rock->Update(); + return rock; + } + default: break; + } + + uint32_t draw = Random(); + if (kind == GIB_KIND_ROCK_SMALL) + { + Entity_Effect* tooth = gib_scatter(gibs, EFFECT_TOOTH_PARTICLE, draw); + tooth->SetColor(TOOTH_COLOR, -1, COLOR_PRIORITY_TOP, false, true); + return tooth; + } + if (kind == GIB_KIND_CHAIN) return gib_scatter(gibs, EFFECT_CHAIN_GIB, draw); + return gib_blood_spawn(gibs, kind, draw, speed); +} + +// 006b31b0 Throws a burst's gibs: the amount (eight times it with the extra blood seed) shared among the kinds its +// flags name, each kind flung its own way, and the dust of a dusty burst. A huge burst's gibs come out bigger. +void gibs_spawn(const GibSpawn& gibs) +{ + if (gibs.amount == 0) return; + + int multiplier = g_game->seedEffects.HasSeedEffect(SEED_EXTRA_BLOOD) ? EXTRA_BLOOD_GIBS : 1; + int total = multiplier * gibs.amount + (int)(Random() & 1); + int kinds = std::popcount(gibs.gibFlags & GIB_COUNTED_KINDS); + int each = (kinds == 0 ? total : total / kinds) + 1; + + std::array counts = gib_counts_get(gibs.gibFlags, each); + if ((gibs.gibFlags & GIB_FLAG_DUST) && each / 2 != 0) gib_dust_spawn(gibs, each / 2); + if (kinds == 0) return; + + for (int kind = 0; kind < GIB_KINDS; kind++) + { + for (int i = 0; i < counts[kind]; i++) + { + Entity_Effect* gib = gib_spawn(gibs, kind); + if (gibs.gibFlags & GIB_FLAG_HUGE) + { + if (g_game->room->IsBeastDungeon()) + reconstruction_missing("spawn_gibs 006b31b0: the Beast's huge gibs thrown up"); + float scale = random_unit() + HUGE_GIB_SCALE_MIN; + gib->AddEntityFlags(FLAG_EXTRA_GORE); + gib->sprite.scale = vector_make(scale, scale); + } + gib->Update(); + } + } +} + +// 0067d1f0 The damage flags a hit adds: a blue fly for Mulligan and Guppy (less likely from a lasting laser or +// brimstone ball), a booger tear's, a rock tear's crush, and the hit through cooldowns of a glowing versus tear or of +// bit 100. +uint64_t tear_damage_flags_get(const TearFlags& tearFlags, Entity* source) +{ + uint64_t damageFlags = 0; + Entity* spawner = source ? source->spawnerEntity.get() : nullptr; + if (spawner && spawner->type == ENTITY_FAMILIAR && spawner->variant == FAMILIAR_INCUBUS) + spawner = static_cast(spawner)->player; + if (spawner && spawner->type == ENTITY_PLAYER) + { + Entity_Player& player = *static_cast(spawner); + float flyChance = player.HasCollectible(COLLECTIBLE_MULLIGAN) ? MULLIGAN_FLY_CHANCE : 0; + if (!player.hasCurseMistEffect && !player.isCoopGhost && player.playerForms[PLAYER_FORM_GUPPY] >= PLAYER_FORM_COUNT_NEEDED) + flyChance = GUPPY_FLY_CHANCE; + bool isLastingBall = source->type == ENTITY_EFFECT && source->variant == EFFECT_BRIMSTONE_BALL && + static_cast(source)->timeout == -1; + bool isLastingLaser = source->type == ENTITY_LASER && static_cast(source)->timeout == -1; + if (isLastingBall || isLastingLaser) flyChance *= LASTING_BEAM_FLY_SCALE; + if (flyChance > 0 && player.numBlueFlies < BLUE_FLY_MAX && random_unit() < flyChance) damageFlags |= DAMAGE_SPAWN_FLY; + } + if (g_game->deathmatchManager.is_active() && tearFlags[TEAR_GLOW]) damageFlags |= DAMAGE_THROUGH_COOLDOWN; + if (source && source->type == ENTITY_TEAR && tearFlags[TEAR_BOOGER_FLAG]) damageFlags |= DAMAGE_BOOGER; + if (tearFlags[TEAR_ROCK_FLAG]) damageFlags |= DAMAGE_CRUSH; + if (tearFlags[TEAR_THROUGH_COOLDOWN]) damageFlags |= DAMAGE_THROUGH_COOLDOWN; + return damageFlags; +} + +// What a tear does on touching an entity before it hits it: pass it, stop on it, or go on to hit it. +enum TearContact +{ + TEAR_CONTACT_PASS, + TEAR_CONTACT_STOP, + TEAR_CONTACT_HIT +}; + +// Part of 00673660: pushes the collider along the line from the tear, by their relative speed and masses. A tear +// passing it fast and inward bounces the line off its flight. massScale weighs the tear's mass. +static void tear_push(Entity_Tear& tear, Entity& collider, float massScale) +{ + Vector offset = vector_sub(collider.pos, tear.pos); + float distance = vector_length(offset); + if (distance < TEAR_PUSH_MIN_DISTANCE) return; + + Vector relative = vector_sub(tear.velocity, collider.velocity); + float speed = vector_length(relative); + if ((collider.size + tear.size) * HALF_F < speed && vector_dot(relative, offset) < 0) + { + float bounce = vector_dot(vector_normalized(relative), vector_normalized(offset)); + offset = vector_make(offset.x + bounce * offset.x + bounce * offset.x, + offset.y + bounce * offset.y + bounce * offset.y); + distance = vector_length(offset); + } + float tearMass = tear.collision_mass_get(&collider) * massScale; + float share = tearMass / (collider.collision_mass_get(&tear) + tearMass); + collider.velocity.x += offset.x / distance * speed * share; + collider.velocity.y += offset.y / distance * speed * share; +} + +// Part of 00673660: how a tear meets a player: it passes its own player's line, a charmed enemy's shot glances off +// the player who charmed it, and Infamy stops it half the time (a quarter in versus) with a flash. +static TearContact tear_player_contact(Entity_Tear& tear, Entity_Player& player) +{ + if (tear.IsDescendantOf(&player)) return TEAR_CONTACT_PASS; + + Entity* shooter = tear.spawnerEntity; + Entity* charmer = shooter && shooter->HasEntityFlags(FLAG_CHARM) ? shooter->charmSource.entity : nullptr; + if (charmer && charmer->IsDescendantOf(&player)) + { + tear.velocity = vector_scale(random_direction(), vector_length(tear.velocity)); + return TEAR_CONTACT_PASS; + } + + int infamyChance = g_game->deathmatchManager.is_active() ? INFAMY_CHANCE_VERSUS : INFAMY_CHANCE; + if (!player.HasCollectible(COLLECTIBLE_INFAMY) || random_below(infamyChance) != 0) return TEAR_CONTACT_HIT; + player.SetColor(INFAMY_COLOR, INFAMY_FLASH_FRAMES, COLOR_PRIORITY_TOP, true, true); + tear.Kill(EntityRef(&player)); + return TEAR_CONTACT_PASS; +} + +// Part of 00673660: two tears of different shooters meet only when one is shielded, which destroys the other. +static TearContact tear_tear_contact(Entity_Tear& tear, Entity_Tear& other) +{ + if (tear.spawnerEntity.get() == other.spawnerEntity.get()) return TEAR_CONTACT_PASS; + if (!tear.tearFlags[TEAR_SHIELDED] && !other.tearFlags[TEAR_SHIELDED]) return TEAR_CONTACT_PASS; + if (tear.tearFlags[TEAR_SHIELDED]) other.Kill(EntityRef(&tear)); + else tear.Kill(EntityRef(&other)); + return TEAR_CONTACT_HIT; +} + +// Part of 00673660: a Chaos Card kills any enemy it touches outright, passing the props and Dogma's and the Beast's +// bodies. +static TearContact chaos_card_contact(Entity_Tear& tear, Entity& collider) +{ + if (collider.type == ENTITY_GENERIC_PROP) return TEAR_CONTACT_PASS; + if ((collider.type == ENTITY_DOGMA || collider.type == ENTITY_BEAST) && collider.variant == 0) return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_DELIRIUM) reconstruction_missing("Entity_Tear::HandleCollision 00673660: a Chaos Card hitting Delirium"); + if (!collider.IsEnemy()) return TEAR_CONTACT_HIT; + + collider.Kill(EntityRef(&tear)); + if (collider.type == ENTITY_CHAOS_REMOVED) tear.Remove(); + return TEAR_CONTACT_PASS; +} + +// Part of 00673660: a tear meeting a bomb passes it while chained or orbiting, while just fired away from it, and +// past a fetus bomb unless a player's fetus tear hits it. +static TearContact tear_bomb_contact(Entity_Tear& tear, Entity_Bomb& bomb) +{ + if (tear.tearFlags[TEAR_CHAIN] || tear.tearFlags[TEAR_ORBIT_ADVANCED]) return TEAR_CONTACT_PASS; + bool isFiredAway = vector_dot(vector_sub(bomb.pos, tear.pos), tear.velocity) < 0 && + g_game->frameCount - tear.spawnFrame < BOMB_GRACE_FRAMES; + if (isFiredAway) return TEAR_CONTACT_PASS; + if (!bomb.isFetus) return TEAR_CONTACT_HIT; + return tear.spawnerType != ENTITY_PLAYER || tear.tearFlags[TEAR_FETUS_FLAG] ? TEAR_CONTACT_PASS : TEAR_CONTACT_HIT; +} + +// Part of 00673660: how a tear meets what it touches before hitting it: its own familiars, Dark Esau, friendly enemies, +// rockets and invincible bosses it passes, a shielded tear stops shots, and a few entities deflect it. +static TearContact tear_contact_get(Entity_Tear& tear, Entity& collider, Entity* owner, bool isExplosive) +{ + if (collider.type == ENTITY_PLAYER) + { + TearContact contact = tear_player_contact(tear, *static_cast(&collider)); + if (contact != TEAR_CONTACT_HIT) return contact; + } + if (collider.type == ENTITY_TEAR && tear_tear_contact(tear, *static_cast(&collider)) == TEAR_CONTACT_PASS) + return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_FAMILIAR && collider.IsDescendantOf(owner)) return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_DARK_ESAU) return TEAR_CONTACT_PASS; + if (collider.IsEnemy() && collider.IsFriendly() && collider.IsDamageSourceFriendly(EntityRef(&tear))) + return TEAR_CONTACT_PASS; + + if (collider.type == ENTITY_FROZEN_ENEMY && &collider == tear.spawnerEntity.get()) return TEAR_CONTACT_STOP; + if (collider.type == ENTITY_BOMB && static_cast(collider).IsRocket()) return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_FAMILIAR && collider.IsDescendantOf(tear.spawnerEntity)) return TEAR_CONTACT_PASS; + + if (tear.variant == TEAR_CHAOS_CARD) + { + TearContact contact = chaos_card_contact(tear, collider); + if (contact != TEAR_CONTACT_HIT) return contact; + } + if (collider.type == ENTITY_HUSH && collider.isInvincible) return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_BOMB && tear_bomb_contact(tear, static_cast(collider)) == TEAR_CONTACT_PASS) + return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_IGNORED_BY_TEARS) return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_BIG_HORN && collider.isInvincible) return TEAR_CONTACT_PASS; + if (collider.type == ENTITY_FAMILIAR && collider.variant == FAMILIAR_TEAR_DEFLECTOR) + { + if (!EntityList::HitListContains(tear.hitList, collider)) + { + hit_list_add(tear.hitList, collider); + tear_push(tear, collider, TEAR_DEFLECTOR_MASS_SCALE); + } + return TEAR_CONTACT_PASS; + } + if (!isExplosive && collider.type == ENTITY_REFLECTING_ENEMY) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: an enemy reflecting tears"); + + if (collider.type == ENTITY_PROJECTILE) + { + Entity_Projectile& shot = static_cast(collider); + bool isUnstoppable = !tear.tearFlags[TEAR_SHIELDED] || (shot.projectileFlags & PROJECTILE_CANT_BE_STOPPED); + if (isUnstoppable && !(shot.projectileFlags & PROJECTILE_SHIELDED)) return TEAR_CONTACT_PASS; + shot.projectileFlags = 0; + shot.isDead = true; + } + return TEAR_CONTACT_HIT; +} + +// Part of 00673660: a tear hitting what it may hurt: whether its owner's side may hurt it, and whether it faces the +// tear's way (a shielded front blocks). Piercing passes the fronts, and a spectral tear an obstacle with no grid +// damage. Whether the tear flies through. +static bool tear_damage_deal(Entity_Tear& tear, Entity& collider, bool& isHit) +{ + float damage = tear.collisionDamage; + uint64_t damageFlags = tear_damage_flags_get(tear.tearFlags, &tear); + Entity_NPC* npc = dynamic_cast(&collider); + bool isFacing = !npc || npc->CanBeDamagedFromVelocity(tear.velocity); + + Entity* shooter = tear.spawnerEntity; + bool isOwnSide = shooter && (shooter->IsDescendantOf(&collider) || collider.IsDescendantOf(tear.GetRootPlayer())); + bool isHostile = !isOwnSide || (Entity::is_enemy_type(collider.type) && !collider.IsFriendly()); + bool isAlwaysHit = collider.type == ENTITY_FIREPLACE || collider.type == ENTITY_POOP || collider.type == ENTITY_BLOOD_PUPPY; + isHit = false; + if (!isAlwaysHit && !isHostile) return false; + + bool isObstacle = is_static_obstacle(collider); + bool isPiercing = tear.tearFlags[TEAR_PIERCING]; + bool isSpectral = tear.tearFlags[TEAR_SPECTRAL]; + if (collider.IsEnemy() && (!isPiercing || isObstacle) && (!isSpectral || !isObstacle) && !isFacing) return false; + if (isSpectral && isObstacle && tear.tearFlags[TEAR_NO_GRID_DAMAGE]) return true; + if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Tear::HandleCollision 00673660: the versus trinkets"); + + isHit = true; + collider.TakeDamage(damage, damageFlags, EntityRef(&tear), TEAR_HIT_COUNTDOWN); + if (tear.tearFlags[TEAR_FETUS_FLAG] && !isObstacle) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: a fetus tear's bounce and bomber"); + if (collider.IsEnemy()) tear.isCanTriggerStreakEnd = false; + return collider.IsEnemy() && (tear.tearFlags[TEAR_BOOGER_FLAG] || tear.tearFlags[TEAR_STICKY] || tear.tearFlags[TEAR_SPORE_FLAG]); +} + +// Part of 00673660: Dead Eye charges when its player's tear hits an active enemy. +static void dead_eye_charge(Entity_Tear& tear, Entity& collider) +{ + Entity* parent = tear.parent; + if (!parent || !collider.IsActiveEnemy(DEAD_EXCLUDED) || parent->type != ENTITY_PLAYER) return; + Entity_Player& player = *static_cast(parent); + if (player.HasCollectible(COLLECTIBLE_DEAD_EYE)) player.AddDeadEyeCharge(); +} + +// Part of 00673660: what a hit does beside its damage: a burning tear may turn explosive by luck, a piercing or +// lasting tear pushes what it passes, and flies are knocked along. +static void tear_hit_push(Entity_Tear& tear, Entity& collider, Entity* owner) +{ + if (tear.tearFlags[TEAR_BURN] && collider.type != ENTITY_FIREPLACE) + { + float luck = owner && owner->type == ENTITY_PLAYER ? static_cast(owner)->luck : 0; + int chance = BURN_EXPLODE_CHANCE - (int)(luck * BURN_EXPLODE_LUCK); + if (random_below(chance < 1 ? 1 : chance) == 0 && (!tear.tearFlags[TEAR_LUDOVICO] || tear.is_not_familiar_spawned())) + tear.tearFlags[TEAR_EXPLOSIVE] = true; + } + if ((tear.variant == TEAR_TOOTH || tear.variant == TEAR_BLACK_TOOTH) && tear.tearFlags[TEAR_LUDOVICO] && + collider.IsVulnerableEnemy(nullptr)) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: a tooth Ludovico's particles"); + + bool isPassing = tear.tearFlags[TEAR_PIERCING] || tear.tearFlags[TEAR_PERSISTENT]; + if ((isPassing || tear.tearFlags[TEAR_FETUS_FLAG]) && !collider.HasEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK)) + tear_push(tear, collider, 1); + if ((collider.type == ENTITY_POOTER || collider.type == ENTITY_ATTACKFLY) && !isPassing) + collider.velocity = vector_add(collider.velocity, vector_scale(tear.velocity, FLY_PUSH)); +} + +// Part of 00673660: a lasting tear loses the damage it dealt and shrinks with it, dying once it has none left over or +// the enemy faced it. +static void tear_persist(Entity_Tear& tear, Entity& collider) +{ + Entity_NPC* npc = dynamic_cast(&collider); + if (tear.collisionDamage <= collider.health || (npc && !npc->CanBeDamagedFromVelocity(tear.velocity))) + { + tear.deathFlags |= TEAR_DEATH_ENTITY; + tear.isDead = true; + return; + } + float damage = tear.collisionDamage; + tear.collisionDamage = damage - collider.health; + tear.SetScale(tear.collisionDamage * tear.baseScale / damage); + tear.isCanTriggerStreakEnd = false; +} + +// Part of 00673660: whether a tear flies on after its hit: a bouncing one turns at random (a piercing one a quarter +// of the time off enemies), a lasting one keeps going, and piercing, Ludovico, spectral and Chaos Card tears pass. +static bool tear_flies_on(Entity_Tear& tear, Entity& collider) +{ + bool isObstacle = is_static_obstacle(collider); + bool isPiercing = tear.tearFlags[TEAR_PIERCING]; + if (tear.tearFlags[TEAR_FETUS_FLAG]) + { + tear.isCanTriggerStreakEnd = false; + return true; + } + if (tear.tearFlags[TEAR_BOUNCE] && (!isPiercing || isObstacle || (Random() & TEAR_BOUNCE_PIERCE_MASK) == 0)) + { + tear.velocity = vector_scale(random_direction(), vector_length(tear.velocity)); + tear.tearFlags[TEAR_TRACTOR_BEAM] = false; + tear.isCanTriggerStreakEnd = false; + return true; + } + bool isSpectralBlocked = tear.tearFlags[TEAR_SPECTRAL] && isObstacle; + if (tear.tearFlags[TEAR_PERSISTENT] && (!isPiercing || isObstacle) && !tear.tearFlags[TEAR_LUDOVICO] && + !isSpectralBlocked) + { + tear_persist(tear, collider); + dead_eye_charge(tear, collider); + return true; + } + return (isPiercing && !isObstacle) || tear.tearFlags[TEAR_LUDOVICO] || isSpectralBlocked || + tear.variant == TEAR_CHAOS_CARD; +} + +// 00673660 Hits what it collides with, after a mod's MC_PRE_TEAR_COLLISION: past what it passes (its own player and +// familiars, friends, rockets, other tears) and once per entity unless it pierces, it deals its damage with its hit +// flags, knocks flies along and applies its flags' effects, then dies there unless it flies on. An explosive tear +// bursts on any hit. Whether the collision is ignored. +bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) +{ + LuaResult lua = lua_engine_get().PreTearCollision(this, collider, isLow); + if (lua != LUA_RESULT_NIL) return lua == LUA_RESULT_TRUE; + + bool isExplosive = tearFlags[TEAR_EXPLOSIVE] && !tearFlags[TEAR_LUDOVICO]; + if (!isLow || isDead) return false; + Entity* owner = GetPlayerAncestor(); + if (owner == collider) return true; + + TearContact contact = tear_contact_get(*this, *collider, owner, isExplosive); + if (contact != TEAR_CONTACT_HIT) return contact == TEAR_CONTACT_PASS; + + bool isPassing = tearFlags[TEAR_PIERCING] || tearFlags[TEAR_PERSISTENT] || tearFlags[TEAR_SPECTRAL] || + tearFlags[TEAR_BOUNCE] || tearFlags[TEAR_LUDOVICO] || tearFlags[TEAR_BOOGER_FLAG] || + tearFlags[TEAR_STICKY] || tearFlags[TEAR_SPORE_FLAG] || tearFlags[TEAR_FETUS_FLAG]; + if (EntityList::HitListContains(hitList, *collider) && isPassing) return true; + hit_list_add(hitList, *collider); + bool isSticking = tearFlags[TEAR_STICKY] || tearFlags[TEAR_BOOGER_FLAG] || tearFlags[TEAR_SPORE_FLAG]; + if (collider->IsActiveEnemy(DEAD_EXCLUDED) && isSticking) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: a sticky tear sticking to an enemy"); + + if (!isExplosive) + { + bool isHit = false; + if (tear_damage_deal(*this, *collider, isHit)) return true; + if (isHit) dead_eye_charge(*this, *collider); + tear_hit_push(*this, *collider, owner); + } + ApplyTearFlagEffects(collider, pos, tearFlags, this, collisionDamage); + if (variant == TEAR_ERASER && collider->IsVulnerableEnemy(nullptr) && (!collider->IsBoss() || collider->HasMortalDamage())) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: the Eraser erasing an enemy"); + if (tearFlags[TEAR_TELEPORT] && collider->IsVulnerableEnemy(nullptr) && !collider->IsBoss()) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: a teleporting tear's reroll"); + + if (isExplosive) + { + deathFlags |= TEAR_DEATH_ENTITY | TEAR_DEATH_EXPLOSION; + isDead = true; + if (tearFlags[TEAR_LUDOVICO] && is_not_familiar_spawned()) + for (Entity* link = child; link; link = link->child) link->Kill(EntityRef()); + } + else + { + apply_death_flag_effects(collider); + if (tearFlags[TEAR_BELIAL_FLAG]) reconstruction_missing("Entity_Tear::HandleCollision 00673660: Belial's homing"); + if (g_game->deathmatchManager.is_active() && collider->type == ENTITY_FAMILIAR) + reconstruction_missing("Entity_Tear::HandleCollision 00673660: a versus familiar's block"); + if (tear_flies_on(*this, *collider)) return true; + deathFlags |= TEAR_DEATH_ENTITY; + isDead = true; + pos = vector_add(pos, vector_scale(collider->velocity, TEAR_HIT_MOVE)); + } + dead_eye_charge(*this, *collider); + return false; +} + +// 0067af60 What a hit's tear flags do to what it hits: the status effects, drops, knockback, light beams, eggs and +// the rest. A friendly target is spared, and a plain hit does nothing. +void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector&, const TearFlags& flags, Entity* source, float) +{ + if (entity && source && entity->IsDamageSourceFriendly(EntityRef(source))) return; + if (flags.any()) reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: the tear flags' effects"); +} + +// Part of 006d4a00: whether a hit comes at My Shadow's charger from behind its face, which turns diagonal while it +// attacks. +static bool is_charger_hit_from_behind(Entity_NPC& npc, Vector hitVelocity) +{ + std::string_view animation = npc.sprite.animState.GetAnimation(); + int facing = npc.sprite.isFlipX ? DIRECTION_LEFT : DIRECTION_RIGHT; + if (animation.ends_with("Up")) facing = DIRECTION_UP; + else if (animation.ends_with("Down")) facing = DIRECTION_DOWN; + + Vector face = vector_make(facing == DIRECTION_LEFT ? -1 : facing == DIRECTION_RIGHT ? 1 : 0, + facing == DIRECTION_UP ? -1 : facing == DIRECTION_DOWN ? 1 : 0); + if (animation.starts_with("Attack")) + face = vector_make(npc.sprite.isFlipX ? -DIAGONAL : DIAGONAL, facing == DIRECTION_UP ? -DIAGONAL : DIAGONAL); + return vector_dot(face, hitVelocity) >= 0; +} + +// 006d4a00 Whether a hit moving this way may hurt it: the knights and the Mask of Infamy guard the side they face, a +// shield-carrying enemy its own, and My Shadow's charger anything coming at its face. +bool Entity_NPC::CanBeDamagedFromVelocity(Vector hitVelocity) +{ + int facing = DIRECTION_DOWN; + if (type == ENTITY_KNIGHT || type == ENTITY_SELFLESS_KNIGHT || type == ENTITY_FLOATING_KNIGHT) + { + const std::string& animation = sprite.animState.GetAnimation(); + if (animation == "Up") facing = DIRECTION_UP; + else if (animation == "Hori") facing = sprite.isFlipX ? DIRECTION_LEFT : DIRECTION_RIGHT; + } + else if (type == ENTITY_MASK_OF_INFAMY) facing = get_velocity_direction(); + else if (type == ENTITY_FACING_SHIELD && variant == FACING_SHIELD_VARIANT) + { + if (vector_is_zero(hitVelocity)) return true; + int hitDirection = std::fabs(hitVelocity.y) < std::fabs(hitVelocity.x) + ? (hitVelocity.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT) + : (hitVelocity.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP); + return hitDirection == i1; + } + else if (type == ENTITY_CHARGER && variant == CHARGER_MY_SHADOW) return is_charger_hit_from_behind(*this, hitVelocity); + else return true; + + return !((hitVelocity.x < 0 && facing == DIRECTION_RIGHT) || (hitVelocity.x > 0 && facing == DIRECTION_LEFT) || + (hitVelocity.y > 0 && facing == DIRECTION_UP) || (hitVelocity.y < 0 && facing == DIRECTION_DOWN)); +} + +// 006d6d20 What a player's hurt does to the enemies that taunt: Gurdy and Satan take note, and the Beast's background +// horsemen cheer. +void Entity_NPC::on_player_damaged() +{ + if (type == ENTITY_GURDY || type == ENTITY_SATAN) v1.x = 1; + else if (type == ENTITY_BEAST && variant >= BEAST_BACKGROUND_FIRST && variant < BEAST_BACKGROUND_FIRST + BEAST_BACKGROUND_COUNT && + state == NPC_STATE_IDLE) + { + state = NPC_STATE_ATTACK; + stateFrame = (int)(Random() % BEAST_CHEER_RANGE) + BEAST_CHEER_MIN; + } +} + +// Part of 0078e1f0: the damage a player's touch deals: Mom's Heels, The Virus and Serpent's Kiss, Isaac's Heart's +// melee, the crow baby, Little Horn, Breath of Life, Aries at speed (which makes the player heavy and briefly unhurt), +// Tooth and Nail, all tripled when thrown. Whether Breath of Life adds to it goes back through isBreath. +static float player_contact_damage(Entity_Player& player, Entity& collider, bool& isBreath) +{ + bool isVersus = g_game->deathmatchManager.is_active(); + TemporaryEffects& effects = player.temporaryEffects; + float damage = 0; + if (collider.type == ENTITY_PLAYER && g_game->deathmatchManager.is_fighting()) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the versus rules' contact damage"); + + TemporaryEffect* taurus = effects.GetCollectibleEffect(COLLECTIBLE_TAURUS); + bool isRamming = effects.HasCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN) || + effects.HasCollectibleEffect(COLLECTIBLE_GAMEKID) || effects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL) || + (taurus && taurus->cooldown != 0); + if (isRamming) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the ramming items' contact damage"); + if (player.HasCollectible(COLLECTIBLE_MOMS_HEELS)) damage += isVersus ? HEELS_DAMAGE_VERSUS : HEELS_DAMAGE; + if (player.HasCollectible(COLLECTIBLE_VIRUS)) damage += isVersus ? VIRUS_DAMAGE_VERSUS : VIRUS_DAMAGE; + if (player.HasCollectible(COLLECTIBLE_SERPENTS_KISS)) damage += isVersus ? VIRUS_DAMAGE_VERSUS : VIRUS_DAMAGE; + + Entity_Player* twin = player.twin_get(); + Entity_Player& heartOwner = player.playerType == PLAYER_THESOUL_B && twin ? *twin : player; + if (heartOwner.HasCollectible(COLLECTIBLE_ISAACS_HEART)) damage = player.meleeDamage + player.meleeDamage + damage; + if (player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH)) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Midas' Touch (Entity::AddMidasFreeze)"); + if (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_CROW) damage += BABY_CONTACT_DAMAGE; + if (player.HasCollectible(COLLECTIBLE_LITTLE_HORN)) damage += HORN_DAMAGE; + isBreath = effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); + if (isBreath) damage += HORN_DAMAGE; + + bool isAries = player.HasCollectible(COLLECTIBLE_ARIES) || player.GetZodiacEffect() == COLLECTIBLE_ARIES; + if (isAries && vector_length(player.velocity) > ARIES_SPEED) + { + if (player.damageCooldown < 1) player.AddEntityFlags(FLAG_NO_DAMAGE_BLINK); + player.damageCooldown = std::max(player.damageCooldown, ARIES_COOLDOWN); + damage += isVersus ? ARIES_DAMAGE_VERSUS : ARIES_DAMAGE; + player.mass = ARIES_MASS; + } + if (effects.HasNullEffect(NULLITEM_TOOTH_AND_NAIL)) damage += isVersus ? NULL_CONTACT_DAMAGE_VERSUS : NULL_CONTACT_DAMAGE; + if (player.HasEntityFlags(FLAG_THROWN)) damage = damage * THROWN_DAMAGE_SCALE + THROWN_DAMAGE_BONUS; + return damage; +} + +// Part of 0078e1f0: the player's ways of touching that are not written yet: shoving an iced enemy, Tainted +// Magdalene's swing, Mega Mush's stomp, Tainted Soul grabbing her body and the suplex grab. +static void player_contact_missing_check(Entity_Player& player, Entity& collider) +{ + bool isEnemyLike = Entity::is_enemy_type(collider.type) || + (g_game->deathmatchManager.is_active() && collider.type == ENTITY_PLAYER); + bool isShoved = isEnemyLike && collider.HasEntityFlags(FLAG_ICE_FROZEN) && !collider.HasEntityFlags(FLAG_KNOCKED_BACK) && + vector_length_squared(player.velocity) > ICE_KNOCKBACK_SPEED_SQUARED; + if (isShoved) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: shoving an iced enemy (AddKnockback)"); + if (player.playerType == PLAYER_MAGDALENE_B && collider.IsVulnerableEnemy(nullptr) && + player.maggySwingCooldown < MAGGY_SWING_READY && !collider.IsFriendly()) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Tainted Magdalene's swing"); + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Mega Mush's stomp"); + if (player.playerType == PLAYER_THESOUL_B && collider.type == ENTITY_PLAYER && + static_cast(collider).playerType == PLAYER_THEFORGOTTEN_B) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Tainted Soul holding her body"); + if (player.suplexState == 1) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the suplex grab"); +} + +// 0078e1f0 Touches another entity, after a mod's MC_PRE_PLAYER_COLLISION: mid-suplex it passes enemies and shots, +// it hurts a vulnerable enemy by its items' contact damage, poisons with The Virus or Serpent's Kiss, and a thrown +// Tainted Forgotten slows on enemies. Whether the collision is ignored, which a pony's dash makes it. +bool Entity_Player::HandleCollision(Entity* collider, bool isLow) +{ + LuaResult lua = lua_engine_get().PrePlayerCollide(this, collider, isLow); + if (lua == LUA_RESULT_TRUE) return true; + if (lua == LUA_RESULT_FALSE) return false; + + player_contact_missing_check(*this, *collider); + if (suplexState >= SUPLEX_STATE_PASSING && (collider->IsEnemy() || collider->type == ENTITY_PROJECTILE)) return true; + + bool isIgnored = false; + if (collider->IsVulnerableEnemy(nullptr)) + { + isIgnored = ponyCharge > 0 || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_RECALL); + bool isBreath = false; + float damage = player_contact_damage(*this, *collider, isBreath); + if (damage > 0 && collider->TakeDamage(damage, DAMAGE_COUNTDOWN, EntityRef(this), CONTACT_COUNTDOWN) && isBreath) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Breath of Life's burst"); + } + bool isPoisoning = HasCollectible(COLLECTIBLE_VIRUS) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VIRUS) || + HasCollectible(COLLECTIBLE_SERPENTS_KISS); + if (collider->IsActiveEnemy(DEAD_EXCLUDED) && isPoisoning && !collider->HasEntityFlags(FLAG_NO_STATUS_EFFECTS) && + !collider->IsFriendly()) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: The Virus' poison (Entity::AddPoison)"); + if (playerType == PLAYER_THEFORGOTTEN_B && !isIgnored && collider->IsEnemy() && HasEntityFlags(FLAG_THROWN) && + !collider->IsFriendly()) + velocity = vector_scale(velocity, SLOW_ON_CONTACT); + if (collider->IsEnemy() && !collider->HasEntityFlags(FLAG_CHARM) && temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MARS)) + reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Mars' dash impact"); + return isIgnored; +} diff --git a/src/entity_combat.h b/src/entity_combat.h new file mode 100644 index 0000000..f526d9a --- /dev/null +++ b/src/entity_combat.h @@ -0,0 +1,21 @@ +#pragma once + +#include "entity.h" + +// The gibs a burst throws: how many and how far apart, which kinds (the config's GibFlag bits), their color, the push +// they share and the speed they fly at. +struct GibSpawn +{ + ColorMod color = COLOR_DEFAULT; + Vector position{}; + Vector velocity{}; + Entity* spawner = nullptr; + float speed = 1; + float spread = 0; + int amount = 0; + uint32_t gibFlags = 0; +}; + +void gibs_spawn(const GibSpawn& gibs); +Entity* bishop_nearest_find(const Vector& position, bool isCharmed); +uint64_t tear_damage_flags_get(const TearFlags& tearFlags, Entity* source); diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 9f25f74..8e29ba9 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -104,9 +104,6 @@ constexpr float RIGHT_ANGLE = 90; constexpr int SOUND_BOOMERANG_LOOP = 837; constexpr int SOUND_PORTAL_ENTITY_LOOP = 846; constexpr int SOUND_CHAIN_LOOP = 503; -constexpr int LUA_CALLBACK_POST_EFFECT_INIT = 54; -constexpr int LUA_CALLBACK_POST_EFFECT_UPDATE = 55; -constexpr int LUA_CALLBACK_POST_EFFECT_RENDER = 56; template static bool is_listed(const std::array& list, int value) @@ -206,7 +203,7 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u sprite.LoadGraphics(); if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Effect::Init 005cdb20: the versus mode's entity registration"); - lua_callback_check(LUA_CALLBACK_POST_EFFECT_INIT, "LuaEngine::PostEffectInit 00861330"); + lua_engine_get().PostEffectInit(this); } // 005d4380 Runs the effect for a frame at the room's time scale, held in place while paused and kept on its parent @@ -247,7 +244,7 @@ void Entity_Effect::Update() else poof_update(); if (timeout > 0 && --timeout < 1) isDead = true; pausePosition = pos; - lua_callback_check(LUA_CALLBACK_POST_EFFECT_UPDATE, "LuaEngine::PostEffectUpdate 00861410"); + 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 @@ -499,7 +496,7 @@ void Entity_Effect::Render(const Vector& offset) 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, {}, {}}); - lua_callback_check(LUA_CALLBACK_POST_EFFECT_RENDER, "LuaEngine::PostEffectRender 008614f0"); + lua_engine_get().PostEffectRender(this, offset); } // 005d2420 Stops the boomerang and portal loops unless another such effect still plays them, then removes it. diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index 14bf343..0f5ad83 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -22,10 +22,6 @@ constexpr uint64_t NS_PER_MS = 1000000; -// The Lua callbacks a spawn runs (ModCallbacks ids), which wait for their bindings. -constexpr int MC_PRE_ENTITY_SPAWN = 24; -constexpr int MC_PRE_ROOM_ENTITY_SPAWN = 71; - // An entity made by a Delirium form (by the original's use: Delirium's look and lowered thresholds), which its own // spawns inherit. constexpr uint64_t FLAG_DELIRIUM_FORM = 1ull << 60; @@ -79,22 +75,8 @@ constexpr int ENTITY_DOGMA = 950; constexpr int EFFECT_CRAWLSPACE_LADDER = 192; constexpr int BOSS_SATAN = 24; -constexpr int PICKUP_HEART = 10; constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_RUNE_CHANCE = 10; -constexpr int PICKUP_COIN = 20; -constexpr int PICKUP_KEY = 30; -constexpr int PICKUP_BOMB = 40; -constexpr int PICKUP_CHEST = 50; -constexpr int PICKUP_MIMIC_CHEST = 56; -constexpr int PICKUP_WOODEN_CHEST = 57; -constexpr int PICKUP_HAUNTED_CHEST = 58; -constexpr int PICKUP_LOCKED_CHEST = 60; -constexpr int PICKUP_GRAB_BAG = 69; -constexpr int PICKUP_LIL_BATTERY = 90; -constexpr int PICKUP_COLLECTIBLE = 100; -constexpr int PICKUP_SHOP_ITEM = 150; -constexpr int PICKUP_TAROT_CARD = 300; constexpr int PICKUP_RANDOM_CARD = 301; constexpr int COLLECTIBLE_DIRTY_MIND = 576; constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; @@ -436,11 +418,11 @@ Entity* Game::Spawn(const EntitySpawn& spawn) // 006fe410 Game::SpawnEx: takes an entity from its pool, places and inits it, and adds it to the room. A spawn of an // active enemy inherits from it, an erased enemy vanishes in a poof, and a TMTRAINER item may react. -Entity* game_spawn(const EntitySpawn& spawn, PoolMode mode) +Entity* game_spawn(const EntitySpawn& request, PoolMode mode) { Game& game = *g_game; - if (static_cast(g_luaEngine)->enabledCallbacks[MC_PRE_ENTITY_SPAWN]) - reconstruction_missing("lua_callback_run_pre_entity_spawn 008646e0"); + EntitySpawn spawn = request; + lua_engine_get().Callback_PreEntitySpawn(spawn); if (game.deathmatchManager.state >= DEATHMATCH_INTRO) reconstruction_missing("Game::SpawnEx 006fe410: a versus match's " "blacklisted pickups (0042b560)"); @@ -565,9 +547,9 @@ constexpr std::array LOCKED_ENTRIES = {{ {ENTITY_PICKUP, PICKUP_KEY, 4, ACHIEVEMENT_KEY_CHARGED, -1, 0}, {ENTITY_PICKUP, PICKUP_GRAB_BAG, 2, ACHIEVEMENT_GRAB_BAG_BLACK, -1, 0}, {ENTITY_PICKUP, PICKUP_LIL_BATTERY, 4, ACHIEVEMENT_LIL_BATTERY_GOLDEN, -1, 0}, - {ENTITY_PICKUP, PICKUP_MIMIC_CHEST, -1, ACHIEVEMENT_MIMIC_CHEST, PICKUP_CHEST, -1}, - {ENTITY_PICKUP, PICKUP_HAUNTED_CHEST, -1, ACHIEVEMENT_HAUNTED_CHEST, PICKUP_CHEST, -1}, - {ENTITY_PICKUP, PICKUP_WOODEN_CHEST, -1, ACHIEVEMENT_WOODEN_CHEST, PICKUP_LOCKED_CHEST, -1}, + {ENTITY_PICKUP, PICKUP_WOODENCHEST, -1, ACHIEVEMENT_MIMIC_CHEST, PICKUP_CHEST, -1}, + {ENTITY_PICKUP, PICKUP_HAUNTEDCHEST, -1, ACHIEVEMENT_HAUNTED_CHEST, PICKUP_CHEST, -1}, + {ENTITY_PICKUP, PICKUP_MEGACHEST, -1, ACHIEVEMENT_WOODEN_CHEST, PICKUP_LOCKEDCHEST, -1}, {ENTITY_SLOT, SLOT_HELL_GAME, -1, ACHIEVEMENT_HELL_GAME, SLOT_DEVIL_BEGGAR, -1}, {ENTITY_SLOT, SLOT_ROTTEN_BEGGAR, -1, ACHIEVEMENT_ROTTEN_BEGGAR, SLOT_KEY_MASTER, -1}, {ENTITY_SLOT, SLOT_CRANE_GAME, -1, ACHIEVEMENT_CRANE_GAME, SLOT_MACHINE, -1}, @@ -583,7 +565,7 @@ static void entry_card_replace(RoomEntry& entry, uint32_t seed) int card = ItemPool::GetCardEx((int)seed, CARD_SPECIAL_CHANCE, CARD_RUNE_CHANCE, CARD_RUNE_CHANCE, true); RNG cardRng = {seed, ENTRY_RNG._shift1, ENTRY_RNG._shift2, ENTRY_RNG._shift3}; - entry.subtype = lua_callback_run_get_card(&cardRng, card, true, true, false); + entry.subtype = lua_engine_get().GetCard({.rng = &cardRng, .card = card, .isPlaying = true, .isRunes = true}); } // A pickup or slot a layout names that is not unlocked yet becomes its basic kind. The Confessional is a soul heart @@ -593,7 +575,7 @@ static void entry_locked_replace(RoomEntry& entry, RNG& rng) if (entry.type == ENTITY_PICKUP) { uint32_t cardSeed = rng.Next(); - if (entry.variant == PICKUP_TAROT_CARD) return entry_card_replace(entry, cardSeed); + if (entry.variant == PICKUP_TAROTCARD) return entry_card_replace(entry, cardSeed); } else if (entry.type == ENTITY_SLOT && entry.variant == SLOT_CONFESSIONAL) { @@ -815,15 +797,14 @@ void room_entry_transform(Room& room, RoomEntry& entry, int gridIndex, uint32_t entry.variant = entry.type == ENTRY_FIREPLACE_RED || rng.Next() % FIREPLACE_RED_ODDS == 0; entry.type = ENTITY_FIREPLACE; } - if (static_cast(g_luaEngine)->enabledCallbacks[MC_PRE_ROOM_ENTITY_SPAWN]) - reconstruction_missing("LuaEngine::Callback_PreEntitySpawn 00866490"); + lua_callback_check(MC_PRE_ROOM_ENTITY_SPAWN, "LuaEngine::PreRoomEntitySpawn 00866490"); if (entry.type == ENTITY_PICKUP && entry.variant == PICKUP_RANDOM_CARD) { - entry.variant = PICKUP_TAROT_CARD; + entry.variant = PICKUP_TAROTCARD; uint32_t cardSeed = rng.Next(); int card = ItemPool::GetCardEx((int)cardSeed, 0, 1, 0, true); RNG cardRng = {cardSeed, ENTRY_RNG._shift1, ENTRY_RNG._shift2, ENTRY_RNG._shift3}; - entry.subtype = lua_callback_run_get_card(&cardRng, card, false, true, true); + entry.subtype = lua_engine_get().GetCard({.rng = &cardRng, .card = card, .isOnlyRunes = true, .isRunes = true}); } entry_locked_replace(entry, rng); @@ -833,7 +814,7 @@ void room_entry_transform(Room& room, RoomEntry& entry, int gridIndex, uint32_t bool isDevilTreasure = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE; if (room.roomType == ROOM_TREASURE && isDevilTreasure && entry.type == ENTITY_PICKUP && entry.variant == PICKUP_COLLECTIBLE && entry.subtype == 0) - entry.variant = PICKUP_SHOP_ITEM; + entry.variant = PICKUP_SHOPITEM; if (entry.type == ENTITY_SLOT) { RNG slotRng = {seed, SLOT_RNG._shift1, SLOT_RNG._shift2, SLOT_RNG._shift3}; diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index 490285a..9cb803a 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -193,6 +193,7 @@ constexpr int COLLECTIBLE_CONTAGION_ID = 466; constexpr int COLLECTIBLE_BROKEN_MODEM_ID = 514; constexpr int COLLECTIBLE_SANGUINE_BOND_ID = 640; constexpr int COLLECTIBLE_VASCULITIS_ID = 657; +constexpr int COLLECTIBLE_GUPPYS_EYE_ID = 665; constexpr int COLLECTIBLE_BONE_SPURS_ID = 683; constexpr int COLLECTIBLE_LIL_ABADDON_ID = 684; constexpr int COLLECTIBLE_SALVATION_ID = 696; @@ -612,7 +613,7 @@ void Entity_NPC::Init(int entityType, int entityVariant, int entitySubType, uint pathfinder.Reset(); if (isBoss) reconstruction_missing("Entity_NPC::Init 006b8b20: the room's boss count (Room+0x7224)"); totalDamageTaken = 0; - lua_callback_check(CALLBACK_POST_NPC_INIT, "Entity_NPC::Init 006b8b20: MC_POST_NPC_INIT"); + lua_engine_get().PostNPCInit(this); } // The odds a boss spawns in one of its alternate colors. @@ -837,17 +838,247 @@ void Entity_NPC::SetBossColorIdx(int bossColorIdx, int) ResetColor(); } -// 006d03e0 -void Entity_NPC::MakeChampion(uint32_t, int, bool) +// A champion color's look, the exe's table at 00c354c0: the color its _champion sheets draw in (none without alpha) +// and the color its sprite otherwise shows. +struct ChampionLook { - reconstruction_missing("Entity_NPC::MakeChampion 006d03e0"); + ColorMod sheetColor; + ColorMod spriteColor; +}; + +// A look from its sheet color's channels and its sprite's tint and offset. +constexpr ChampionLook champion_look(float red, float green, float blue, float alpha, ColorMod spriteColor = COLOR_DEFAULT) +{ + return {{{red, green, blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, spriteColor}; } -// 00c354c0 (data) The table of champion looks. +constexpr float CHAMPION_GLOW = 30 / 255.0f; +constexpr std::array CHAMPION_LOOKS = {{ + champion_look(1, 0.1f, 0.1f, 1), + champion_look(0.6f, 0.6f, 0, 1), + champion_look(0.1f, 0.8f, 0.2f, 1), + champion_look(1, 0.6f, 0.2f, 1), + champion_look(0.2f, 0.2f, 1, 1), + champion_look(0.03f, 0.24f, 0.24f, 1), + champion_look(1, 1, 1, 1, {{1, 1, 1, 1}, {0, 0, 0, 0}, {90 / 255.0f, 90 / 255.0f, 90 / 255.0f}}), + champion_look(0.5f, 0.5f, 0.5f, 1), + champion_look(1, 1, 1, 1, {{1, 1, 1, 0.6f}, {0, 0, 0, 0}, {120 / 255.0f, 120 / 255.0f, 120 / 255.0f}}), + champion_look(0, 0, 0, 0, {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}), + champion_look(1, 0, 1, 1), + champion_look(0.75f, 0, 1, 1), + champion_look(0.5f, 0, 0, 1), + champion_look(0.5f, 0.5f, 1, 1), + champion_look(0, 0, 0, 0), + champion_look(0.1f, 0.8f, 0.2f, 1, {{0.9f, 1, 0.9f, 1}, {0, 0, 0, 0}, {0, CHAMPION_GLOW, 0}}), + champion_look(0.5f, 0.5f, 0.5f, 1, {{0.9f, 0.9f, 0.9f, 1}, {0, 0, 0, 0}, {CHAMPION_GLOW, CHAMPION_GLOW, CHAMPION_GLOW}}), + champion_look(0.8f, 0.8f, 0.8f, 1, {{1, 1, 1, 1}, {0, 0, 0, 0}, {50 / 255.0f, 50 / 255.0f, 50 / 255.0f}}), + champion_look(0, 0, 0, 0), + champion_look(0, 0, 0, 0), + champion_look(1, 0.2f, 0.2f, 1, {{1, 0.9f, 0.9f, 1}, {0, 0, 0, 0}, {CHAMPION_GLOW, 0, 0}}), + champion_look(0, 0, 0, 0), + champion_look(0, 0, 0, 0), + champion_look(0.3f, 0.3f, 0.3f, 1, {{0.8f, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}), + champion_look(0.28f, 0.14f, 0.134f, 1), + champion_look(1, 1, 1, 1), +}}; + +// The colors a seed's champion roll picks among: the common ones (the late stages' with yellow), the rare, the +// pulsing and sized, the late stages' special ones, and the late stages' uncommon ones. +constexpr std::array CHAMPIONS_EARLY = {CHAMPION_RED, CHAMPION_GREEN, CHAMPION_DARK_GREEN, + CHAMPION_GREY, CHAMPION_PINK, CHAMPION_LIGHT_BLUE}; +constexpr std::array CHAMPIONS_LATE = {CHAMPION_RED, CHAMPION_YELLOW, CHAMPION_GREEN, CHAMPION_DARK_GREEN, + CHAMPION_GREY, CHAMPION_PINK, CHAMPION_LIGHT_BLUE}; +constexpr std::array CHAMPIONS_RARE = {CHAMPION_ORANGE, CHAMPION_DARK_BLUE, CHAMPION_DARK_RED}; +constexpr std::array CHAMPIONS_PULSING = {CHAMPION_CAMO, CHAMPION_PULSE_GREEN, CHAMPION_PULSE_GREY, + CHAMPION_FLY_PROTECTED, CHAMPION_TINY, CHAMPION_GIANT}; +constexpr std::array CHAMPIONS_SPECIAL = {CHAMPION_PULSE_RED, CHAMPION_SIZE_PULSE, CHAMPION_KING, + CHAMPION_DEATH}; +constexpr std::array CHAMPIONS_UNCOMMON = {CHAMPION_TRANSPARENT, CHAMPION_FLICKER, CHAMPION_PURPLE, + CHAMPION_BROWN}; +constexpr uint32_t CHAMPION_RNG_SHIFT_INDEX = 33; +constexpr uint32_t CHAMPION_LATE_STAGE = 5; +constexpr uint32_t CHAMPION_YELLOW_STAGE = 3; +constexpr uint32_t CHAMPION_PULSING_EARLY_COUNT = 4; +constexpr float CHAMPION_ROLL_WHITE = 0.005f; +constexpr float CHAMPION_ROLL_RAINBOW = 0.01f; +constexpr float CHAMPION_ROLL_UNCOMMON = 0.05f; +constexpr float CHAMPION_ROLL_RARE = 0.15f; +constexpr float CHAMPION_ROLL_PULSING = 0.3f; +constexpr float CHAMPION_ROLL_SPECIAL = 0.35f; +constexpr std::array CHAMPION_NO_DARK_RED_TYPES = {240, 241, 242, 304}; +constexpr int ENTITY_NO_WHITE_CHAMPION = 889; + +// The champions' health, speed, size and contact damage, and the effect variant some keep around them. +constexpr float CHAMPION_SCALE = 1.15f; +constexpr float CHAMPION_TINY_SCALE = 0.5f; +constexpr float CHAMPION_GIANT_SCALE = 1.5f; +constexpr float CHAMPION_CONTACT_DAMAGE = 2; +constexpr float CHAMPION_DEATH_CONTACT_DAMAGE = 4; +constexpr float CHAMPION_HP_RED = 1.333f; +constexpr float CHAMPION_HP_YELLOW = 0.75f; +constexpr float CHAMPION_HP_GREY = 0.333f; +constexpr float CHAMPION_HP_BIG = 1.5f; +constexpr float CHAMPION_HP_KING = 3; +constexpr float CHAMPION_SPEED_FAST = 1.333f; +constexpr float CHAMPION_SPEED_SLOW = 0.8f; +constexpr float CHAMPION_SPEED_GIANT = 0.9f; +constexpr int CHAMPION_FLICKER_MIN = 60; +constexpr int CHAMPION_FLICKER_RANGE = 30; +constexpr int CHAMPION_SHOT_MIN = 40; +constexpr int CHAMPION_SHOT_RANGE = 20; +constexpr int EFFECT_PULLING = 57; +constexpr int EFFECT_CREEP_GREEN = 23; +constexpr int CHAMPION_CREEP_FRAMES = 7; +constexpr int CHAMPION_CREEP_TIMEOUT = 30; +constexpr float CHAMPION_SHOT_SPEED = 5; +constexpr float CHAMPION_SHOT_FALL_ACCEL = 0.3f; +constexpr float CHAMPION_SHOT_FALL_SPEED = -5; +constexpr int SOUND_BLOODSHOOT = 178; +constexpr float FLICKER_FADE = 0.05f; +constexpr ColorMod FRIENDLY_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, -0.5f}, {0.1f, 0.1f, 0.1f}}; +constexpr ColorMod FROZEN_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 0.5f}, {0.3f, 0.5f, 0.8f}}; + +// Where a flickering champion is in its fade. +enum FlickerState : int +{ + FLICKER_SHOWN, + FLICKER_FADING_OUT, + FLICKER_FADING_IN, + FLICKER_HIDDEN +}; +constexpr int PULLING_PURPLE = 0; +constexpr int PULLING_GREY = 1; +constexpr int PULLING_RED = 2; +constexpr ColorMod PULLING_RED_COLOR = {{1, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// 00505b80 The color a champion shows over a sprite without its sheets: its sheet color laid over its sprite color +// (Color::__mul), or the sprite color for a look drawn on no sheet. +static ColorMod champion_sprite_color_get(int championColor) +{ + const ChampionLook& look = CHAMPION_LOOKS[championColor]; + if (look.sheetColor._tint[3] <= 0) return look.spriteColor; + + ColorMod color = look.sheetColor; + const ColorMod& other = look.spriteColor; + for (int i = 0; i < 4; i++) color._tint[i] *= other._tint[i]; + if (other._colorize[0] + other._colorize[1] + other._colorize[2] != 0) + for (int i = 0; i < 4; i++) color._colorize[i] = other._colorize[i]; + for (int i = 0; i < 3; i++) color._offset[i] += other._offset[i]; + return color; +} + +// The sheet color of a champion color's look, or none for a look drawn on no _champion sheet. const ColorMod* champion_color_get(int championColor) { if (championColor < 0 || championColor >= CHAMPION_COUNT) return nullptr; - reconstruction_missing("Entity_NPC champion colors: the table at 00c354c0"); + const ColorMod& sheetColor = CHAMPION_LOOKS[championColor].sheetColor; + return sheetColor._tint[3] > 0 ? &sheetColor : nullptr; +} + +// Part of 006d03e0: a seed's champion color by the stage: rarely white or rainbow and uncommonly a strange one late, +// else a rare, pulsing or sized, special late, or common one. +static int champion_color_roll(uint32_t seed) +{ + RNG rng; + rng.SetSeed(seed, CHAMPION_RNG_SHIFT_INDEX); + float roll = rng.RandomFloat(); + uint32_t stage = g_game->stage; + bool isLate = stage >= CHAMPION_LATE_STAGE; + + if (roll < CHAMPION_ROLL_RAINBOW && isLate) return roll < CHAMPION_ROLL_WHITE ? CHAMPION_WHITE : CHAMPION_RAINBOW; + if (roll < CHAMPION_ROLL_UNCOMMON && isLate) return CHAMPIONS_UNCOMMON[rng.RandomInt(CHAMPIONS_UNCOMMON.size())]; + if (roll < CHAMPION_ROLL_RARE) return CHAMPIONS_RARE[rng.RandomInt(CHAMPIONS_RARE.size())]; + if (roll < CHAMPION_ROLL_PULSING) + { + uint32_t count = stage >= CHAMPION_YELLOW_STAGE ? CHAMPIONS_PULSING.size() : CHAMPION_PULSING_EARLY_COUNT; + return CHAMPIONS_PULSING[rng.RandomInt(count)]; + } + if (roll < CHAMPION_ROLL_SPECIAL && isLate) return CHAMPIONS_SPECIAL[rng.RandomInt(CHAMPIONS_SPECIAL.size())]; + if (stage < CHAMPION_YELLOW_STAGE) return CHAMPIONS_EARLY[rng.RandomInt(CHAMPIONS_EARLY.size())]; + return CHAMPIONS_LATE[rng.RandomInt(CHAMPIONS_LATE.size())]; +} + +// Part of 006d03e0: what a champion color changes beside the look: health, speed, grid collision, timers, and the +// pulling effect or eternal fly some keep with them. +void Entity_NPC::champion_traits_apply(bool isInit) +{ + switch (championColorIdx) + { + case CHAMPION_RED: maxHitPoints *= CHAMPION_HP_RED; break; + case CHAMPION_YELLOW: + championSpeed = CHAMPION_SPEED_FAST; + maxHitPoints *= CHAMPION_HP_YELLOW; + break; + case CHAMPION_GREY: maxHitPoints *= CHAMPION_HP_GREY; [[fallthrough]]; + case CHAMPION_DARK_BLUE: championSpeed = CHAMPION_SPEED_SLOW; break; + case CHAMPION_TRANSPARENT: entityGridCollisionClass = GRIDCOLL_WALLS; break; + case CHAMPION_FLICKER: flickerTimer = random_below(CHAMPION_FLICKER_RANGE) + CHAMPION_FLICKER_MIN; break; + case CHAMPION_PINK: championTimer = random_below(CHAMPION_SHOT_RANGE) + CHAMPION_SHOT_MIN; break; + case CHAMPION_PURPLE: spawn_at(ENTITY_EFFECT, EFFECT_PULLING, PULLING_PURPLE, pos, this)->parent = this; break; + case CHAMPION_PULSE_GREY: spawn_at(ENTITY_EFFECT, EFFECT_PULLING, PULLING_GREY, pos, this)->parent = this; break; + case CHAMPION_FLY_PROTECTED: + if (!isInit) reconstruction_missing("Entity_NPC::MakeChampion 006d03e0: the fly protected champion's fly"); + break; + case CHAMPION_TINY: + maxHitPoints *= CHAMPION_HP_GREY; + championSpeed *= CHAMPION_SPEED_FAST; + break; + case CHAMPION_GIANT: + maxHitPoints *= CHAMPION_HP_BIG; + championSpeed *= CHAMPION_SPEED_GIANT; + [[fallthrough]]; + case CHAMPION_DEATH: + if (collisionDamage > 0) collisionDamage = CHAMPION_DEATH_CONTACT_DAMAGE; + break; + case CHAMPION_PULSE_RED: + { + Entity* pulling = spawn_at(ENTITY_EFFECT, EFFECT_PULLING, PULLING_RED, pos, this); + pulling->parent = this; + pulling->SetColor(PULLING_RED_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + break; + } + case CHAMPION_KING: maxHitPoints *= CHAMPION_HP_KING; break; + case CHAMPION_RAINBOW: reconstruction_missing("Entity_NPC::MakeChampion 006d03e0: the rainbow champion"); + default: break; + } +} + +// 006d03e0 Makes it a champion of a color, or of one its seed draws for the stage at -1: twice the health and 2 +// contact damage, its size (half for the tiny, 1.5 for the giant, 1.15 else), its champion sprite and its color's +// traits. Dark red never befalls the slides and white not the fly protected kind. Only Init makes a champion twice. +void Entity_NPC::MakeChampion(uint32_t seed, int championColor, bool isInit) +{ + if (isChampion && !isInit) return; + + float baseMaxHitPoints = maxHitPoints; + maxHitPoints = baseMaxHitPoints + baseMaxHitPoints; + ResetColor(); + if (collisionDamage > 0) collisionDamage = CHAMPION_CONTACT_DAMAGE; + isChampion = true; + championColorIdx = championColor; + if (championColor < 0) championColor = champion_color_roll(seed); + + bool isNoDarkRed = std::ranges::find(CHAMPION_NO_DARK_RED_TYPES, type) != CHAMPION_NO_DARK_RED_TYPES.end(); + if (championColor == CHAMPION_DARK_RED && isNoDarkRed) championColor = CHAMPION_RED; + else if (championColor == CHAMPION_WHITE && type == ENTITY_NO_WHITE_CHAMPION) championColor = CHAMPION_FLY_PROTECTED; + championColorIdx = std::clamp(championColor, (int)CHAMPION_RED, (int)CHAMPION_RAINBOW); + + float championScale = CHAMPION_SCALE; + if (championColorIdx == CHAMPION_TINY) + { + SetSize(size * CHAMPION_TINY_SCALE, sizeMulti, config->gridCollisionPoints); + championScale = CHAMPION_TINY_SCALE; + } + else if (championColorIdx == CHAMPION_GIANT) championScale = CHAMPION_GIANT_SCALE; + scale = championScale; + sprite.scale = vector_make(championScale * shrinkStatus1, championScale * shrinkStatus1); + load_graphics(false); + champion_traits_apply(isInit); + + if (type == ENTITY_MULLIGAN && variant == MULLIGAN_VARIANT_FLEEING) + maxHitPoints = std::min(maxHitPoints, baseMaxHitPoints); + if (!isInit) health = maxHitPoints; + ResetColor(); } // The enemy a "random enemy" spawn (type 306) turns into on each stage, on Normal and on Hard. @@ -1212,7 +1443,7 @@ void Entity_NPC::appear_update() poof->posOffset = posOffset; poof->renderDepthOffset = posOffset.y + 1; if (isChampion && championColorIdx < CHAMPION_COUNT) - reconstruction_missing("Entity_NPC::Update 006c4b30: a champion's appear poof color (GetColorWithFlash)"); + poof->SetColor(champion_sprite_color_get(championColorIdx), -1, COLOR_PRIORITY_DEFAULT, false, true); int sound = isDeathSoundAlt ? SOUND_SUMMON_POOF : SOUND_SUMMONSOUND; g_manager->sfxManager.Stop(sound); @@ -1343,12 +1574,105 @@ void Entity_NPC::decoy_update() // creep and shot champions), and Wrath's twin flicker. void Entity_NPC::champion_update() { - if (isChampion || type == ENTITY_FLICKER_TYPE) - reconstruction_missing("Entity_NPC::Update 006c4b30: the champion colors' effects"); - if (HasEntityFlags(FLAG_SHRINK) && shrinkCountdown >= 1 && shrinkCountdown < SHRINK_PULSE_FRAMES) + const NullFrame* overlay = sprite.animState.animData ? sprite.animState.GetNullFrame("OverlayEffect") : nullptr; + bool isEffectShown = !overlay || overlay->isVisible; + bool isShrunk = HasEntityFlags(FLAG_SHRINK); + int champion = championColorIdx; + + bool isGreen = champion == CHAMPION_GREEN || champion == CHAMPION_RAINBOW; + if (isGreen && isEffectShown && IsFrame(CHAMPION_CREEP_FRAMES, 0) && !isShrunk) + { + Entity_Effect* creep = static_cast(spawn_at(ENTITY_EFFECT, EFFECT_CREEP_GREEN, 0, pos, this)); + creep->SetTimeout(CHAMPION_CREEP_TIMEOUT); + creep->Update(); + } + if (champion == CHAMPION_BROWN) reconstruction_missing("Entity_NPC::Update 006c4b30: the brown champion's poop"); + if (champion == CHAMPION_WHITE) white_champion_update(); + if (champion == CHAMPION_FLICKER || type == ENTITY_FLICKER_TYPE) flicker_update(); + if (champion == CHAMPION_TRANSPARENT) entityGridCollisionClass = GRIDCOLL_WALLS; + else if ((champion == CHAMPION_PINK || champion == CHAMPION_RAINBOW) && --championTimer < 1 && isEffectShown && + !isShrunk) + champion_shot_fire(); + if ((champion == CHAMPION_PURPLE || champion == CHAMPION_RAINBOW) && isEffectShown) + reconstruction_missing("Entity_NPC::Update 006c4b30: the purple champion's pull"); + if (champion == CHAMPION_DARK_RED && (isDead || championRegenTimer != 0)) + reconstruction_missing("Entity_NPC::Update 006c4b30: the dark red champion's regeneration"); + bool isPulsing = champion == CHAMPION_CAMO || champion == CHAMPION_PULSE_GREEN || champion == CHAMPION_PULSE_GREY || + champion == CHAMPION_PULSE_RED || champion == CHAMPION_KING || champion == CHAMPION_RAINBOW; + if (isPulsing) reconstruction_missing("Entity_NPC::Update 006c4b30: the camouflaged, pulsing and king champions"); + if (champion == CHAMPION_SIZE_PULSE && championTimer > 0) championTimer--; + if (isShrunk && shrinkCountdown >= 1 && shrinkCountdown < SHRINK_PULSE_FRAMES) reconstruction_missing("Entity_NPC::Update 006c4b30: the shrinking pulse"); } +// Part of 006c4b30: a white champion cannot be hurt while another enemy holding the doors lives, unless that one is +// white too. +void Entity_NPC::white_champion_update() +{ + isInvincible = false; + ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + for (Entity* entity : g_game->room->GetEntities()->updateEL) + { + Entity_NPC* npc = entity->IsEnemy() ? dynamic_cast(entity) : nullptr; + if (!npc || !npc->CanShutDoors() || (npc->isChampion && npc->championColorIdx == CHAMPION_WHITE)) continue; + isInvincible = true; + AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + } +} + +// Part of 006c4b30: the flickering champion (and the Flicker kind) waits visible, fades out, hides, then fades back +// in, its sprite's alpha following. +void Entity_NPC::flicker_update() +{ + switch (flickerState) + { + case FLICKER_SHOWN: + if (flickerTimer-- < 0) flickerState = FLICKER_FADING_OUT; + break; + case FLICKER_FADING_OUT: + if (flickerAlpha > 0) flickerAlpha -= FLICKER_FADE; + else + { + flickerState = FLICKER_HIDDEN; + flickerTimer = random_below(CHAMPION_FLICKER_RANGE) + CHAMPION_FLICKER_MIN; + } + break; + case FLICKER_FADING_IN: + if (flickerAlpha < 1) flickerAlpha += FLICKER_FADE; + else + { + flickerState = FLICKER_SHOWN; + flickerTimer = random_below(CHAMPION_FLICKER_RANGE) + CHAMPION_FLICKER_MIN; + } + break; + case FLICKER_HIDDEN: + isVisible = false; + if (flickerTimer-- < 0) + { + isVisible = true; + flickerState = FLICKER_FADING_IN; + } + break; + default: break; + } + sprite.color._tint[3] = flickerAlpha; +} + +// Part of 006c4b30: the pink champion shoots along its walk every 40 to 59 frames while it moves. +void Entity_NPC::champion_shot_fire() +{ + float speed = vector_length(velocity); + if (speed <= 0) return; + + Vector direction = vector_scale(velocity, 1 / speed); + championTimer = random_below(CHAMPION_SHOT_RANGE) + CHAMPION_SHOT_MIN; + ProjectileParams params; + params.fallingAccelModifier = CHAMPION_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = CHAMPION_SHOT_FALL_SPEED; + FireProjectiles(pos, vector_scale(direction, CHAMPION_SHOT_SPEED), PROJECTILES_SINGLE, params); + PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); +} + // Part of 006c4b30: in a room that checks it, an enemy no grounded player has a path to stops holding the doors // after its second miss, checked every 60 frames once 900 frames passed. void Entity_NPC::unreachable_update() @@ -1868,12 +2192,24 @@ void Entity_NPC::ClearDequeRefs() entityDeque.clear(); } -// 006c1100 Shows its own color again: a boss's alternate color, or for a champion its champion color. +// 006c1100 Shows its own color again: a champion its sprite color (on its _champion sheets) or its color laid over +// it, a boss its alternate color, else its own. A friendly enemy is washed out and a frozen one iced. void Entity_NPC::ResetColor() { - if (isChampion) reconstruction_missing("Entity_NPC::ResetColor 006c1100: a champion's color"); - if (bosscoloridx < 0) sprite.color = color; + if (isChampion) + { + bool isChampionSheet = std::ranges::any_of(sprite.layerStates, [](const LayerState& layer) + { return layer.bitflags & LAYER_CHAMPION_SHEET; }); + if (championColorIdx >= 0 && championColorIdx < CHAMPION_COUNT) + sprite.color = isChampionSheet ? CHAMPION_LOOKS[championColorIdx].spriteColor + : champion_sprite_color_get(championColorIdx); + } + else if (bosscoloridx < 0) sprite.color = color; else if (bosscoloridx < (int)config->bossColors.size()) sprite.color = config->bossColors[bosscoloridx].color; + + bool isShadowCharger = type == ENTITY_SHADOW_CHARGER && variant == 0 && subtype == SHADOW_CHARGER_SUBTYPE; + if (IsFriendly() && !isShadowCharger) sprite.color = FRIENDLY_COLOR; + if (type == ENTITY_FROZEN_ENEMY) sprite.color = FROZEN_COLOR; } // 006d4e00 Bursts it: a blood explosion its size (or a fly's, a spider's, a poop's), in its splat color, from its @@ -2270,7 +2606,7 @@ void Entity_NPC::Render(const Vector& offset) Entity::Render(offset); if (!isVisible) renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset); - lua_callback_check(CALLBACK_POST_NPC_RENDER, "Entity_NPC::Render 006d2e50: MC_POST_NPC_RENDER"); + lua_engine_get().PostNPCRender(this, offset); RenderMode renderMode = g_game->room->entityList.renderMode; if (renderMode != RENDER_NORMAL && renderMode != RENDER_WATER_ABOVE) return; @@ -2415,7 +2751,7 @@ void Entity_NPC::trigger_kill_item_effects() aimTargetEffect = nullptr; if (HasEntityFlags(FLAG_BRIMSTONE_MARKED) && HasEntityFlags(FLAG_EXTRA_GORE)) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: the marked enemy's spreading status"); - lua_callback_check(CALLBACK_POST_NPC_DEATH, "Entity_NPC::trigger_kill_item_effects 006d5400: MC_POST_NPC_DEATH"); + lua_engine_get().PostNPCDeath(this); } // 006bbdc0 The rewards a dead enemy gives its killers: the damage flags' and Gimpy's drops, the familiars' and @@ -2697,30 +3033,12 @@ void* Entity_NPC::fireplace_get_loot(void*, bool) reconstruction_missing("Entity_NPC::fireplace_get_loot 006d1580"); } -// 006d4a00 -bool Entity_NPC::CanBeDamagedFromVelocity(Vector) -{ - reconstruction_missing("Entity_NPC::CanBeDamagedFromVelocity 006d4a00"); -} - // 006d4db0 bool Entity_NPC::CanReroll() { reconstruction_missing("Entity_NPC::CanReroll 006d4db0"); } -// 006d6d20 -uint32_t Entity_NPC::on_player_damaged() -{ - reconstruction_missing("Entity_NPC::on_player_damaged 006d6d20"); -} - -// 006d6d80 -void Entity_NPC::room_enter() -{ - reconstruction_missing("Entity_NPC::room_enter 006d6d80"); -} - // 006d7520 void Entity_NPC::update_blood_guide_gibs(float*) { @@ -2763,10 +3081,15 @@ uint8_t Entity_NPC::split(float, const EntityRef&, bool) reconstruction_missing("Entity_NPC::split 006d97e0"); } -// 006da530 +// 006da530 While a player holds Guppy's Eye, a lit fireplace or a living shopkeeper shows the loot it would drop as +// ghosts. Otherwise the ghosts shown before go. void Entity_NPC::UpdatePickupGhosts() { - reconstruction_missing("Entity_NPC::UpdatePickupGhosts 006da530"); + bool isLootHolder = (type == ENTITY_FIREPLACE && health > 1) || (type == ENTITY_SHOPKEEPER && !isDead); + + if (isLootHolder && g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_GUPPYS_EYE_ID, LAZARUS_SHARE_CHECK)) + reconstruction_missing("Entity_NPC::UpdatePickupGhosts 006da530 (the loot ghosts)"); + if (pickupGhostsEntity) pickupGhostsEntity->Remove(); } // 0096ce90 diff --git a/src/entity_npc.h b/src/entity_npc.h index c1b4171..676af2f 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -258,6 +258,10 @@ struct Entity_NPC : Entity void death_animation_start(); void decoy_update(); void champion_update(); + void champion_traits_apply(bool isInit); + void white_champion_update(); + void flicker_update(); + void champion_shot_fire(); void unreachable_update(); void dead_update(); void midas_coins_spawn(); @@ -342,7 +346,7 @@ struct Entity_NPC : Entity void CreateGoldParticles(uint32_t count); void* shopkeeper_get_loot(void* outLoot, bool isShouldAdvance); void* fireplace_get_loot(void* outLoot, bool isShouldAdvance); - uint32_t on_player_damaged(); + void on_player_damaged(); static int FindTargetPit(const Vector& pos1, const Vector& pos2, uint32_t pitIndex); static Entity_NPC* ThrowStrider(const Vector& pos, Entity* spawner, const Vector& targetPos); static void* QueryNPCsType(void* outList, int type, int variant); diff --git a/src/entity_npc_room.cpp b/src/entity_npc_room.cpp new file mode 100644 index 0000000..cf5cf8e --- /dev/null +++ b/src/entity_npc_room.cpp @@ -0,0 +1,91 @@ +#include "entity_npc.h" +#include "entity_player.h" +#include "game.h" +#include "level_generator.h" +#include "npc_ai.h" + +constexpr int ENTITY_MOTHERS_SHADOW = 867; +constexpr int DARK_ESAU_SECOND = 1; +constexpr int EFFECT_POOF01 = 15; +constexpr int COLOR_PRIORITY_DEFAULT = 255; +constexpr ColorMod DARK_ESAU_POOF_COLOR = {{0.1f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// A room's size in the world, which a shadow following the players moves by for each room they moved. +constexpr float ROOM_STEP_X = 520; +constexpr float ROOM_STEP_Y = 280; + +// The door slot's side when the rooms have no place on the floor: the xorshift (1, 11, 16) of the decoration seed. +constexpr uint32_t DOOR_SIDE_SHIFT_INDEX = 5; +constexpr int DOOR_SIDES = 4; + +// A persistent enemy is spared contact damage for its first 20 frames in the new room. +constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; +constexpr int ROOM_ENTER_DAMAGE_COUNTDOWN = 20; + +// How many rooms the players moved, by the rooms' places on the floor, else by the side of the door they came in by +// (left, up, right, down), a side drawn from the decoration seed when there was none. +// The original stops on a zero decoration seed. Here the generator logs it and the side reads as left. +static Vector room_step_get() +{ + Game& game = *g_game; + int last = game.GetRoomByIdx(game.lastRoomIdx, game.lastRoomDimensionIdx)->gridIndex; + int current = game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx)->gridIndex; + if (last >= 0 && current >= 0) + return vector_make((float)(last % LEVEL_GRID_WIDTH - current % LEVEL_GRID_WIDTH), + (float)(last / LEVEL_GRID_WIDTH - current / LEVEL_GRID_WIDTH)); + + int slot = game.enterDoor; + if (slot < 0) + { + RNG rng = rng_make(game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx)->decorationSeed, + DOOR_SIDE_SHIFT_INDEX); + slot = (int)(rng.Next() % DOOR_SIDES); + } + switch (slot % DOOR_SIDES) + { + case PATH_DIRECTION_LEFT: + return vector_make(-1, 0); + case PATH_DIRECTION_UP: + return vector_make(0, -1); + case PATH_DIRECTION_RIGHT: + return vector_make(1, 0); + default: + return vector_make(0, 1); + } +} + +// Whether this is the second Dark Esau, which only Tainted Jacob's Birthright keeps. +static bool is_second_dark_esau_unearned(Entity_NPC& npc) +{ + if (npc.type != ENTITY_DARK_ESAU || npc.variant != 0 || npc.subtype != DARK_ESAU_SECOND) return false; + if (!npc.parent || npc.parent->type != ENTITY_DARK_ESAU) return false; + + Entity* spawner = npc.spawnerEntity; + if (!spawner || spawner->type != ENTITY_PLAYER) return false; + + Entity_Player& jacob = *static_cast(spawner); + bool isJacob = jacob.playerType == PLAYER_JACOB_B || jacob.playerType == PLAYER_JACOB2_B; + return isJacob && !jacob.HasCollectible(COLLECTIBLE_BIRTHRIGHT); +} + +// 006d6d80 Follows the players into the next room: Dark Esau and Mother's Shadow keep their place relative to the +// players by moving as many rooms as they did, and a second Dark Esau without Tainted Jacob's Birthright vanishes in a dark +// poof. A persistent one is spared contact damage for a moment. +void Entity_NPC::room_enter() +{ + bool isShadow = (type == ENTITY_DARK_ESAU && variant == 0) || type == ENTITY_MOTHERS_SHADOW; + if (isShadow && g_game->frameCount - spawnFrame > 1) + { + Vector step = room_step_get(); + pos.x = step.x * ROOM_STEP_X + pos.x; + pos.y = step.y * ROOM_STEP_Y + pos.y; + if (is_second_dark_esau_unearned(*this)) + { + Remove(); + Entity* poof = g_game->Spawn( + {.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->SetColor(DARK_ESAU_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + } + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING)) damageCountdown = ROOM_ENTER_DAMAGE_COUNTDOWN; +} diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 8f75bf1..664e769 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -15,41 +15,6 @@ #include #include -// Lua's PickupVariant: the kinds of pickup. -enum PickupVariant : int -{ - PICKUP_NULL = 0, - PICKUP_HEART = 10, - PICKUP_COIN = 20, - PICKUP_KEY = 30, - PICKUP_BOMB = 40, - PICKUP_THROWABLEBOMB = 41, - PICKUP_POOP = 42, - PICKUP_CHEST = 50, - PICKUP_BOMBCHEST = 51, - PICKUP_SPIKEDCHEST = 52, - PICKUP_ETERNALCHEST = 53, - PICKUP_MIMICCHEST = 54, - PICKUP_OLDCHEST = 55, - PICKUP_WOODENCHEST = 56, - PICKUP_MEGACHEST = 57, - PICKUP_HAUNTEDCHEST = 58, - PICKUP_LOCKEDCHEST = 60, - PICKUP_GRAB_BAG = 69, - PICKUP_PILL = 70, - PICKUP_LIL_BATTERY = 90, - PICKUP_COLLECTIBLE = 100, - PICKUP_BROKEN_SHOVEL = 110, - PICKUP_SHOPITEM = 150, - PICKUP_TAROTCARD = 300, - PICKUP_BIGCHEST = 340, - PICKUP_TRINKET = 350, - PICKUP_REDCHEST = 360, - PICKUP_TROPHY = 370, - PICKUP_BED = 380, - PICKUP_MOMSCHEST = 390 -}; - // The chest variants (chest, locked, red, bomb, eternal, spiked, mimic, mom's, old, wooden, mega, haunted). constexpr std::array CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_REDCHEST, PICKUP_BOMBCHEST, PICKUP_ETERNALCHEST, PICKUP_SPIKEDCHEST, PICKUP_MIMICCHEST, PICKUP_MOMSCHEST, @@ -345,12 +310,9 @@ constexpr float DUNGEON_LAVA_MARGIN = 30; constexpr uint32_t DUNGEON_PIT_COLLISION = 4; constexpr int DUNGEON_SETTLE_FRAMES = 2; constexpr float HALF = 0.5f; - -constexpr int LUA_CALLBACK_POST_PICKUP_INIT = 34; -constexpr int LUA_CALLBACK_POST_PICKUP_UPDATE = 35; -constexpr int LUA_CALLBACK_POST_PICKUP_RENDER = 36; -constexpr int LUA_CALLBACK_POST_PICKUP_SELECTION = 37; -constexpr int LUA_CALLBACK_GET_CARD = 20; +constexpr float PEDESTAL_MASS = 8; +constexpr float PEDESTAL_FRICTION = 0.8f; +constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // How deep pickup_variant_pick is in itself, which Nuh Uh! only rerolls at the top of. static int pickDepth = 0; @@ -360,12 +322,13 @@ static bool is_listed(std::initializer_list list, int value) return std::find(list.begin(), list.end(), value) != list.end(); } -// A card from the pools as MC_GET_CARD leaves it (lua_callback_run_get_card 00865340), which no mod changes yet. +// A card from the pools as MC_GET_CARD leaves it, drawn with an RNG seeded from rng. static int card_draw(RNG& rng) { - int card = ItemPool::GetCardEx((int)rng.Next(), CARD_SPECIAL_CHANCE, CARD_RUNE_CHANCE, CARD_SUIT_CHANCE, true); - lua_callback_check(LUA_CALLBACK_GET_CARD, "lua_callback_run_get_card 00865340"); - return card; + uint32_t seed = rng.Next(); + int card = ItemPool::GetCardEx((int)seed, CARD_SPECIAL_CHANCE, CARD_RUNE_CHANCE, CARD_SUIT_CHANCE, true); + RNG cardRng = rng_make(seed, PICKUP_RNG_SHIFT); + return lua_engine_get().GetCard({.rng = &cardRng, .card = card, .isPlaying = true, .isRunes = true}); } static bool is_unlocked(int achievement) @@ -759,7 +722,8 @@ bool pickup_variant_pick(PickupChoice& choice) battery_subtype_pick(choice, rng); break; case PICKUP_COLLECTIBLE: - reconstruction_missing("Pickup_PickVariant 006ddcd0: an item"); + collectible_subtype_pick(choice, rng); + break; case PICKUP_BROKEN_SHOVEL: choice.subType = COLLECTIBLE_BROKEN_SHOVEL_1; break; @@ -887,11 +851,12 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u entity_spawn({pos, {}, nullptr, 0, ENTITY_FLY, 0, dropRNG.Next()})->scoreMultiplier = 0; return; } - if (is_listed({PICKUP_SHOPITEM, PICKUP_COLLECTIBLE, PICKUP_BROKEN_SHOVEL, PICKUP_BIGCHEST, PICKUP_TROPHY, - PICKUP_BED, PICKUP_MOMSCHEST}, + if (is_listed({PICKUP_SHOPITEM, PICKUP_BROKEN_SHOVEL, PICKUP_BIGCHEST, PICKUP_TROPHY, PICKUP_BED, + PICKUP_MOMSCHEST}, choice.variant)) - reconstruction_missing("Entity_Pickup::Init 006e02f0: items, shop wares and the big pickups"); - lua_callback_check(LUA_CALLBACK_POST_PICKUP_SELECTION, "lua_callback_run_post_pickup_selection 00863340"); + reconstruction_missing("Entity_Pickup::Init 006e02f0: shop wares and the big pickups"); + if (choice.variant == PICKUP_COLLECTIBLE) collectible_choose(choice.subType, seed); + lua_engine_get().PostPickupSelection(this, choice.variant, choice.subType); bool isPoopBomb = choice.variant == PICKUP_BOMB && g_game->playerManager.are_all_players_tainted_blue_baby() && !is_listed({BOMB_TROLL, BOMB_SUPERTROLL, BOMB_GOLDENTROLL}, choice.subType); @@ -913,7 +878,12 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u sprite.Load(config->anm2Path, GRAPHICS_DEFER); UpdateSprite(false); } - appear_start(); + if (variant == PICKUP_COLLECTIBLE) + { + AddEntityFlags(FLAG_NO_KNOCKBACK); + pedestal_start(); + } + else appear_start(); optionsPickupIndex = 0; bool isSaleSeed = g_game->seedEffects.HasSeedEffect(SEED_ITEMS_COST_MONEY) && variant != PICKUP_COIN && @@ -928,7 +898,7 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u UpdateLootPreview(); log_printf(LOG_INFO, "Entity Pickup Initialized as: %d.%d.%d Seed: %08x \n", type, variant, subtype, initSeed); itemPoolType = g_game->itemPool.lastPool; - lua_callback_check(LUA_CALLBACK_POST_PICKUP_INIT, "LuaEngine::PostPickupInit 00862f00"); + lua_engine_get().PostPickupInit(this); } // Plays the pickup's appear animation, uncollectable until it lands, or shows it idle in a room the players are @@ -961,7 +931,7 @@ void Entity_Pickup::appear_start() // 006e21f0 Swaps in the spritesheets a variant shows: a trinket's own and its golden flag, a collectible's image, and // Pay To Play's coin slot chests, then loads them. -void Entity_Pickup::UpdateSprite(bool) +void Entity_Pickup::UpdateSprite(bool isIgnoreBlind) { if (variant == PICKUP_TRINKET) { @@ -970,8 +940,14 @@ void Entity_Pickup::UpdateSprite(bool) if (trinket) sprite.ReplaceSpritesheet(0, trinket->gfxFilename); sprite.bitflags = ((uint32_t)subtype >> 8) & GOLDEN_TRINKET_SPRITE_FLAG; } - else if (variant == PICKUP_COLLECTIBLE || variant == PICKUP_BED || isPayToPlay) - reconstruction_missing("Entity_Pickup::UpdateSprite 006e21f0: items, the bed and the coin slot chests"); + else if (variant == PICKUP_COLLECTIBLE) + { + bool isBlind = !isIgnoreBlind && g_game->currentDimensionIdx != DIMENSION_DEATH_CERTIFICATE && + ((g_game->GetCurses() & CURSE_OF_BLIND) || isForceBlind); + load_collectible_gfx(sprite, 1, subtype, initSeed, isBlind); + } + else if (variant == PICKUP_BED || isPayToPlay) + reconstruction_missing("Entity_Pickup::UpdateSprite 006e21f0: the bed and the coin slot chests"); sprite.LoadGraphics(); } @@ -982,7 +958,11 @@ void Entity_Pickup::update_price_sprite(int newPrice) if (newPrice != 0 || price != 0) reconstruction_missing("Entity_Pickup::update_price_sprite 006e2570: a price"); if (variant == PICKUP_COLLECTIBLE) - reconstruction_missing("Entity_Pickup::update_price_sprite 006e2570: an item's pedestal"); + { + if (g_game->room->roomType == ROOM_DUNGEON) posOffset.y = 0; + sprite.Play("Idle"); + SetAlternatePedestal(0); + } priceANM2.Reset(); if (child) child->Remove(); } @@ -1008,10 +988,10 @@ void Entity_Pickup::Render(const Vector& offset) { if (!isExists || !isVisible || dropDelay >= 1) return; - if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::Render 006e69b0: an item's pedestal"); - Entity::Render(offset); + if (variant == PICKUP_COLLECTIBLE) pedestal_render(offset); + else Entity::Render(offset); if (priceANM2.isLoaded) priceANM2.Render(SpriteDraw{renderPosition, {}, {}}); - lua_callback_check(LUA_CALLBACK_POST_PICKUP_RENDER, "LuaEngine::PostPickupRender 008630c0"); + lua_engine_get().PostPickupRender(this, offset); } // 006e3940 Runs the pickup for a frame: a thrown chest's flight, Keeper's hearts turning into flies, Sack Head's @@ -1053,7 +1033,7 @@ void Entity_Pickup::Update() posOffset.y = height; if (parent && HasEntityFlags(FLAG_HELD)) velocity = vector_sub(parent->pos, pos); } - if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::Update 006e3940: an item"); + if (variant == PICKUP_COLLECTIBLE) pedestal_update(); if (price == 0 && variant == PICKUP_HEART && keeper_flies_update()) return; if (anyone_has_collectible(COLLECTIBLE_SACK_HEAD) && price == 0 && spawnerType != ENTITY_PLAYER) @@ -1104,7 +1084,13 @@ void Entity_Pickup::Update() Entity::Update(); if (IsChest(variant) && !HasEntityFlags(FLAG_THROWN)) velocity = vector_make(velocity.x * CHEST_DRAG, velocity.y * CHEST_DRAG); - if (!HasEntityFlags(FLAG_THROWN)) friction *= PICKUP_FRICTION; + if (variant == PICKUP_COLLECTIBLE) + { + mass = PEDESTAL_MASS; + friction *= PEDESTAL_FRICTION; + update_cycle_collectible(false); + } + else if (!HasEntityFlags(FLAG_THROWN)) friction *= PICKUP_FRICTION; update_magnet_attraction(); if (isAutoUpdatePrice && price != 0) reconstruction_missing("Entity_Pickup::Update 006e3940: a price"); appear_update(); @@ -1176,7 +1162,7 @@ void Entity_Pickup::Update() } bool isAppearing = sprite.IsPlaying("Appear") || sprite.IsPlaying("AppearFast"); if (collisionCooldown > 0 && !isAppearing) collisionCooldown--; - lua_callback_check(LUA_CALLBACK_POST_PICKUP_UPDATE, "LuaEngine::PostPickupUpdate 00862fe0"); + lua_engine_get().PostPickupUpdate(this); } // A heart's swap for blue flies when every main player is a Keeper: the flies go to one of them at random, more for @@ -1210,14 +1196,20 @@ bool Entity_Pickup::keeper_flies_update() // moved off a blocked cell when it was just spawned. void Entity_Pickup::target_position_update() { - if (targetPosition.x == 0 && targetPosition.y == 0) targetPosition = pos; + if (targetPosition.x == 0 && targetPosition.y == 0) + { + targetPosition = pos; + int gridIndex = variant == PICKUP_COLLECTIBLE ? g_game->room->GetGridIndex(pos) : -1; + GridEntity* below = gridIndex >= 0 ? g_game->room->GetGridEntity((uint32_t)gridIndex) : nullptr; + if (below) below->Destroy(false, EntityRef{}); + } if (gridRepositionState == 2) { targetPosition = pos; gridRepositionState = 0; } - bool isHeld = price != 0 || variant == PICKUP_BED || (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) || + bool isHeld = price != 0 || variant == PICKUP_COLLECTIBLE || variant == PICKUP_BED || (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) || variant == PICKUP_MOMSCHEST || variant == PICKUP_MEGACHEST; if (isHeld) { @@ -1277,7 +1269,8 @@ void Entity_Pickup::update_magnet_attraction() // change what a pickup gives are not reconstructed yet. bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) { - if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: an item"); + if (variant == PICKUP_COLLECTIBLE && (megaChestCollectible[0] || megaChestCollectible[1])) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a Mega Chest's items"); LuaResult result = static_cast(g_luaEngine)->PrePickupCollision(this, collider, isLow); if (result == LUA_RESULT_TRUE) return true; if (result == LUA_RESULT_FALSE) return false; @@ -1289,6 +1282,9 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) collisionCooldown = COLLISION_COOLDOWN; return true; } + if (variant == PICKUP_COLLECTIBLE && ItemConfig::IsQuestItem(subtype) && collider->parent && + collider->subtype == PLAYER_KEEPER) + return false; if (g_game->seedEffects.HasSeedEffect(SEED_PICKUPS_TIMEOUT)) ResetColor(); if (HasEntityFlags(FLAG_THROWN) && spawnerType == ENTITY_POLTY) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a thrown pickup's hit"); @@ -1343,7 +1339,8 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a co-op baby rerolling it"); if (player->variant != 0) isRefused = true; else if (player->isCoopGhost) isRefused |= !isGhostPickup; - else if (player->parent) isRefused |= isHelperRefused; + else isRefused |= (player->parent && isHelperRefused) || + (variant == PICKUP_COLLECTIBLE && is_collectible_refused(*player)); if (isRefused) return g_game->room->roomType == ROOM_DUNGEON || price != 0 || player->variant == 1; if (price != 0) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: buying"); @@ -1364,13 +1361,16 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_BOMB: isPickedUp = bomb_collect(*player); break; + case PICKUP_COLLECTIBLE: + isPickedUp = collectible_collect(*player); + break; default: reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: chests, sacks, pocket items and trinkets"); } if (!isPickedUp) { - if (CanReroll() && isCollidesWithGrid) + if (variant != PICKUP_COLLECTIBLE && CanReroll() && isCollidesWithGrid) velocity = vector_make(gridCollisionNormal.y * BUMP_SLIDE + velocity.x, -gridCollisionNormal.x * BUMP_SLIDE + velocity.y); return g_game->room->roomType == ROOM_DUNGEON || price != 0; @@ -1384,12 +1384,17 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) if (isDevilDeal && (state == 1 || spawnGridIndex >= 0)) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a devil deal"); g_game->scoreSheet.add_pickup_points(variant, collectedSubtype, pos); - PlayPickupSound(); - collect_finish(player); + if (variant != PICKUP_COLLECTIBLE) + { + PlayPickupSound(); + collect_finish(player); + } + else if (!player->proceduralItems.empty()) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the procedural items' pickup trigger"); if (g_game->playerManager.IsCoopPlay() && coopDuplicateIndex != -1) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a co-op item copy"); - return true; + return variant != PICKUP_COLLECTIBLE || g_game->room->roomType == ROOM_DUNGEON || price != 0; } // The end of a collection: the procedural items' triggers, the pickup flying into its "Collect" animation and dying, @@ -1714,7 +1719,7 @@ void Entity_Pickup::PlayPickupSound() break; } case PICKUP_COLLECTIBLE: - reconstruction_missing("Entity_Pickup::PlayPickupSound 006e7dc0: an item"); + return collectible_sound_play(); case PICKUP_THROWABLEBOMB: sound = SOUND_FETUS_FEET; break; @@ -1773,8 +1778,10 @@ bool Entity_Pickup::CanRerollVariant(int pickupVariant, int pickupSubType) // The Death Certificate floor's items are not reconstructed yet. void Entity_Pickup::RemoveOtherOptions() { - if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::RemoveOtherOptions 006ee750: an item"); if (optionsPickupIndex == 0) return; + if (optionsPickupIndex == 1 && variant == PICKUP_COLLECTIBLE && + g_game->currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE && g_game->deathCertificateExitTimer < 1) + reconstruction_missing("Entity_Pickup::RemoveOtherOptions 006ee750: Death Certificate's exit"); std::vector pickups(g_game->room->entityList.updateEL); for (Entity* entity : pickups) @@ -1863,18 +1870,6 @@ bool Entity_Pickup::TryFlip(Entity_Player*, uint32_t) reconstruction_missing("Entity_Pickup::TryFlip 006e1640"); } -// 006e1a80 -void Entity_Pickup::SetAlternatePedestal(int) -{ - reconstruction_missing("Entity_Pickup::SetAlternatePedestal 006e1a80"); -} - -// 006e1d70 -int Entity_Pickup::GetAlternatePedestal() -{ - reconstruction_missing("Entity_Pickup::GetAlternatePedestal 006e1d70"); -} - // 006e1e60 void Entity_Pickup::SetForceBlind(uint8_t) { @@ -1905,18 +1900,6 @@ void Entity_Pickup::CollectTrinket(Entity_Player*, uint32_t) reconstruction_missing("Entity_Pickup::CollectTrinket 006e84d0"); } -// 006ed580 -uint8_t Entity_Pickup::empty_pedestal() -{ - reconstruction_missing("Entity_Pickup::empty_pedestal 006ed580"); -} - -// 006edfa0 -void Entity_Pickup::update_cycle_collectible(bool) -{ - reconstruction_missing("Entity_Pickup::update_cycle_collectible 006edfa0"); -} - // 006ee3f0 bool Entity_Pickup::CanJeraDuplicate() { @@ -1934,9 +1917,3 @@ int Entity_Pickup::AssignOptionsIndex() { reconstruction_missing("Entity_Pickup::AssignOptionsIndex 006eed30"); } - -// 007ef420 -void Entity_Pickup::RestoreState(Room*, Entity_Pickup*, void*) -{ - reconstruction_missing("Entity_Pickup::RestoreState 007ef420"); -} diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 185b7a8..05db3d4 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -5,6 +5,41 @@ #include #include +// Lua's PickupVariant: the kinds of pickup. +enum PickupVariant : int +{ + PICKUP_NULL = 0, + PICKUP_HEART = 10, + PICKUP_COIN = 20, + PICKUP_KEY = 30, + PICKUP_BOMB = 40, + PICKUP_THROWABLEBOMB = 41, + PICKUP_POOP = 42, + PICKUP_CHEST = 50, + PICKUP_BOMBCHEST = 51, + PICKUP_SPIKEDCHEST = 52, + PICKUP_ETERNALCHEST = 53, + PICKUP_MIMICCHEST = 54, + PICKUP_OLDCHEST = 55, + PICKUP_WOODENCHEST = 56, + PICKUP_MEGACHEST = 57, + PICKUP_HAUNTEDCHEST = 58, + PICKUP_LOCKEDCHEST = 60, + PICKUP_GRAB_BAG = 69, + PICKUP_PILL = 70, + PICKUP_LIL_BATTERY = 90, + PICKUP_COLLECTIBLE = 100, + PICKUP_BROKEN_SHOVEL = 110, + PICKUP_SHOPITEM = 150, + PICKUP_TAROTCARD = 300, + PICKUP_BIGCHEST = 340, + PICKUP_TRINKET = 350, + PICKUP_REDCHEST = 360, + PICKUP_TROPHY = 370, + PICKUP_BED = 380, + PICKUP_MOMSCHEST = 390 +}; + // The most items a glitched pedestal cycles through. constexpr int CYCLE_COLLECTIBLE_LIMIT = 8; @@ -110,7 +145,7 @@ struct Entity_Pickup : Entity void RemoveOtherOptions(); void MakeShopItem(int shopId); int AssignOptionsIndex(); - static void RestoreState(Room* room, Entity_Pickup* entity, void* saveState); + static void load_collectible_gfx(ANM2& itemSprite, int layerId, int collectibleId, uint32_t seed, bool isBlind); private: void appear_start(); @@ -122,7 +157,17 @@ private: bool key_collect(Entity_Player& player); bool bomb_collect(Entity_Player& player); void collect_finish(Entity_Player* player); + + // The item pedestal's parts of Init, Update, Render, HandleCollision and PlayPickupSound (item_pickup.cpp). + void collectible_choose(int& collectibleId, uint32_t seed); + void pedestal_start(); + void pedestal_update(); + void pedestal_render(const Vector& offset); + bool is_collectible_refused(Entity_Player& player); + bool collectible_collect(Entity_Player& player); + void collectible_sound_play(); }; bool pickup_variant_pick(PickupChoice& choice); +void collectible_subtype_pick(PickupChoice& choice, RNG& rng); bool entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerType, bool isRoomEntry); diff --git a/src/entity_player.cpp b/src/entity_player.cpp index f829045..782bf64 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -114,7 +114,7 @@ static int card_roll(uint32_t seed, int runeChance, bool isPlaying) { int card = ItemPool::GetCardEx((int)seed, CARD_SPECIAL_CHANCE, runeChance, runeChance, true); RNG rng = rng_make(seed, ITEM_RNG_SHIFT); - return lua_callback_run_get_card(&rng, card, isPlaying, isPlaying, false); + return lua_engine_get().GetCard({.rng = &rng, .card = card, .isPlaying = isPlaying, .isRunes = isPlaying}); } // Room methods the room's takeover has not declared yet. @@ -1269,27 +1269,6 @@ void Entity_Player::RemoveCostume(ItemConfig_Item* item) UpdateCostumes(); } -// 0075bf00 Lays the worn costumes over the player's layers by priority and recolors them for its skin. Only the case -// with no costumes and an unchanged skin color is reconstructed: the costume layout stops the game until reached. -void Entity_Player::UpdateCostumes() -{ - static bool isUpdating = false; - - if (variant == PLAYER_VARIANT_COOP_BABY || isUpdating) return; - if (!costumeSpriteDescs.empty()) - reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (laying out costumes)"); - - isUpdating = true; - EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType); - if (!playerConfig) log_printf(LOG_ASSERT, "Could not load config for player type %d\n", playerType); - costume_map_reset(-1); - int skinColor = playerConfig ? playerConfig->skinColor : -1; - if (headColor != skinColor || bodyColor != skinColor) - reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (recoloring the skin)"); - if (isCoopGhost) reset_body_sprite(); - isUpdating = false; -} - // 007bebb0 Dresses the player in its character's skin: the challenge's or the config's spritesheet on every layer and // the matching ghost layer, then the character's costume, the blindfold of characters that cannot shoot, the seeds' // and dailies' costumes and the Hot Potato bomb. Co-op ghosts only get the ghost body. The name follows the character. @@ -1410,39 +1389,6 @@ bool Entity_Player::is_dead_bird_kept() return boneHearts + soulHearts + red <= (playerType == PLAYER_EVE ? 2 : 1); } -// 00763570 Recomputes the stats the cache flags ask for from the character, its items, effects, trinkets, seeds and -// challenge, then lets mods change them. Only the skeleton is reconstructed: a player whose stats nothing changes keeps -// the base stats Init gave it. Any item, effect or character bonus stops the game until reached, as does the weapon a -// changed weapon type needs (Isaac::CreateWeapon is not taken over). -void Entity_Player::EvaluateItems() -{ - if (!is_evaluation_plain()) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (items, effects or bonuses)"); - - for (uint32_t flag = CACHE_DAMAGE; flag <= CACHE_PICKUP_VISION; flag <<= 1) - if (cacheFlags & flag) static_cast(g_luaEngine)->EvaluateItems(this, (int)flag); - cacheFlags = 0; -} - -// Whether nothing would change a player's base stats: Isaac with no items, effects, pills, Eden rolls, modifiers or -// D8 rolls, outside challenges, dailies and seeds. -bool Entity_Player::is_evaluation_plain() -{ - Game& game = *g_game; - bool isOwningNothing = std::ranges::all_of(collectibleCounts, [](int count) { return count == 0; }) && - std::ranges::all_of(activeItems, [](ActiveItemDesc& active) { return active.item == 0; }) && - trinkets == std::array{} && temporaryEffects.effects.empty() && - std::ranges::all_of(pillEffectUses, [](int uses) { return uses == 0; }); - bool isUnmodified = speedModifier == 0 && fireDelayModifier == 0 && damageModifier == 0 && tearRangeModifier == 0 && - shotSpeedModifier == 0 && luckModifier == 0 && donateLuck == 0 && d8DamageModifier == 1 && - d8FireDelayModifier == 1 && d8RangeModifier == 1 && d8SpeedModifier == 1 && edenDamage == 0 && - edenSpeed == 0 && edenFireDelay == 0 && edenTearRange == 0 && edenShotSpeed == 0 && - edenLuck == 0; - return playerType == PLAYER_ISAAC && variant == PLAYER_VARIANT_PLAYER && isOwningNothing && isUnmodified && - !isCoopGhost && !hasCurseMistEffect && game.challenge == 0 && game.dailyChallenge._id == 0 && - game.seedEffects.CountSeedEffects() == 0 && !game.deathmatchManager.is_active(); -} - // 00757a40 Drops the entity links, then lets go of the weapons and the effects the player spawned. void Entity_Player::ClearReferences() { diff --git a/src/entity_player.h b/src/entity_player.h index 7adfd6e..7926ffe 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -908,6 +908,16 @@ public: bool TryThrow(const EntityRef& source, const Vector& velocity, float height) override; bool HandleCollision(Entity* collider, bool isLow) override; void AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData); + void SetQueuedItem(const QueueItemData& queued); + int tagged_item_count(uint64_t tag); + void collectible_unlocks_check(int collectibleId, ItemConfig_Item& item); + void collectible_pickups_add(ItemConfig_Item& item); + bool is_character_plain(); + bool is_frame_plain(); + bool is_tear_hit_plain(); + 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); void RemoveCollectible(int type, bool isIgnoreModifiers, int activeSlot, bool isRemoveFromForm); Entity_Familiar* AddWisp(int collectible, Vector position, bool isAdjustOrbitLayer, bool isDontUpdate); @@ -960,7 +970,6 @@ private: ANM2& layer_sprite(int layer); int layer_id(int layer); static bool is_body_layer(int layer); - bool is_evaluation_plain(); public: int GetBatteryCharge(int slot); diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index 7a1dc33..e79ec3c 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -117,7 +117,6 @@ constexpr int LAST_DAMAGE_STAGE_MAX = 13; constexpr int HURT_FRAMES_PER_HEART = 60; constexpr int HURT_HEARTS_MAX = 2; constexpr int HIT_COOLDOWN = 4; -constexpr int MC_ENTITY_TAKE_DMG = 11; constexpr uint32_t DEBUG_INFINITE_HP = 1 << 2; constexpr uint32_t DEBUG_DAMAGE_VALUES = 1 << 6; constexpr uint32_t STAGE_FULL_HEART_DAMAGE = 7; @@ -437,8 +436,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Holy Mantle's shield)"); if (hallowedGroundCountdown > 0 && !(damageFlags & DAMAGE_NO_MODIFIERS)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hallowed Ground)"); - if (static_cast(g_luaEngine)->enabledCallbacks.test(MC_ENTITY_TAKE_DMG)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (LuaEngine::EntityTakeDamage 00864560)"); + lua_callback_check(MC_ENTITY_TAKE_DMG, "Entity_Player::TakeDamage 007729d0: LuaEngine::EntityTakeDamage 00864560"); (void)damageCountdown; if (try_end_astral_projection()) return false; if (playerType == PLAYER_JACOB_B && source.type == ENTITY_DARK_ESAU) diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp new file mode 100644 index 0000000..4fd73e1 --- /dev/null +++ b/src/entity_player_death.cpp @@ -0,0 +1,545 @@ +#include "game_over.h" +#include "entity_familiar.h" +#include "entity_list.h" +#include "entity_player.h" +#include "game.h" +#include "item_config.h" +#include "log.h" +#include "manager.h" +#include "platform.h" +#include "player_manager.h" +#include "room.h" +#include +#include +#include + +constexpr int COLLECTIBLE_1UP = 11; +constexpr int COLLECTIBLE_POOP = 36; +constexpr int COLLECTIBLE_YUM_HEART = 45; +constexpr int COLLECTIBLE_SHOOP_DA_WHOOP = 49; +constexpr int COLLECTIBLE_CHARM_VAMPIRE = 62; +constexpr int COLLECTIBLE_BATTERY = 63; +constexpr int COLLECTIBLE_DEAD_CAT = 81; +constexpr int COLLECTIBLE_THE_NAIL = 83; +constexpr int COLLECTIBLE_PEEPER = 155; +constexpr int COLLECTIBLE_ANKH = 161; +constexpr int COLLECTIBLE_GUPPYS_COLLAR = 212; +constexpr int COLLECTIBLE_STARTER_DECK = 251; +constexpr int COLLECTIBLE_LITTLE_BAGGY = 252; +constexpr int COLLECTIBLE_JUDAS_SHADOW = 311; +constexpr int COLLECTIBLE_LAZARUS_RAGS = 332; +constexpr int COLLECTIBLE_POLYDACTYLY = 454; +constexpr int COLLECTIBLE_WAVY_CAP = 582; +constexpr int COLLECTIBLE_MOMS_BRACELET = 604; +constexpr int COLLECTIBLE_VADE_RETRO = 653; +constexpr int COLLECTIBLE_INNER_CHILD = 688; +constexpr int TRINKET_AAA_BATTERY = 3; +constexpr int TRINKET_BROKEN_ANKH = 28; +constexpr int TRINKET_FISH_TAIL = 94; +constexpr int TRINKET_LOCUST_OF_WRATH = 113; +constexpr int TRINKET_LOCUST_OF_CONQUEST = 117; +constexpr int TRINKET_BAT_WING = 118; +constexpr int TRINKET_AZAZELS_STUMP = 162; +constexpr int NULLITEM_BATWING_WINGS = 40; +constexpr int NULLITEM_WAVY_CAP_1 = 71; +constexpr int NULLITEM_BLOODY_BABYLON = 110; +constexpr int NULLITEM_LAZARUS_SOUL_REVIVE = 113; +constexpr int CARD_SOUL_LAZARUS = 89; +constexpr int ACHIEVEMENT_THE_LOST = 82; +constexpr int BABY_FOUND_SOUL = 59; +constexpr int FAMILIAR_BLUE_FLY = 43; +constexpr int FAMILIAR_BLOOD_BABY = 238; +constexpr int CLOT_SUBTYPE_UNCOUNTED = 7; +constexpr int SPECIAL_DAILY_SHUFFLED_ITEMS = 7; +constexpr uint32_t QUEUED_TOUCHED = 0x1; + +constexpr int SOUND_BLOOD_LASER = 5; +constexpr int SOUND_BLOOD_LASER_LARGE = 7; +constexpr int SOUND_FART = 37; +constexpr int SOUND_ISAAC_HURT_GRUNT = 55; +constexpr int SOUND_MONSTER_YELL_A = 119; +constexpr int SOUND_POWERUP_SPEWER = 132; +constexpr int SOUND_REDLIGHTNING_ZAP = 133; +constexpr int SOUND_TEARIMPACTS = 150; +constexpr int SOUND_VAMP_GULP = 157; +constexpr int SOUND_BATTERYCHARGE = 170; +constexpr int SOUND_BEEP = 171; +constexpr int SOUND_ISAACDIES = 217; +constexpr int SOUND_ITEMRECHARGE = 218; +constexpr int SOUND_PLOP = 237; +constexpr int SOUND_SPLATTER = 258; +constexpr int SOUND_THUMBS_DOWN = 267; +constexpr int SOUND_THUMBSUP = 268; + +constexpr float DEATH_FRICTION = 0.6f; +constexpr int DEATH_FRAME_TWIN_FALLS = 7; +constexpr int DEATH_FRAME_BONES_BREAK = 19; +constexpr int PAPER_FRAME_PERIOD = 4; +constexpr int PAPER_FRAME_SINGLE = 3; +constexpr int PAPER_FRAME_DOUBLE = 2; +constexpr int BROKEN_ANKH_CHANCES[] = {22, 33}; +constexpr int BROKEN_ANKH_CHANCE_MAX = 50; +constexpr int BROKEN_ANKH_ROLL = 100; +constexpr int FISH_TAIL_EXTRA_ROLL = 5; +constexpr int FISH_TAIL_LUCKY_MAX = 3; +constexpr int POCKET_ACTIVE_FIRST_SLOT = 2; +constexpr int CONQUEST_EXTRA_ROLL = 4; +constexpr int CONQUEST_EXTRA_ROLL_DOUBLE = 5; + +// The player and its twin, the one with the lower player index first, as a death handles them together. +static std::vector death_players_get(Entity_Player& player) +{ + Entity_Player* twin = player.twin_get(); + + if (!twin) return {&player}; + if (twin->playerIndex != -1 && twin->playerIndex < player.playerIndex && twin != &player) return {twin, &player}; + return {&player, twin}; +} + +// The first of the players with a collectible, or null. +static Entity_Player* collectible_holder_find(std::vector& players, int collectible) +{ + auto isHolder = [&](Entity_Player* player) { return player->HasCollectible(collectible); }; + auto found = std::ranges::find_if(players, isHolder); + return found == players.end() ? nullptr : *found; +} + +// The first of the players with a trinket, or null. +static Entity_Player* trinket_holder_find(std::vector& players, uint32_t trinket) +{ + auto isHolder = [&](Entity_Player* player) { return player->HasTrinket(trinket); }; + auto found = std::ranges::find_if(players, isHolder); + return found == players.end() ? nullptr : *found; +} + +// Whether Missing Poster revives: once the Lost is unlocked, and always in a daily or debug run. +static bool is_missing_poster_unlocked() +{ + Manager& manager = *g_manager; + bool isExemptRun = + manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug); + + return manager.persistentGameData.achievements[ACHIEVEMENT_THE_LOST] || isExemptRun; +} + +// What revives a dying player and its twin, in the order the game tries them, or null. Broken Ankh's roll draws from +// its RNG even when the death is only checked. A Missing Poster still locked ends the search. +static const char* revival_find(Entity_Player& player, std::vector& players) +{ + for (Entity_Player* each : players) + if (each->temporaryEffects.HasNullEffect(NULLITEM_LAZARUS_SOUL_REVIVE)) return "Soul of Lazarus's revival"; + for (Entity_Player* each : players) + for (uint32_t slot = 0; slot < each->GetMaxPocketItems(); slot++) + { + PocketItem& pocket = each->pocketItems[std::min(slot, POCKET_SLOT_COUNT - 1)]; + if (pocket.type == POCKET_CARD && pocket.id == CARD_SOUL_LAZARUS) return "Soul of Lazarus's revival"; + } + + if (collectible_holder_find(players, COLLECTIBLE_1UP)) return "1up!'s revival"; + if (player.playerType == PLAYER_LAZARUS) return "Lazarus rising"; + if (collectible_holder_find(players, COLLECTIBLE_DEAD_CAT)) return "Dead Cat's revival"; + if (collectible_holder_find(players, COLLECTIBLE_INNER_CHILD)) return "Inner Child's revival"; + Entity_Player* collar = collectible_holder_find(players, COLLECTIBLE_GUPPYS_COLLAR); + if (collar && collar->GetCollectibleRNG(COLLECTIBLE_GUPPYS_COLLAR)._seed & 1) return "Guppy's Collar's revival"; + if (collectible_holder_find(players, COLLECTIBLE_LAZARUS_RAGS)) return "Lazarus' Rags's revival"; + if (collectible_holder_find(players, COLLECTIBLE_ANKH)) return "Ankh's revival"; + + if (Entity_Player* ankh = trinket_holder_find(players, TRINKET_BROKEN_ANKH)) + { + int multiplier = ankh->GetTrinketMultiplier(TRINKET_BROKEN_ANKH); + int chance = multiplier >= 1 && multiplier <= 2 ? BROKEN_ANKH_CHANCES[multiplier - 1] : BROKEN_ANKH_CHANCE_MAX; + if ((int)ankh->GetTrinketRNG(TRINKET_BROKEN_ANKH).RandomInt(BROKEN_ANKH_ROLL) < chance) + return "Broken Ankh's revival"; + } + if (collectible_holder_find(players, COLLECTIBLE_JUDAS_SHADOW)) return "Judas' Shadow's revival"; + if (trinket_holder_find(players, TRINKET_MISSING_POSTER)) + return is_missing_poster_unlocked() ? "Missing Poster's revival" : nullptr; + if (player.playerType == PLAYER_THELOST_B && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT)) + return "Tainted Lost's Birthright revival"; + return nullptr; +} + +// 007a1090 The death of a player out of health, with its twin, once its death animation ended: the first revival +// its items give, else a co-op ghost while others live, else the end of the run. A co-op baby leaves the run. +// With isCheckOnly, only whether it would revive. A locked Missing Poster says so in a Sacrifice Room, where dying +// with it unlocks the Lost. +// Only the death that ends the run is reconstructed: revivals and helpers stop the game when reached. +bool Entity_Player::TriggerDeath(bool isCheckOnly) +{ + Game& game = *g_game; + + if (variant == PLAYER_VARIANT_COOP_BABY) + { + if (isCheckOnly) return false; + coop_baby_death_effect(); + game.playerManager.trigger_coop_baby_death(this); + isVisible = false; + return false; + } + + std::vector players = death_players_get(*this); + bool isSacrificeRoom = game.room->roomType == ROOM_SACRIFICE; + if (!isCheckOnly && HasTrinket(TRINKET_MISSING_POSTER) && isSacrificeRoom) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_THE_LOST); + + const char* revival = revival_find(*this, players); + if (isCheckOnly) return revival || (trinket_holder_find(players, TRINKET_MISSING_POSTER) && isSacrificeRoom); + if (revival) reconstruction_missing(revival); + + for (Entity_Player* player : players) + { + player->pitfallState = 0; + player->isControlsEnabled = true; + player->entityCollisionClass = ENTCOLL_ALL; + } + + Entity_Player& first = *players[0]; + PlayerManager& playerManager = game.playerManager; + if (first.isDead && !first.parent && playerManager.IsCoopPlay() && playerManager.GetNumAlivePlayers() > 1 && + !first.isCoopGhost) + for (Entity_Player* player : players) player->MorphToCoopGhost(); + if (!first.isDead) reconstruction_missing("Entity_Player::TriggerDeath 007a1090 (a co-op ghost's return)"); + if (first.parent && first.variant == PLAYER_VARIANT_PLAYER && first.parent->is_player()) + reconstruction_missing("Entity_Player::TriggerDeath 007a1090 (a helper player's death)"); + + playerManager.trigger_coop_baby_death(this); + isVisible = false; + return true; +} + +// 007cbb60 Whether the player would revive from its death. +bool Entity_Player::WillPlayerRevive() +{ + return TriggerDeath(true); +} + +// Whether a death loses the run: no other main player (its twin aside) lives on or revives. +static bool is_run_lost(Entity_Player& dying) +{ + Game& game = *g_game; + + for (size_t i = 0; i < game.playerManager.playerList.size(); i++) + { + Entity_Player* player = game.GetPlayer((int)i); + bool isOther = player != &dying && player != dying.twin_get(); + if (!isOther || player->parent || player->variant != PLAYER_VARIANT_PLAYER) continue; + if (!player->isDead || player->WillPlayerRevive()) return false; + } + return true; +} + +// Plays a sound in the player's voice, as the fart seed may replace it. +static void voice_play(int sound, float pitch) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.pitch = pitch}); +} + +// The death part of the player's frame, Update 00782af0: outside transitions the death animation starts once (with +// Mysterious Paper's chance of Missing Poster), the held entity is thrown, the ghost shows, and a run lost forgets its +// save. The player slows to a halt, cries out on the animation's DeathSound, takes its twin down with it once the +// animation shows, and vanishes when it ends. +// Update returns into this before its base entity update, which the original runs for the dead too, so it runs here. +void Entity_Player::death_update() +{ + Entity::Update(); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) bodySprite.Update(); + + Game& game = *g_game; + std::string_view animation = GetDeathAnimName(); + bool isTransitioning = game.roomTransition.mode != TRANSITION_NONE || game.stageTransition._state != 0; + + if (!isTransitioning && sprite.GetAnimation() != animation) + { + isVisible = true; + PlayExtraAnimation(animation); + int paper = GetTrinketMultiplier(TRINKET_MYSTERIOUS_PAPER); + int paperFrame = game.frameCount % PAPER_FRAME_PERIOD; + if ((paper >= 1 && paperFrame == PAPER_FRAME_SINGLE) || (paper >= 2 && paperFrame == PAPER_FRAME_DOUBLE)) + temporaryEffects.AddTrinketEffect(TRINKET_MISSING_POSTER, true, 1); + if (heldEntity) ThrowHeldEntity(Vector{}); + if (LayerState* ghost = sprite.GetLayer("ghost")) ghost->isVisible = true; + + bool isMainPlayer = !parent && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost; + if (isMainPlayer && !WillPlayerRevive() && is_run_lost(*this) && !game.deathmatchManager.is_active()) + { + game_save_delete(); + persistent_game_data_set_writable(); + } + if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_FOUND_SOUL && parent && parent->is_player()) + parent->ToPlayer()->temporaryEffects.AddTrinketEffect(TRINKET_FOUND_SOUL, true, 1); + velocity = Vector{}; + } + friction *= DEATH_FRICTION; + + if (activeItems[0].item == COLLECTIBLE_VADE_RETRO && sprite.IsPlaying()) + reconstruction_missing("Entity_Player::Update 00782af0 (Vade Retro used by a dead player's ghost)"); + if (playerType == PLAYER_THEFORGOTTEN_B) + { + if (sprite.IsPlaying(animation) && sprite.GetFrame() == DEATH_FRAME_BONES_BREAK) + reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Forgotten's bones break)"); + } + else if (sprite.IsPlaying(animation) && sprite.IsEventTriggered("DeathSound")) + { + if (!IsHologram()) voice_play(SOUND_ISAACDIES, get_voice_pitch()); + if (playerType == PLAYER_BLUEBABY_B) + reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Blue Baby's last poops)"); + } + + bool isDeathShown = (sprite.IsPlaying(animation) && + (sprite.GetFrame() > DEATH_FRAME_TWIN_FALLS || playerType == PLAYER_THEFORGOTTEN_B)) || + sprite.IsFinished(); + Entity_Player* twin = twin_get(); + if (!isTransitioning && isDeathShown && twin && !twin->isDead && !twin->sprite.IsPlaying(twin->GetDeathAnimName())) + { + if (game.playerManager.IsCoopPlay()) + { + if (!twin->isCoopGhost) twin->Kill(EntityRef()); + } + else + { + twin->lastDamageFlags = lastDamageFlags; + twin->lastDamageSource = lastDamageSource; + twin->Kill(EntityRef()); + twin->isVisible = true; + twin->PlayExtraAnimation(twin->GetDeathAnimName()); + } + } + if (sprite.IsFinished(animation)) isVisible = false; +} + +// 007a6680 Leaves the room: the queued item is added, room-long states end (Holy Mantle's unless kept), the compass, +// Metronome's item, Bat Wing's wings and Wavy Cap's trip wear off, the temporary effects clear, the costumes of actives +// no longer worn come off, a held item is put away, and a soul player of the Forgotten or Jacob leaves. +// The after-images and the deathmatch's damage are not modeled. +void Entity_Player::room_exit(bool isKeepHolyMantle) +{ + ItemConfig& items = g_manager->itemConfig; + Game& game = *g_game; + + FlushQueueItem(); + if (!isKeepHolyMantle) holyMantleState = 0; + isBrokenRemotePending = false; + cursedPennyPending = 0; + roomDamageTaken = 0; + + if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_COMPASS) && !HasCollectible(COLLECTIBLE_COMPASS)) + game.RemoveCompassEffect(); + if (int metronomeItem = metronomeCollectibleId) + { + temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_METRONOME, 1); + ItemConfig_Item* item = items.GetCollectible(metronomeItem); + metronomeCollectibleId = 0; + if (activeItems[0].item != metronomeItem && !HasCollectible(metronomeItem)) RemoveCostume(item); + } + if (temporaryEffects.HasTrinketEffect(TRINKET_BAT_WING)) RemoveCostume(items.GetNullItem(NULLITEM_BATWING_WINGS)); + if (TemporaryEffect* wavyCap = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_WAVY_CAP)) + for (int count = wavyCap->count; count > 0; count--) + { + temporaryEffects.AddNullEffect(NULLITEM_WAVY_CAP_1, false, 1); + temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_WAVY_CAP, 1); + } + if (temporaryEffects.HasNullEffect(NULLITEM_BLOODY_BABYLON)) + { + int hearts = boneHearts + goldenHearts + soulHearts + eternalHearts + redHearts; + auto isClot = [this](Entity* entity) + { + bool isOwned = entity && entity->IsFamiliar() && static_cast(entity)->player == this; + return isOwned && entity->variant == FAMILIAR_BLOOD_BABY && entity->subtype != CLOT_SUBTYPE_UNCOUNTED && + !entity->isDead; + }; + EntityList_EL& persistent = game.room->entityList.persistentEL; + if (playerType != PLAYER_EVE_B || hearts != 1 || std::ranges::any_of(persistent, isClot)) + temporaryEffects.RemoveNullEffect(NULLITEM_BLOODY_BABYLON, -1); + } + ClearTemporaryEffects(); + + for (ActiveItemDesc& active : activeItems) + { + int id = active.item; + if (id == 0 || (id != COLLECTIBLE_SHOOP_DA_WHOOP && temporaryEffects.HasCollectibleEffect(id))) continue; + ItemConfig_Item* item = items.GetCollectible(id); + if (item && (!item->isAddCostumeOnPickup || !HasCollectible(id))) RemoveCostume(item); + } + if (itemState != COLLECTIBLE_MOMS_BRACELET || game.stageTransition._state != 0) + { + bodySprite.Reset(); + isPlayingItemAnimation = false; + ResetItemState(); + itemStateCooldown = 0; + } + + bool isSoulPlayer = temporaryEffects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN) || + temporaryEffects.HasNullEffect(NULLITEM_SOUL_JACOB); + if (parent && isSoulPlayer) game.playerManager.RemoveCoPlayer(this); +} + +// 0075e1d0 Adds the item held over the head, golden or not, as picked up for the first time unless it was touched +// before, then lets Astral Projection trigger. False when nothing was queued. +bool Entity_Player::FlushQueueItem() +{ + if (!queuedItem.item) + { + try_trigger_astral_projection(); + return false; + } + + log_printf(LOG_INFO, "item queue flush\n"); + QueueItemData queued = queuedItem; + queuedItem.item = nullptr; + queuedItem.charge = 0; + queuedItem.varData = 0; + bool isFirstTime = !(queued.flags & QUEUED_TOUCHED); + bool isShuffledDaily = g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_SHUFFLED_ITEMS; + + if (queued.item->type == ITEM_TRINKET) + { + if (isShuffledDaily) + reconstruction_missing("Entity_Player::FlushQueueItem 0075e1d0 (a shuffled daily's trinket)"); + uint32_t id = (uint32_t)queued.item->id; + AddTrinket((int)(queued.flags & QUEUED_GOLDEN ? id | TRINKET_GOLDEN_FLAG : id), isFirstTime); + } + else if (queued.item->type != ITEM_NULL) + { + if (isShuffledDaily) reconstruction_missing("Entity_Player::FlushQueueItem 0075e1d0 (a shuffled daily's item)"); + AddCollectible(queued.item->id, queued.charge, isFirstTime, 0, queued.varData); + } + try_trigger_astral_projection(); + return true; +} + +// 007907a0 Ends the room's temporary effects: the effects clear, Strength's heart containers go, the color override +// resets, the Lost curse lifts outside the mirror world, Azazel's Stump's form ends, the room's lent collectibles are +// taken back and the pocket active slot empties. +void Entity_Player::ClearTemporaryEffects() +{ + Game& game = *g_game; + + if (!temporaryEffects.effects.empty()) temporaryEffects.ClearEffects(false); + for (int i = 0; i < strengthMaxHearts; i++) + if (soulHearts + boneHearts * 2 + maxHearts > 2) AddMaxHearts(-2, false); + strengthMaxHearts = 0; + colorOverride = COLOR_DEFAULT; + + TemporaryEffect* lostCurse = temporaryEffects.GetNullEffect(NULLITEM_LOST_CURSE); + int dimension = game.roomTransition.mode != TRANSITION_NONE ? game.roomTransition.roomDimension + : game.currentDimensionIdx; + if (lostCurse && lostCurse->count == 2 && (!game.HasMirrorDimension() || dimension == 0)) + { + temporaryEffects.RemoveNullEffect(NULLITEM_LOST_CURSE, -1); + if (backupPlayer && backupPlayer->temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE)) + backupPlayer->temporaryEffects.RemoveNullEffect(NULLITEM_LOST_CURSE, -1); + } + if (TemporaryEffect* stump = temporaryEffects.GetTrinketEffect(TRINKET_AZAZELS_STUMP); stump && stump->count == 1) + temporaryEffects.RemoveTrinketEffect(TRINKET_AZAZELS_STUMP, 1); + + for (auto& [id, count] : roomTemporaryCollectibles) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id); + if (item && item->type != ITEM_ACTIVE) + for (int i = 0; i < count; i++) RemoveCollectible(item->id, true, 0, true); + count = 0; + } + roomTemporaryCollectibles.clear(); + SetPocketActiveItem(0, ACTIVE_SLOT_COUNT - 1, false); +} + +// 007d41d0 Puts an active item in a pocket slot (2 or 3), the one there before removed with its pocket. +// Only emptying the slot is reconstructed: a new item stops the game. +void Entity_Player::SetPocketActiveItem(int collectible, int slot, bool) +{ + if (slot < POCKET_ACTIVE_FIRST_SLOT || slot >= ACTIVE_SLOT_COUNT) return; + + for (int i = 0; i < POCKET_SLOT_COUNT; i++) + { + if (pocketItems[i].type != POCKET_ACTIVE || pocketItems[i].id != slot + 1) continue; + if (int item = activeItems[pocketItems[i].id - 1].item) RemoveCollectible(item, true, slot, true); + std::shift_left(pocketItems.begin() + i, pocketItems.end(), 1); + pocketItems.back() = {0, POCKET_CARD}; + } + if (collectible != 0 && g_manager->itemConfig.GetCollectible(collectible)) + reconstruction_missing("Entity_Player::SetPocketActiveItem 007d41d0 (a new pocket active)"); +} + +// 007ad440 How many pocket slots the player has: one, two with Starter Deck, Little Baggy or Polydactyly, and one +// more per pocket active. +uint32_t Entity_Player::GetMaxPocketItems() +{ + bool isExtraSlot = HasCollectible(COLLECTIBLE_STARTER_DECK) || HasCollectible(COLLECTIBLE_LITTLE_BAGGY) || + HasCollectible(COLLECTIBLE_POLYDACTYLY); + auto isActive = [](PocketItem& pocket) { return pocket.type == POCKET_ACTIVE && pocket.id > 0; }; + + return (isExtraSlot ? 2 : 1) + (uint32_t)std::ranges::count_if(pocketItems, isActive); +} + +// 007c3a60 Loads the sounds the player's weapons and items will play before the room needs them. +void Entity_Player::preload_item_sounds() +{ + SFXManager& sfx = g_manager->sfxManager; + + if (weaponTypes[WEAPON_TEARS]) + for (int sound : {SOUND_SPLATTER, SOUND_TEARIMPACTS}) sfx.Preload(sound); + if (weaponTypes[WEAPON_LASER]) sfx.Preload(SOUND_REDLIGHTNING_ZAP); + if (weaponTypes[WEAPON_BRIMSTONE]) sfx.Preload(SOUND_BLOOD_LASER_LARGE); + if (HasCollectible(COLLECTIBLE_PEEPER)) sfx.Preload(SOUND_PLOP); + sfx.Preload(SOUND_ISAAC_HURT_GRUNT); + if (HasCollectible(COLLECTIBLE_SHOOP_DA_WHOOP)) sfx.Preload(SOUND_BLOOD_LASER); + if (activeItems[0].item != 0) + { + for (int sound : {SOUND_BEEP, SOUND_ITEMRECHARGE}) sfx.Preload(sound); + if (HasCollectible(COLLECTIBLE_BATTERY) || HasTrinket(TRINKET_AAA_BATTERY)) sfx.Preload(SOUND_BATTERYCHARGE); + } + if (HasCollectible(COLLECTIBLE_POOP)) sfx.Preload(SOUND_FART); + if (HasCollectible(COLLECTIBLE_YUM_HEART) || HasCollectible(COLLECTIBLE_CHARM_VAMPIRE)) + sfx.Preload(SOUND_VAMP_GULP); + if (HasCollectible(COLLECTIBLE_THE_NAIL)) sfx.Preload(SOUND_MONSTER_YELL_A); + if (pocketItems[0].type == POCKET_PILL && pocketItems[0].id != 0) + for (int sound : {SOUND_POWERUP_SPEWER, SOUND_THUMBSUP, SOUND_THUMBS_DOWN}) sfx.Preload(sound); +} + +// How many locusts Fish Tail makes of each: two, sometimes three or four with a golden or doubled tail, else one. +static int fish_tail_factor_get(Entity_Player& player) +{ + if (!player.HasTrinket(TRINKET_FISH_TAIL)) return 1; + + int multiplier = player.GetTrinketMultiplier(TRINKET_FISH_TAIL); + bool isLucky = multiplier >= 2 && multiplier <= FISH_TAIL_LUCKY_MAX && Random() % FISH_TAIL_EXTRA_ROLL == 0; + return isLucky ? multiplier + 1 : 2; +} + +// 007c8830 Sends out the player's locusts as the room starts: one per copy of each Locust trinket (Fish Tail +// multiplying them), Conquest's with a few extra from its RNG. +void Entity_Player::spawn_locusts() +{ + for (int trinket = TRINKET_LOCUST_OF_WRATH; trinket <= TRINKET_LOCUST_OF_CONQUEST; trinket++) + { + if (!HasTrinket(trinket)) continue; + + int count = GetTrinketMultiplier(trinket); + if (trinket == TRINKET_LOCUST_OF_CONQUEST) + { + int roll = count == 2 ? CONQUEST_EXTRA_ROLL_DOUBLE : CONQUEST_EXTRA_ROLL; + count += (int)(GetTrinketRNG(trinket).Next() % roll) * fish_tail_factor_get(*this); + } + else count *= fish_tail_factor_get(*this); + + int subType = trinket - TRINKET_LOCUST_OF_WRATH + 1; + for (int i = 0; i < count; i++) + { + EntitySpawn spawn = {.position = pos, .spawner = this, .subType = subType, .type = ENTITY_FAMILIAR, + .variant = FAMILIAR_BLUE_FLY, .seed = Random()}; + Entity* locust = g_game->Spawn(spawn); + locust->ClearEntityFlags(FLAG_APPEAR); + } + } +} + +// 007bf3d0 Whether the player can pick an item up now: alive, not dying, not firing Mega Blast, and not in an +// animation other than its hurt one unless it holds an item up. +bool Entity_Player::CanPickupItem() +{ + const std::string& animation = sprite.GetAnimation(); + + if ((isPlayingExtraAnimation || isPlayingItemAnimation) && animation != "Hit" && !IsHoldingItem()) return false; + return !isDead && animation != "Death" && megaBlastDuration < 1; +} diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 6ee23bb..e7bd250 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -23,8 +23,6 @@ constexpr float WALK_SLOW_SPEED = 2.3f; constexpr int DAMAGE_BLINK_PERIOD = 6; constexpr int DAMAGE_BLINK_HIDDEN = 3; constexpr int COLLECTIBLE_INTRUDER = 575; -constexpr int BABY_FOUND_SOUL = 59; -constexpr float DEATH_FRICTION = 0.6f; constexpr float EMOTE_HEIGHT = 52; constexpr float EMOTE_MOVING_SPEED = 0.1f; constexpr float GRAVITY_PULL = 0.225f; @@ -596,9 +594,7 @@ void Entity_Player::update_shooting() if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost) reconstruction_missing("Entity_Player::update_shooting 0077b020 (co-op babies' and ghosts' heads)"); sprite.SetOverlayFrame(headAnim, blinkFrame); - for (PlayerCostumeMap& map : playerCostumeMap) - if (map.index >= 0 && !map.isBodyLayer) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (head costumes)"); + costume_heads_update(blinkFrame); } if (isFireReady && HasCollectible(COLLECTIBLE_EPIPHORA)) reconstruction_missing("Entity_Player::update_shooting 0077b020 (Epiphora)"); @@ -622,6 +618,12 @@ void Entity_Player::update_shooting() void Entity_Player::Update() { if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; + if (isPlayingItemAnimation && bodySprite.IsFinished() && !bodySprite.IsFinished("LiftItem")) + { + isPlayingItemAnimation = false; + bodySprite.Reset(); + heldSprite.Reset(); + } if (isHurtPending && !isPlayingExtraAnimation) { isHurtPending = false; @@ -629,42 +631,28 @@ void Entity_Player::Update() reconstruction_missing("Entity_Player::Update 00782af0 (the spiders a hurt sets loose)"); } if (isDead) return death_update(); - if (!is_evaluation_plain() || isPlayingItemAnimation || heldEntity || queuedItem.item) + 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}) if (isControlsEnabled && action_value(action, controllerIndex) > 0) reconstruction_missing("Entity_Player::Update 00782af0 (bombs, items, pockets and drop)"); Entity::Update(); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) + { + bodySprite.Update(); + heldSprite.Update(); + for (CostumeSpriteDesc& costume : costumeSpriteDescs) costume.sprite.Update(); + for (int layer = PLAYER_LAYER_BODY; layer <= PLAYER_LAYER_BODY1; layer++) + if (playerCostumeMap[layer].index >= 0) + reconstruction_missing("Entity_Player::Update 00782af0 (body costumes following the walk)"); + } update_body_animations(); update_shooting(); walk_animation_update(); if (damageCooldown > 0) damageCooldown--; } -// The death sequence part of 00782af0: the player plays its death animation once, stops, and slows to a halt. Whether -// it revives, and the save deletion of a run lost, are WillPlayerRevive's (not written yet). -void Entity_Player::death_update() -{ - std::string_view animation = GetDeathAnimName(); - - if (g_game->roomTransition.mode == TRANSITION_NONE && sprite.GetAnimation() != animation) - { - isVisible = true; - PlayExtraAnimation(animation); - if (GetTrinketMultiplier(TRINKET_MYSTERIOUS_PAPER) > 0) - reconstruction_missing("Entity_Player::Update 00782af0 (Mysterious Paper's revival chance)"); - if (heldEntity) ThrowHeldEntity(Vector{}); - if (LayerState* ghost = sprite.GetLayer("ghost")) ghost->isVisible = true; - if (!parent && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && !WillPlayerRevive()) - reconstruction_missing("Entity_Player::Update 00782af0 (the save deletion of a lost run)"); - if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_FOUND_SOUL && parent && parent->is_player()) - parent->ToPlayer()->temporaryEffects.AddTrinketEffect(TRINKET_FOUND_SOUL, true, 1); - velocity = Vector{}; - } - friction *= DEATH_FRICTION; -} - // 0078ca00 Draws the player at its place, lifted by its flight and its offset: blinking while hurt, the held entity // in front or behind, its after-images, then its overlays (the co-op indicator, charge bars and status effect) in the // room's pass. Netplay's shadows and colors are offline. @@ -735,8 +723,7 @@ void Entity_Player::render_pass(const Vector& offset, RenderPass pass) posOffset = {}; sprite.overlayAnimState.SetAnimationData(nullptr); Entity::Render(offset); - if (pass == RENDER_PASS_MAIN && IsHoldingItem()) - reconstruction_missing("Entity_Player::render_pass 0078b640 (the held item over the whole sprite)"); + if (pass == RENDER_PASS_MAIN && IsHoldingItem()) heldSprite.Render(SpriteDraw{renderPosition, {}, {}}); posOffset = heldOffset; return; } @@ -800,8 +787,13 @@ void Entity_Player::RenderBody(const Vector& position) isBodyRendered = true; continue; } - if (canFly && !costumeSpriteDescs[index].isFlying) continue; - reconstruction_missing("Entity_Player::RenderBody 0078dde0 (body costumes)"); + CostumeSpriteDesc& costume = costumeSpriteDescs[index]; + if (canFly && !costume.isFlying) continue; + int layerId = playerCostumeMap[layer].layerId; + costume.sprite.RenderLayer(layerId, SpriteDraw{position, {}, {}}); + const AnimationFrame* frame = + costume.sprite.animState.animData ? costume.sprite.animState.GetLayerFrame(layerId) : nullptr; + if (frame && frame->isVisible) isBodyRendered = true; } if (isBodyRendered && IsHeadless()) reconstruction_missing("Entity_Player::RenderBody 0078dde0 (the blood gush)"); } diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 2b07d49..81f6454 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -1,9 +1,14 @@ #include "entity_player.h" +#include "entity_familiar.h" #include "game.h" +#include "lua_engine.h" #include "room.h" #include "log.h" #include "manager.h" #include "platform.h" +#include +#include +#include constexpr int ROOM_TRINKET_ROLL_SHIFT = 13; constexpr int RAINBOW_WORM_FRAMES = 90; @@ -539,3 +544,1180 @@ void Entity_Player::TriggerNewRoom_TemporaryEffects() temporaryEffects.AddEffect(TemporaryEffect(item), true, 1); holyMantleState = holyMantleState > 1; } + +// The items, tags, unlocks and counters taking a collectible asks about. +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_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 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 +{ + uint64_t tag = 0; + int above = 0; + int achievement = 0; +}; + +constexpr std::array TAG_UNLOCKS = {{{TAG_DEAD, 1, 31}, + {TAG_SYRINGE, 1, 146}, + {TAG_MOM, 2, 35}, + {TAG_TECH, 1, 369}, + {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}; + +// 007aa800 Whether the player may take a collectible now: not while the hold cooldown runs, and a helper player never +// takes an active. +bool Entity_Player::CanAddCollectible(int collectibleId) +{ + if (collectibleId != 0) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (item && item->type == ITEM_ACTIVE && parent) return false; + } + return itemHoldCooldown == 0; +} + +// 0075e050 Holds an item over the head until it is added, adding any item held before first. The G FUEL! seed's +// glitched item plays its jingle. +void Entity_Player::SetQueuedItem(const QueueItemData& queued) +{ + FlushQueueItem(); + queuedItem = queued; + ItemConfig_Item* item = queued.item; + bool isGlitchedFuel = item && item->id == -1 && item->type == ITEM_PASSIVE; + if (isGlitchedFuel && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) + reconstruction_missing("Entity_Player::SetQueuedItem 0075e050 (the G FUEL! jingle)"); +} + +// 0075e190 Forgets the queued item, and the held sprite while one is held up. +void Entity_Player::ClearQueueItem() +{ + if (IsHoldingItem()) heldSprite.Reset(); + queuedItem = {}; +} + +// 0056ff90 Whether no item waits to be added. +bool Entity_Player::IsItemQueueEmpty() +{ + return !queuedItem.item; +} + +// 007ab130 Lifts a pickup over the head: plays the lift animation and holds a copy of the pickup's sprite, its shadow +// hidden when asked, a little above the player. Netplay's online variant of the animation is offline. +void Entity_Player::AnimatePickup(ANM2* pickupSprite, bool isHideShadow, std::string_view animName) +{ + constexpr float HELD_SPRITE_RISE = -4; + + PlayExtraAnimation(animName, false); + heldSprite = *pickupSprite; + heldSprite.bitflags = pickupSprite->bitflags; + if (isHideShadow) + if (LayerState* shadow = heldSprite.GetLayer("shadow")) shadow->color = ColorMod{}; + heldSprite.offset = vector_make(0, HELD_SPRITE_RISE); +} + +// 007bf5c0 Whether the held item shows: the body's held null is visible in a holding animation. +bool Entity_Player::IsHeldItemVisible() +{ + if (!IsHoldingItem() || !bodySprite.animState.animData) return false; + const NullFrame* held = bodySprite.animState.GetNullFrameById(0); + return held && held->isVisible; +} + +// 007d4170 Whether Tainted Isaac's inventory can hold a collectible: a passive that is not a quest item, Damocles or +// Birthright. +bool Entity_Player::CanAddCollectibleToInventory(int id) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id); + if (!item || item->type == ITEM_ACTIVE || id == COLLECTIBLE_PASSIVE_DAMOCLES || id == COLLECTIBLE_BIRTHRIGHT) + return false; + return !item->HasTags(TAG_QUEST); +} + +// 0075f020 How many of the player's items carry a tag: each owned collectible once, each held trinket slot once. +int Entity_Player::tagged_item_count(uint64_t tag) +{ + int count = 0; + + for (ItemConfig_Item* item : g_manager->itemConfig.GetTaggedItems(tag)) + { + if (item->IsCollectible()) count += std::min(collectibleCounts[item->id], 1); + else if (item->type == ITEM_TRINKET) + for (uint32_t trinket : trinkets) count += trinket == (uint32_t)item->id ? 1 : 0; + } + return count; +} + +// 007584b0 Marks the items of the co-op babies and helpers this player owns as changed. How many players there are. +uint32_t Entity_Player::InvalidateCoPlayerItems() +{ + PlayerManager& players = g_game->playerManager; + + for (Entity_Player* other : players.playerList) + { + Entity_Player* owner = other->parent && other->parent->is_player() ? other->parent->ToPlayer() : nullptr; + if (!owner && other->variant == PLAYER_VARIANT_COOP_BABY) owner = g_game->GetPlayer(0); + if (owner == this) reconstruction_missing("Entity_Player::InvalidateCoPlayerItems 007584b0 (a co-op player)"); + } + return (uint32_t)players.playerList.size(); +} + +// 00721a70 Adds an item to the history, in time order, shifting Tainted Isaac's inventory to match and putting a new +// passive in a free inventory slot. A locked history keeps its items. +void History::AddHistoryItem(const HistoryItem& item) +{ + if (isLocked) return; + + auto later = std::ranges::find_if(historyItems, [&](HistoryItem& other) { return item.time < other.time; }); + int index = (int)(later - historyItems.begin()); + historyItems.insert(later, item); + + int freeSlot = -1; + for (int slot = 0; slot < INVENTORY_SIZE; slot++) + { + int& entry = player->inventory[slot]; + if (entry < 0 && freeSlot < 0) freeSlot = slot; + else if (index <= entry) entry++; + } + if (freeSlot >= 0 && !item.isTrinket && player->CanAddCollectibleToInventory(item.id)) + player->inventory[freeSlot] = index; + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + +// 007d3200 Puts Book of Virtues, or Book of Belial for Judas's Birthright, in the first active slot when it holds none +// or the other book, charged for Bethany's new book. Judas's book leaves the pools. +void Entity_Player::UpdateBookOfVirtues(bool isAddedBookOfVirtues) +{ + Game& game = *g_game; + std::vector& removed = game.itemPool.removedCollectibles; + int book = HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) ? COLLECTIBLE_BOOK_OF_VIRTUES : 0; + + if (HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + { + book = COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE; + if ((int)removed.size() > COLLECTIBLE_BOOK_OF_BELIAL_ACTIVE && !removed[COLLECTIBLE_BOOK_OF_BELIAL_ACTIVE] && + game.challenge != CHALLENGE_CANTRIPPED) + removed[COLLECTIBLE_BOOK_OF_BELIAL_ACTIVE] = true; + } + + ActiveItemDesc& active = activeItems[0]; + bool isBookSlot = active.item == COLLECTIBLE_BOOK_OF_VIRTUES || active.item == COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE; + if (book == 0) + { + if (isBookSlot) active.item = 0; + return; + } + if (book == active.item || (active.item != 0 && !isBookSlot)) return; + + active.item = book; + bool isCharged = isAddedBookOfVirtues || (playerType == PLAYER_BETHANY && book == COLLECTIBLE_BOOK_OF_VIRTUES); + active.charge = isCharged ? GetCollectibleMaxCharge(book, active.varData) : 0; + active.batteryCharge = 0; + active.subCharge = 0; + active.partialCharge = 0; + active.timeRechargeCooldown = 0; + active.varData = 0; +} + +// 0075e320 Counts items towards a transformation (the Missing Pages' from its two books and trinket). Only the counting is +// reconstructed: a transformation won or lost stops the game until reached. +void Entity_Player::IncrementPlayerFormCounter(int ePlayerForm, int num) +{ + constexpr int PLAYER_FORM_MISSING_PAGES = 15; + constexpr int COLLECTIBLE_NECRONOMICON = 35; + constexpr int COLLECTIBLE_MISSING_PAGE_2 = 262; + + bool wasActive = HasPlayerForm(ePlayerForm); + playerForms[ePlayerForm] = std::max(playerForms[ePlayerForm] + num, 0); + if (ePlayerForm == PLAYER_FORM_MISSING_PAGES) + playerForms[ePlayerForm] = (int)HasCollectible(COLLECTIBLE_NECRONOMICON) + + (int)HasCollectible(COLLECTIBLE_MISSING_PAGE_2) + (int)HasTrinket(TRINKET_MISSING_PAGE); + if (HasPlayerForm(ePlayerForm) != wasActive) + 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 +// three star items. +void Entity_Player::collectible_unlocks_check(int collectibleId, ItemConfig_Item& item) +{ + PersistentGameData& save = g_manager->persistentGameData; + + 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); + + int tearsUps = PILL_TEARS_UP < (int)pillEffectUses.size() ? pillEffectUses[PILL_TEARS_UP] : 0; + for (ItemConfig_Item* tagged : g_manager->itemConfig.GetTaggedItems(TAG_TEARS_UP)) + if (tagged->IsCollectible()) tearsUps += collectibleCounts[tagged->id]; + if (tearsUps >= TEARS_UP_UNLOCK_COUNT) save.TryUnlock(ACHIEVEMENT_TEARS_UP_ITEMS); + + if (item.HasTags(STARS_UNLOCK.tag) && tagged_item_count(STARS_UNLOCK.tag) > STARS_UNLOCK.above) + save.TryUnlock(STARS_UNLOCK.achievement); +} + +// The pickups, coins, keys, bombs and hearts a collectible gives the first time it is taken. Tainted Bethany takes +// at most six red hearts. +void Entity_Player::collectible_pickups_add(ItemConfig_Item& item) +{ + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (the deathmatch's item changes)"); + + int hearts = playerType == PLAYER_BETHANY_B ? std::min(item.addHearts, T_BETHANY_HEART_CAP) : item.addHearts; + int maxHeartsBefore = maxHearts; + AddBombs(item.addBombs); + AddKeys(item.addKeys); + AddCoins(item.addCoins); + AddMaxHearts(item.addMaxHearts, false); + AddHearts(hearts, false, false); + AddSoulHearts(item.addSoulHearts, false); + AddBlackHearts(item.addBlackHearts); + + HealthType health = GetHealthType(); + bool isCapped = (health == HEALTH_COIN || health == HEALTH_DEFAULT) && + item.addMaxHearts - maxHearts + maxHeartsBefore > 0; + if (isCapped) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (heart containers over the cap)"); +} + +// 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. +void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData) +{ + Game& game = *g_game; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(type); + 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) + 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) + return twin->AddCollectible(type, charge, isFirstTime, slot, varData); + + log_printf(LOG_INFO, "Adding collectible %d (%s) to player %d (%s) from pool %s\n", type, + item->GetLocalizedName(LANGUAGE_CURRENT).c_str(), playerIndex, name.c_str(), ""); + + bool isMainPlayer = variant == PLAYER_VARIANT_PLAYER && !isCoopGhost; + if (isMainPlayer) + { + InvalidateCoPlayerItems(); + if (isFirstTime) game.itemPool.unkFloat674 = std::min(game.itemPool.unkFloat674, game.itemPool.unkFloat678); + } + g_manager->persistentGameData.AddToCollection(type); + if (type < 0) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (a procedural item)"); + collectibleCounts[type]++; + + if (isMainPlayer) + { + collectible_unlocks_check(type, *item); + int time = isPostLevelInitFinished ? game.frameCount : 0; + history.AddHistoryItem({time, false, type, (int)game.stage, (int)game.stageType, game.room->roomType, + HISTORY_POOL_NONE}); + stop_costume_item_anims(); + if (isFirstTime) collectible_pickups_add(*item); + } + + if (item->type == ITEM_ACTIVE) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (an active item)"); + 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) + { + redStewBonusDuration = std::max(redStewBonusDuration, BINGE_EATER_STEW_FRAMES); + AddHearts(2, false, false); + } + + if (variant == PLAYER_VARIANT_PLAYER && isFirstTime) + { + std::vector>& forms = g_manager->itemConfig.playerForms; + for (int form = 0; form < (int)forms.size(); form++) + if (forms[form] && forms[form]->tags != 0 && item->HasTags(forms[form]->tags)) + IncrementPlayerFormCounter(form, 1); + } + EvaluateItems(); + if (item->isAddCostumeOnPickup) AddCostume(item, false); + + int owned = 0; + for (int count : collectibleCounts) owned += count; + if (owned > COLLECTIBLE_COUNT_UNLOCK) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_MANY_COLLECTIBLES); + 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; +constexpr int COLLECTIBLE_DOUBLED_COSTUME_B = 730; +constexpr int NULLITEM_BRIMSTONE_DOUBLE = 45; +constexpr int NULLITEM_DOUBLED_COSTUME_A = 125; +constexpr int NULLITEM_DOUBLED_COSTUME_B = 126; +constexpr int NULLITEM_EDEN_HAIR = 12; +constexpr int NULLITEM_EDEN_HAIR_B = 88; +constexpr int COLLECTIBLE_TRANSCENDENCE = 20; +constexpr int NULLITEM_INTRUDER_TRANSCENDENCE = 132; +constexpr int COLLECTIBLE_SACK_HEAD_COSTUME = 424; +constexpr int COLLECTIBLE_HOLY_GRAIL = 184; +constexpr int SPECIAL_DAILY_COSTUME_PRIORITY = 13; +constexpr int DAILY_COSTUME_PRIORITY_BONUS = 3; + +// The costume an item puts on for its copies: a second Brimstone and the two doubled collectibles wear a null item's. +static ItemConfig_Item* costume_item_get(Entity_Player& player, ItemConfig_Item* item) +{ + ItemConfig& items = g_manager->itemConfig; + if (item->type != ITEM_PASSIVE) return item; + + if (item->id == COLLECTIBLE_BRIMSTONE && player.GetCollectibleNum(COLLECTIBLE_BRIMSTONE) > 1) + item = items.GetNullItem(NULLITEM_BRIMSTONE_DOUBLE); + if (item && item->type == ITEM_PASSIVE && item->id == COLLECTIBLE_DOUBLED_COSTUME_A && + player.GetCollectibleNum(COLLECTIBLE_DOUBLED_COSTUME_A) > 1) + item = items.GetNullItem(NULLITEM_DOUBLED_COSTUME_A); + if (item && item->type == ITEM_PASSIVE && item->id == COLLECTIBLE_DOUBLED_COSTUME_B && + player.GetCollectibleNum(COLLECTIBLE_DOUBLED_COSTUME_B) > 1) + item = items.GetNullItem(NULLITEM_DOUBLED_COSTUME_B); + return item; +} + +// 0075d1d0 Puts an item's costume on: a second copy of a few items wears another, a Lazarus twin shares it, and its +// sprite joins the worn costumes (once, as a costume worn before is taken off first), split in two when it covers both +// the head and the body. Co-op babies and ghosts wear none, and one challenge allows only Holy Grail's. +void Entity_Player::AddCostume(ItemConfig_Item* item, bool isItemStateOnly) +{ + constexpr int CHALLENGE_COSTUMELESS = 30; + if (variant == PLAYER_VARIANT_COOP_BABY || !item || isCoopGhost) return; + + item = costume_item_get(*this, item); + if (!item) return; + if (item->type == ITEM_NULL && item->id == NULLITEM_INTRUDER && HasCollectible(COLLECTIBLE_TRANSCENDENCE)) + temporaryEffects.AddNullEffect(NULLITEM_INTRUDER_TRANSCENDENCE, true, 1); + if (item->costume.anm2Path.empty()) return; + if (isValid && item->HasTags(TAG_LAZ_SHARED) && backupPlayer) backupPlayer->AddCostume(item, isItemStateOnly); + bool isHolyGrail = item->IsCollectible() && item->id == COLLECTIBLE_HOLY_GRAIL; + if (g_game->challenge == CHALLENGE_COSTUMELESS && !isHolyGrail) return; + + if (std::erase_if(costumeSpriteDescs, [item](CostumeSpriteDesc& worn) { return worn.item == item; }) > 0) + log_printf(LOG_INFO, "Adding costume for %d (%s) which was added before and never removed.\n", item->id, + item->GetLocalizedName(LANGUAGE_CURRENT).c_str()); + + CostumeSpriteDesc& costume = costumeSpriteDescs.emplace_back(); + costume.item = item; + costume.priority = item->costume.priority; + costume.isFlying = item->costume.isFlying; + costume.isHasOverlay = item->costume.isHasOverlay; + costume.skinColor = item->costume.skinColor; + costume.defaultSkinColor = item->costume.skinColor; + costume.isHasSkinAlt = item->costume.isHasSkinAlt; + costume.isOverwriteColor = item->costume.isOverwriteColor; + costume.isItemStateOnly = isItemStateOnly; + costume.playerType = -1; + if (g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_COSTUME_PRIORITY && item->IsCollectible() && + item->id == COLLECTIBLE_SACK_HEAD_COSTUME) + costume.priority += DAILY_COSTUME_PRIORITY_BONUS; + costume.sprite.Load(item->costume.anm2Path, GRAPHICS_DEFER); + bool isEdenHair = item->type == ITEM_NULL && (item->id == NULLITEM_EDEN_HAIR || item->id == NULLITEM_EDEN_HAIR_B); + if (isEdenHair) reconstruction_missing("Entity_Player::AddCostume 0075d1d0 (Eden's hair)"); + costume.sprite.LoadGraphics(); + + bool isHead = false; + bool isBody = false; + for (int layer = 0; layer < COSTUME_LAYER_COUNT; layer++) + { + LayerState* own = sprite.GetLayer(layer); + std::string_view layerName = own && own->layerData ? std::string_view(own->layerData->name) : ""; + if (!costume.sprite.GetLayer(layerName)) continue; + if (playerCostumeMap[layer].isBodyLayer) isBody = true; + else isHead = true; + } + if (!isHead && !isBody) + log_printf(LOG_INFO, "[warn] Costume for item %d (%s) has no layers!\n", item->id, + item->GetLocalizedName(LANGUAGE_CURRENT).c_str()); + else if (isHead && isBody) costumeSpriteDescs.push_back(CostumeSpriteDesc(costumeSpriteDescs.back())); + UpdateCostumes(); +} + +// The UpdateCostumes part that hands the player's layers to the worn costumes of highest priority (a costume covering +// head and body uses its two copies), skipping body layers a flying player does not show of a walking costume. +// Whether the head or body color would change, which is not reconstructed yet. +void Entity_Player::costume_layers_map(int skinColor) +{ + for (int index = 0; index < (int)costumeSpriteDescs.size(); index++) + { + CostumeSpriteDesc& costume = costumeSpriteDescs[index]; + int headIndex = index; + int bodyIndex = index; + int matched = 0; + bool wasBody = false; + + for (int layer = 0; layer < COSTUME_LAYER_COUNT; layer++) + { + PlayerCostumeMap& map = playerCostumeMap[layer]; + LayerState* own = sprite.GetLayer(layer); + std::string_view layerName = own && own->layerData ? std::string_view(own->layerData->name) : ""; + LayerState* worn = costume.sprite.GetLayer(layerName); + if (!worn) continue; + if (costume.priority < map.priority || (canFly && !costume.isFlying && map.isBodyLayer)) continue; + + if (matched != 0 && bodyIndex == headIndex && layer != 0 && map.isBodyLayer != wasBody) + { + if (map.isBodyLayer) bodyIndex++; + else headIndex++; + } + wasBody = map.isBodyLayer; + map.index = map.isBodyLayer ? bodyIndex : headIndex; + map.layerId = worn->layerData ? worn->layerData->id : -1; + map.priority = costume.priority; + matched++; + if (costume.defaultSkinColor != skinColor && (layer == PLAYER_LAYER_HEAD || layer == PLAYER_LAYER_BODY)) + reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (a costume's skin color)"); + } + if (costume.item && (costume.item->costume.isForceHeadColor || costume.item->costume.isForceBodyColor)) + reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (a costume forcing the skin color)"); + index = std::max(bodyIndex, headIndex); + } +} + +// The UpdateCostumes part that dresses a mapped costume for the character: its sheets from the character's costume +// folder and, for a costume with skin alts drawn for another skin, the skin color's sheets, darkened for Black Judas +// when the folder has none, and its animation kept as it was. The dark tint is the one the original keeps in its data. +void Entity_Player::costume_skin_apply(CostumeSpriteDesc& costume, int skinColor) +{ + bool isDark = playerType == PLAYER_BLACKJUDAS || playerType == PLAYER_JUDAS_B; + bool isAlt = costume.isHasSkinAlt && costume.defaultSkinColor != skinColor; + bool isAnyFound = false; + + if (isDark) reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (Black Judas's costume tint)"); + std::string animation = costume.sprite.animState.animData ? costume.sprite.GetAnimation() : std::string(); + bool isPlaying = costume.sprite.animState.animData && costume.sprite.animState.isPlaying; + int frame = (int)costume.sprite.animState.animFrame; + + for (int layer = 0; layer < (int)costume.sprite.layerStates.size(); layer++) + { + LayerState* state = costume.sprite.GetLayer(layer); + std::string path = state && state->layerData ? state->layerData->spriteSheetPath : std::string(); + bool isSkinFound = false; + bool isCharacterFound = false; + std::string skinned = costume_path_apply_skin_color(path, isAlt ? skinColor : -1, playerType, + isAlt ? &isSkinFound : nullptr, &isCharacterFound); + costume.sprite.ReplaceSpritesheet(layer, skinned); + if (LayerState* recolored = costume.sprite.GetLayer(layer)) recolored->color = COLOR_DEFAULT; + isAnyFound |= isSkinFound || isCharacterFound; + } + if (isAlt && !isAnyFound) + log_printf(LOG_INFO, "Costume %s supports skin color alts but no alt spritesheet could be found! (skin color %d)\n", + costume.sprite.filename.c_str(), skinColor); + costume.skinColor = skinColor; + costume.playerType = playerType; + costume.sprite.LoadGraphics(); + + if (animation.empty()) return; + if (!isPlaying) + { + costume.sprite.SetFrame(animation, frame); + return; + } + const AnimationState& state = costume.sprite.animState; + bool isStopped = state.animData && state.animData->isLooping && !state.isPlaying; + if (!state.animData || costume.sprite.GetAnimation() != animation || isStopped) costume.sprite.Play(animation, PLAY_FORCED); +} + +// 0075bf00 Lays the worn costumes over the player's layers by priority, dresses each for the character, poses them +// at the first frame of HeadDown or WalkDown with their SubAnim overlay, and recolors the player for its skin. +// Jupiter's and Berserk's costumes, the cursed mist, Mega Mush and skin colors other than the character's stop the +// game until reached. +void Entity_Player::UpdateCostumes() +{ + static bool isUpdating = false; + constexpr int COLLECTIBLE_JUPITER_COSTUME = 594; + constexpr int COLLECTIBLE_MEGA_MUSH_COSTUME = 625; + constexpr int COLLECTIBLE_BERSERK_COSTUME = 704; + + if (variant == PLAYER_VARIANT_COOP_BABY || isUpdating) return; + for (CostumeSpriteDesc& costume : costumeSpriteDescs) + { + int id = costume.item && costume.item->IsCollectible() ? costume.item->id : 0; + if (id == COLLECTIBLE_JUPITER_COSTUME || id == COLLECTIBLE_MEGA_MUSH_COSTUME || id == COLLECTIBLE_BERSERK_COSTUME) + reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (Jupiter, Mega Mush and Berserk)"); + } + if (!costumeSpriteDescs.empty() && hasCurseMistEffect) + reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (the cursed mist)"); + + isUpdating = true; + EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType); + if (!playerConfig) log_printf(LOG_ASSERT, "Could not load config for player type %d\n", playerType); + int skinColor = playerConfig ? playerConfig->skinColor : -1; + costume_map_reset(-1); + if (!isCoopGhost) costume_layers_map(skinColor); + + for (int layer = 0; layer < COSTUME_LAYER_COUNT; layer++) + { + int index = playerCostumeMap[layer].index; + if (index < 0) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[index]; + bool isDressed = (!costume.isHasSkinAlt || costume.skinColor == skinColor) && costume.playerType == playerType; + if (costume.item && costume.item->type == ITEM_NULL && + (costume.item->id == NULLITEM_EDEN_HAIR || costume.item->id == NULLITEM_EDEN_HAIR_B)) + reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (Eden's hair)"); + if (!isDressed) costume_skin_apply(costume, skinColor); + } + if (headColor != skinColor || bodyColor != skinColor) + reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (recoloring the skin)"); + + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0) continue; + ANM2& worn = costumeSpriteDescs[map.index].sprite; + if (worn.SetAnimation(map.isBodyLayer ? "WalkDown" : "HeadDown") && worn.animState.animData) + { + worn.animState.SetFrameFloat(0); + worn.animState.isPlaying = false; + } + if (worn.GetAnimationData("SubAnim")) worn.PlayOverlay("SubAnim"); + } + if (isCoopGhost) reset_body_sprite(); + 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. +void Entity_Player::costume_heads_update(int blinkFrame) +{ + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0 || map.isBodyLayer) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + const AnimationData* head = costume.sprite.GetAnimationData(headAnim); + if (costume.isItemAnimPlay || !head) continue; + + if (!head->isLooping) + { + if (costume.sprite.GetAnimationData(headAnim + "_Idle")) + reconstruction_missing("Entity_Player::update_shooting 0077b020 (an idle head costume)"); + costume.sprite.SetFrame(headAnim, blinkFrame); + } + else + { + costume.sprite.Play(headAnim); + if (LayerState* layer = costume.sprite.GetLayer(map.layerId)) + layer->pos.y = (float)blinkFrame * layer->size.y; + } + if (!costume.isHasOverlay) continue; + std::string overlay = headAnim + "_Overlay"; + if (const AnimationData* data = costume.sprite.GetAnimationData(overlay)) + { + if (data->isLooping) costume.sprite.PlayOverlay(overlay); + else costume.sprite.SetOverlayFrame(overlay, blinkFrame); + } + } +} diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 54ba130..9d6f48f 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -5,14 +5,6 @@ bool Entity_Player::TryThrow(const EntityRef&, const Vector&, float) { reconstruction_missing("Entity_Player::TryThrow 007d2930"); } -bool Entity_Player::HandleCollision(Entity*, bool) -{ - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0"); -} -void Entity_Player::AddCollectible(int, int, bool, int, int) -{ - reconstruction_missing("Entity_Player::AddCollectible 0075f0e0"); -} void Entity_Player::AddActiveCharge(int, int, bool, bool, bool) { reconstruction_missing("Entity_Player::AddActiveCharge 007915a0"); @@ -40,7 +32,6 @@ void Entity_Player::SetMinDamageCooldown(int) } int Entity_Player::GetActiveItem(int) { reconstruction_missing("Entity_Player::GetActiveItem 00505c80"); } bool Entity_Player::AreControlsEnabled() { reconstruction_missing("Entity_Player::AreControlsEnabled 00505cc0"); } -bool Entity_Player::IsItemQueueEmpty() { reconstruction_missing("Entity_Player::IsItemQueueEmpty 0056ff90"); } 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"); } @@ -92,10 +83,6 @@ void Entity_Player::release_weapons_and_effects(bool) { reconstruction_missing("Entity_Player::release_weapons_and_effects 00757ac0"); } -uint32_t Entity_Player::InvalidateCoPlayerItems() -{ - reconstruction_missing("Entity_Player::InvalidateCoPlayerItems 007584b0"); -} void Entity_Player::cycle_spectate_target() { reconstruction_missing("Entity_Player::cycle_spectate_target 007585b0"); } void Entity_Player::trigger_max_hearts_removed(int) { @@ -122,14 +109,7 @@ Entity* Entity_Player::AddSwarmFlyOrbital(Vector) reconstruction_missing("Entity_Player::AddSwarmFlyOrbital 00759bf0"); } bool Entity_Player::TryUseKey() { reconstruction_missing("Entity_Player::TryUseKey 00759e20"); } -void Entity_Player::AddCostume(ItemConfig_Item*, bool) { reconstruction_missing("Entity_Player::AddCostume 0075d1d0"); } void Entity_Player::AddNullCostume(int) { reconstruction_missing("Entity_Player::AddNullCostume 0075d800"); } -void Entity_Player::ClearQueueItem() { reconstruction_missing("Entity_Player::ClearQueueItem 0075e190"); } -bool Entity_Player::FlushQueueItem() { reconstruction_missing("Entity_Player::FlushQueueItem 0075e1d0"); } -void Entity_Player::IncrementPlayerFormCounter(int, int) -{ - reconstruction_missing("Entity_Player::IncrementPlayerFormCounter 0075e320"); -} void Entity_Player::AddPlayerFormCostume(int) { reconstruction_missing("Entity_Player::AddPlayerFormCostume 0075e9a0"); @@ -169,7 +149,6 @@ void Entity_Player::TriggerCollectibleRemoved(int) { reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90"); } -void Entity_Player::ClearTemporaryEffects() { reconstruction_missing("Entity_Player::ClearTemporaryEffects 007907a0"); } int Entity_Player::GetTotalActiveCharge(int) { reconstruction_missing("Entity_Player::GetTotalActiveCharge 007910f0"); } int Entity_Player::GetCollectibleMaxCharge(int, int) { @@ -187,7 +166,6 @@ Entity_Bomb* Entity_Player::FireBomb(Vector, Vector, Entity*) { reconstruction_missing("Entity_Player::FireBomb 007a0970"); } -bool Entity_Player::TriggerDeath(bool) { reconstruction_missing("Entity_Player::TriggerDeath 007a1090"); } void Entity_Player::Revive() { reconstruction_missing("Entity_Player::Revive 007a2220"); } void Entity_Player::ReviveFromTrinket(uint32_t) { reconstruction_missing("Entity_Player::ReviveFromTrinket 007a3430"); } void Entity_Player::remove_twin() { reconstruction_missing("Entity_Player::remove_twin 007a37c0"); } @@ -205,13 +183,7 @@ void Entity_Player::RemovePocketItem(int) { reconstruction_missing("Entity_Playe 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::room_exit(bool) { reconstruction_missing("Entity_Player::room_exit 007a6680"); } void Entity_Player::TriggerRoomClear() { reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0"); } -bool Entity_Player::CanAddCollectible(int) { reconstruction_missing("Entity_Player::CanAddCollectible 007aa800"); } -void Entity_Player::AnimatePickup(ANM2*, bool, std::string_view) -{ - reconstruction_missing("Entity_Player::AnimatePickup 007ab130"); -} void Entity_Player::AnimateCollectible(int, std::string_view, std::string_view) { reconstruction_missing("Entity_Player::AnimateCollectible 007ab380"); @@ -253,7 +225,6 @@ void Entity_Player::TryRemoveNullCostume(int) { reconstruction_missing("Entity_Player::TryRemoveNullCostume 007ad400"); } -uint32_t Entity_Player::GetMaxPocketItems() { reconstruction_missing("Entity_Player::GetMaxPocketItems 007ad440"); } void Entity_Player::ClearCollectibleAnim(int) { reconstruction_missing("Entity_Player::ClearCollectibleAnim 007ad5a0"); @@ -304,8 +275,6 @@ Entity_Laser* Entity_Player::FireDelayedBrimstone(float, Entity*) { reconstruction_missing("Entity_Player::FireDelayedBrimstone 007bf1a0"); } -bool Entity_Player::CanPickupItem() { reconstruction_missing("Entity_Player::CanPickupItem 007bf3d0"); } -bool Entity_Player::IsHeldItemVisible() { reconstruction_missing("Entity_Player::IsHeldItemVisible 007bf5c0"); } void Entity_Player::AddBlueSpider(Vector) { reconstruction_missing("Entity_Player::AddBlueSpider 007bf5f0"); } Entity_Familiar* Entity_Player::ThrowBlueSpider(Vector, Vector) { @@ -324,7 +293,6 @@ void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Pl 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"); } -void Entity_Player::preload_item_sounds() { reconstruction_missing("Entity_Player::preload_item_sounds 007c3a60"); } 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"); } void Entity_Player::AddDeadEyeCharge() { reconstruction_missing("Entity_Player::AddDeadEyeCharge 007c78b0"); } @@ -339,7 +307,6 @@ void Entity_Player::AddImmaculateConceptionCounter(int) reconstruction_missing("Entity_Player::AddImmaculateConceptionCounter 007c8050"); } void Entity_Player::dash_impact() { reconstruction_missing("Entity_Player::dash_impact 007c8240"); } -void Entity_Player::spawn_locusts() { reconstruction_missing("Entity_Player::spawn_locusts 007c8830"); } Entity_Laser* Entity_Player::SpawnMawOfVoid(int) { reconstruction_missing("Entity_Player::SpawnMawOfVoid 007c8dc0"); } void Entity_Player::AddGoldenBomb() { reconstruction_missing("Entity_Player::AddGoldenBomb 007c8f80"); } void Entity_Player::RemoveGoldenBomb() { reconstruction_missing("Entity_Player::RemoveGoldenBomb 007c8fc0"); } @@ -366,7 +333,6 @@ void Entity_Player::apply_coop_baby_spawn_bonus() { reconstruction_missing("Entity_Player::apply_coop_baby_spawn_bonus 007cb090"); } -bool Entity_Player::WillPlayerRevive() { reconstruction_missing("Entity_Player::WillPlayerRevive 007cbb60"); } float Entity_Player::GetGreedDonationBreakChance() { reconstruction_missing("Entity_Player::GetGreedDonationBreakChance 007cbb70"); @@ -423,7 +389,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::UpdateBookOfVirtues(bool) { reconstruction_missing("Entity_Player::UpdateBookOfVirtues 007d3200"); } void Entity_Player::trigger_vampire_charm_kill() { reconstruction_missing("Entity_Player::trigger_vampire_charm_kill 007d3350"); @@ -432,14 +397,6 @@ void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Playe 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"); } int Entity_Player::GetMaxInventorySize() { reconstruction_missing("Entity_Player::GetMaxInventorySize 007d4150"); } -bool Entity_Player::CanAddCollectibleToInventory(int) -{ - reconstruction_missing("Entity_Player::CanAddCollectibleToInventory 007d4170"); -} -void Entity_Player::SetPocketActiveItem(int, int, bool) -{ - reconstruction_missing("Entity_Player::SetPocketActiveItem 007d41d0"); -} void Entity_Player::get_salvation_scale() { reconstruction_missing("Entity_Player::get_salvation_scale 007d4340"); } void Entity_Player::update_suplex() { reconstruction_missing("Entity_Player::update_suplex 007d4390"); } uint32_t Entity_Player::bag_of_crafting_collect(Entity_Pickup*) @@ -521,7 +478,6 @@ void Entity_Player::PlayCollectibleAnim(int, bool, std::string_view, int) { reconstruction_missing("Entity_Player::PlayCollectibleAnim 00759f50"); } -void History::AddHistoryItem(const HistoryItem&) { reconstruction_missing("History::AddHistoryItem 00721a70"); } bool History::RemoveHistoryItemByIndex(int) { reconstruction_missing("History::RemoveHistoryItemByIndex 00721c00"); } void History::merge(History&) { reconstruction_missing("History::merge 00721c80"); } void History::remove_index_refs(int) { reconstruction_missing("History::remove_index_refs 007220a0"); } diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index b48706e..86cc748 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -67,7 +67,6 @@ constexpr int BABY_TWENTY_TWENTY = 65; constexpr int PLAYERFORM_CONJOINED = 7; constexpr int PLAYERFORM_BOOKWORM = 10; constexpr int TRANSFORMATION_COUNT = 3; -constexpr int LUA_CALLBACK_POST_FIRE_TEAR = 61; constexpr int TEAR_COLOR_PRIORITY = 255; constexpr int COLLECTIBLE_20_20 = 245; @@ -383,7 +382,7 @@ PosVel Entity_Player::GetMultiShotPositionVelocity(int loopIndex, WeaponType wea // game until reached. TearParams Entity_Player::GetTearHitParams(WeaponType weaponType, float damageScale, int displacement, Entity* source) { - if ((source && source->IsFamiliar()) || !is_evaluation_plain() || redStewBonusDuration > RED_STEW_BLOOD_FRAMES) + if ((source && source->IsFamiliar()) || !is_tear_hit_plain() || redStewBonusDuration > RED_STEW_BLOOD_FRAMES) reconstruction_missing("Entity_Player::GetTearHitParams 007bf6c0 (items, effects and familiars)"); TearParams params; @@ -475,8 +474,7 @@ Entity_Tear* Entity_Player::FireTear(const PosVel& shot, uint32_t fireFlags, Ent tear->Update(); tear->pos = vector_make(tear->pos.x - tear->velocity.x, tear->pos.y - tear->velocity.y); - if (static_cast(g_luaEngine)->enabledCallbacks.test(LUA_CALLBACK_POST_FIRE_TEAR)) - reconstruction_missing("lua_callback_run_post_fire_tear 00863f70"); + lua_engine_get().PostFireTear(tear); if (HasCollectible(COLLECTIBLE_EVIL_EYE) && !(fireFlags & TEAR_FIRE_NO_EVIL_EYE)) reconstruction_missing("Entity_Player::FireTear 00790af0 (Evil Eye)"); return tear; diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 4124142..cb8136b 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -116,9 +116,6 @@ constexpr float STREAK_DAMAGE = 1; constexpr uint64_t DAMAGE_INVINCIBLE = 1ull << 13; constexpr int STREAK_DAMAGE_COUNTDOWN = 30; -constexpr int LUA_CALLBACK_POST_TEAR_INIT = 39; -constexpr int LUA_CALLBACK_POST_TEAR_UPDATE = 40; -constexpr int LUA_CALLBACK_POST_TEAR_RENDER = 41; constexpr uint32_t GRAPHICS_PREMULTIPLIED_ALPHA = 4; constexpr const char* GFUEL_NAIL_ANM2 = "gfx/promo/gfuel/bullet tear.anm2"; constexpr const char* GFUEL_NAIL_BLOOD_ANM2 = "gfx/promo/gfuel/missile.anm2"; @@ -331,7 +328,7 @@ void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uin sprite.Load(variant == TEAR_NAIL ? GFUEL_NAIL_ANM2 : GFUEL_NAIL_BLOOD_ANM2, GRAPHICS_LOAD); layer_additive_set(sprite, variant == TEAR_NAIL ? 0 : 1); } - lua_callback_check(LUA_CALLBACK_POST_TEAR_INIT, "LuaEngine::PostTearInit 008629c0"); + lua_engine_get().PostTearInit(this); } // 006670f0 Flies the tear for a frame, or splashes and removes it once it has died. While held it bobs at its @@ -370,7 +367,7 @@ void Entity_Tear::Update() flight_update(); if (is_crawlspace() && !room.IsPositionInRoom(pos, CRAWLSPACE_ROOM_MARGIN)) Remove(); if (room.HasSlowDown()) SetColor(SLOWDOWN_COLOR, SLOWDOWN_COLOR_FRAMES, COLOR_PRIORITY_TOP, false, true); - lua_callback_check(LUA_CALLBACK_POST_TEAR_UPDATE, "LuaEngine::PostTearUpdate 00862aa0"); + lua_engine_get().PostTearUpdate(this); } // Counts down a held tear, pinning it bobbing at its parent and updating it there. Whether it is still held. @@ -624,7 +621,7 @@ void Entity_Tear::Render(const Vector& offset) Entity::Render(offset); if (tearEffectANM2.isLoaded && !isEffectBehind) tearEffectANM2.Render(draw); if (deadEyeIntensity != 0) deadEyeANM2.Render(draw); - lua_callback_check(LUA_CALLBACK_POST_TEAR_RENDER, "LuaEngine::PostTearRender 00862b80"); + lua_engine_get().PostTearRender(this, offset); } // 00675fa0 Sets the damage it deals, and the damage it started with. @@ -664,18 +661,6 @@ void Entity_Tear::ClearReferences() for (Entity* link = child; link && link->type == ENTITY_TEAR; link = link->child) link->Remove(); } -// 00673660 Lets a mod's MC_PRE_TEAR_COLLISION decide first, then ignores low collisions, a dead tear and its own -// player. Whether the collision is ignored. -bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) -{ - LuaResult result = static_cast(g_luaEngine)->PreTearCollision(this, collider, isLow); - if (result != LUA_RESULT_NIL) return result == LUA_RESULT_TRUE; - if (!isLow || isDead) return false; - if (GetPlayerAncestor() == collider) return true; - if (collider->type == ENTITY_PLAYER && IsDescendantOf(collider)) return true; - reconstruction_missing("Entity_Tear::HandleCollision 00673660: the hit on what it collides with"); -} - // 00665b00 The player at the end of its spawner chain, or none when that is not a player. Entity_Player* Entity_Tear::GetRootPlayer() { diff --git a/src/entity_tear.h b/src/entity_tear.h index 6cd3b58..33d3297 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -4,9 +4,24 @@ #include "anm2.h" #include -// Lua's TearFlags bits that the entity code reads. +// Lua's TearFlags bits that the entity code reads (bit 100, a hit through cooldowns, has no Lua name). 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_GROW = 7, TEAR_EXPLOSIVE = 12, TEAR_WAIT = 17, @@ -87,6 +102,8 @@ enum TearDeath : uint32_t TEAR_DEATH_GRID = 1 << 0, TEAR_DEATH_WALL = 1 << 1, TEAR_DEATH_FLOOR = 1 << 2, + TEAR_DEATH_ENTITY = 1 << 3, + TEAR_DEATH_EXPLOSION = 1 << 5, TEAR_DEATH_FORCED = 1 << 6 }; @@ -95,8 +112,8 @@ enum TearDeath : uint32_t // 0060cd00, 0085dd60, 0085dd70, 0085dd90) are the public fields. // A player's tear (Lua's EntityTear): its height and fall, scale and damage, the tear flags that change how it flies // and hits, the entity it sticks to, and the tears and lasers it links to. -// Only a plain tear is reconstructed yet: Update and Interpolate stop at any tear flag or special variant, and -// HandleCollision past its early checks. +// Only a plain tear is reconstructed yet: Update, Interpolate and HandleCollision stop at most tear flags and special +// variants. struct Entity_Tear : Entity { ANM2 deadEyeANM2; @@ -174,6 +191,8 @@ struct Entity_Tear : Entity void apply_link_spring_forces(); bool try_make_bridges(const Vector& position); void reroll_hit_entity(int unused); + static void ApplyTearFlagEffects(Entity* entity, const Vector& position, const TearFlags& flags, Entity* source, + float damage); private: float animation_update(); diff --git a/src/game.cpp b/src/game.cpp index eab006f..6ca02e2 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -147,7 +147,8 @@ void Game::LoadConfigXmls() game.load_bossoverlays_xml(mods.TryRedirectPath(BOSS_OVERLAYS_XML)); // The original also zeroes GameOver's second int and the ints at Game+0x1d63c and Game+0x1d64c, not modeled yet. - game.gameOver._state = 0; + game.gameOver.state = GAME_OVER_HIDDEN; + game.gameOver.isStopSoundsPending = false; game.leaderboard.LoadAnm2(); game.emoteWheel.Init(); game.onlineStatsScreen.Load(); @@ -523,7 +524,7 @@ void Game::Start(int playerType, uint32_t startChallenge, const Seeds& seeds, Di encounteredBosses.clear(); room->Update(); framesSinceRoomTransition = 0; - static_cast(g_luaEngine)->PostGameStart(false); + lua_engine_get().PostGameStart(false); } // 006f5210 Fades the screen in from a color at a speed, from full (or nearly no) cover as the instant fade asks, with @@ -750,7 +751,7 @@ static void overlays_render(Game& game) if (game.pauseScreen.state != PAUSE_HIDDEN) game.pauseScreen.Render(); game.emoteWheel.Render(); game.revivePlayerMenu.Render(); - if (game.gameOver._state != 0) game.gameOver.Render(); + game.gameOver.Render(); game.leaderboard.Render(); popups.render_layer(2); g_manager->modManager.shaders_render(); @@ -854,7 +855,7 @@ void Game::Render() graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); if (isTransitionShown) roomTransition.Render(); else room->Render(); - static_cast(g_luaEngine)->PostRender(); + lua_engine_get().PostRender(); bool isFlashing = hallucinationTimer > std::max(hallucinationDuration - HALLUCINATION_FLASH_FRAMES, 0); if (isFlashing && !isRoomSnapshot && hallucinationSnapshot) { @@ -877,7 +878,7 @@ bool Game::IsPaused() bool isOffline = !g_manager->netplayManager.is_online(); if (console.state != CONSOLE_CLOSED && isOffline) return true; - return freezeFrames > 0 || gameOver._state != 0 || leaderboard.displayState != LEADERBOARD_HIDDEN || + return freezeFrames > 0 || gameOver.state != GAME_OVER_HIDDEN || leaderboard.displayState != LEADERBOARD_HIDDEN || 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 369b6bb..80d9490 100644 --- a/src/game.h +++ b/src/game.h @@ -6,6 +6,7 @@ #include "console.h" #include "deathmatch_manager.h" #include "entity_factory.h" +#include "game_over.h" #include "game_state.h" #include "generic_prompt.h" #include "hud.h" diff --git a/src/game_over.cpp b/src/game_over.cpp new file mode 100644 index 0000000..fa98666 --- /dev/null +++ b/src/game_over.cpp @@ -0,0 +1,392 @@ +#include "game_over.h" +#include "entity_config.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "lua_callbacks.h" +#include "manager.h" +#include "mod_manager.h" +#include "platform.h" +#include "render_passes.h" +#include +#include +#include + +constexpr std::string_view DEATH_SCREEN_ANM2 = "gfx/ui/Death Screen.anm2"; +constexpr std::string_view DIARY_ANIMATION = "Diary"; +constexpr std::string_view SEED_NULL = "SeedPos"; + +// The layers of the diary page, by id. +enum DiaryLayer : int +{ + DIARY_LAYER_PORTRAIT = 1, + DIARY_LAYER_LOCATION, + DIARY_LAYER_BOSS, + DIARY_LAYER_NAME, + DIARY_LAYER_ENEMY, + DIARY_LAYER_ITEMS, + DIARY_LAYER_LOCATION_PREFIX = 8 +}; + +constexpr int DIARY_PORTRAIT_COUNT = 12; +constexpr int DIARY_ITEM_LIMIT = 16; +constexpr int DIARY_ITEM_UNKNOWN_FRAME = COLLECTIBLE_VANILLA_COUNT; +constexpr float DIARY_ITEM_STEP_X = 16; +constexpr float DIARY_ITEM_STEP_Y = 2.5f; +constexpr float DIARY_ROW_END = 128; +constexpr float DIARY_ROW_BACK_X = 132; +constexpr float DIARY_ROW_BACK_Y = 4; +constexpr float DIARY_CENTER_OFFSET = 16; +constexpr float SEED_OFFSET_X = 4; +constexpr float SEED_LINE_1_Y = 2; +constexpr float SEED_LINE_2_Y = 17; +constexpr size_t SEED_HALF_LENGTH = 4; +constexpr size_t SEED_SECOND_HALF = 5; +constexpr uint32_t SEED_COLOR_ARGB = 0xff362f2d; +constexpr float SHADE_ALPHA = 128 / 255.0f; + +// The location frames of the stages, by stage number, and the first of the Repentance alt paths (stages 1 to 8). +constexpr std::array LOCATION_FRAMES = {4, 0, 0, 1, 1, 2, 2, 3, 3, 5, 4, 4, 6, 11}; +constexpr int LOCATION_FRAME_DEFAULT = 4; +constexpr int LOCATION_FRAME_ALT = 7; +constexpr int LOCATION_FRAME_ASCENT = 12; +constexpr int LOCATION_ALT_LAST_STAGE = 8; +constexpr int ASCENT_LAST_STAGE = 6; +constexpr int GREED_STAGE_SHOP = 5; +constexpr int GREED_SHOP_LOCATION = 10; + +constexpr int PORTRAIT_UNKNOWN = 149; +constexpr int PORTRAIT_BOMB = 65; + +constexpr uint64_t DAMAGE_SPIKES = 1ull << 7; +constexpr uint64_t DAMAGE_DEVIL = 1ull << 10; +constexpr uint64_t DAMAGE_TNT = 1ull << 12; +constexpr uint64_t DAMAGE_CURSED_DOOR = 1ull << 16; +constexpr uint64_t DAMAGE_TIMER = 1ull << 17; +constexpr uint64_t DAMAGE_IV_BAG = 1ull << 18; + +// The portraits of the deaths no entity caused: by the damage source's id, then by the damage flags, first match first. +constexpr std::pair SOURCE_PORTRAITS[] = {{25, 202}, {10000, 229}, {10001, 235}, {10002, 239}, {10003, 253}}; +constexpr std::pair DAMAGE_PORTRAITS[] = { + {DAMAGE_SPIKES, 66}, {DAMAGE_CURSED_DOOR, 117}, {DAMAGE_POOP, 67}, {DAMAGE_TNT, 113}, {DAMAGE_FIRE, 68}, + {DAMAGE_DEVIL, 110}, {DAMAGE_EXPLOSION, 65}, {DAMAGE_TIMER, 112}, {DAMAGE_IV_BAG, 114}}; + +constexpr int EVENT_COUNTER_DEATHS = 10; +constexpr int EVENT_COUNTER_STREAK = 22; +constexpr int EVENT_COUNTER_NEGATIVE_STREAK = 113; +constexpr int MUSIC_GAME_OVER = 8; +constexpr int MUSIC_JINGLE_GAME_OVER = 93; +constexpr int GAME_OVER_LEFT_LABEL = 3; +constexpr int GAME_OVER_RIGHT_LABEL = 2; +constexpr int REVIVE_CLOSE_FRAMES = 8; + +// What the diary shows of a death: the entity config behind it (if any), its portrait and whether a boss dealt it. +struct DeathPortrait +{ + EntityConfig_Entity* entity = nullptr; + int frame = -1; + bool isBoss = false; +}; + +// The player whose death the diary tells: the one who died last, else the first, and Tainted Forgotten for his soul. +static Entity_Player& dead_player_get() +{ + Game& game = *g_game; + Entity_Player* player = game.playerManager.deadPlayer ? game.playerManager.deadPlayer : game.GetPlayer(0); + + return player->playerType == PLAYER_THESOUL_B ? *player->twin_get() : *player; +} + +// The frame of the diary's location layers for the floor the run ended on. +static int location_frame_get() +{ + Game& game = *g_game; + int stage = game.stage; + + if (game.IsGreedMode()) + stage = stage < GREED_STAGE_SHOP ? stage * 2 - 1 : stage == GREED_STAGE_SHOP ? GREED_SHOP_LOCATION : 0; + + bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + int frame = LOCATION_FRAME_DEFAULT; + if (stage >= 1 && stage <= LOCATION_ALT_LAST_STAGE && isAltPath) frame = LOCATION_FRAME_ALT + (stage - 1) / 2; + else if (stage >= 0 && stage < (int)LOCATION_FRAMES.size()) frame = LOCATION_FRAMES[stage]; + + if (game.stage > 0 && game.stage <= ASCENT_LAST_STAGE && game.GetStateFlag(GAME_STATE_BACKWARDS_PATH)) + frame = LOCATION_FRAME_ASCENT; + return frame; +} + +// The portrait of what killed the player: its entity's, else its spawner's, else one for the kind of damage. +static DeathPortrait death_portrait_get(Entity_Player& player) +{ + EntityConfig& configs = g_manager->entityConfig; + const EntityRef& source = player.lastDamageSource; + DeathPortrait portrait; + + for (auto [type, variant] : {std::pair{source.type, source.variant}, + std::pair{source.spawnerType, (int)source.spawnerVariant}}) + { + if (type == 0) continue; + portrait.entity = configs.GetEntity(type, variant, 0); + portrait.frame = portrait.entity ? portrait.entity->portrait : -1; + if (portrait.frame != -1) break; + } + + if (portrait.frame == -1) + { + int sourceId = 0; + if (source.type == ENTITY_BOMB) portrait.frame = PORTRAIT_BOMB; + else if (source.type == 0 && source.variant != 0) sourceId = source.variant; + else if (source.spawnerType == 0 && source.spawnerVariant != 0) sourceId = (int)source.spawnerVariant; + + for (auto [id, frame] : SOURCE_PORTRAITS) + if (sourceId != 0 && id == sourceId) portrait.frame = frame; + if (source.type != ENTITY_BOMB && portrait.frame == -1) + for (auto [flag, frame] : DAMAGE_PORTRAITS) + if (player.lastDamageFlags & flag) + { + portrait.frame = frame; + break; + } + } + + portrait.isBoss = portrait.entity && portrait.entity->isBoss; + if (portrait.frame < 0) portrait.frame = PORTRAIT_UNKNOWN; + return portrait; +} + +// 009997c0 Opens the diary of the run lost: closes the pause screen, slides the restart and menu buttons in, and fills +// the page with a portrait the seed picks, the floor, what killed the player (boss or enemy) and its name. +// Online, the original opens the Deeds page with its vote instead. Netplay is offline. +void GameOver::Show() +{ + Game& game = *g_game; + Manager& manager = *g_manager; + + if (game.pauseScreen.state != PAUSE_HIDDEN) game.pauseScreen.hide(); + state = GAME_OVER_SHOWN; + isStopSoundsPending = true; + manager.popupButtons.reset(BUTTONS_SLIDE_IN); + manager.popupButtons.buttons[0].textFrame = GAME_OVER_LEFT_LABEL; + manager.popupButtons.buttons[1].textFrame = GAME_OVER_RIGHT_LABEL; + + sprite.Load(DEATH_SCREEN_ANM2, GRAPHICS_LOAD); + sprite.SetFrame(DIARY_ANIMATION, 0); + + int locationFrame = location_frame_get(); + Entity_Player& player = dead_player_get(); + const EntityRef& source = player.lastDamageSource; + log_printf(LOG_INFO, "Game Over. Killed by (%d.%d) spawned by (%d.%d) damage flags (%d)\n", source.type, + source.variant, source.spawnerType, (int)source.spawnerVariant, (int)player.lastDamageFlags); + DeathPortrait portrait = death_portrait_get(player); + + sprite.SetLayerFrame(DIARY_LAYER_PORTRAIT, (int)(game.seedEffects.GetStartSeed() % DIARY_PORTRAIT_COUNT)); + sprite.SetLayerFrame(DIARY_LAYER_LOCATION, locationFrame); + if (sprite.layerStates.size() > DIARY_LAYER_LOCATION_PREFIX) + sprite.SetLayerFrame(DIARY_LAYER_LOCATION_PREFIX, locationFrame); + + int portraitLayer = portrait.isBoss ? DIARY_LAYER_BOSS : DIARY_LAYER_ENEMY; + sprite.GetLayer(DIARY_LAYER_BOSS)->isVisible = portrait.isBoss; + sprite.GetLayer(DIARY_LAYER_ENEMY)->isVisible = !portrait.isBoss; + sprite.SetLayerFrame(portraitLayer, portrait.frame); + if (portrait.entity && portrait.entity->modEntry && portrait.entity->isPortraitModded) + { + sprite.GetLayer(DIARY_LAYER_BOSS)->isVisible = false; + sprite.GetLayer(DIARY_LAYER_ENEMY)->isVisible = false; + sprite.SetLayerFrame(DIARY_LAYER_ENEMY, 0); + moddedEnemy = portrait.entity; + } + sprite.SetLayerFrame(DIARY_LAYER_NAME, player.playerType); +} + +// The game over screen's frame, a part of Game::Update 006fadc0: the looping sounds stop once, the pause paper steps +// and the co-op revive menu closes. +// The online vote count is left out: netplay is offline. +void GameOver::Update() +{ + Game& game = *g_game; + RevivePlayerMenu& revive = game.revivePlayerMenu; + + if (isStopSoundsPending) + { + g_manager->sfxManager.StopLoopingSounds(); + isStopSoundsPending = false; + } + game.pauseScreen.animation_update(); + + if (revive.state == REVIVE_MENU_HIDDEN) return; + revive.state = REVIVE_MENU_CLOSING; + revive.closeTimer = REVIVE_CLOSE_FRAMES; + revive.controllerIndex = -1; +} + +// Draws the items the player took onto the diary, up to sixteen in rows: vanilla ones from the diary's item sheet, +// modded ones by their mod. Trinkets, and actives other than the one held, are skipped. +static void diary_items_render(ANM2& sprite, Entity_Player& player, Vector center) +{ + ItemConfig& items = g_manager->itemConfig; + Vector offset{}; + int itemsLeft = DIARY_ITEM_LIMIT; + + sprite.GetLayer(DIARY_LAYER_ITEMS)->isVisible = true; + for (const HistoryItem& entry : player.history.historyItems) + { + if (itemsLeft == 0) break; + + int id = entry.isTrinket ? 0 : entry.id; + ItemConfig_Item* item = items.GetCollectible(id); + if (!item || (item->type == ITEM_ACTIVE && item->id != player.activeItems[0].item)) continue; + + if (id < COLLECTIBLE_VANILLA_COUNT) + { + sprite.SetLayerFrame(DIARY_LAYER_ITEMS, id < 1 ? DIARY_ITEM_UNKNOWN_FRAME : id - 1); + sprite.RenderLayer(DIARY_LAYER_ITEMS, {vector_make(offset.x + center.x, offset.y + center.y)}); + } + else if (const AnimationFrame* frame = sprite.animState.GetLayerFrame(DIARY_LAYER_ITEMS)) + { + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; + ModSpriteDraw draw; + draw.blendMode = {BLEND_EQUATION_ADD, isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}; + draw.position = vector_make(center.x + frame->pos.x + offset.x, center.y + frame->pos.y + offset.y); + g_manager->modManager.RenderCustomCollectionItem(id, draw); + } + + offset = vector_make(offset.x + DIARY_ITEM_STEP_X, offset.y + DIARY_ITEM_STEP_Y); + if (offset.x >= DIARY_ROW_END) offset = vector_make(offset.x - DIARY_ROW_BACK_X, offset.y - DIARY_ROW_BACK_Y); + itemsLeft--; + } +} + +// Draws the modded enemy's death portrait from its mod's sheet where the diary's enemy portrait goes. +static void modded_enemy_render(ANM2& sprite, EntityConfig_Entity& entity, Vector center) +{ + const AnimationFrame* frame = sprite.animState.GetLayerFrame(DIARY_LAYER_ENEMY); + if (!frame || !entity.modEntry) return; + + ANM2& portrait = entity.modEntry->contentSprites[MOD_SPRITE_DEATH_ENEMIES]; + if (!portrait.isLoaded) return; + portrait.SetFrame(portrait.GetDefaultAnimationName(), entity.portrait); + portrait.color = COLOR_DEFAULT; + portrait.scale = vector_make(1, 1); + portrait.Render({vector_make(center.x + frame->pos.x, center.y + frame->pos.y)}); +} + +// Writes the run's seed in two halves at the diary's seed spot. +static void diary_seed_render(ANM2& sprite) +{ + const NullFrame* seedPos = sprite.animState.animData ? sprite.GetNullFrame(SEED_NULL) : nullptr; + if (!seedPos) return; + + std::string seed = Seeds::Seed2String(g_game->seedEffects.GetStartSeed()); + Font& font = g_manager->font2_TeamMeatEx12; + FontSettings settings; + float x = g_screenWidth / 2 + seedPos->pos.x - SEED_OFFSET_X; + float y = g_screenHeight / 2 + seedPos->pos.y; + std::string_view seedView = seed; + font.DrawString(seedView.substr(0, SEED_HALF_LENGTH), vector_make(x, y + SEED_LINE_1_Y), vector_make(1, 1), + kcolor_argb(SEED_COLOR_ARGB), settings); + font.DrawString(seedView.substr(std::min(SEED_SECOND_HALF, seedView.size()), SEED_HALF_LENGTH), + vector_make(x, y + SEED_LINE_2_Y), vector_make(1, 1), kcolor_argb(SEED_COLOR_ARGB), settings); +} + +// 00998880 Draws the diary over the shaded run: the page (a modded character's portrait by its mod), the items taken, +// a modded enemy's portrait and the seed. +// Online, the original draws the Deeds page with each player's deeds instead. Netplay is offline. +void GameOver::Render() +{ + if (state == GAME_OVER_HIDDEN) return; + + Vector screen = vector_make(g_screenWidth, g_screenHeight); + render_color_shader_pass(KAGE::Graphics::color_quad_rect({}, screen, kcolor_rgba(0, 0, 0, SHADE_ALPHA))); + + Vector center = vector_make(screen.x / 2 + DIARY_CENTER_OFFSET, screen.y / 2 + DIARY_CENTER_OFFSET); + Entity_Player& player = dead_player_get(); + sprite.GetLayer(DIARY_LAYER_ITEMS)->isVisible = false; + if (player.playerType < PLAYER_TYPE_COUNT) sprite.Render({center}); + else + { + sprite.GetLayer(DIARY_LAYER_NAME)->isVisible = false; + sprite.Render({center}); + ModManager::RenderCustomGameOver(player.playerType, center); + } + + diary_items_render(sprite, player, center); + if (moddedEnemy) modded_enemy_render(sprite, *moddedEnemy, center); + diary_seed_render(sprite); +} + +// 00959130 Forgets the saved run, outside a daily: its file, its checksum in the save data, and saving on exit. +// Online the original keeps it too. Netplay is offline. +void game_save_delete() +{ + Manager& manager = *g_manager; + + if (g_game->dailyChallenge._id != 0) return; + manager.gamestate.Delete(); + manager.persistentGameData.gameStateChecksum = 0; + manager.persistentGameData.isChangesMade = true; + manager.isSaveOnExit = false; +} + +// 0095a680 Opens the save data to the run's progress once per run, unless the run is custom, cannot unlock +// achievements or is a rerun: the run counts against the win streak (or the losing streak) and clears the run mask. +// Online, the original also reports the run to the netplay layer. Netplay is offline. +void persistent_game_data_set_writable() +{ + Manager& manager = *g_manager; + Game& game = *g_game; + PersistentGameData& data = manager.persistentGameData; + + if (game.seedEffects.isCustomRun || game.seedEffects.AchievementUnlocksDisallowed() || + Manager::AchievementUnlocksDisallowed() || game.isRerun || manager.isPersistentDataWritable) + return; + + bool isReadOnlyBefore = data.isReadOnly; + data.SetReadOnly(false); + int streak = data.eventCounters[EVENT_COUNTER_STREAK]; + if (streak == 0) data.IncreaseEventCounter(EVENT_COUNTER_NEGATIVE_STREAK, 1); + else data.IncreaseEventCounter(EVENT_COUNTER_STREAK, -streak); + data.SetReadOnly(isReadOnlyBefore); + data.set_run_mask(0); + manager.isPersistentDataWritable = true; +} + +// 006f9770 Ends the run (Rebirth's Game::End): a death forgets the saved run and opens the game over screen. Nothing +// ends during a versus match until it is over. +// Netplay is offline: the online stats screen and co-op's end vote are left out. +void game_end(GameEnding ending) +{ + Game& game = *g_game; + + if ((unsigned)ending > ENDING_LAST) + { + log_printf(LOG_INFO, "Invalid ending specified to Game::End()\n"); + return; + } + if (game.deathmatchManager.is_active() && game.deathmatchManager.state != DEATHMATCH_OVER) return; + + if (ending == ENDING_DEATH) game_save_delete(); + if (game.dailyChallenge._id != 0) reconstruction_missing("Game::End 006f9770 (a daily run's end)"); + if (ending != ENDING_DEATH) reconstruction_missing("Game::End 006f9770 (the endings' cutscenes)"); + + game.gameOver.Show(); + persistent_game_data_set_writable(); + lua_callback_check(MC_POST_GAME_END, "FUN_00864fc0 MC_POST_GAME_END"); +} + +// 009bc120 A player's death that ends the run: the deaths counter, the game over jingle with its music queued, and the +// run's end. A co-op baby leaves the run instead. +void PlayerManager::trigger_coop_baby_death(Entity_Player* deadPlayerEntity) +{ + Manager& manager = *g_manager; + + if (deadPlayerEntity->variant != PLAYER_VARIANT_PLAYER) + reconstruction_missing("PlayerManager::trigger_coop_baby_death 009bc120 (a co-op baby leaves)"); + + deadPlayer = deadPlayerEntity; + manager.persistentGameData.IncreaseEventCounter(EVENT_COUNTER_DEATHS, 1); + manager.musicManager.Play(MUSIC_JINGLE_GAME_OVER, manager.optionsConfig.musicVolume); + manager.musicManager.Queue(MUSIC_GAME_OVER); + game_end(ENDING_DEATH); +} diff --git a/src/game_over.h b/src/game_over.h new file mode 100644 index 0000000..d1c1c90 --- /dev/null +++ b/src/game_over.h @@ -0,0 +1,39 @@ +#pragma once + +#include "anm2.h" +#include "classes.h" + +// Whether the game over screen is up. Show is the only writer of a shown state. +enum GameOverState : int +{ + GAME_OVER_HIDDEN, + GAME_OVER_SHOWN = 2 +}; + +// How a run ends (Game::End's ending id). The others are the endings' cutscenes. +enum GameEnding : int +{ + ENDING_DEATH = 1, + ENDING_LAST = 14 +}; + +// Copies and destruction are the defaults. +// Online only, left out: the lobby's item strip (008ebfb0) and the vote the screen starts online. +// The game over screen (Rebirth's DeathScreen): the diary page of the run lost, with the player's portrait and name, +// the floor, what killed it, the items it took and the run's seed. +// moddedEnemy is the modded entity whose death portrait the mod draws, kept from the last death that had one. +struct GameOver +{ + ANM2 sprite; + EntityConfig_Entity* moddedEnemy = nullptr; + GameOverState state = GAME_OVER_HIDDEN; + bool isStopSoundsPending = false; + + void Show(); + void Update(); + void Render(); +}; + +void game_end(GameEnding ending); +void game_save_delete(); +void persistent_game_data_set_writable(); diff --git a/src/game_state.cpp b/src/game_state.cpp index 33602eb..1d21fd1 100644 --- a/src/game_state.cpp +++ b/src/game_state.cpp @@ -1,11 +1,14 @@ #include "game_state.h" +#include "game.h" #include "game_state_player.h" #include "log.h" +#include "manager.h" #include "platform.h" #include #include #include #include +#include // The header a saved run starts with (version 169, with its terminator), and the key its checksum is scrambled with. constexpr char SAVE_HEADER[] = "ISAACNG_GSR0169"; @@ -26,6 +29,39 @@ constexpr uint8_t WRITE_LEVEL_START_PENDING = 2; constexpr uint8_t WRITE_CURSE_MIST = 4; constexpr int ROOM_UNSET_WORDS = 8; +// The versions a saved run reads from, and the first versions that save each later addition. +constexpr uint32_t SAVE_VERSION_OLDEST = 155; +constexpr uint32_t SAVE_VERSION = 169; +constexpr uint32_t SAVE_VERSION_FOLLOWER_FLAG = 156; +constexpr uint32_t SAVE_VERSION_ECHO_CHAMBER = 157; +constexpr uint32_t SAVE_VERSION_FLOAT_STORAGE = 158; +constexpr uint32_t SAVE_VERSION_FINISHED_STAGES = 159; +constexpr uint32_t SAVE_VERSION_SUBTYPE_FLAG = 160; +constexpr uint32_t SAVE_VERSION_ROOM_SCORES = 162; +constexpr uint32_t SAVE_VERSION_REPLAYED_STAGES = 163; +constexpr uint32_t SAVE_VERSION_CURSE_MIST_FAMILIARS = 164; +constexpr uint32_t SAVE_VERSION_BROKEN_WATCH = 165; +constexpr uint32_t SAVE_VERSION_EXCITED = 165; +constexpr uint32_t SAVE_VERSION_BANDAGE = 166; +constexpr uint32_t SAVE_VERSION_LAST_FORM = 167; +constexpr uint32_t SAVE_VERSION_MANTLE_STACKS = 168; +constexpr uint32_t SAVE_VERSION_DUCT_TAPE = 169; + +// What older versions kept of the score's rooms: 31 types each, scored once. +constexpr int OLD_ROOM_SCORE_COUNT = 31; +constexpr float OLD_ROOM_SCORE_MULTIPLIER = 1; + +constexpr int HISTORY_KIND_SHIFT = 24; +constexpr uint32_t HISTORY_ID_MASK = 0xffffff; +constexpr int ITEM_KIND_NULL = 0; +constexpr int ITEM_KIND_TRINKET = 2; +constexpr uint8_t WILD_CARD_POCKET = 1; +constexpr uint8_t WILD_CARD_ACTIVE = 2; +constexpr int UNSET_PLAYER_WORDS = 2; + +// The Death Certificate floor's way back as a saved run keeps it: three words and two flags. +constexpr size_t DEATH_CERTIFICATE_RETURN_SIZE = 3 * sizeof(int) + 2 * sizeof(uint8_t); + // An Esau Jr. slot without a player. static GameStatePlayer esau_jr_empty() { @@ -531,9 +567,10 @@ static std::vector room_map_pack(const std::array } // 009c9340 Writes the saved run in the original's format: the unchecked header, then the run's rules, flags and -// counters, the ambush and the score, the floor and its rooms, the players and the Esau Jr. players, the pools, the seed -// and the special seeds, the histories, the Ascent's stages and the versus rules, closed by the checksum of everything -// after the header, scrambled. More than 255 erased enemies are cut to 255, as the original does. +// counters, the ambush and the score, the floor and its rooms, the starting character and modding, the players and the +// Esau Jr. players, the pools, the seed and the special seeds, the histories, the Ascent's stages and the versus rules, +// closed by the checksum of everything after the header, scrambled. More than 255 erased enemies are cut to 255, as +// the original does. // The Death Certificate floor's way back, which Game does not keep yet, is written as the original's defaults. // The original's rooms are a fixed array, so a state Level never stored writes default rooms. std::vector GameState::write() @@ -596,11 +633,11 @@ std::vector GameState::write() { writer.write(portal.roomIndex); writer.write(portal.gridIndex); - writer.write((uint8_t)portal.isMarked); } + for (const VentricleRazorPortal& portal : ventricleRazorPortals) writer.write((uint8_t)portal.isMarked); writer.write(bombPickupsSpawned); - writer.write(0); - writer.write((uint8_t)0); + writer.write(playerType); + writer.write((uint8_t)isModded); writer.write((uint8_t)players.size()); for (const GameStatePlayer& player : players) writer.player_write(player); @@ -662,7 +699,731 @@ std::vector GameState::write() return writer.bytes; } -// Not reconstructed yet: each stops the game where it is reached. -// Netplay is offline, so read always reads a run as this machine's own (the original's isLocalRun). -bool GameState::read(std::span) { reconstruction_missing("GameState::read 009cc1a0"); } +// 009c7350 Whether an item of a kind (0 a null item, 2 a trinket, else a collectible) exists, or is none. +bool is_valid_item_config_id(int itemKind, int id) +{ + ItemConfig& items = g_manager->itemConfig; + + if (id < 1) return true; + if (itemKind == ITEM_KIND_NULL) return items.GetNullItem(id); + if (itemKind == ITEM_KIND_TRINKET) return items.GetTrinket((uint32_t)id); + return items.GetCollectible(id); +} + +// A saved run as it is read, in the writers' order and widths, by the version it was written with (155 to 169). +// Reading past the end gives zeros, and the run then fails its last check, as the original's failed reads do. +// A list longer than the bytes left is cut to them, where the original would allocate it all. +// Each part of the run has its reader. A part that does not check out logs why and fails the run. +struct StateReader +{ + std::span bytes; + size_t position = 0; + uint32_t version = 0; + const char* path = ""; + + bool is_end() { return position >= bytes.size(); } + + // 009d84a0, 009d8550, 009d8470 Reads a value of a width. + template Value read() + { + Value value{}; + if (position + sizeof(Value) <= bytes.size()) std::memcpy(&value, bytes.data() + position, sizeof(Value)); + position += sizeof(Value); + return value; + } + + bool bool_read() { return read() != 0; } + + // Reads fields in order, each at its own width. + template void fields_read(Values&... values) { ((values = read()), ...); } + + // Reads each value of a list from a type of the original's width. + template void each_read(List&& values) + { + for (auto& value : values) value = (std::remove_reference_t)read(); + } + + // A list's length, at most the bytes left since each element takes one. + template size_t count_read() + { + size_t count = read(); + return std::min(count, bytes.size() - std::min(position, bytes.size())); + } + + // 009d8580 Reads a list's length and its values as 32-bit words. + template void list_read(List& values) + { + values.resize(count_read()); + each_read(values); + } + + // Reads a flag list's length (16 bits), at most the flags kept, then a byte per flag. + template void flags_read(std::bitset& flags) + { + size_t count = std::min(read(), Size); + for (size_t i = 0; i < count; i++) flags[i] = bool_read(); + } + + // 009c84c0 Reads a bit list's length (16 bits), then its bits eight to a byte from the lowest. Bits past the kept + // ones are dropped. + template void bits_read(std::bitset& bits) + { + uint16_t count = read(); + uint8_t packed = 0; + + bits.reset(); + for (size_t i = 0; i < count; i++) + { + if (i % 8 == 0) packed = read(); + if (i < Size) bits[i] = packed >> i % 8 & 1; + } + } + + // Logs why the run does not read, and fails it. + template bool fail(LogLevel level, const char* format, Args... args) + { + log_printf(level, format, args...); + return false; + } + + // Whether pocket cards exist, logging the first that does not. + bool is_pockets_valid(const std::array& pockets, const char* warning) + { + for (const PocketItem& pocket : pockets) + if (pocket.type == POCKET_CARD && pocket.id > 0 && !g_manager->itemConfig.GetCard(pocket.id)) + return fail(LOG_INFO, warning, pocket.type, pocket.id); + return true; + } + + // Whether trinkets exist, logging the first that does not. + bool is_trinkets_valid(const std::array& trinkets, const char* warning) + { + for (uint32_t trinket : trinkets) + if ((int)trinket > 0 && !g_manager->itemConfig.GetTrinket(trinket)) return fail(LOG_INFO, warning, trinket); + return true; + } + + // Whether collectibles exist, logging the first that does not. + template bool is_collectibles_valid(const List& ids, const char* warning) + { + for (int id : ids) + if (id > 0 && !g_manager->itemConfig.GetCollectible(id)) return fail(LOG_INFO, warning, id); + return true; + } + + void entity_read(EntitySaveState& entity); + bool room_read(SavedRoom& room); + void config_read(RoomConfigRef& config); + void co_player_read(CoPlayerState& player); + void consumables_read(ConsumableData& data); + bool familiars_read(std::vector& familiars); + void pockets_read(std::array& pockets); + bool history_read(std::vector& history); + bool player_read(GameStatePlayer& player); + bool item_pool_read(GameStateItemPool& pool); + void score_read(ScoreRecord& score); +}; + +// 009cb020 Reads a saved entity, its extra bytes and the entity it carries. +void StateReader::entity_read(EntitySaveState& entity) +{ + fields_read(entity.type, entity.variant, entity.subtype, entity.intStorage1, entity.intStorage2, entity.intStorage3, + entity.byteStorage, entity.intStorage4, entity.intStorage5); + entity.boolStorage1 = bool_read(); + fields_read(entity.intStorage6, entity.targetPosition, entity.intStorage7, entity.initSeed, entity.dropSeed, + entity.spawnerType, entity.spawnerVariant, entity.int64Storage); + entity.boolStorage2 = bool_read(); + fields_read(entity.floatStorage1, entity.floatStorage2, entity.gridSpawnIdx); + if (version >= SAVE_VERSION_FLOAT_STORAGE) entity.floatStorage3 = read(); + entity.intStorage8 = read(); + + uint8_t carried = read(); + if (carried & WRITE_HAS_EXTRA_DATA) entity.extraData = read(); + if (!(carried & WRITE_HAS_CHILD)) return; + entity.child = std::make_shared(); + entity_read(*entity.child); +} + +// 009c86e0 Reads a room's config: three words, a merged config's two indices packed in the last. +void StateReader::config_read(RoomConfigRef& config) +{ + fields_read(config.packed, config.type, config.variant); +} + +// 009cb620 Reads a saved room as room_write writes it, the grid cells holding nothing keeping their defaults. A room +// past the end does not read. +bool StateReader::room_read(SavedRoom& room) +{ + RoomDescriptor& desc = room.desc; + + if (is_end()) return false; + config_read(room.config); + for (int* value : {&desc.gridIndex, &desc.safeGridIndex, &desc.listIndex}) *value = read(); + desc.dimension = read(); + desc.allowedDoors = read() & UINT8_MAX; + each_read(desc.doors); + fields_read(desc.displayFlags, desc.visitedCount, desc.flags, desc.clearCount, desc.totalMoneySpent, + desc.greedSubType, desc.pitsCount, desc.decorationSeed, desc.spawnSeed, desc.awardSeed, + desc.bossDeathSeed); + + for (GridEntityDesc& cell : desc.savedGridEntities) + { + cell._type = read(); + if (!cell._type) continue; + cell._variant = read(); + cell._state = read(); + cell._spawnCount = read(); + cell._initialized = cell._spawnCount > 0; + fields_read(cell._spawnSeed, cell._variableSeed, cell._varData); + } + + desc.savedEntities.resize(count_read()); + for (EntitySaveState& entity : desc.savedEntities) entity_read(entity); + size_t restrictedCount = count_read(); + for (size_t i = 0; i < restrictedCount; i++) desc.restrictedGridIndexes.insert(read()); + desc.savedEffects.resize(count_read()); + for (EntitySaveState& entity : desc.savedEffects) entity_read(entity); + + fields_read(desc.shopItemDiscountIdx, desc.shopItemIdx); + position += ROOM_UNSET_WORDS * (sizeof(uint16_t) + sizeof(uint8_t)); + fields_read(desc.group, desc.tKeeperCoinSpawns); + return true; +} + +// 009cff40 Reads a co-op baby or sub player as co_player_write writes it, past the unset word. +void StateReader::co_player_read(CoPlayerState& player) +{ + for (int* value : {&player.playerType, &player.redHearts, &player.maxHearts, &player.soulHearts, + &player.eternalHearts, &player.goldenHearts}) + *value = read(); + position += sizeof(int16_t); + player.boneHearts = read(); + fields_read(player.blackHearts, player.boneHeartsMask); + player.brokenHearts = read(); + player.rottenHearts = read(); +} + +// 009d02c0 Reads the consumables Curse of the Mist set aside and the golden key and bomb. +void StateReader::consumables_read(ConsumableData& data) +{ + for (int* value : {&data.coins, &data.keys, &data.bombs}) *value = read(); + uint8_t golden = read(); + data.isGoldenKey = golden & WRITE_GOLDEN_KEY; + data.isGoldenBomb = golden & WRITE_GOLDEN_BOMB; + for (int* value : {&data.soulCharges, &data.gigaBombs, &data.poopMana, &data.bloodCharges}) + *value = read(); +} + +// Reads a list of familiars, failing when it runs past the end. Versions before 156 and 160 lack the flags. +bool StateReader::familiars_read(std::vector& familiars) +{ + familiars.resize(count_read()); + for (FamiliarData& familiar : familiars) + { + if (is_end()) + return fail(LOG_INFO, "[warn] Invalid familiar count %d. Save file %s might be corrupt.\n", + (int)familiars.size(), path); + fields_read(familiar.initSeed, familiar.variant, familiar.subtype, familiar.coins, familiar.hearts, + familiar.keys, familiar.state, familiar.roomClearCount, familiar.formationTargetOffset, + familiar.health, familiar.dropSeed); + if (version >= SAVE_VERSION_FOLLOWER_FLAG) familiar.isNotCountedAsFollower = bool_read(); + if (version >= SAVE_VERSION_SUBTYPE_FLAG) familiar.isSubtype55555 = bool_read(); + } + return true; +} + +// Reads pocket slots, each as its kind (a byte) and id. +void StateReader::pockets_read(std::array& pockets) +{ + for (PocketItem& pocket : pockets) + { + pocket.type = (PocketItemType)read(); + pocket.id = read(); + } +} + +// Reads the items a player picked up, each with its flags unpacked and checked to exist. A frame before the run's +// start is now's, or the first frame while no run plays. +bool StateReader::history_read(std::vector& history) +{ + size_t count = count_read(); + + for (size_t i = 0; i < count; i++) + { + if (is_end()) + log_printf(LOG_INFO, "[warn] Invalid history count %d. Save file %s might be corrupt.\n", (int)count, path); + HistoryItem item; + uint32_t packed = read(); + fields_read(item.levelStage, item.stageType, item.roomType, item.itemPoolType, item.time); + if (item.time < 0) item.time = g_game ? g_game->frameCount : 0; + + uint32_t kind = packed >> HISTORY_KIND_SHIFT; + item.id = (int)(packed & HISTORY_ID_MASK); + item.isTrinket = kind == HISTORY_TRINKET >> HISTORY_KIND_SHIFT || + kind == (HISTORY_TRINKET | HISTORY_NEGATIVE) >> HISTORY_KIND_SHIFT; + bool isNegative = kind == HISTORY_NEGATIVE >> HISTORY_KIND_SHIFT || + kind == (HISTORY_TRINKET | HISTORY_NEGATIVE) >> HISTORY_KIND_SHIFT; + if (isNegative) item.id = -item.id; + else if (item.isTrinket && item.id && !g_manager->itemConfig.GetTrinket(packed)) + return fail(LOG_INFO, "[warn] Invalid history trinket %d\n", item.id); + else if (!item.isTrinket && item.id && !g_manager->itemConfig.GetCollectible(item.id)) + return fail(LOG_INFO, "[warn] Invalid history collectible %d\n", item.id); + history.push_back(item); + } + return true; +} + +// 009d05d0 (009d16ee, 009d2656) Reads a saved player as player_write writes it, checking that its character and every +// item, card, trinket, pill effect, costume and effect it names exist. Versions before 165, 166, 167, 168 and 169 lack +// the I'm Excited countdown, the Potato Peeler bandage counter, the last form, the Holy Mantle stacks and the Duct Tape +// mode. The first Echo Chamber list is only checked, as the original does. +bool StateReader::player_read(GameStatePlayer& player) +{ + ItemConfig& items = g_manager->itemConfig; + + player.playerType = read(); + if (!g_manager->entityConfig.GetPlayer(player.playerType)) + return fail(LOG_INFO, "[warn] Invalid player type: %d\n", player.playerType); + fields_read(player.redHearts, player.maxHearts, player.soulHearts, player.blackHearts, player.eternalHearts, + player.jarHearts, player.jarFlies, player.numCoins, player.numKeys, player.numBombs); + player.hasGoldenKey = bool_read(); + player.hasGoldenBomb = bool_read(); + fields_read(player.monkeyPawCounter, player.totalDamageTaken); + uint8_t flags = read(); + player.isHolyMantle = flags & 1; + player.isLevelStartPending = flags & WRITE_LEVEL_START_PENDING; + player.hasCurseMistEffect = flags & WRITE_CURSE_MIST; + fields_read(player.tonsilCounter, player.tonsilCount, player.numLeprosy, player.planCKillCountdown); + if (version >= SAVE_VERSION_EXCITED) player.imExcitedSpeedupCountdown = read(); + fields_read(player.lastPillColor, player.boneHearts, player.boneHeartsMask, player.speedModifier, + player.fireDelayModifier, player.damageModifier, player.tearRangeModifier, player.shotSpeedModifier, + player.luckModifier, player.donateLuck, player.potatoPeelerCounter); + if (version >= SAVE_VERSION_BANDAGE) player.potatoPeelerBandageCounter = read(); + fields_read(player.edenSpeed, player.edenFireDelay, player.edenDamage, player.edenTearRange, player.edenShotSpeed, + player.edenLuck, player.vampireCharmKills, player.killCounter); + + for (ActiveItemDesc& active : player.activeItems) + { + active.item = read(); + if (active.item > 0 && !items.GetCollectible(active.item)) + return fail(LOG_WARN, "Invalid collectible ID: %d\n", active.item); + fields_read(active.unknown, active.charge, active.batteryCharge, active.partialCharge, active.varData); + } + fields_read(player.playerSpriteScale, player.headScale, player.bodyScale); + pockets_read(player.pocketItems); + if (!is_pockets_valid(player.pocketItems, "[warn] Invalid pocket item (type: %d, ID: %d)\n")) return false; + std::span forms = player.playerForms; + each_read(version < SAVE_VERSION_LAST_FORM ? forms.first(PLAYER_FORM_SLOTS - 1) : forms); + player.playerFormsRewarded = read() & UINT16_MAX; + list_read(player.collectibleCounts); + if (player.collectibleCounts.size() > items.collectibles.size()) return false; + list_read(player.voidedCollectibles); + if (!is_collectibles_valid(player.voidedCollectibles, "[warn] Invalid voided active item %d\n")) return false; + player.voidedPassives.resize(count_read()); + for (VoidedPassive& passive : player.voidedPassives) + { + passive.id = read(); + passive.value = read(); + } + for (const VoidedPassive& passive : player.voidedPassives) + if (!is_collectibles_valid(std::array{passive.id}, "[warn] Invalid voided passive item %d\n")) return false; + each_read(player.trinkets); + if (!is_trinkets_valid(player.trinkets, "[warn] Invalid trinket %d\n")) return false; + + player.costumes.resize(count_read()); + for (CostumeItem& costume : player.costumes) + { + if (is_end()) + return fail(LOG_INFO, "[warn] Invalid costume count %d. Save file %s might be corrupt.\n", + (int)player.costumes.size(), path); + fields_read(costume.type, costume.id); + if (!is_valid_item_config_id(costume.type, costume.id)) + return fail(LOG_INFO, "[warn] Invalid costume (type: %d, ID: %d)\n", costume.type, costume.id); + } + for (auto* seeds : {&player.collectibleRngSeeds, &player.trinketRngSeeds, &player.pillRngSeeds, + &player.cardRngSeeds}) + list_read(*seeds); + list_read(player.pillEffectUses); + for (int effect = 1; effect < (int)player.pillEffectUses.size(); effect++) + if (!items.GetPillEffect(effect)) return fail(LOG_INFO, "Invalid pill effect %d\n", effect); + + fields_read(player.glitchBabySeed, player.randomBabyCount, player.randomBabies, player.rUaWizardTimer, + player.bloodLustCounter, player.deadCatLives); + EntityDesc& ball = player.friendBallEnemy; + fields_read(ball.type, ball.variant, ball.subtype, ball.championId, ball.health, ball.maxHealth); + player.charmedEnemies.resize(std::min(read(), SAVED_CHARMED_ENEMY_LIMIT)); + for (EntityDesc& enemy : player.charmedEnemies) + { + fields_read(enemy.type, enemy.variant, enemy.subtype, enemy.championId, enemy.health, enemy.maxHealth); + enemy.isPlayerControlled = bool_read(); + } + player.movingBoxContents.resize(count_read()); + for (EntitySaveState& entity : player.movingBoxContents) entity_read(entity); + + fields_read(player.purityState, player.immaculateConceptionState, player.cambionConceptionState, + player.conceptionFamiliarFlags, player.d8DamageModifier, player.d8SpeedModifier, + player.d8RangeModifier, player.d8FireDelayModifier, player.goldenHearts); + position += UNSET_PLAYER_WORDS * sizeof(int); + if (!familiars_read(player.familiars)) return false; + player.coopBabies.resize(read()); + for (CoPlayerState& baby : player.coopBabies) + { + if (is_end()) + return fail(LOG_INFO, "[warn] Invalid co-player count %d. Save file %s might be corrupt.\n", + (int)player.coopBabies.size(), path); + co_player_read(baby); + } + if (bool_read()) co_player_read(player.subPlayer.emplace()); + + fields_read(player.brittleBonesUpgrades, player.bleedOutHealth); + player.greedsGulletHearts = read(); + fields_read(player.greedsGulletOverflow, player.redStewBonusDuration, player.brokenHearts, player.rottenHearts, + player.effectiveSoulCharge, player.candyHeartStatUps, player.soulLocketStatUps, player.unknownCounter); + player.soulCharge = read(); + player.numGigaBombs = read(); + player.urnSouls = read(); + fields_read(player.rockBottomMoveSpeed, player.rockBottomMaxFireDelay, player.rockBottomDamage, + player.rockBottomTearRange, player.rockBottomShotSpeed, player.rockBottomLuck, + player.reverseEmpressMaxHearts); + player.persistentEffects.resize(count_read()); + for (PersistentEffect& effect : player.persistentEffects) + { + if (is_end()) + return fail(LOG_INFO, "[warn] Invalid costume count %d. Save file %s might be corrupt.\n", + (int)player.persistentEffects.size(), path); + fields_read(effect.type, effect.id, effect.count, effect.cooldown); + if (!is_valid_item_config_id(effect.type, effect.id)) + return fail(LOG_INFO, "[warn] Invalid temporary effect (type: %d, ID: %d)\n", effect.type, effect.id); + } + fields_read(player.reverseSunBoneHearts, player.unknownTimer); + player.unknownValue = read(); + fields_read(player.forgottenBodyRoomIdx, player.forgottenBodyPos, player.lastCollectibleFrame, + player.maggyHealthDrainCooldown); + + uint8_t echoCount = read(); + for (int i = 0; i < echoCount; i++) + { + std::array echo{}; + echo[0].type = (PocketItemType)read(); + echo[0].id = read(); + if (!is_pockets_valid(echo, "[warn] Invalid pocket item (type: %d, ID: %d)\n")) return false; + } + fields_read(player.bagOfCraftingContent, player.bagOfCraftingOutput, player.bagOfCraftingPool); + std::span spells = player.poopSpellQueue; + each_read(spells.first(POOP_SPELL_QUEUE_SIZE)); + each_read(spells.subspan(POOP_SPELL_QUEUE_SIZE, std::min(read(), POOP_SPELL_SLOTS - POOP_SPELL_QUEUE_SIZE))); + fields_read(player.poopSpellCounter, player.poopMana, player.poopSpellFloat, player.effectiveBloodCharge); + player.isBackupPlayer = read() != 0; + player.parentIndex = read(); + position += sizeof(int); + player.darkEsauHealth = read(); + + consumables_read(player.consumablesBackup); + if (version < SAVE_VERSION_CURSE_MIST_FAMILIARS) player.curseMistRedHearts = player.redHearts; + else if (!familiars_read(player.curseMistFamiliars)) return false; + else player.curseMistRedHearts = read(); + pockets_read(player.curseMistPocketItems); + if (!is_pockets_valid(player.curseMistPocketItems, "[warn] Invalid pre curse pocket item (type: %d, ID: %d)\n")) + return false; + each_read(player.curseMistTrinkets); + if (!is_trinkets_valid(player.curseMistTrinkets, "[warn] Invalid pre curse trinket %d\n")) return false; + player.isCoopGhost = bool_read(); + pockets_read(player.ghostPocketItems); + if (player.isCoopGhost && + !is_pockets_valid(player.ghostPocketItems, "[warn] Invalid pre coop ghost pocket item (type: %d, ID: %d)\n")) + return false; + each_read(player.ghostTrinkets); + if (player.isCoopGhost && !is_trinkets_valid(player.ghostTrinkets, "[warn] Invalid pre coop ghost trinket %d\n")) + return false; + fields_read(player.samsonBerserkCharge, player.ibsCharge); + if (version >= SAVE_VERSION_MANTLE_STACKS) player.holyMantleStacks = read(); + if (version >= SAVE_VERSION_DUCT_TAPE) player.ductTapeMode = read(); + player.controllerIndex = read(); + + player.itemCards.resize(read()); + each_read(player.itemCards); + if (!is_collectibles_valid(player.itemCards, "[warn] Invalid item card %d\n")) return false; + player.modelingClayEffect = read(); + if (!is_collectibles_valid(std::array{player.modelingClayEffect}, "[warn] Invalid modeling clay effect %d\n")) + return false; + fields_read(player.keepersSackBonus, player.wildCardItemType); + if (player.wildCardItemType != WILD_CARD_NONE) + { + fields_read(player.wildCardItem, player.wildCardVarData); + bool isActive = player.wildCardItemType == WILD_CARD_ACTIVE; + if (isActive && !is_collectibles_valid(std::array{player.wildCardItem}, + "[warn] Invalid active item wildcard effect %d\n")) + return false; + bool isCardValid = player.wildCardItem <= 0 || items.GetCard(player.wildCardItem); + if (player.wildCardItemType == WILD_CARD_POCKET && !isCardValid) + return fail(LOG_INFO, "[warn] Invalid pocket item wildcard effect (type: %d, id: %d)\n", + player.wildCardItemType, player.wildCardItem); + } + + if (!history_read(player.history)) return false; + uint8_t inventoryCount = read(); + for (int i = 0; i < inventoryCount; i++) + { + int16_t id = read(); + if (i < INVENTORY_SIZE) player.inventory[i] = id; + } + player.levelEffectItems.resize(read()); + each_read(player.levelEffectItems); + if (!is_collectibles_valid(player.levelEffectItems, "[warn] Invalid Monster Manual collectible %d\n")) return false; + size_t proceduralCount = count_read(); + for (size_t i = 0; i < proceduralCount; i++) + { + int16_t key = read(); + player.proceduralItems.emplace(key, read()); + } + if (version < SAVE_VERSION_ECHO_CHAMBER) return true; + player.echoChamberItems.resize(count_read()); + for (PocketItem& item : player.echoChamberItems) fields_read(item.id, item.type); + return true; +} + +// 009ce720 Reads the item pools as item_pool_write writes them, failing on more removed collectibles or pool trinkets +// than the configs have. +bool StateReader::item_pool_read(GameStateItemPool& pool) +{ + ItemConfig& items = g_manager->itemConfig; + + for (std::vector& weights : pool.poolsItemWeights) + { + weights.resize(count_read()); + each_read(weights); + } + fields_read(pool.bibleUpgrades, pool.seed, pool.lastPool, pool.itemPoolRNGseed, pool.trinketPoolRNGseed, + pool.unkFloat674, pool.unkFloat678); + for (auto [bits, limit] : {std::pair{&pool.removedCollectibles, items.collectibles.size()}, + std::pair{&pool.trinketPoolItems, items.trinkets.size()}}) + { + uint32_t count = read(); + if (count > limit) return false; + bits->resize(count); + for (uint32_t i = 0; i < count; i++) (*bits)[i] = bool_read(); + } + each_read(pool.pillEffects); + each_read(pool.identifiedPillEffects); + each_read(pool.remainingGenesisItems); + return true; +} + +// 009d71b0 Reads the score's record as score_write writes it. Versions before 162 kept only each room's type, 31 of +// each, and versions before 159 and 163 lack the finished and replayed floors. +void StateReader::score_read(ScoreRecord& score) +{ + fields_read(score.runTimeLevel, score.runTimeLevelType, score.runTime, score.pickupPoints, score.enemyPoints, + score.runEnding); + if (version < SAVE_VERSION_ROOM_SCORES) + for (int i = 0; i < OLD_ROOM_SCORE_COUNT; i++) + for (std::vector* rooms : {&score.clearedRooms, &score.visitedRooms}) + rooms->push_back({OLD_ROOM_SCORE_MULTIPLIER, read(), false}); + else + for (std::vector* rooms : {&score.visitedRooms, &score.clearedRooms}) + { + rooms->resize(count_read()); + for (RoomScore& room : *rooms) + { + room.type = read(); + room.isRedRoom = bool_read(); + room.multiplier = read(); + } + } + fields_read(score.bossChallengesCleared, score.angelsKilled); + + for (auto [stages, oldest] : {std::pair{&score.finishedStages, SAVE_VERSION_FINISHED_STAGES}, + std::pair{&score.replayedStages, SAVE_VERSION_REPLAYED_STAGES}}) + { + if (version < oldest) continue; + stages->resize(count_read()); + for (StageVisit& visit : *stages) + { + fields_read(visit.stage, visit.stageType); + visit.isAscent = bool_read(); + } + } +} + +// The map's cells from their packed words: each room index, and each run of empty cells as its length minus one over +// ROOM_MAP_EMPTY_RUN. Cells past the words are empty. +static std::array room_map_unpack(const std::vector& packed) +{ + std::array roomMap; + size_t next = 0; + int emptyRun = 0; + + for (int& roomIdx : roomMap) + { + roomIdx = -1; + if (emptyRun) + { + emptyRun--; + continue; + } + if (next == packed.size()) continue; + uint16_t word = packed[next++]; + if (word & ROOM_MAP_EMPTY_RUN) emptyRun = word & ~ROOM_MAP_EMPTY_RUN; + else roomIdx = word; + } + return roomMap; +} + +// 009cc1a0 Reads the saved run (written by versions 155 to 169) as write writes it, once its header names such a +// version and its checksum matches both its own and the one the progress file remembers. A wrong header deletes the +// file. A bad room, player, character or item fails the read, as does a run that does not end where its checksum is. +// Netplay is offline, so the checksum is always checked and the run read as this machine's own. +// The Death Certificate floor's way back, which Game does not keep yet, is read past. +bool GameState::read(std::span file) +{ + std::array header{}; + uint32_t version = 0; + + std::copy_n(file.begin(), std::min(file.size(), sizeof(SAVE_HEADER)), header.begin()); + bool isHeaderRead = std::sscanf(header.data(), "ISAACNG_GSR%u", &version) == 1; + if (!isHeaderRead || version < SAVE_VERSION_OLDEST || version > SAVE_VERSION) + { + log_printf(LOG_INFO, "[warn] GameState header is incorrect (%u != %u).\n", version, SAVE_VERSION); + Delete(); + return false; + } + log_printf(LOG_INFO, "GameState Version Loaded: %u\n", version); + + uint32_t sealed = 0; + Checksum fileChecksum; + bool isSealed = file.size() >= sizeof(SAVE_HEADER) + sizeof(sealed); + if (isSealed) + { + fileChecksum.Update(file.subspan(sizeof(SAVE_HEADER), file.size() - sizeof(SAVE_HEADER) - sizeof(sealed))); + std::memcpy(&sealed, file.data() + file.size() - sizeof(sealed), sizeof(sealed)); + } + checksum = fileChecksum.value_get(); + bool isChecksumValid = (sealed ^ CHECKSUM_KEY) == checksum && checksum == g_manager->persistentGameData.gameStateChecksum; + if (!isSealed || !isChecksumValid) + { + log_printf(LOG_INFO, "[warn] GameState File %s: Checksum invalid!\n", savePath.c_str()); + return false; + } + + StateReader reader = {file, sizeof(SAVE_HEADER), version, savePath.c_str()}; + challenge = reader.read(); + isRerun = reader.bool_read(); + seeds.isCustomRun = reader.bool_read(); + isConsoleUsedThisRun = reader.bool_read(); + difficulty = reader.read(); + reader.flags_read(gameStateFlags); + reader.fields_read(lastDevilRoomStage, treasureRoomsVisited, planetariumsVisited, stagesWithoutHeartsPicked, + stagesWithoutDamage, devilRoomDeals, shopVisits, donationModGreed, donationModAngel, + reviveMachineCoinsLeft, reviveMachineUses, bossRushParTime, blueWombParTime, frameCount, + timeCounter, stageNameNumeral, victoryLap, lastLevelWithoutHalfHp); + isAmbushActive = reader.bool_read(); + ambushWave = reader.read(); + reader.score_read(scoreSheet); + + reader.fields_read(stage, stageType, startingRoomIdx, lastBossRoomListIdx, curses, dungeonPlacementSeed, + devilAngelRoomSeed, angelRoomChance); + for (bool* flag : {&isHeartPicked, &isDevilRoomDisabled, &isCanSeeEverything, &isBossChallenge}) + *flag = reader.bool_read(); + reader.flags_read(levelStateFlags); + reader.fields_read(greedModeWave, greedWaveSeeds, greedModeTreasureRoomIdx, greedLastBeatenWave, greedLastPaidWave, + nightmareStageIcons); + + mergedRoomConfigs.resize(reader.count_read()); + for (RoomConfigRef& config : mergedRoomConfigs) reader.config_read(config); + roomCount = reader.read(); + if ((uint32_t)roomCount >= ROOM_MAP_CELLS) + return reader.fail(LOG_INFO, "[warn] Invalid room count %d. Save file %s might be corrupt.\n", roomCount, + savePath.c_str()); + rooms.assign(ROOM_DESCRIPTOR_COUNT, {}); + for (int i = 0; i < ROOM_DESCRIPTOR_COUNT; i++) + { + if (i == roomCount) i = ROOM_MAP_CELLS; + if (!reader.room_read(rooms[i])) + return reader.fail(LOG_INFO, "[warn] Could not read room #%d. Save file %s might be corrupt.\n", i, + savePath.c_str()); + } + std::vector packedMap(reader.count_read()); + reader.each_read(packedMap); + roomMap = room_map_unpack(packedMap); + + reader.fields_read(currentRoomIdx, currentDimensionIdx, lastRoomDimensionIdx, lastRoomIdx); + if (version >= SAVE_VERSION_BROKEN_WATCH) reader.fields_read(brokenWatchState, slowdownDuration); + reader.fields_read(dungeonReturnPosition, dungeonReturnRoomIndex); + reader.position += DEATH_CERTIFICATE_RETURN_SIZE; + enterDoor = reader.read(); + for (VentricleRazorPortal& portal : ventricleRazorPortals) reader.fields_read(portal.roomIndex, portal.gridIndex); + for (VentricleRazorPortal& portal : ventricleRazorPortals) portal.isMarked = reader.bool_read(); + reader.fields_read(bombPickupsSpawned, playerType); + if (!g_manager->entityConfig.GetPlayer(playerType)) + return reader.fail(LOG_INFO, "[warn] Invalid starting player type: %d\n", playerType); + isModded = reader.bool_read(); + + players.assign(std::max(reader.read(), 0), {}); + for (GameStatePlayer& player : players) + if (!reader.player_read(player)) + { + log_printf(LOG_ERROR, "Failed to read player data from gamestate \n"); + return false; + } + int esauJrCount = reader.read(); + for (int i = 0; i < esauJrCount; i++) + { + if (!reader.bool_read()) continue; + GameStatePlayer dropped; + bool isRead = reader.player_read(i < ESAU_JR_STATE_COUNT ? esauJrStates[i] : dropped); + if (i < ESAU_JR_STATE_COUNT && !isRead) return false; + } + reader.item_pool_read(itemPool); + + std::array seedString{}; + reader.each_read(std::span(seedString).first(SEED_STRING_LENGTH)); + seeds.set_start_seed(Seeds::String2Seed(seedString.data())); + seeds.ClearSeedEffects(); + int specialSeedBytes = reader.read(); + for (int i = 0, effect = 0; i < specialSeedBytes && effect < SPECIAL_SEED_COUNT; i++) + { + uint8_t packed = reader.read(); + for (int bit = 0; bit < 8 && effect < SPECIAL_SEED_COUNT; bit++, effect++) + if (packed >> bit & 1) seeds.AddSeedEffect(effect); + } + reader.fields_read(playerManagerSeed, fortuneSeed, lastLevelWithDamage); + + encounteredBosses.resize(reader.count_read()); + for (BossId& boss : encounteredBosses) reader.fields_read(boss.type, boss.variant); + reader.bits_read(bossPool.removedBosses); + uint16_t bossSeedCount = reader.read(); + for (int i = 0; i < bossSeedCount; i++) + { + uint32_t seed = reader.read(); + if (i < BOSS_POOL_COUNT) bossPool.rngSeeds[i] = seed; + } + magicSkinUses = reader.read(); + erasedEntities.resize(reader.read()); + for (ErasedEnemy& enemy : erasedEntities) reader.fields_read(enemy.type, enemy.variant, enemy.subtype); + pixelationTimer = reader.read(); + pixelationDuration = reader.read(); + isAscent = reader.bool_read(); + + for (BackwardsStageDesc& backwards : backwardsStages) + { + backwards.stageType = (uint32_t)reader.read(); + for (std::vector* stageRooms : {&backwards.bossRooms, &backwards.treasureRooms}) + { + stageRooms->resize(std::max(reader.read(), 0)); + for (SavedRoom& room : *stageRooms) reader.room_read(room); + } + backwards.isXL = reader.bool_read(); + } + deathCertificateExitTimer = reader.read(); + reader.list_read(proceduralItemSeeds); + versusRules = reader.read(); + reader.list_read(versusPlayers); + + bool isEndEarly = reader.is_end(); + bool isSealMatching = (reader.read() ^ CHECKSUM_KEY) == checksum; + if (!isEndEarly && isSealMatching && reader.position == file.size()) return true; + log_printf(LOG_INFO, "[warn] Bad Gamestate Offset! Gamestate corrupted or has new data!\n"); + return false; +} + bool GameState::read_rerun(std::span) { reconstruction_missing("GameState::read_rerun 009d7d50"); } diff --git a/src/game_state.h b/src/game_state.h index fe20ee1..4930736 100644 --- a/src/game_state.h +++ b/src/game_state.h @@ -66,8 +66,8 @@ struct BackwardsStageDesc // A save slot's saved run (gamestate.dat), to continue from the menus, and its rerun (rep+rerunstate.dat), // the last run's character and seed to play again. // It keeps the run's rules, seeds, counters and histories, the floor and its rooms, the players, the pools, the -// Ascent's saved stages and the versus rules, as Game::store_game_state copies them, and write saves them in the -// original's format. +// Ascent's saved stages and the versus rules, as Game::store_game_state copies them. write saves them in the +// original's format and read loads them back. // Its rooms are every room descriptor of the floor once Level stored them. The Esau Jr. players are always four, a // player type of -1 for an empty one. // Construction and destruction (009c73c0, 009c7800) are the defaults, defined where GameStatePlayer is complete. @@ -190,3 +190,4 @@ struct GlowingHourglassState }; void room_config_ref_save(RoomConfig_Room& config, RoomConfigRef& ref, std::vector* mergedConfigs); +bool is_valid_item_config_id(int itemKind, int id); diff --git a/src/game_update.cpp b/src/game_update.cpp index 52992f1..6a9fa60 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -36,7 +36,6 @@ constexpr int HUD_REFRESH_INTERVAL = 30; constexpr int ITEM_OVERLAY_PLAYING = 2; constexpr uint64_t FADE_IN_ICON_MS = 3000; constexpr uint64_t NS_PER_MS = 1000000; -constexpr int REVIVE_CLOSE_FRAMES = 8; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // The room's render surface, its size and margin, centered on the screen. constexpr float ROOM_SURFACE_WIDTH = 338; @@ -47,7 +46,6 @@ constexpr int EVENT_STREAK_COUNTER = 22; constexpr int STAGE_TRANSITION_START = 1; constexpr int STAGE_TRANSITION_LANDING = 4; -constexpr int MC_POST_UPDATE = 1; // The menu each menu fade out returns to. constexpr std::array FADEOUT_MENUS = {MENU_NONE, MENU_SAVE, MENU_GAME, MENU_ONLINE, MENU_TITLE}; @@ -237,24 +235,6 @@ static bool fadeout_update(Game& game) return true; } -// The game over screen's frame: the looping sounds stop once, the pause paper steps and the co-op revive menu closes. -// The online vote count is left out: netplay is offline. -static void game_over_update(Game& game) -{ - if (game.gameOver._isStopSoundsPending) - { - g_manager->sfxManager.StopLoopingSounds(); - game.gameOver._isStopSoundsPending = false; - } - game.pauseScreen.animation_update(); - - RevivePlayerMenu& revive = game.revivePlayerMenu; - if (revive.state == REVIVE_MENU_HIDDEN) return; - revive.state = REVIVE_MENU_CLOSING; - revive.closeTimer = REVIVE_CLOSE_FRAMES; - revive.controllerIndex = -1; -} - // Steps the fade in, unless the loading icon has not shown its three seconds yet. Once clear (or at once when instant) // the floor's name shows and the players move, outside a versus match, and the loading icons are freed. // Whether the fade still covers the screen. @@ -400,7 +380,7 @@ void Game::Update() freezeFrames--; return hud.PostUpdate(); } - if (gameOver._state != 0) return game_over_update(*this); + if (gameOver.state != GAME_OVER_HIDDEN) return gameOver.Update(); if (leaderboard.displayState != LEADERBOARD_HIDDEN) return leaderboard.Update(); if (stageTransition._state != 0) { @@ -436,8 +416,7 @@ void Game::Update() playerManager.Update(); screen_effects_update(*this); hud.PostUpdate(); - if (static_cast(g_luaEngine)->enabledCallbacks[MC_POST_UPDATE]) - reconstruction_missing("LuaEngine::PostUpdate 008607a0"); + lua_engine_get().PostUpdate(); } // 006fd3f0 The in-between update of odd frames with interpolation on, unless the console holds it. A room transition diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 97e6516..8599ee2 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -1,22 +1,236 @@ #include "grid_entity_pressure_plate.h" -#include "log.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "font.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_poop.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include +#include +#include -// 00985f00 Loads the plate for its variant. +// The sounds a plate plays: pressed, and a reward plate's reward and ambush. +constexpr int SOUND_BUTTON_PRESS = 469; +constexpr int SOUND_THUMBSUP = 268; +constexpr int SOUND_THUMBS_DOWN = 267; + +// Who presses a plate, and how close: the entities a query finds around it, within reach of its center. +constexpr int ENTITY_DOPLE = 53; +constexpr int ENTITY_GRUDGE = 877; +constexpr float PLATE_QUERY_RADIUS = 60; +constexpr float PLATE_PRESS_RADIUS = 30; + +// An unpressed plate claims its cell's path, and a plain one holds the room's clear back. +constexpr int PLATE_PATH = 300; +constexpr int ROOM_CLEAR_HOLD = 10; + +// A reward plate whose ambush was left unbeaten spawns it again this many frames into the next visit. +constexpr int AMBUSH_RESPAWN_FRAME = 4; + +// Greed's timer under the button: seconds and minutes, how far below the button it shows, and its grey blink. +constexpr int TIMER_FRAMES_PER_SECOND = 30; +constexpr int SECONDS_PER_MINUTE = 60; +constexpr int TIMER_TEXT_SIZE = 32; +constexpr int TIMER_BLINK_FRAMES = 4; +constexpr float TIMER_PLATE_DROP = 21; +constexpr float TIMER_TEXT_DROP = 13; +constexpr KColor TIMER_WHITE = kcolor_rgba(1, 1, 1, 1); +constexpr KColor TIMER_GREY = kcolor_rgba(0.3f, 0.3f, 0.3f, 1); + +// The waves Greed's button shows a boss's skull and the last boss's pentagram from, one later in Greedier. +constexpr uint32_t GREED_BOSS_WAVE = 9; +constexpr uint32_t GREED_FINAL_BOSS_WAVE = 11; + +// What a reward plate's roll out of 100 gives below each bound, the most of a pickup it drops at once, and the +// chests it picks from. +constexpr int REWARD_ROLLS = 100; +constexpr int ROLL_TRAPDOOR = 5; +constexpr int ROLL_GOLDEN_POOP = 10; +constexpr int ROLL_POOP = 11; +constexpr int ROLL_ITEM = 12; +constexpr int ROLL_COINS = 30; +constexpr int ROLL_HEARTS = 50; +constexpr int ROLL_BOMBS = 70; +constexpr int ROLL_CHEST = 80; +constexpr int ROLL_SLOT = 85; +constexpr int ROLL_DONATION = 90; +constexpr uint32_t REWARD_COINS_MAX = 3; +constexpr uint32_t REWARD_HEARTS_MAX = 2; +constexpr uint32_t REWARD_BOMBS_MAX = 2; +constexpr int REWARD_CHESTS[] = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_BOMBCHEST, PICKUP_REDCHEST}; + +// The slots and bomb a reward plate drops (Lua's SlotVariant and BombVariant). +constexpr int SLOT_MACHINE = 1; +constexpr int SLOT_FORTUNE_TELLING = 3; +constexpr int SLOT_DONATION = 8; +constexpr int BOMB_TROLL = 3; + +// An ambush brings two to four enemies, near the doors no player stands within reach of, scattered a little. +constexpr uint32_t AMBUSH_EXTRA_MAX = 3; +constexpr int AMBUSH_MIN = 2; +constexpr float AMBUSH_DOOR_REACH = 80; +constexpr float AMBUSH_SCATTER = 20; +constexpr uint32_t AMBUSH_START_MASK = 3; + +// The doors of the secret rooms, which an ambush shuts with their plain open animation. +constexpr int SECRET_DOOR_ROOM_TYPES[] = {ROOM_SECRET, ROOM_SUPERSECRET, ROOM_ULTRASECRET}; + +// The void's backdrops take the ambush of the floor they copy, by their order: Basement, Caves, Depths and Womb three +// each, then Blue Womb, Sheol, Cathedral, Dark Room and Chest. +constexpr int VOID_BACKDROPS_PER_CHAPTER = 3; +constexpr int VOID_CHAPTERS = 4; +constexpr int VOID_BACKDROP_BLUE_WOMB = 13; +constexpr int VOID_BACKDROP_LAST = 17; + +// An enemy an ambush brings. +struct AmbushEnemy +{ + int type = 0; + int variant = 0; +}; + +// The ambushes of each floor: the chapters, the Blue Womb, Sheol and the Cathedral, the Dark Room and the Chest, and +// Greed mode's shop floor and last floor. +constexpr AmbushEnemy AMBUSH_BASEMENT[] = {{18}, {222}, {256}, {12}, {23}, {85}}; +constexpr AmbushEnemy AMBUSH_CAVES[] = {{23}, {25}, {22}, {205}, {26}, {234}}; +constexpr AmbushEnemy AMBUSH_DEPTHS[] = {{38}, {24}, {227}, {41}, {209}, {237}}; +constexpr AmbushEnemy AMBUSH_WOMB[] = {{57}, {223}, {56}, {213}, {216}}; +constexpr AmbushEnemy AMBUSH_BLUE_WOMB[] = {{23, 1}, {257, 1}}; +constexpr AmbushEnemy AMBUSH_SHEOL[] = {{404}, {50}, {405}}; +constexpr AmbushEnemy AMBUSH_CATHEDRAL[] = {{20}, {79}, {67}}; +constexpr AmbushEnemy AMBUSH_DARK_ROOM[] = {{404}, {252}}; +constexpr AmbushEnemy AMBUSH_CHEST[] = {{20}, {51, 1}}; +constexpr AmbushEnemy AMBUSH_GREED_SHOP[] = {{20}, {51, 1}, {404}, {252}}; +constexpr AmbushEnemy AMBUSH_GREED_LAST[] = {{102}}; +constexpr std::span AMBUSH_VOID[] = {AMBUSH_BASEMENT, AMBUSH_CAVES, AMBUSH_DEPTHS, + 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}); +} + +// The entities near a position, as EntityList::QueryRadius finds them in the enemy partition and among the players: +// those whose size reaches into the radius and that queries may see. +static EntityList_EL radius_query(Vector center, float radius) +{ + EntityList_EL found; + + g_game->room->entityList.partitions[PARTITION_ENEMIES].query_box(found, center, vector_make(radius, radius)); + 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_NO_QUERY) || vector_length_squared(vector_sub(entity->pos, center)) >= reach * reach; + }); + return found; +} + +// Whether an entity presses plates: a coop ghost always, a living player but a hologram, a living Dople or Grudge. +static bool is_presser(Entity& entity) +{ + if (entity.type != ENTITY_PLAYER) return !entity.isDead && (entity.type == ENTITY_DOPLE || entity.type == ENTITY_GRUDGE); + + Entity_Player& player = static_cast(entity); + return player.isCoopGhost || (!player.isDead && !player.IsHologram()); +} + +// Whether one who presses plates stands on a plate's center. +static bool is_plate_stood_on(Vector center) +{ + return std::ranges::any_of(radius_query(center, PLATE_QUERY_RADIUS), [&](Entity* entity) { + return is_presser(*entity) && + vector_length_squared(vector_sub(center, entity->pos)) < PLATE_PRESS_RADIUS * PLATE_PRESS_RADIUS; + }); +} + +// 00985f00 Loads the plate with its variant's spritesheet, Greed's timer plate, and starts it off or on. void GridEntity_PressurePlate::subclass_init() { - reconstruction_missing("GridEntity_PressurePlate::subclass_init 00985f00"); + sprite.Load("gfx/grid/grid_pressureplate.anm2", GRAPHICS_DEFER); + nextGreedAnimation = ""; + switch (variant) + { + case PLATE_ROOM_CLEAR: + sprite.ReplaceSpritesheet(0, "gfx/grid/grid_pressureplate_silver.png"); + if (state == PLATE_UNPRESSED) g_game->room->roomClearDelay = ROOM_CLEAR_HOLD; + break; + case PLATE_GREED: + timerPlate.Load("gfx/grid/TimerPlate.anm2", GRAPHICS_LOAD); + timerPlate.Play("Idle"); + break; + case PLATE_RAIL: sprite.ReplaceSpritesheet(0, "gfx/grid/grid_button_rail.png"); break; + case PLATE_KILL: sprite.ReplaceSpritesheet(0, "gfx/grid/grid_button_kill.png"); break; + default: + if (variant >= PLATE_OUTPUT_FIRST && variant <= PLATE_OUTPUT_LAST) + sprite.ReplaceSpritesheet(0, "gfx/grid/grid_button_output.png"); + } + sprite.LoadGraphics(); + + if (variant == PLATE_GREED) + { + update_greed_button_anim(GREED_BUTTON_NORMAL); + play_pending_animation(); + } + else if (state == PLATE_UNPRESSED) sprite.Play("Off"); + else if (state == PLATE_PRESSED || state == PLATE_AMBUSH) sprite.Play("On"); + greedModeRNG = {spawnSeed, 4, 3, 27}; } -// 00983330 Presses the plate under a player and runs Greed's button. +// 00983330 Animates the plate, runs Greed's button or the press, and claims the cell's path while unpressed. void GridEntity_PressurePlate::Update() { - reconstruction_missing("GridEntity_PressurePlate::Update 00983330"); + sprite.Update(); + if (variant == PLATE_GREED) update_greed_button(); + else update_press(); + + if (state == PLATE_UNPRESSED && (uint32_t)gridIndex < ROOM_GRID_CELLS && g_game->room->gridPaths[gridIndex] < PLATE_PATH) + path_set(PLATE_PATH); } -// 00985c10 Draws the plate and Greed's timer. -void GridEntity_PressurePlate::Render(const Vector&) +// Greed mode's wave timer under the button in minutes and seconds, grey once it ran out and blinking grey at zero. +static void greed_timer_render(Vector position) { - reconstruction_missing("GridEntity_PressurePlate::Render 00985c10"); + Game& game = *g_game; + Font& font = g_manager->font4_terminus; + int timer = game.room->greedWaveTimer; + int seconds = (timer - 1) / TIMER_FRAMES_PER_SECOND; + int minutes = seconds / SECONDS_PER_MINUTE; + char text[TIMER_TEXT_SIZE]; + + std::snprintf(text, sizeof text, "%02d:%02d", minutes, seconds % SECONDS_PER_MINUTE); + bool isZero = minutes < 1 && seconds % SECONDS_PER_MINUTE < 1; + bool isGrey = timer <= 0 || (isZero && game.frameCount % TIMER_BLINK_FRAMES <= 1); + float x = position.x - (float)(font.GetStringWidth(text) / 2) + game.screenShakeOffset.x; + float y = position.y + TIMER_TEXT_DROP + game.screenShakeOffset.y; + FontSettings settings; + font.DrawString(text, vector_make(x, y), vector_make(1, 1), isGrey ? TIMER_GREY : TIMER_WHITE, settings); +} + +// 00985c10 Draws the plate in the floor's color, Greed's timer plate and its timer. +void GridEntity_PressurePlate::Render(const Vector& offset) +{ + Vector position = vector_add(get_render_position(), offset); + + GridEntity::Render(offset); + timerPlate.Render({.position = vector_make(position.x, position.y + TIMER_PLATE_DROP)}); + if (variant == PLATE_GREED) greed_timer_render(position); } // 00986430 Water stands raised around the plate. @@ -25,22 +239,77 @@ WaterClipInfo GridEntity_PressurePlate::GetWaterClipInfo() return {WATER_CLIP_RAISED, 0}; } -// 009833c0 Fires the plate's effect when pressed. +// 009833c0 A player (or a Dople or Grudge) on an unpressed plate switches it with a click, and once switched it +// turns on and rewards. A plain plate holds the room's clear while up. A reward plate whose ambush was left unbeaten +// brings it back on the next visit, and counts as pressed once the room is clear. void GridEntity_PressurePlate::update_press() { - reconstruction_missing("GridEntity_PressurePlate::update_press 009833c0"); + Game& game = *g_game; + Room& room = *game.room; + + if (state == PLATE_UNPRESSED && is_plate_stood_on(Position())) + { + if (!sprite.IsPlaying("Switched")) grid_sound_play(SOUND_BUTTON_PRESS); + sprite.Play("Switched"); + } + if (!sprite.IsPlaying() && state == PLATE_UNPRESSED) + { + state = PLATE_PRESSED; + sprite.Play("On"); + Reward(); + } + + if (state == PLATE_UNPRESSED && variant == PLATE_ROOM_CLEAR) room.roomClearDelay = ROOM_CLEAR_HOLD; + if (state != PLATE_AMBUSH || variant != PLATE_REWARD || !room.isInitialized) return; + + int frames = game.frameCount - room.enterFrame; + if (frames == AMBUSH_RESPAWN_FRAME) Reward(); + else if (frames > AMBUSH_RESPAWN_FRAME && room.IsClear()) state = PLATE_PRESSED; } -// 009837b0 Plays Greed's button's animation. -void GridEntity_PressurePlate::update_greed_button_anim(bool) +// Greed's button for the coming wave: the last boss wave's look, a boss wave's, or the plain one. +static std::string_view greed_look_pick(std::string_view finalBoss, std::string_view boss, std::string_view plain) { - reconstruction_missing("GridEntity_PressurePlate::update_greed_button_anim 009837b0"); + Game& game = *g_game; + uint32_t wave = (uint32_t)game.greedModeWave + 1; + uint32_t greedier = game.difficulty == DIFFICULTY_GREEDIER; + + if (!game.IsGreedMode()) return plain; + if (wave >= greedier + GREED_FINAL_BOSS_WAVE) return finalBoss; + return wave >= greedier + GREED_BOSS_WAVE ? boss : plain; } -// 009838c0 Plays the queued Greed animation. +// 009837b0 Picks the animation Greed's button plays next for its state: off (red starting at once), switched, or on. +void GridEntity_PressurePlate::update_greed_button_anim(GreedButtonColor color) +{ + bool isRed = color == GREED_BUTTON_RED; + + switch (state) + { + case PLATE_UNPRESSED: + if (!isRed) + { + nextGreedAnimation = greed_look_pick("OffPentagram", "OffSkull", "Off"); + return; + } + sprite.Play("OffRedStart"); + nextGreedAnimation = "OffRed"; + return; + case PLATE_GREED_PRESSED: + case PLATE_GREED_HELD: + nextGreedAnimation = isRed ? "SwitchedRed" : greed_look_pick("SwitchedPentagram", "SwitchedSkull", "Switched"); + return; + case PLATE_PRESSED: nextGreedAnimation = greed_look_pick("OnPentagram", "OnSkull", "On"); return; + default: return; + } +} + +// 009838c0 Plays Greed's button's next animation unless it shows already or the red start still plays. void GridEntity_PressurePlate::play_pending_animation() { - reconstruction_missing("GridEntity_PressurePlate::play_pending_animation 009838c0"); + if (sprite.GetAnimation() == nextGreedAnimation || sprite.IsPlaying("OffRedStart")) return; + + sprite.Play(nextGreedAnimation); } // 009839f0 Runs Greed mode's wave button. @@ -49,8 +318,188 @@ void GridEntity_PressurePlate::update_greed_button() reconstruction_missing("GridEntity_PressurePlate::update_greed_button 009839f0"); } -// 00984550 Spawns a reward plate's reward. +// Where a slot fits: the spot, when a cell beside it on both axes is free, else a free spot near the room's center. +static Vector slot_position_get(Vector position) +{ + Room& room = *g_game->room; + auto isFree = [&](float x, float y) { + return room.GetGridCollision(room.GetGridIndex(vector_make(position.x + x, position.y + y))) == COLLISION_NONE; + }; + + 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); +} + +// A reward plate's reward, by a roll out of 100: a trapdoor (golden poop where none may open), golden poop, poop, an +// item, coins, hearts or bombs, a chest, a slot machine or fortune teller, a donation machine, or a troll bomb. +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); + 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()); + }; + + if (roll < ROLL_TRAPDOOR && g_game->CanSpawnTrapDoor()) + { + uint32_t seed = rng.Next(); + room.SpawnGridEntity(room.GetGridIndex(position), GRID_TRAPDOOR, 0, seed, 0); + } + else if (roll < ROLL_POOP) + { + uint32_t seed = rng.Next(); + room.SpawnGridEntity(room.GetGridIndex(position), GRID_POOP, roll < ROLL_GOLDEN_POOP ? POOP_GOLDEN : POOP_NORMAL, seed, 0); + } + else if (roll < ROLL_ITEM) entity_spawn(ENTITY_PICKUP, PICKUP_COLLECTIBLE, position, rng.Next()); + else if (roll < ROLL_COINS) pickupsSpawn(PICKUP_COIN, REWARD_COINS_MAX); + else if (roll < ROLL_HEARTS) pickupsSpawn(PICKUP_HEART, REWARD_HEARTS_MAX); + else if (roll < ROLL_BOMBS) pickupsSpawn(PICKUP_BOMB, REWARD_BOMBS_MAX); + else if (roll < ROLL_CHEST) + { + uint32_t seed = rng.Next(); + entity_spawn(ENTITY_PICKUP, REWARD_CHESTS[rng.RandomInt(std::size(REWARD_CHESTS))], position, seed); + } + else if (roll < ROLL_SLOT) + { + position = slot_position_get(position); + uint32_t seed = rng.Next(); + entity_spawn(ENTITY_SLOT, rng.RandomInt(2) != 0 ? SLOT_FORTUNE_TELLING : SLOT_MACHINE, position, seed); + } + else if (roll < ROLL_DONATION) + { + position = slot_position_get(position); + entity_spawn(ENTITY_SLOT, SLOT_DONATION, position, rng.Next()); + } + else entity_spawn(ENTITY_BOMB, BOMB_TROLL, position, rng.Next()); +} + +// The enemies an ambush draws from: by Greed's floor, by the floor (the Sheol and Dark Room sides of the last +// chapters apart), and in the Void by the backdrop of the floor it copies. +static std::span ambush_pool_get() +{ + Game& game = *g_game; + bool isOriginal = game.stageType == STAGETYPE_ORIGINAL; + + if (game.IsGreedMode()) + { + switch (game.stage) + { + case 2: return AMBUSH_CAVES; + case 3: return AMBUSH_DEPTHS; + case 4: return AMBUSH_WOMB; + case 5: return AMBUSH_SHEOL; + case 6: return AMBUSH_GREED_SHOP; + case 7: return AMBUSH_GREED_LAST; + default: return AMBUSH_BASEMENT; + } + } + switch (game.stage) + { + case 3: + case 4: return AMBUSH_CAVES; + case 5: + case 6: return AMBUSH_DEPTHS; + case 7: + case 8: return AMBUSH_WOMB; + case 9: return AMBUSH_BLUE_WOMB; + case 10: return isOriginal ? AMBUSH_SHEOL : AMBUSH_CATHEDRAL; + case 11: return isOriginal ? AMBUSH_DARK_ROOM : AMBUSH_CHEST; + case 12: + { + int backdrop = game.room->backdropType; + if (backdrop < 1 || backdrop > VOID_BACKDROP_LAST) return AMBUSH_DARK_ROOM; + if (backdrop < VOID_BACKDROP_BLUE_WOMB) return AMBUSH_VOID[(backdrop - 1) / VOID_BACKDROPS_PER_CHAPTER]; + return AMBUSH_VOID[backdrop - VOID_BACKDROP_BLUE_WOMB + VOID_CHAPTERS]; + } + default: return AMBUSH_BASEMENT; + } +} + +// The doors no player stands near, where an ambush comes in, or the room's center when every door has a player. +static std::vector ambush_positions_get() +{ + Room& room = *g_game->room; + std::vector positions; + + for (GridEntity_Door* door : room.doors) + { + if (!door) continue; + + Vector position = room.GetGridPosition(door->gridIndex); + Entity_Player* player = game_nearest_player(position); + if (vector_length_squared(vector_sub(position, player->pos)) > AMBUSH_DOOR_REACH * AMBUSH_DOOR_REACH) + positions.push_back(position); + } + if (positions.empty()) positions.push_back(Room::GetCenterPos()); + return positions; +} + +// A reward plate's ambush: two to four of the floor's enemies come in at the doors no player is near. New enemies +// shut the doors (secret ones with their plain animation) and unclear the room, which then gives no clear reward. +static void plate_ambush_spawn(GridEntity& plate, RNG& rng) +{ + Game& game = *g_game; + Room& room = *game.room; + + if (plate.state != PLATE_AMBUSH) grid_sound_play(SOUND_THUMBS_DOWN); + int enemiesBefore = room.GetAliveEnemiesCount(); + int count = (int)rng.RandomInt(AMBUSH_EXTRA_MAX) + AMBUSH_MIN; + std::span pool = ambush_pool_get(); + AmbushEnemy enemy = pool.size() > 1 ? pool[rng.RandomInt((uint32_t)pool.size())] : pool[0]; + std::vector positions = ambush_positions_get(); + + rng.Next(); + RNG seeds = rng; + int first = (int)(rng._seed & AMBUSH_START_MASK); + 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); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float distance = random_unit() * AMBUSH_SCATTER; + position = vector_add(position, vector_make(std::cos(angle) * distance, std::sin(angle) * distance)); + entity_spawn(enemy.type, enemy.variant, position, seed); + } + + if (enemiesBefore < room.GetAliveEnemiesCount()) + { + for (GridEntity_Door* door : room.doors) + { + if (!door || door->state == DOOR_STATE_CLOSED) continue; + + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + for (int type : SECRET_DOOR_ROOM_TYPES) + if (door->currentRoomType == type || door->targetRoomType == type) door->openAnimation = "Open"; + } + if (room.IsClear()) game.GetRoomByIdx(game.currentRoomIdx)->flags |= ROOM_DESCRIPTOR_FLAG_NO_REWARD; + room.descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; + } + if (!room.IsClear()) plate.state = PLATE_AMBUSH; +} + +// 00984550 What a pressed plate does: a reward plate rewards or ambushes by its seed, the rail button raises the +// mineshaft's rail, the kill button kills the room's enemies and the output buttons fire their group. +// The kill button's timer and the output groups stop, as Game::ShakeScreen and Room::TriggerOutput are not here yet. void GridEntity_PressurePlate::Reward() { - reconstruction_missing("GridEntity_PressurePlate::Reward 00984550"); + if (variant == PLATE_REWARD) + { + RNG rng = {spawnSeed, 5, 9, 7}; + rng.Next(); + if ((rng._seed & 1) == 0) plate_reward_spawn(*this, rng); + else plate_ambush_spawn(*this, rng); + } + else if (variant == PLATE_RAIL) g_game->raise_mineshaft_rail(); + else if (variant == PLATE_KILL && g_game->room->GetAliveEnemiesCount() > 0) + reconstruction_missing("GridEntity_PressurePlate::Reward 00984550: the kill button (Game::ShakeScreen, " + "pressure_plate_kill_enemies_timer_callback 00983f30)"); + else if (variant >= PLATE_OUTPUT_FIRST && variant <= PLATE_OUTPUT_LAST) + reconstruction_missing("GridEntity_PressurePlate::Reward 00984550: Room::TriggerOutput 00823080"); } diff --git a/src/grid_entity_pressure_plate.h b/src/grid_entity_pressure_plate.h index c903766..1480a14 100644 --- a/src/grid_entity_pressure_plate.h +++ b/src/grid_entity_pressure_plate.h @@ -1,6 +1,38 @@ #pragma once #include "grid_entity.h" +#include + +// A pressure plate's variant: the plain plate every one of which clears the room, the reward plate, Greed mode's wave +// button, the mineshaft's rail button, the kill button and the four buttons that fire an output group. +enum PressurePlateVariant : int +{ + PLATE_ROOM_CLEAR = 0, + PLATE_REWARD = 1, + PLATE_GREED = 2, + PLATE_RAIL = 3, + PLATE_KILL = 9, + PLATE_OUTPUT_FIRST = 10, + PLATE_OUTPUT_LAST = 13 +}; + +// A pressure plate's state: unpressed, Greed's button pressed and held through its wave, pressed, and a reward plate +// whose ambush is not beaten yet. +enum PressurePlateState : int +{ + PLATE_UNPRESSED = 0, + PLATE_GREED_PRESSED = 1, + PLATE_GREED_HELD = 2, + PLATE_PRESSED = 3, + PLATE_AMBUSH = 4 +}; + +// The look Greed's button takes: its own, or red while the wave cannot be called. +enum GreedButtonColor +{ + GREED_BUTTON_NORMAL, + GREED_BUTTON_RED +}; // Destruction (0070bd00) is the default. // A pressure plate (Lua's GRID_PRESSURE_PLATE): pressed, it fires the room's outputs, opens doors or rewards. Greed @@ -9,14 +41,14 @@ struct GridEntity_PressurePlate : GridEntity { ANM2 timerPlate; RNG greedModeRNG = GRID_RNG_DEFAULT; - const char* nextGreedAnimation = nullptr; + std::string_view nextGreedAnimation; void subclass_init() override; void Update() override; void Render(const Vector& offset) override; WaterClipInfo GetWaterClipInfo() override; void update_press(); - void update_greed_button_anim(bool isRed); + void update_greed_button_anim(GreedButtonColor color); void play_pending_animation(); void update_greed_button(); void Reward(); diff --git a/src/hud.cpp b/src/hud.cpp index 75e6aa1..55e8edd 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -1,4 +1,5 @@ #include "hud.h" +#include "item_pickup.h" #include "entity_player.h" #include "game.h" #include "level.h" @@ -617,9 +618,9 @@ bool HUD::IsVisible() } // 009a2d20 Shows an item's name and description on the stacked banners, or on its player's corner in co-op. -void HUD::ShowItemText(Entity_Player*, ItemConfig_Item*) +void HUD::ShowItemText(Entity_Player* player, ItemConfig_Item* item) { - reconstruction_missing("HUD::ShowItemText 009a2d20"); + item_text_show(*this, player, item); } // 0085e750 Lua's HUD:ShowItemText, for a player and item or a title and description. diff --git a/src/item_config.cpp b/src/item_config.cpp index c0d079a..fe838be 100644 --- a/src/item_config.cpp +++ b/src/item_config.cpp @@ -44,6 +44,7 @@ constexpr int COLLECTIBLE_BREAKFAST = 25; constexpr int COLLECTIBLE_BREATH_OF_LIFE = 326; constexpr int COLLECTIBLE_BOOK_OF_VIRTUES = 584; constexpr int COLLECTIBLE_SPIN_TO_WIN = 655; +constexpr int COLLECTIBLE_SACRED_ORB = 691; constexpr int COLLECTIBLE_VANISHING_TWIN = 697; constexpr int TRINKET_NO = 88; constexpr int TRINKET_BUTTER = 122; @@ -464,12 +465,6 @@ static bool is_deathmatch_banned() reconstruction_missing("DeathmatchType ban checks, vtable slots 9 to 12"); } -// Whether a player holds Sacred Orb. PlayerManager::FirstCollectibleOwner has no declaration to call yet. -static bool is_sacred_orb_owned() -{ - reconstruction_missing("PlayerManager::FirstCollectibleOwner 009be080"); -} - static bool is_achievement_unlocked(int achievementId) { return achievementId < 0 || g_manager->persistentGameData.Unlocked(achievementId); @@ -536,7 +531,7 @@ bool ItemConfig_Item::IsAvailableEx(uint32_t checks) if (quality <= QUALITY_LOW_LAST && is_roll_skipped(id, TAINTED_LOST_RNG_SHIFT, TAINTED_LOST_SKIP_ROLL)) return false; } - if (is_sacred_orb_owned()) + if (players.FirstCollectibleOwner(COLLECTIBLE_SACRED_ORB, LAZARUS_SHARE_CHECK)) { if (quality < QUALITY_MIDDLE) return false; if (quality == QUALITY_MIDDLE && is_roll_skipped(id, SACRED_ORB_RNG_SHIFT, SACRED_ORB_SKIP_ROLL)) diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp new file mode 100644 index 0000000..740ea8f --- /dev/null +++ b/src/item_pickup.cpp @@ -0,0 +1,521 @@ +#include "item_pickup.h" +#include "entity_config.h" +#include "hud.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "item_pool.h" +#include "log.h" +#include "manager.h" +#include "room.h" +#include "seeds.h" + +// The items, characters, rooms and unlocks the pedestals ask about. +constexpr int COLLECTIBLE_BOOK_OF_BELIAL = 34; +constexpr int COLLECTIBLE_KEY_PIECE_A = 238; +constexpr int COLLECTIBLE_KEY_PIECE_B = 239; +constexpr int COLLECTIBLE_PEDESTAL_POLAROID = 327; +constexpr int COLLECTIBLE_PEDESTAL_NEGATIVE = 328; +constexpr int COLLECTIBLE_RESTOCK = 376; +constexpr int COLLECTIBLE_BROKEN_SHOVEL_A = 550; +constexpr int COLLECTIBLE_BROKEN_SHOVEL_B = 551; +constexpr int COLLECTIBLE_KNIFE_PIECE_A = 626; +constexpr int COLLECTIBLE_KNIFE_PIECE_B = 627; +constexpr int COLLECTIBLE_DAMOCLES_PASSIVE = 656; +constexpr int COLLECTIBLE_BINGE_EATER = 664; +constexpr int COLLECTIBLE_DADS_NOTE = 668; +constexpr int COLLECTIBLE_GLITCHED_CROWN = 689; +constexpr int COLLECTIBLE_FLIP = 711; +constexpr int COLLECTIBLE_TMTRAINER = 721; +constexpr int COLLECTIBLE_GLITCHED_GFUEL = -1; +constexpr int ACHIEVEMENT_GLITCHED_ITEMS = 593; +constexpr int DIMENSION_DEATH_CERTIFICATE = 2; +constexpr int EVENT_ANGEL_ITEMS_TAKEN = 15; +constexpr uint32_t QUEUED_TOUCHED = 0x1; +constexpr int COLLECTIBLE_MONSTER_MANUAL = 123; +constexpr uint32_t MONSTER_MANUEL_ODDS = 3; +constexpr int EFFECT_POOF01 = 15; + +// The pedestals Alternates frames that change the pickup's size: Mom's Chest's, and the two halves of a Mega Chest's. +constexpr int PEDESTAL_MOMS_CHEST = 11; +constexpr int PEDESTAL_MEGA_CHEST_A = 14; +constexpr int PEDESTAL_MEGA_CHEST_B = 19; +constexpr int PEDESTAL_LAYER = 1; +constexpr int PEDESTAL_WAIT = 20; +constexpr int PEDESTAL_INVISIBLE_FRAMES = 3; + +// The cycles a pedestal starts with: Isaac's Birthright and Tainted Isaac add one item, Glitched Crown four. +constexpr int CYCLE_BIRTHRIGHT = 1; +constexpr int CYCLE_GLITCHED_CROWN = 4; +constexpr uint32_t CYCLE_SHIFT_A = 5; +constexpr uint32_t CYCLE_SHIFT_B = 13; +constexpr uint32_t CYCLE_SHIFT_C = 6; +constexpr int BINGE_EATER_FOOD_FALLBACK = 25; + +// The rolls that start a pedestal: Butter Bean's Wait What?, Binge Eater's food and the glitched item of error and +// secret rooms. +constexpr uint32_t BUTTER_BEAN_SHIFT = 77; +constexpr uint32_t BINGE_EATER_SHIFT = 9; +constexpr uint32_t GLITCH_SHIFT = 11; +constexpr uint32_t WAIT_WHAT_ODDS = 20; +constexpr uint32_t GLITCH_ERROR_ODDS = 16; +constexpr uint32_t GLITCH_SECRET_ODDS = 60; +constexpr uint32_t PICKUP_RNG_SHIFT_COLLECTIBLE = 35; +constexpr uint32_t ITEM_LAYER_UNFILTERED = 0x20; +constexpr int COLLECTIBLE_UNFILTERED_GFX = 633; +constexpr int CHALLENGE_APRILS_FOOL = 32; + +// The sounds an item makes when taken, by the room it was in. +constexpr int SOUND_1UP = 1; +constexpr int SOUND_CHOIR_UNLOCK = 23; +constexpr int SOUND_POWERUP1 = 128; +constexpr int SOUND_POWERUP2 = 129; +constexpr int SOUND_POWERUP3 = 130; +constexpr int SOUND_VAMP_GULP = 169; +constexpr int SOUND_SHELLGAME = 252; +constexpr int SOUND_DEVILROOM_DEAL = 316; +constexpr int ONE_UP_FRAME_DELAY = 30; +constexpr float ITEM_SOUND_HALF_VOLUME = 0.5f; +constexpr int COLLECTIBLE_1UP = 11; +constexpr int COLLECTIBLE_MAGIC_MUSHROOM = 12; +constexpr int COLLECTIBLE_SUPER_BANDAGE = 92; +constexpr int COLLECTIBLE_MINI_MUSH = 71; + +// The sprite named for its file's question mark, which Curse of the Blind shows on every pedestal. +constexpr std::string_view QUESTION_MARK_GFX = "gfx/Items/Collectibles/questionmark.png"; + +static bool is_anyone_owning(int collectible) +{ + return g_game->playerManager.FirstCollectibleOwner(collectible, LAZARUS_SHARE_CHECK) != nullptr; +} + +// One step of the xorshift the pedestals cycle their items with, which the original's generators never reach. +static uint32_t cycle_seed_next(uint32_t seed) +{ + if (seed == 0) log_printf(LOG_ASSERT, "RNG Seed is zero!\n"); + seed ^= seed >> CYCLE_SHIFT_A; + seed ^= seed << CYCLE_SHIFT_B; + return seed ^ (seed >> CYCLE_SHIFT_C); +} + +// The item part of 006ddcd0: a pedestal without an item draws one from the room's pool. TMTRAINER draws a new one +// for any pedestal but a quest item's. +void collectible_subtype_pick(PickupChoice& choice, RNG& rng) +{ + if (choice.subType != 0 && !g_pickupIgnoreModifiers && is_anyone_owning(COLLECTIBLE_TMTRAINER) && + !ItemConfig::IsQuestItem(choice.subType)) + choice.subType = 0; + if (choice.subType != 0) return; + + uint32_t flags = choice.draw == POOL_DRAW_TAKE ? 0 : POOL_FLAG_NO_DECREASE; + choice.subType = g_game->itemPool.GetSeededCollectible(rng.Next(), flags, *g_game->room->descriptor); +} + +// The item part of 006e02f0 before the entity starts: an unknown item is drawn again from the room's pool, its +// charge starts full (or at its initial charge), a save that has seen Butter Bean turns it into Wait What? one time +// in 20, and the pedestal waits before it can be taken. +// The original reads a missing item's config. A redraw that finds none leaves the pedestal without a charge here. +void Entity_Pickup::collectible_choose(int& collectibleId, uint32_t seed) +{ + ItemConfig& items = g_manager->itemConfig; + RNG rng = rng_make(seed, PICKUP_RNG_SHIFT_COLLECTIBLE); + + ItemConfig_Item* item = items.GetCollectible(collectibleId); + if (!item) + { + collectibleId = g_game->itemPool.GetSeededCollectible(rng.Next(), 0, *g_game->room->descriptor); + item = items.GetCollectible(collectibleId); + } + if (!item) return; + + charge = item->maxCharges; + bool isBeanSeen = g_manager->persistentGameData.itemsCollection[COLLECTIBLE_BUTTER_BEAN]; + if (!g_pickupIgnoreModifiers && collectibleId == COLLECTIBLE_BUTTER_BEAN && isBeanSeen) + { + RNG beanRng = rng_make(g_game->seedEffects.GetStartSeed(), BUTTER_BEAN_SHIFT); + if (beanRng.RandomInt(WAIT_WHAT_ODDS) == 0) + { + collectibleId = COLLECTIBLE_WAIT_WHAT; + item = items.GetCollectible(COLLECTIBLE_WAIT_WHAT); + charge = item->maxCharges; + } + } + if (item->initCharge >= 0) charge = item->initCharge; + wait = PEDESTAL_WAIT; +} + +// Whether a pedestal cycles: not a quest item's, Dad's Note's or a glitched G FUEL!'s. +static bool is_cycle_allowed(int collectibleId) +{ + bool isGlitchedFuel = + g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && collectibleId == COLLECTIBLE_GLITCHED_GFUEL; + for (int quest : {COLLECTIBLE_DADS_NOTE, COLLECTIBLE_KNIFE_PIECE_A, COLLECTIBLE_KNIFE_PIECE_B, + COLLECTIBLE_PEDESTAL_POLAROID, COLLECTIBLE_PEDESTAL_NEGATIVE, COLLECTIBLE_KEY_PIECE_A, + COLLECTIBLE_KEY_PIECE_B}) + if (collectibleId == quest) return false; + return !isGlitchedFuel; +} + +// The pedestal part of 006e02f0: the item idles on its pedestal and stays solid, Damocles marks it to be doubled, +// Isaac's Birthright, Tainted Isaac and Glitched Crown make it cycle through more items, Binge Eater adds a food, a +// new error or secret room may hold a glitched item, and an item spawned into the room the players are in appears in +// a poof. +void Entity_Pickup::pedestal_start() +{ + Game& game = *g_game; + Room& room = *game.room; + PlayerManager& players = game.playerManager; + + sprite.Play("Idle"); + SetAlternatePedestal(0); + if (price == 0 && !g_pickupIgnoreModifiers && is_anyone_owning(COLLECTIBLE_DAMOCLES_PASSIVE)) + { + AddEntityFlags(FLAG_NO_SPIKE_DAMAGE); + room.isUnknown7769 = true; + } + entityCollisionClass = ENTCOLL_ALL; + if (room.roomType == ROOM_DUNGEON) entityGridCollisionClass = GRIDCOLL_NONE; + + if (!g_pickupIgnoreModifiers && CanReroll()) + { + bool isGlitchedCrown = is_anyone_owning(COLLECTIBLE_GLITCHED_CROWN); + bool isCycling = isGlitchedCrown || players.FirstPlayerByType(PLAYER_ISAAC_B) || + players.FirstBirthrightOwner(PLAYER_ISAAC); + if (isCycling && cycleCollectibleCount == 0 && !isDead && is_cycle_allowed(subtype)) + { + uint32_t seed = dropRNG._seed; + cycleCollectibleCount = isGlitchedCrown ? CYCLE_GLITCHED_CROWN : CYCLE_BIRTHRIGHT; + for (uint32_t i = 0; i < cycleCollectibleCount; i++) + { + seed = cycle_seed_next(seed); + cycleCollectibleList[i] = (uint32_t)game.itemPool.GetSeededCollectible(seed, 0, *room.descriptor); + } + } + if (is_anyone_owning(COLLECTIBLE_BINGE_EATER)) + { + std::vector foods; + for (ItemConfig_Item* item : g_manager->itemConfig.GetTaggedItems(TAG_FOOD)) + if (item->IsCollectible()) foods.push_back(item->id); + RNG foodRng = rng_make(initSeed, BINGE_EATER_SHIFT); + int food = foods.empty() ? BINGE_EATER_FOOD_FALLBACK : foods[foodRng.RandomInt((uint32_t)foods.size())]; + if (cycleCollectibleCount < CYCLE_COLLECTIBLE_LIMIT) cycleCollectibleList[cycleCollectibleCount++] = food; + } + + bool isNew = room.GetFrameCount() < 2 && is_run_unlocked(ACHIEVEMENT_GLITCHED_ITEMS); + uint32_t glitchOdds = room.roomType == ROOM_ERROR ? GLITCH_ERROR_ODDS : GLITCH_SECRET_ODDS; + bool isGlitchRoom = room.roomType == ROOM_ERROR || room.roomType == ROOM_SECRET; + if (isNew && isGlitchRoom && rng_make(initSeed, GLITCH_SHIFT).RandomInt(glitchOdds) == 0) + AddEntityFlags(FLAG_GLITCH); + } + if (room.GetFrameCount() > 1) + { + AddEntityFlags(FLAG_APPEAR); + isVisible = false; + } + + bool isKeeperPriced = players.FirstPlayerByType(PLAYER_KEEPER_B) && !g_pickupIgnoreModifiers && price == 0 && + !room.isInitialized && !ItemConfig::IsQuestItem(subtype); + if (isKeeperPriced) reconstruction_missing("Entity_Pickup::Init 006e02f0: Tainted Keeper's prices"); +} + +// 006e1e90 Shows a collectible's image on a layer of a sprite: the question mark when blind, a procedural item's icon +// from the procedural items' sheet, or the item's own image, which a challenge swaps for a random item's. +void Entity_Pickup::load_collectible_gfx(ANM2& itemSprite, int layerId, int collectibleId, + [[maybe_unused]] uint32_t seed, bool isBlind) +{ + if (collectibleId == 0) return; + + LayerState* layer = itemSprite.GetLayer(layerId); + if (isBlind) + { + if (layer) layer->cropOffset = {}; + itemSprite.ReplaceSpritesheet(layerId, QUESTION_MARK_GFX); + return; + } + + ItemConfig& items = g_manager->itemConfig; + ItemConfig_Item* item = items.GetCollectible(collectibleId); + std::string gfx = item ? item->gfxFilename : std::string(); + if (g_game->challenge == CHALLENGE_APRILS_FOOL) reconstruction_missing("Entity_Pickup::load_collectible_gfx 006e1e90"); + if (collectibleId < 0) reconstruction_missing("Entity_Pickup::load_collectible_gfx 006e1e90: a procedural item"); + + if (layer) layer->cropOffset = {}; + itemSprite.ReplaceSpritesheet(layerId, gfx); + if (LayerState* shown = itemSprite.GetLayer(layerId)) + { + if (collectibleId == COLLECTIBLE_UNFILTERED_GFX) shown->bitflags |= ITEM_LAYER_UNFILTERED; + else shown->bitflags &= ~ITEM_LAYER_UNFILTERED; + } +} + +// 006e1a80 Shows a pedestal from the Alternates animation under a free item outside the crawl spaces, and takes the +// size that pedestal has: Mom's Chest's, a Mega Chest half's (which pairs with the other half), or the pickup's own. +void Entity_Pickup::SetAlternatePedestal(int pedestalType) +{ + if (variant != PICKUP_COLLECTIBLE || pedestalType < 0 || price != 0 || g_game->room->roomType == ROOM_DUNGEON) + return; + + if (sprite.SetOverlayAnimation("Alternates") && sprite.overlayAnimState.animData) + sprite.overlayAnimState.SetFrameFloat((float)pedestalType); + const NullFrame* frame = sprite.overlayAnimState.GetNullFrameById(0); + if (LayerState* layer = sprite.GetLayer(PEDESTAL_LAYER)) layer->pos = frame ? frame->pos : Vector{}; + + EntityConfig& entities = g_manager->entityConfig; + EntityConfig_Entity* sized = config; + if (pedestalType == PEDESTAL_MOMS_CHEST) sized = entities.GetEntity(ENTITY_PICKUP, PICKUP_MOMSCHEST, 0); + else if (pedestalType == PEDESTAL_MEGA_CHEST_A || pedestalType == PEDESTAL_MEGA_CHEST_B) + sized = entities.GetEntity(ENTITY_PICKUP, PICKUP_MEGACHEST, 0); + if (!sized) sized = entities.GetEntity(ENTITY_PICKUP, 0, 0); + if (sized) SetSize(sized->collisionRadius, sized->collisionRadiusMulti, sized->gridCollisionPoints); + + bool isMegaHalf = pedestalType == PEDESTAL_MEGA_CHEST_A || pedestalType == PEDESTAL_MEGA_CHEST_B; + if (isMegaHalf && !megaChestCollectible[0] && !megaChestCollectible[1]) + reconstruction_missing("Entity_Pickup::SetAlternatePedestal 006e1a80: a Mega Chest's pair"); +} + +// 006e1d70 The Alternates frame an item's pedestal shows, or -1. +int Entity_Pickup::GetAlternatePedestal() +{ + if (variant != PICKUP_COLLECTIBLE || !sprite.overlayAnimState.animData) return -1; + if (sprite.GetOverlayAnimation() != "Alternates") return -1; + return (int)sprite.overlayAnimState.animFrame; +} + +// 006ed580 Takes the item off its pedestal, which shows empty. A bought item's pedestal goes with it, unless Flip +// holds its other item. A broken shovel's pickup goes. Whether there was an item to take. +uint8_t Entity_Pickup::empty_pedestal() +{ + if (variant == PICKUP_BROKEN_SHOVEL) + { + Remove(); + return true; + } + if (variant != PICKUP_COLLECTIBLE || subtype == 0) return false; + + subtype = 0; + if (price != 0) + { + if (!flipSaveState || !altPedestalANM2.isLoaded) + { + Remove(); + return true; + } + reconstruction_missing("Entity_Pickup::empty_pedestal 006ed580: Flip's bought item"); + } + if (sprite.SetAnimation("Empty") && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + if (LayerState* shadow = sprite.GetLayer("itemshadow")) shadow->isVisible = false; + return true; +} + +// The pedestal part of 006e3940: an item spawned into the room appears in a poof, a hidden pedestal shows again +// after a few frames, and Flip's other item shows over it. +void Entity_Pickup::pedestal_update() +{ + if (HasEntityFlags(FLAG_APPEAR)) + { + g_game->Spawn({pos, {}, nullptr, 0, ENTITY_EFFECT, EFFECT_POOF01, Random()})->Update(); + ClearEntityFlags(FLAG_APPEAR); + if (g_game->playerManager.GetGFuelCount() > 1) + reconstruction_missing("Entity_Pickup::Update 006e3940: the G FUEL! explosion"); + } + if (!isVisible && entityCollisionClass != ENTCOLL_NONE && ++invisibleFrames > PEDESTAL_INVISIBLE_FRAMES) + isVisible = true; + + bool isFlipShown = flipSaveState && is_anyone_owning(COLLECTIBLE_FLIP); + if (isFlipShown) reconstruction_missing("Entity_Pickup::Update 006e3940: Flip's other item"); + if (altPedestalANM2.isLoaded) altPedestalANM2.Reset(); + if (subtype == COLLECTIBLE_BROKEN_SHOVEL_A && isTouched) + reconstruction_missing("Entity_Pickup::Update 006e3940: the broken shovel"); + if (megaChestCollectible[0]) reconstruction_missing("Entity_Pickup::Update 006e3940: a Mega Chest's item"); +} + +// The pedestal part of 006e69b0: the pedestal and its Alternates frame at the snapped position, then the item layer +// over them. +void Entity_Pickup::pedestal_render(const Vector& offset) +{ + if (megaChestCollectible[0] || megaChestCollectible[1]) + reconstruction_missing("Entity_Pickup::Render 006e69b0: a Mega Chest's items"); + + Vector snapped = render_position_get(vector_make(pos.x + posOffset.x, pos.y + posOffset.y), RENDER_SNAPPED); + renderPosition = vector_make(snapped.x + offset.x, snapped.y + offset.y); + SpriteDraw draw = {renderPosition, {}, {}}; + if (altPedestalANM2.isLoaded) + reconstruction_missing("Entity_Pickup::Render 006e69b0: Flip's other item"); + + LayerState* item = sprite.GetLayer(PEDESTAL_LAYER); + if (item) item->isVisible = false; + sprite.overlayAnimState.Render(draw, sprite); + sprite.animState.Render(draw, sprite); + if (item) item->isVisible = true; + sprite.RenderLayer(PEDESTAL_LAYER, draw); +} + +// The collectible refusals of 006e8ae0: Book of Belial for a player who has its passive, and anything Strawman and +// the other helper players cannot take (actives, unknown items, or while their lift effects run). +bool Entity_Pickup::is_collectible_refused(Entity_Player& player) +{ + if (subtype == COLLECTIBLE_BOOK_OF_BELIAL && player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + return true; + if (!player.parent) return false; + + TemporaryEffects& effects = player.temporaryEffects; + if (effects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN) || effects.HasNullEffect(NULLITEM_SOUL_JACOB)) return true; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(subtype); + return !item || item->type == ITEM_ACTIVE; +} + +// The collectible part of 006e8ae0: a free hand takes the item off its pedestal. The item leaves the pools, its sound +// and name play, the player lifts it in the pedestal's sprite and queues it to be added, and the pedestal empties. +// Whether it was taken. +bool Entity_Pickup::collectible_collect(Entity_Player& player) +{ + Game& game = *g_game; + int collectibleId = subtype; + + if (collectibleId == 0 || player.IsHoldingItem() || !player.CanAddCollectible(collectibleId) || wait >= 1) + return false; + timeout = -1; + if (player.playerType == PLAYER_CAIN_B) + { + bool isKept = ItemConfig::is_collectible_tagged(collectibleId, TAG_QUEST) || + game.challenge == CHALLENGE_CANTRIPPED || + game.currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE || + game.currentRoomIdx == ROOM_GENESIS_IDX; + if (!isKept) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Cain's pedestal burst"); + } + if (collectibleId == COLLECTIBLE_DADS_NOTE) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Dad's Note"); + + game.itemPool.RemoveCollectible(collectibleId, REMOVE_ANY, REMOVE_APPLY); + int pedestalVariant = variant; + if (variant != PICKUP_COLLECTIBLE) + { + targetPosition = pos; + variant = PICKUP_COLLECTIBLE; + } + PlayPickupSound(); + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (collectibleId == COLLECTIBLE_BROKEN_SHOVEL_B && player.HasCollectible(COLLECTIBLE_BROKEN_SHOVEL_A)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Mom's Shovel"); + if (((game.GetCurses() & CURSE_OF_BLIND) || isForceBlind) && item) UpdateSprite(true); + item_text_show(game.hud, &player, item); + + int heldCharge = charge; + int heldVarData = varData; + int alternatePedestal = GetAlternatePedestal(); + bool isRetaken = isTouched; + if (pedestalVariant == PICKUP_COLLECTIBLE) + { + sprite.overlayAnimState.SetAnimationData(nullptr); + sprite.Play("PlayerPickupSparkle"); + } + else sprite.Play("Idle"); + player.AnimatePickup(&sprite, false, HasEntityFlags(FLAG_NO_DEATH_TRIGGER) ? "UseItem" : "Pickup"); + + if (item->type == ITEM_ACTIVE) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: an active item"); + if (player.playerType == PLAYER_ISAAC_B && player.CanAddCollectibleToInventory(item->id)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Isaac's inventory"); + if (game.deathmatchManager.is_active()) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the deathmatch's items"); + + SetAlternatePedestal(alternatePedestal); + player.SetQueuedItem({item, heldCharge, isRetaken ? QUEUED_TOUCHED : 0u, heldVarData}); + if (!isRetaken && game.room->roomType == ROOM_ANGEL) + g_manager->persistentGameData.IncreaseEventCounter(EVENT_ANGEL_ITEMS_TAKEN, 1); + + log_printf(LOG_INFO, "item taken without exchange\n"); + variant = pedestalVariant; + empty_pedestal(); + cycleCollectibleCount = 0; + isForceBlind = false; + if (price != 0 && (game.playerManager.AnyoneHasCollectible(COLLECTIBLE_RESTOCK) || game.IsGreedMode())) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the shop's restock"); + return true; +} + +// The collectible part of 006e7dc0: a bought item rings like a pickup, 1up and the mushrooms and Super Bandage have +// their own sound, and any other item sounds by its room (the boss rooms, the treasure rooms and library, the shop, +// the devil's rooms, or any other). +void Entity_Pickup::collectible_sound_play() +{ + SFXManager& sounds = g_manager->sfxManager; + int sound = SOUND_CHOIR_UNLOCK; + SoundPlay play = {}; + + if (HasEntityFlags(FLAG_NO_DEATH_TRIGGER)) sound = SOUND_SHELLGAME; + else if (subtype < 0) reconstruction_missing("Entity_Pickup::PlayPickupSound 006e7dc0: a procedural item"); + else if (subtype == COLLECTIBLE_GLITCHED_GFUEL && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) + reconstruction_missing("Entity_Pickup::PlayPickupSound 006e7dc0: the G FUEL!"); + else if (subtype == COLLECTIBLE_1UP || subtype == COLLECTIBLE_MAGIC_MUSHROOM || subtype == COLLECTIBLE_MEGA_MUSH || + subtype == COLLECTIBLE_MINI_MUSH || subtype == COLLECTIBLE_SUPER_BANDAGE) + { + sound = subtype == COLLECTIBLE_SUPER_BANDAGE ? SOUND_VAMP_GULP : SOUND_1UP; + play.frameDelay = ONE_UP_FRAME_DELAY; + } + else + { + Room& room = *g_game->room; + bool isDevil = room.roomType == ROOM_DEVIL || room.roomType == ROOM_BLACK_MARKET || + (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE); + play.volume = ITEM_SOUND_HALF_VOLUME; + if (room.roomType == ROOM_BOSS || room.roomType == ROOM_MINIBOSS) sound = SOUND_POWERUP2; + else if (room.roomType == ROOM_TREASURE || room.roomType == ROOM_LIBRARY) sound = SOUND_POWERUP1; + else if (room.roomType == ROOM_SHOP) sound = SOUND_POWERUP3; + else if (isDevil) + { + sound = SOUND_DEVILROOM_DEAL; + play.volume = 1; + } + } + seed_fart_sound_override(&sound); + sounds.Play(sound, play); +} + +// 009a2d20 (HUD::ShowItemText, with ShowStackedItemTextCustom 009a34a0) Shows a taken item's name and description in +// the first free banner of the stack. Monster Manual is misspelled a third of the time. Birthright's character text, +// the seed that scrambles text and TMTRAINER's pattern stop the game until reached. +void item_text_show(HUD& hud, Entity_Player* player, ItemConfig_Item* item) +{ + std::string name = item->GetLocalizedName(LANGUAGE_CURRENT); + std::string description = item->description_get(); + + if (item->IsCollectible() && item->id == COLLECTIBLE_MONSTER_MANUAL && Random() % MONSTER_MANUEL_ODDS == 0 && + name == "Monster Manual") + name = "Monster Manuel"; + if (item->IsCollectible() && item->id == COLLECTIBLE_BIRTHRIGHT && player) + reconstruction_missing("HUD::ShowItemText 009a2d20: Birthright's character text"); + if (g_game->seedEffects.HasSeedEffect(SEED_DYSLEXIA)) + reconstruction_missing("HUD::ShowItemText 009a2d20: the scrambled text"); + if (item->id == COLLECTIBLE_TMTRAINER) reconstruction_missing("HUD::ShowItemText 009a2d20: TMTRAINER's pattern"); + + for (HUD_Message& message : hud.messageStack) + if (!message.isShowing) return message.Show(name.c_str(), description.c_str(), true, false); +} + +// 006edfa0 Turns a cycling pedestal to its next item every 30 frames (every 6 with four or more, every frame with +// eight), every frame while paused, or at once when forced. An emptied pedestal stops cycling. Only the wait is +// reconstructed: a turn stops the game until reached. +void Entity_Pickup::update_cycle_collectible(bool isForce) +{ + constexpr int CYCLE_FRAMES_FEW = 30; + constexpr int CYCLE_FRAMES_MANY = 6; + constexpr uint32_t CYCLE_MANY = 4; + + if (cycleCollectibleCount == 0) return; + int frequency = cycleCollectibleCount >= CYCLE_COLLECTIBLE_LIMIT ? 1 + : cycleCollectibleCount < CYCLE_MANY ? CYCLE_FRAMES_FEW + : CYCLE_FRAMES_MANY; + if (subtype == 0) + { + cycleCollectibleCount = 0; + return; + } + bool isTurn = isForce || (g_game->frameCount - spawnFrame >= 1 && IsFrame(frequency, 0)) || g_game->IsPaused(); + if (isTurn) reconstruction_missing("Entity_Pickup::update_cycle_collectible 006edfa0 (a turn)"); +} diff --git a/src/item_pickup.h b/src/item_pickup.h new file mode 100644 index 0000000..7a0a94c --- /dev/null +++ b/src/item_pickup.h @@ -0,0 +1,9 @@ +#pragma once + +#include "classes.h" + +class HUD; +struct Entity_Player; +struct ItemConfig_Item; + +void item_text_show(HUD& hud, Entity_Player* player, ItemConfig_Item* item); diff --git a/src/item_pool.cpp b/src/item_pool.cpp index bdf9e27..2cbc9fa 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -132,7 +132,6 @@ constexpr int PILLEFFECT_FULL_HEALTH = 5; constexpr int PILLEFFECT_HEALTH_DOWN = 6; constexpr int PILLEFFECT_HEALTH_UP = 7; constexpr int PILLEFFECT_I_FOUND_PILLS = 8; -constexpr int PILL_GET_COLOR_CALLBACK = 9; // The effect class each shuffled color slot must have, or -1 for any. constexpr int PILL_SLOT_CLASSES[PILL_COLOR_SLOTS - 1] = {3, 3, 3, 3, 2, 1, 0, -1, -1, 3, 2, 1, -1, -1}; // PHD's good side of a bad pill (0x00b6a240), and False PHD's bad side of a good one (its jump table at 0x00734c40). @@ -539,7 +538,8 @@ int ItemPool::GetCollectible(ItemPoolType poolType, uint32_t drawSeed, uint32_t g_game->room->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_CHAOS); int pool = isChaos ? get_chaos_pool(poolRng) : poolType; lastPool = pool; - if (int item = (int)FUN_00865dc0(poolType, isDecrease, drawSeed)) return item; + LuaCollectibleDraw luaDraw = {.poolType = poolType, .seed = drawSeed, .isDecrease = isDecrease}; + if (int item = lua_engine_get().PreGetCollectible(luaDraw)) return item; RNG dailyRng = rng_make(drawSeed, DAILY_SHIFT); if (daily == DAILY_APPLE_BOSSES && poolType == POOL_BOSS) return COLLECTIBLE_APPLE; @@ -604,7 +604,8 @@ int ItemPool::GetCollectible(ItemPoolType poolType, uint32_t drawSeed, uint32_t result = COLLECTIBLE_HOST_HAT; } - int overridden = (int)FUN_00865f10(result, poolType, isDecrease, drawSeed); + luaDraw.collectible = result; + int overridden = lua_engine_get().PostGetCollectible(luaDraw); return overridden ? overridden : result; } @@ -843,7 +844,7 @@ uint32_t ItemPool::GetTrinket(TrinketDraw draw) if (draw == TRINKET_DRAW_TAKE) numAvailableTrinkets--; trinket = trinketPoolItems[*found].id; } - if (uint32_t overridden = FUN_008658c0(trinket, &trinketPoolRNG._seed)) return overridden; + if (uint32_t overridden = lua_engine_get().GetTrinket((int)trinket, trinketPoolRNG)) return overridden; if (!g_manager->persistentGameData.Unlocked(ACHIEVEMENT_GOLDEN_TRINKETS)) return trinket; bool isGolden = rng_make(rng._seed, GOLDEN_SHIFT).Next() % GOLDEN_TRINKET_ODDS == 0 || @@ -896,7 +897,7 @@ int ItemPool::GetPill(uint32_t drawSeed) if (rng.Next() % PILL_HORSE_ODDS == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_HORSE_PILLS)) color |= PILL_HORSE; - int overridden = (int)FUN_00865c80(PILL_GET_COLOR_CALLBACK, drawSeed); + int overridden = lua_engine_get().GetPillColor(drawSeed); return overridden ? overridden : color; } @@ -936,7 +937,7 @@ int ItemPool::GetPillEffect(uint32_t pillColor, Entity_Player* player) effect = isFalsePhd ? PILLEFFECT_I_FOUND_PILLS : PILLEFFECT_HEALTH_UP; } - int overridden = static_cast(g_luaEngine)->GetPillEffect(effect, color); + int overridden = lua_engine_get().GetPillEffect(effect, color); return overridden != -1 ? overridden : effect; } diff --git a/src/level.cpp b/src/level.cpp index 3b4464e..ba9f1dc 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -483,7 +483,7 @@ void Level::Init(bool isResetLilPortalRoom) break; } } - curses = FUN_00864ae0(curses); + curses = lua_engine_get().PostCurseEval(curses); } if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_CURSED) curses |= SPECIAL_DAILY_CURSES; @@ -567,7 +567,7 @@ void Level::Init(bool isResetLilPortalRoom) room->camera->position_center(); room->camera->DoUpdate(false); TextureCache::Purge(); - static_cast(g_luaEngine)->PostNewLevel(); + lua_engine_get().PostNewLevel(); isLevelGenerating = false; } @@ -2499,7 +2499,7 @@ void Level::load_room() if (isUpdated && game.frameCount == entity.spawnFrame) entity.Update(); } - static_cast(g_luaEngine)->PostNewRoom(); + lua_engine_get().PostNewRoom(); if (!game.deathmatchManager.is_active()) return; game.deathmatchManager.type->Init(); game.dizzyTargetIntensity = 0; diff --git a/src/lua_callbacks.cpp b/src/lua_callbacks.cpp new file mode 100644 index 0000000..5fd7e96 --- /dev/null +++ b/src/lua_callbacks.cpp @@ -0,0 +1,513 @@ +#include "lua_engine.h" +#include "classes.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include +#include + +extern "C" +{ +#include "lua.h" +} + +constexpr int CALLBACK_PARAM_NONE = -1; +constexpr int PILL_EFFECT_UNCHANGED = -1; + +// A game object a callback hands to Lua by pointer, and the class whose metatable it gets. +struct LuaObject +{ + void* object; + LuaClass luaClass; +}; + +// One run of a callback: the name its errors log, its id, and the parameter mods filter it by. +struct CallbackRun +{ + const char* name; + LuaCallback id; + int param = CALLBACK_PARAM_NONE; +}; + +// Stops where a mod has a function for a callback LuaEngine does not run yet. +void lua_callback_check(LuaCallback callback, const char* name) +{ + if (lua_engine_get().enabledCallbacks[callback]) reconstruction_missing(name); +} + +// Pushes a callback argument: integers and booleans as themselves. +static void value_push(lua_State* state, int value) +{ + lua_pushinteger(state, value); +} + +static void value_push(lua_State* state, unsigned int value) +{ + lua_pushinteger(state, value); +} + +static void value_push(lua_State* state, bool value) +{ + lua_pushboolean(state, value); +} + +// Pushes an object as a userdata holding its pointer, with its class's metatable, or nil for none. +static void value_push(lua_State* state, LuaObject value) +{ + if (!value.object) return lua_pushnil(state); + *(void**)lua_newuserdata(state, sizeof(void*)) = value.object; + lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(value.luaClass)); + lua_setmetatable(state, -2); +} + +// Pushes a copy Lua owns, as LuaBridge's UserdataValue: the copy's pointer first, as an object's, then the copy. +template +static void copy_push(lua_State* state, const T& value, LuaClass luaClass) +{ + static_assert(std::is_trivially_destructible_v); + void** block = (void**)lua_newuserdata(state, sizeof(void*) + sizeof(T)); + *block = new (block + 1) T(value); + lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(luaClass)); + lua_setmetatable(state, -2); +} + +static void value_push(lua_State* state, const RNG& value) +{ + copy_push(state, value, LUA_CLASS_RNG); +} + +static void value_push(lua_State* state, const Vector& value) +{ + copy_push(state, value, LUA_CLASS_VECTOR); +} + +// Calls _RunCallback with a callback's id, its filter parameter and its arguments when a mod added a function for it, +// leaving its one result on the stack. Whether it ran, false without a function or on an error, which is logged. +// The callers, result readers and error throws the original instantiates per callback are this and its readers +// (00872980, 00872c60, 00873470, 00873980, 00873d00, 00873fc0, 00874120, 00874210, 00874310, 00874a10, 00874f60) +// (0085c080, 008727d0, 0086130e, 00861225, 00861d96, 00861e7f, 008623a6, 0086248f, 008628b6, 0086299f, 00864453) +// (0086453c, 00865bbc, 00872a20, 00872b10, 00872ff0, 008730e0, 00873890, 00873ac0, 00873bb0, 00873e40, 008746b0) +// (00874860, 00874910, 00874ac0, 00874d20, 00874dd0, 00874e90, 00865a04, 0085bfd0, 0085bff0, 0085c270, 00873f40), +// and their catches log through lua_error_log +// (00860ea3, 008611da, 0086191f, 00861d4b, 0086235b, 0086286b, 00862ea4, 008632e1) +// (00863706, 00863b6a, 00863e31, 00863f1e, 008640de, 00864408, 00864f6e, 00865b69, 008661cc, 00860826, 0086090e) +// (00860a70, 00860b4b, 00860c36, 00860d1e, 008613bf, 0086149f, 00861587, 00862a4c, 00862b2f, 00862cb8, 00862f8c) +// (0086306c, 00863154, 0086354b, 00863fff, 00864a6a, 00864bb8, 00864d16, 00865209, 008652e9, 00865424, 008659a7) +// (00865d53, 00865e99, 00865fe8, 008660ec). +template +static bool callback_run(LuaEngine& engine, CallbackRun run, Args... args) +{ + if (!engine.enabledCallbacks[run.id]) return false; + lua_State* state = engine.state; + + lua_rawgeti(state, LUA_REGISTRYINDEX, engine.runCallbackRef); + value_push(state, (int)run.id); + value_push(state, run.param); + (value_push(state, args), ...); + if (lua_pcall(state, sizeof...(Args) + 2, 1, 0) == LUA_OK) return true; + + lua_error_log(state, run.name); + return false; +} + +// Runs a callback whose result the game ignores. +template +static void callback_notify(LuaEngine& engine, CallbackRun run, Args... args) +{ + if (callback_run(engine, run, args...)) lua_pop(engine.state, 1); +} + +// Runs a callback whose result is an integer that replaces fallback. +// The original aborts on a result that is neither nil nor an integer. This keeps fallback instead. +template +static int callback_integer_run(LuaEngine& engine, CallbackRun run, int fallback, Args... args) +{ + if (!callback_run(engine, run, args...)) return fallback; + + int isInteger = 0; + lua_Integer result = lua_tointegerx(engine.state, -1, &isInteger); + lua_pop(engine.state, 1); + return isInteger ? (int)result : fallback; +} + +// Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing. +static LuaResult collision_run(LuaEngine& engine, CallbackRun run, LuaObject entity, Entity* collider, bool isLow) +{ + if (!callback_run(engine, run, entity, LuaObject{collider, LUA_CLASS_ENTITY}, isLow)) return LUA_RESULT_NIL; + + LuaResult result = lua_isnil(engine.state, -1) ? LUA_RESULT_NIL + : lua_toboolean(engine.state, -1) ? LUA_RESULT_TRUE + : LUA_RESULT_FALSE; + lua_pop(engine.state, 1); + return result; +} + +// Sets value to a field of the table on top of the stack, when the field is not nil. +static void field_read(lua_State* state, const char* key, bool& value) +{ + lua_getfield(state, -1, key); + if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1); + lua_pop(state, 1); +} + +// Sets value to an element of the table on top of the stack, when the element is not nil. +// The original aborts on an element that is not an integer. This keeps the value instead. +template +static void element_read(lua_State* state, int key, T& value) +{ + int isInteger = 0; + lua_geti(state, -1, key); + lua_Integer element = lua_tointegerx(state, -1, &isInteger); + if (isInteger) value = (T)element; + lua_pop(state, 1); +} + +// Pops a callback's result, and when it is a table sets values in order to its elements 1, 2 ... +template +static void elements_pop(lua_State* state, T&... values) +{ + int key = 1; + if (lua_istable(state, -1)) (element_read(state, key++, values), ...); + lua_pop(state, 1); +} + +// 00862250 Runs MC_PRE_BOMB_COLLISION, filtered by the bomb's variant. +LuaResult LuaEngine::PreBombCollision(Entity_Bomb* bomb, Entity* collider, bool isLow) +{ + CallbackRun run = {"PreBombCollision", MC_PRE_BOMB_COLLISION, (int)bomb->variant}; + return collision_run(*this, run, {bomb, LUA_CLASS_BOMB}, collider, isLow); +} + +// 008610d0 Runs MC_PRE_FAMILIAR_COLLISION, filtered by the familiar's variant. +LuaResult LuaEngine::PreFamiliarCollision(Entity_Familiar* familiar, Entity* collider, bool isLow) +{ + CallbackRun run = {"PreFamiliarCollision", MC_PRE_FAMILIAR_COLLISION, (int)familiar->variant}; + return collision_run(*this, run, {familiar, LUA_CLASS_FAMILIAR}, collider, isLow); +} + +// 00861c40 Runs MC_PRE_KNIFE_COLLISION, filtered by the knife's subtype. +LuaResult LuaEngine::PreKnifeCollision(Entity_Knife* knife, Entity* collider, bool isLow) +{ + CallbackRun run = {"PreKnifeCollision", MC_PRE_KNIFE_COLLISION, (int)knife->subtype}; + return collision_run(*this, run, {knife, LUA_CLASS_KNIFE}, collider, isLow); +} + +// 00860d70 Runs MC_PRE_NPC_COLLISION, filtered by the NPC's type. +LuaResult LuaEngine::PreNPCCollision(Entity_NPC* npc, Entity* collider, bool isLow) +{ + CallbackRun run = {"PreNPCCollision", MC_PRE_NPC_COLLISION, (int)npc->type}; + return collision_run(*this, run, {npc, LUA_CLASS_NPC}, collider, isLow); +} + +// 008631b0 Runs MC_PRE_PICKUP_COLLISION, filtered by the pickup's variant. +LuaResult LuaEngine::PrePickupCollision(Entity_Pickup* pickup, Entity* collider, bool isLow) +{ + CallbackRun run = {"PrePickupCollision", MC_PRE_PICKUP_COLLISION, (int)pickup->variant}; + return collision_run(*this, run, {pickup, LUA_CLASS_PICKUP}, collider, isLow); +} + +// 00864300 Runs MC_PRE_PLAYER_COLLISION, filtered by the player's variant. +LuaResult LuaEngine::PrePlayerCollide(Entity_Player* player, Entity* collider, bool isLow) +{ + CallbackRun run = {"PrePlayerCollision", MC_PRE_PLAYER_COLLISION, (int)player->variant}; + return collision_run(*this, run, {player, LUA_CLASS_PLAYER}, collider, isLow); +} + +// 00862760 Runs MC_PRE_PROJECTILE_COLLISION, filtered by the projectile's variant. +LuaResult LuaEngine::PreProjectileCollision(Entity_Projectile* projectile, Entity* collider, bool isLow) +{ + CallbackRun run = {"PreProjectileCollision", MC_PRE_PROJECTILE_COLLISION, (int)projectile->variant}; + return collision_run(*this, run, {projectile, LUA_CLASS_PROJECTILE}, collider, isLow); +} + +// 00862d70 Runs MC_PRE_TEAR_COLLISION, filtered by the tear's variant. +LuaResult LuaEngine::PreTearCollision(Entity_Tear* tear, Entity* collider, bool isLow) +{ + CallbackRun run = {"PreTearCollision", MC_PRE_TEAR_COLLISION, (int)tear->variant}; + return collision_run(*this, run, {tear, LUA_CLASS_TEAR}, collider, isLow); +} + +// 00865340 Runs MC_GET_CARD for a card the pools drew. The card a mod chose, or the drawn one. +int LuaEngine::GetCard(const LuaCardDraw& draw) +{ + return callback_integer_run(*this, {"GetCard", MC_GET_CARD}, draw.card, LuaObject{draw.rng, LUA_CLASS_RNG}, + draw.card, draw.isPlaying, draw.isRunes, draw.isOnlyRunes); +} + +// 00865c80 Runs MC_GET_PILL_COLOR for a pill drawn from seed. The color a mod chose, 0 to keep the drawn one. +// The original's first argument is an unused 9, and Lua gets only the seed, not the drawn color. +int LuaEngine::GetPillColor(uint32_t seed) +{ + return callback_integer_run(*this, {"GetPill", MC_GET_PILL_COLOR}, 0, seed); +} + +// 00865ad0 Runs MC_GET_PILL_EFFECT for the effect a pill color got. The effect a mod chose, -1 to keep it. +int LuaEngine::GetPillEffect(int pillEffect, int pillColor) +{ + CallbackRun run = {"GetPillEffect", MC_GET_PILL_EFFECT}; + return callback_integer_run(*this, run, PILL_EFFECT_UNCHANGED, pillEffect, pillColor); +} + +// 008658c0 Runs MC_GET_TRINKET for a trinket the pool drew, with a copy of the pool's RNG. The trinket a mod chose, 0 +// to keep the drawn one. +int LuaEngine::GetTrinket(int trinket, const RNG& rng) +{ + return callback_integer_run(*this, {"GetTrinket", MC_GET_TRINKET}, 0, trinket, rng); +} + +// 00864c30 Runs MC_INPUT_ACTION for a boolean input hook, filtered by the hook. What a mod answered, nothing when no +// mod did. +std::optional LuaEngine::InputAction(Entity* entity, int hook, int action) +{ + CallbackRun run = {"PreActionHookB", MC_INPUT_ACTION, hook}; + if (!callback_run(*this, run, LuaObject{entity, LUA_CLASS_ENTITY}, hook, action)) return std::nullopt; + + std::optional value; + if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1); + lua_pop(state, 1); + return value; +} + +// 00864ae0 Runs MC_POST_CURSE_EVAL for the curses a floor got. The curses a mod chose, or those. +int LuaEngine::PostCurseEval(int curses) +{ + return callback_integer_run(*this, {"PostCurseEval", MC_POST_CURSE_EVAL}, curses, curses); +} + +// 00865f10 Runs MC_POST_GET_COLLECTIBLE for the collectible a pool gave. The collectible a mod chose, 0 to keep it. +int LuaEngine::PostGetCollectible(const LuaCollectibleDraw& draw) +{ + CallbackRun run = {"PostGetCollectible", MC_POST_GET_COLLECTIBLE}; + return callback_integer_run(*this, run, 0, draw.collectible, draw.poolType, draw.isDecrease, draw.seed); +} + +// 00865dc0 Runs MC_PRE_GET_COLLECTIBLE before a pool draws. The collectible a mod chose, 0 to draw as usual. +int LuaEngine::PreGetCollectible(const LuaCollectibleDraw& draw) +{ + CallbackRun run = {"PreGetCollectible", MC_PRE_GET_COLLECTIBLE}; + return callback_integer_run(*this, run, 0, draw.poolType, draw.isDecrease, draw.seed); +} + +// 00860960 Runs MC_PRE_NPC_UPDATE, filtered by the NPC's type. Whether a mod skips the NPC's AI this frame. +bool LuaEngine::PreNPCUpdate(Entity_NPC* npc) +{ + CallbackRun run = {"PreNPCUpdate", MC_PRE_NPC_UPDATE, (int)npc->type}; + if (!callback_run(*this, run, LuaObject{npc, LUA_CLASS_NPC})) return false; + + bool isSkipped = lua_toboolean(state, -1); + lua_pop(state, 1); + return isSkipped; +} + +// 008646e0 Runs MC_PRE_ENTITY_SPAWN for a spawn. A table result replaces its type, variant, subtype and seed, in that +// order, with each element that is not nil. +void LuaEngine::Callback_PreEntitySpawn(EntitySpawn& spawn) +{ + if (!callback_run(*this, {"PreEntitySpawn", MC_PRE_ENTITY_SPAWN}, spawn.type, spawn.variant, spawn.subType, + spawn.position, spawn.velocity, LuaObject{spawn.spawner, LUA_CLASS_ENTITY}, spawn.seed)) + return; + elements_pop(state, spawn.type, spawn.variant, spawn.subType, spawn.seed); +} + +// 00863340 Runs MC_POST_PICKUP_SELECTION for the kind a pickup was given. A table result replaces its variant and +// subtype, in that order, with each element that is not nil. +void LuaEngine::PostPickupSelection(Entity_Pickup* pickup, int& variant, int& subType) +{ + CallbackRun run = {"PostPickupSelection", MC_POST_PICKUP_SELECTION}; + if (callback_run(*this, run, LuaObject{pickup, LUA_CLASS_PICKUP}, variant, subType)) + elements_pop(state, variant, subType); +} + +// 008638d0 Runs MC_USE_ITEM for an active item, filtered by its type. A table result sets Discharge, Remove and +// ShowAnim, any other result ShowAnim alone. Whether to show the use animation, false without a result. +bool LuaEngine::UseItem(LuaItemUse& use) +{ + CallbackRun run = {"PostUseItem", MC_USE_ITEM, use.collectibleType}; + if (!callback_run(*this, run, use.collectibleType, LuaObject{use.rng, LUA_CLASS_RNG}, + LuaObject{use.player, LUA_CLASS_PLAYER}, use.useFlags, use.activeSlot, use.customVarData)) + return false; + + bool isShowAnimation = false; + if (!lua_istable(state, -1)) isShowAnimation = lua_toboolean(state, -1); + else + { + field_read(state, "Discharge", use.isDischarge); + field_read(state, "Remove", use.isRemove); + field_read(state, "ShowAnim", isShowAnimation); + } + lua_pop(state, 1); + return isShowAnimation; +} + +// 00863e90 Runs MC_EVALUATE_CACHE for a player's stat, filtered by the cache flag. +void LuaEngine::EvaluateItems(Entity_Player* player, int cacheFlag) +{ + callback_notify(*this, {"PostEvaluateItems", MC_EVALUATE_CACHE, cacheFlag}, LuaObject{player, LUA_CLASS_PLAYER}, + cacheFlag); +} + +// 00861330 Runs MC_POST_EFFECT_INIT, filtered by the effect's variant. +void LuaEngine::PostEffectInit(Entity_Effect* effect) +{ + callback_notify(*this, {"PostEffectInit", MC_POST_EFFECT_INIT, (int)effect->variant}, + LuaObject{effect, LUA_CLASS_EFFECT}); +} + +// 008614f0 Runs MC_POST_EFFECT_RENDER with the render offset, filtered by the effect's variant. +void LuaEngine::PostEffectRender(Entity_Effect* effect, const Vector& offset) +{ + callback_notify(*this, {"PostEffectRender", MC_POST_EFFECT_RENDER, (int)effect->variant}, + LuaObject{effect, LUA_CLASS_EFFECT}, offset); +} + +// 00861410 Runs MC_POST_EFFECT_UPDATE, filtered by the effect's variant. +void LuaEngine::PostEffectUpdate(Entity_Effect* effect) +{ + callback_notify(*this, {"PostEffectUpdate", MC_POST_EFFECT_UPDATE, (int)effect->variant}, + LuaObject{effect, LUA_CLASS_EFFECT}); +} + +// 00866140 Runs MC_POST_ENTITY_KILL, filtered by the entity's type. +void LuaEngine::PostEntityKill(Entity* entity) +{ + callback_notify(*this, {"PostEntityKill", MC_POST_ENTITY_KILL, (int)entity->type}, + LuaObject{entity, LUA_CLASS_ENTITY}); +} + +// Runs MC_POST_ENTITY_REMOVE for Entity::ReleaseLuaRef, filtered by the entity's type. +void LuaEngine::PostEntityRemove(Entity* entity) +{ + callback_notify(*this, {"PostEntityRemove", MC_POST_ENTITY_REMOVE, (int)entity->type}, + LuaObject{entity, LUA_CLASS_ENTITY}); +} + +// 00863f70 Runs MC_POST_FIRE_TEAR for a tear a player fired. +void LuaEngine::PostFireTear(Entity_Tear* tear) +{ + callback_notify(*this, {"PostFireTear", MC_POST_FIRE_TEAR}, LuaObject{tear, LUA_CLASS_TEAR}); +} + +// 00864ee0 Runs MC_POST_GAME_STARTED with whether the run continues a saved one. +void LuaEngine::PostGameStart(bool isContinued) +{ + callback_notify(*this, {"PostGameStart", MC_POST_GAME_STARTED}, isContinued); +} + +// 00861890 Runs MC_POST_KNIFE_INIT, filtered by the knife's subtype. +void LuaEngine::PostKnifeInit(Entity_Knife* knife) +{ + callback_notify(*this, {"PostKnifeInit", MC_POST_KNIFE_INIT, (int)knife->subtype}, + LuaObject{knife, LUA_CLASS_KNIFE}); +} + +// 00865260 Runs MC_POST_NEW_LEVEL once a floor is generated and its first room entered. +void LuaEngine::PostNewLevel() +{ + callback_notify(*this, {"PostLevelLoad", MC_POST_NEW_LEVEL}); +} + +// 00865180 Runs MC_POST_NEW_ROOM once a room is loaded. +void LuaEngine::PostNewRoom() +{ + callback_notify(*this, {"PostRoomLoad", MC_POST_NEW_ROOM}); +} + +// 00860c90 Runs MC_POST_NPC_DEATH, filtered by the NPC's type. +void LuaEngine::PostNPCDeath(Entity_NPC* npc) +{ + callback_notify(*this, {"PostNPCDeath", MC_POST_NPC_DEATH, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}); +} + +// 00860880 Runs MC_POST_NPC_INIT, filtered by the NPC's type. +void LuaEngine::PostNPCInit(Entity_NPC* npc) +{ + callback_notify(*this, {"PostNPCInit", MC_POST_NPC_INIT, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}); +} + +// 00860ba0 Runs MC_POST_NPC_RENDER with the render offset, filtered by the NPC's type. +void LuaEngine::PostNPCRender(Entity_NPC* npc, const Vector& offset) +{ + callback_notify(*this, {"PostNPCRender", MC_POST_NPC_RENDER, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}, + offset); +} + +// 00860ac0 Runs MC_NPC_UPDATE after an NPC's AI, filtered by the NPC's type. +void LuaEngine::PostNPCUpdate(Entity_NPC* npc) +{ + callback_notify(*this, {"PostNPCUpdate", MC_NPC_UPDATE, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}); +} + +// 00862f00 Runs MC_POST_PICKUP_INIT, filtered by the pickup's variant. +void LuaEngine::PostPickupInit(Entity_Pickup* pickup) +{ + callback_notify(*this, {"PostPickupInit", MC_POST_PICKUP_INIT, (int)pickup->variant}, + LuaObject{pickup, LUA_CLASS_PICKUP}); +} + +// 008630c0 Runs MC_POST_PICKUP_RENDER with the render offset, filtered by the pickup's variant. +void LuaEngine::PostPickupRender(Entity_Pickup* pickup, const Vector& offset) +{ + callback_notify(*this, {"PostPickupRender", MC_POST_PICKUP_RENDER, (int)pickup->variant}, + LuaObject{pickup, LUA_CLASS_PICKUP}, offset); +} + +// 00862fe0 Runs MC_POST_PICKUP_UPDATE, filtered by the pickup's variant. +void LuaEngine::PostPickupUpdate(Entity_Pickup* pickup) +{ + callback_notify(*this, {"PostPickupUpdate", MC_POST_PICKUP_UPDATE, (int)pickup->variant}, + LuaObject{pickup, LUA_CLASS_PICKUP}); +} + +// 00864050 Runs MC_POST_PLAYER_INIT, filtered by the player's variant. +void LuaEngine::PostPlayerInit(Entity_Player* player) +{ + callback_notify(*this, {"PostPlayerInit", MC_POST_PLAYER_INIT, (int)player->variant}, + LuaObject{player, LUA_CLASS_PLAYER}); +} + +// 00863680 Runs MC_POST_RENDER after the game renders. +void LuaEngine::PostRender() +{ + callback_notify(*this, {"PostRender", MC_POST_RENDER}); +} + +// 008629c0 Runs MC_POST_TEAR_INIT, filtered by the tear's variant. +void LuaEngine::PostTearInit(Entity_Tear* tear) +{ + callback_notify(*this, {"PostTearInit", MC_POST_TEAR_INIT, (int)tear->variant}, LuaObject{tear, LUA_CLASS_TEAR}); +} + +// 00862b80 Runs MC_POST_TEAR_RENDER with the render offset, filtered by the tear's variant. +void LuaEngine::PostTearRender(Entity_Tear* tear, const Vector& offset) +{ + callback_notify(*this, {"PostTearRender", MC_POST_TEAR_RENDER, (int)tear->variant}, + LuaObject{tear, LUA_CLASS_TEAR}, offset); +} + +// 00862aa0 Runs MC_POST_TEAR_UPDATE, filtered by the tear's variant. +void LuaEngine::PostTearUpdate(Entity_Tear* tear) +{ + callback_notify(*this, {"PostTearUpdate", MC_POST_TEAR_UPDATE, (int)tear->variant}, + LuaObject{tear, LUA_CLASS_TEAR}); +} + +// 008607a0 Runs MC_POST_UPDATE after the game updates. +void LuaEngine::PostUpdate() +{ + callback_notify(*this, {"PostUpdate", MC_POST_UPDATE}); +} + +// 00863da0 Runs MC_USE_PILL for a pill effect, filtered by it. +void LuaEngine::UsePill(int pillEffect, Entity_Player* player, unsigned int useFlags) +{ + callback_notify(*this, {"PostUsePillEffect", MC_USE_PILL, pillEffect}, pillEffect, + LuaObject{player, LUA_CLASS_PLAYER}, useFlags); +} diff --git a/src/lua_callbacks.h b/src/lua_callbacks.h new file mode 100644 index 0000000..2b502f9 --- /dev/null +++ b/src/lua_callbacks.h @@ -0,0 +1,129 @@ +#pragma once + +#include + +struct Entity_Player; +struct RNG; + +// The callbacks the game runs mods' functions for, by their ModCallbacks ids in enums.lua. +enum LuaCallback +{ + MC_NPC_UPDATE, + MC_POST_UPDATE, + MC_POST_RENDER, + MC_USE_ITEM, + MC_POST_PEFFECT_UPDATE, + MC_USE_CARD, + MC_FAMILIAR_UPDATE, + MC_FAMILIAR_INIT, + MC_EVALUATE_CACHE, + MC_POST_PLAYER_INIT, + MC_USE_PILL, + MC_ENTITY_TAKE_DMG, + MC_POST_CURSE_EVAL, + MC_INPUT_ACTION, + MC_LEVEL_GENERATOR, + MC_POST_GAME_STARTED, + MC_POST_GAME_END, + MC_PRE_GAME_EXIT, + MC_POST_NEW_LEVEL, + MC_POST_NEW_ROOM, + MC_GET_CARD, + MC_GET_SHADER_PARAMS, + MC_EXECUTE_CMD, + MC_PRE_USE_ITEM, + MC_PRE_ENTITY_SPAWN, + MC_POST_FAMILIAR_RENDER, + MC_PRE_FAMILIAR_COLLISION, + MC_POST_NPC_INIT, + MC_POST_NPC_RENDER, + MC_POST_NPC_DEATH, + MC_PRE_NPC_COLLISION, + MC_POST_PLAYER_UPDATE, + MC_POST_PLAYER_RENDER, + MC_PRE_PLAYER_COLLISION, + MC_POST_PICKUP_INIT, + MC_POST_PICKUP_UPDATE, + MC_POST_PICKUP_RENDER, + MC_POST_PICKUP_SELECTION, + MC_PRE_PICKUP_COLLISION, + MC_POST_TEAR_INIT, + MC_POST_TEAR_UPDATE, + MC_POST_TEAR_RENDER, + MC_PRE_TEAR_COLLISION, + MC_POST_PROJECTILE_INIT, + MC_POST_PROJECTILE_UPDATE, + MC_POST_PROJECTILE_RENDER, + MC_PRE_PROJECTILE_COLLISION, + MC_POST_LASER_INIT, + MC_POST_LASER_UPDATE, + MC_POST_LASER_RENDER, + MC_POST_KNIFE_INIT, + MC_POST_KNIFE_UPDATE, + MC_POST_KNIFE_RENDER, + MC_PRE_KNIFE_COLLISION, + MC_POST_EFFECT_INIT, + MC_POST_EFFECT_UPDATE, + MC_POST_EFFECT_RENDER, + MC_POST_BOMB_INIT, + MC_POST_BOMB_UPDATE, + MC_POST_BOMB_RENDER, + MC_PRE_BOMB_COLLISION, + MC_POST_FIRE_TEAR, + MC_PRE_GET_COLLECTIBLE, + MC_POST_GET_COLLECTIBLE, + MC_GET_PILL_COLOR, + MC_GET_PILL_EFFECT, + MC_GET_TRINKET, + MC_POST_ENTITY_REMOVE, + MC_POST_ENTITY_KILL, + MC_PRE_NPC_UPDATE, + MC_PRE_SPAWN_CLEAN_AWARD, + MC_PRE_ROOM_ENTITY_SPAWN, + MC_PRE_ENTITY_DEVOLVE, + MC_PRE_MOD_UNLOAD +}; + +constexpr int LUA_CALLBACK_COUNT = MC_PRE_MOD_UNLOAD + 1; + +// What a callback returned that can be true, false or nothing, as the game's Pre*Collision checks read it. +enum LuaResult +{ + LUA_RESULT_FALSE = -1, + LUA_RESULT_NIL, + LUA_RESULT_TRUE +}; + +// A card draw as MC_GET_CARD sees it: the card the pools gave and the kinds the draw allows. +struct LuaCardDraw +{ + RNG* rng = nullptr; + int card = 0; + bool isOnlyRunes = false; + bool isPlaying = false; + bool isRunes = false; +}; + +// A collectible draw as MC_PRE and MC_POST_GET_COLLECTIBLE see it. The pre callback has no collectible yet. +struct LuaCollectibleDraw +{ + int collectible = 0; + int poolType = 0; + uint32_t seed = 0; + bool isDecrease = false; +}; + +// An active item's use as MC_USE_ITEM sees it. A table result sets isDischarge and isRemove when it has their keys. +struct LuaItemUse +{ + Entity_Player* player = nullptr; + RNG* rng = nullptr; + int activeSlot = 0; + int collectibleType = 0; + int customVarData = 0; + unsigned int useFlags = 0; + bool isDischarge = false; + bool isRemove = false; +}; + +void lua_callback_check(LuaCallback callback, const char* name); diff --git a/src/lua_engine.cpp b/src/lua_engine.cpp index 39d4cd0..29d3e9f 100644 --- a/src/lua_engine.cpp +++ b/src/lua_engine.cpp @@ -1,14 +1,6 @@ #include "lua_engine.h" #include "classes.h" #include "data.h" -#include "entity_bomb.h" -#include "entity_familiar.h" -#include "entity_knife.h" -#include "entity_npc.h" -#include "entity_pickup.h" -#include "entity_player.h" -#include "entity_projectile.h" -#include "entity_tear.h" #include "game.h" #include "manager.h" #include "platform.h" @@ -43,7 +35,6 @@ constexpr const char* UNLOAD_MOD = "_UnloadMod"; constexpr int API_VERSION_NONE = -1; constexpr int API_VERSION_CURRENT = 1; -constexpr int PILL_EFFECT_UNCHANGED = -1; constexpr int GC_COOLDOWN_FRAMES = 600; constexpr int GC_SHRINK_DIVISOR = 100; constexpr int GC_SHRINK_MIN = 10; @@ -58,21 +49,6 @@ constexpr luaL_Reg SANDBOX_LIBRARIES[] = { {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_UTF8LIBNAME, luaopen_utf8}, {LUA_DBLIBNAME, luaopen_debug}}; -// A game object a callback hands to Lua by pointer, and the class whose metatable it gets. -struct LuaObject -{ - void* object; - LuaClass luaClass; -}; - -// One run of a callback: the name its errors log, its id, and the parameter mods filter it by (-1 for none). -struct CallbackRun -{ - const char* name; - LuaCallback id; - int param = -1; -}; - // One distinct address per class, the registry keys of their metatables, as LuaBridge's class keys are. static std::array classKeys; @@ -81,105 +57,18 @@ const void* lua_class_key(LuaClass luaClass) return &classKeys[luaClass]; } -// Stops where a mod has a function for a callback LuaEngine does not run yet. -void lua_callback_check(int callback, const char* name) +// Logs the error a failed call left on top of the stack, popping it, and shows it on the console once a game exists. +// The original leaves the message on the stack. +void lua_error_log(lua_State* state, const char* name) { - if (static_cast(g_luaEngine)->enabledCallbacks[callback]) reconstruction_missing(name); -} - -// Pushes a callback argument: integers and booleans as themselves. -static void value_push(lua_State* state, int value) -{ - lua_pushinteger(state, value); -} - -static void value_push(lua_State* state, unsigned int value) -{ - lua_pushinteger(state, value); -} - -static void value_push(lua_State* state, bool value) -{ - lua_pushboolean(state, value); -} - -// Pushes an object as a userdata holding its pointer, with its class's metatable, or nil for none. -static void value_push(lua_State* state, LuaObject value) -{ - if (!value.object) return lua_pushnil(state); - *(void**)lua_newuserdata(state, sizeof(void*)) = value.object; - lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(value.luaClass)); - lua_setmetatable(state, -2); -} - -// The message a failed call left on top of the stack, popped. The original leaves it there. -static std::string error_pop(lua_State* state) -{ - if (lua_gettop(state) < 1) return "missing error"; - const char* text = lua_tostring(state, -1); + const char* text = lua_gettop(state) < 1 ? "missing error" : lua_tostring(state, -1); std::string error = text ? text : ""; - lua_pop(state, 1); - return error; -} + if (lua_gettop(state) > 0) lua_pop(state, 1); -// Logs a callback's error, and shows it on the console once a game exists. -static void error_log(const char* name, const std::string& error) -{ log_printf(LOG_INFO, "Error in \"%s\" call: %s\n", name, error.c_str()); if (g_game) g_game->console.print_format(CONSOLE_ERROR, "\"%s\" failed: %s\n", name, error.c_str()); } -// Calls _RunCallback with a callback's id, its filter parameter and its arguments when a mod added a function for it, -// leaving its one result on the stack. Whether it ran, false without a function or on an error, which is logged. -// The callers, result readers and error throws the original instantiates per callback are this and its readers -// (00872980, 00872c60, 00873470, 00873980, 00873d00, 00873fc0, 00874120, 00874210, 00874310, 00874a10, 00874f60) -// (0085c080, 008727d0, 0086130e, 00861225, 00861d96, 00861e7f, 008623a6, 0086248f, 008628b6, 0086299f, 00864453) -// (0086453c, 00865bbc), and their catches log through error_log (00860ea3, 008611da, 0086191f, 00861d4b, 0086235b) -// (0086286b, 00862ea4, 008632e1, 00863706, 00863b6a, 00863e31, 00863f1e, 008640de, 00864408, 00864f6e, 00865b69) -// (008661cc). -template -static bool callback_run(LuaEngine& engine, CallbackRun run, Args... args) -{ - if (!engine.enabledCallbacks[run.id]) return false; - lua_State* state = engine.state; - - lua_rawgeti(state, LUA_REGISTRYINDEX, engine.runCallbackRef); - value_push(state, (int)run.id); - value_push(state, run.param); - (value_push(state, args), ...); - if (lua_pcall(state, sizeof...(Args) + 2, 1, 0) == LUA_OK) return true; - - error_log(run.name, error_pop(state)); - return false; -} - -// Runs a callback whose result the game ignores. -template -static void callback_notify(LuaEngine& engine, CallbackRun run, Args... args) -{ - if (callback_run(engine, run, args...)) lua_pop(engine.state, 1); -} - -// Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing. -static LuaResult collision_run(LuaEngine& engine, CallbackRun run, LuaObject entity, Entity* collider, bool isLow) -{ - if (!callback_run(engine, run, entity, LuaObject{collider, LUA_CLASS_ENTITY}, isLow)) return LUA_RESULT_NIL; - - LuaResult result = lua_isnil(engine.state, -1) ? LUA_RESULT_NIL - : lua_toboolean(engine.state, -1) ? LUA_RESULT_TRUE - : LUA_RESULT_FALSE; - lua_pop(engine.state, 1); - return result; -} - -// Sets value to a field of the table on top of the stack, when the field is not nil. -static void field_read(lua_State* state, const char* key, bool& value) -{ - lua_getfield(state, -1, key); - if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1); - lua_pop(state, 1); -} - // A field of the package table, empty when it is not a string. static std::string package_field_get(lua_State* state, const char* field) { @@ -256,7 +145,7 @@ static void mod_unload(LuaEngine& engine, LuaMod& mod) lua_rawgeti(state, LUA_REGISTRYINDEX, engine.unloadModRef); lua_rawgeti(state, LUA_REGISTRYINDEX, mod.tableRef); if (lua_pcall(state, 1, 1, 0) == LUA_OK) lua_pop(state, 1); - else error_log(UNLOAD_MOD, error_pop(state)); + else lua_error_log(state, UNLOAD_MOD); luaL_unref(state, LUA_REGISTRYINDEX, mod.tableRef); mod.tableRef = LUA_REF_NONE; } @@ -416,152 +305,3 @@ int LuaEngine::Isaac_GetItemIdByName(std::string_view name) auto found = names.find(name); return found == names.end() ? -1 : found->second; } - -// 00862250 Runs MC_PRE_BOMB_COLLISION, filtered by the bomb's variant. -LuaResult LuaEngine::PreBombCollision(Entity_Bomb* bomb, Entity* collider, bool isLow) -{ - CallbackRun run = {"PreBombCollision", MC_PRE_BOMB_COLLISION, (int)bomb->variant}; - return collision_run(*this, run, {bomb, LUA_CLASS_BOMB}, collider, isLow); -} - -// 008610d0 Runs MC_PRE_FAMILIAR_COLLISION, filtered by the familiar's variant. -LuaResult LuaEngine::PreFamiliarCollision(Entity_Familiar* familiar, Entity* collider, bool isLow) -{ - CallbackRun run = {"PreFamiliarCollision", MC_PRE_FAMILIAR_COLLISION, (int)familiar->variant}; - return collision_run(*this, run, {familiar, LUA_CLASS_FAMILIAR}, collider, isLow); -} - -// 00861c40 Runs MC_PRE_KNIFE_COLLISION, filtered by the knife's subtype. -LuaResult LuaEngine::PreKnifeCollision(Entity_Knife* knife, Entity* collider, bool isLow) -{ - CallbackRun run = {"PreKnifeCollision", MC_PRE_KNIFE_COLLISION, (int)knife->subtype}; - return collision_run(*this, run, {knife, LUA_CLASS_KNIFE}, collider, isLow); -} - -// 00860d70 Runs MC_PRE_NPC_COLLISION, filtered by the NPC's type. -LuaResult LuaEngine::PreNPCCollision(Entity_NPC* npc, Entity* collider, bool isLow) -{ - CallbackRun run = {"PreNPCCollision", MC_PRE_NPC_COLLISION, (int)npc->type}; - return collision_run(*this, run, {npc, LUA_CLASS_NPC}, collider, isLow); -} - -// 008631b0 Runs MC_PRE_PICKUP_COLLISION, filtered by the pickup's variant. -LuaResult LuaEngine::PrePickupCollision(Entity_Pickup* pickup, Entity* collider, bool isLow) -{ - CallbackRun run = {"PrePickupCollision", MC_PRE_PICKUP_COLLISION, (int)pickup->variant}; - return collision_run(*this, run, {pickup, LUA_CLASS_PICKUP}, collider, isLow); -} - -// 00864300 Runs MC_PRE_PLAYER_COLLISION, filtered by the player's variant. -LuaResult LuaEngine::PrePlayerCollide(Entity_Player* player, Entity* collider, bool isLow) -{ - CallbackRun run = {"PrePlayerCollision", MC_PRE_PLAYER_COLLISION, (int)player->variant}; - return collision_run(*this, run, {player, LUA_CLASS_PLAYER}, collider, isLow); -} - -// 00862760 Runs MC_PRE_PROJECTILE_COLLISION, filtered by the projectile's variant. -LuaResult LuaEngine::PreProjectileCollision(Entity_Projectile* projectile, Entity* collider, bool isLow) -{ - CallbackRun run = {"PreProjectileCollision", MC_PRE_PROJECTILE_COLLISION, (int)projectile->variant}; - return collision_run(*this, run, {projectile, LUA_CLASS_PROJECTILE}, collider, isLow); -} - -// 00862d70 Runs MC_PRE_TEAR_COLLISION, filtered by the tear's variant. -LuaResult LuaEngine::PreTearCollision(Entity_Tear* tear, Entity* collider, bool isLow) -{ - CallbackRun run = {"PreTearCollision", MC_PRE_TEAR_COLLISION, (int)tear->variant}; - return collision_run(*this, run, {tear, LUA_CLASS_TEAR}, collider, isLow); -} - -// 00863e90 Runs MC_EVALUATE_CACHE for a player's stat, filtered by the cache flag. -void LuaEngine::EvaluateItems(Entity_Player* player, int cacheFlag) -{ - callback_notify(*this, {"PostEvaluateItems", MC_EVALUATE_CACHE, cacheFlag}, LuaObject{player, LUA_CLASS_PLAYER}, - cacheFlag); -} - -// 00865ad0 Runs MC_GET_PILL_EFFECT for the effect a pill color got. The effect a mod chose, -1 to keep it. -// The original aborts on a result that is not an integer. This keeps the effect instead. -int LuaEngine::GetPillEffect(int pillEffect, int pillColor) -{ - CallbackRun run = {"GetPillEffect", MC_GET_PILL_EFFECT}; - if (!callback_run(*this, run, pillEffect, pillColor)) return PILL_EFFECT_UNCHANGED; - - int isInteger = 0; - lua_Integer effect = lua_tointegerx(state, -1, &isInteger); - lua_pop(state, 1); - return isInteger ? (int)effect : PILL_EFFECT_UNCHANGED; -} - -// 00866140 Runs MC_POST_ENTITY_KILL, filtered by the entity's type. -void LuaEngine::PostEntityKill(Entity* entity) -{ - callback_notify(*this, {"PostEntityKill", MC_POST_ENTITY_KILL, (int)entity->type}, - LuaObject{entity, LUA_CLASS_ENTITY}); -} - -// 00864ee0 Runs MC_POST_GAME_STARTED with whether the run continues a saved one. -void LuaEngine::PostGameStart(bool isContinued) -{ - callback_notify(*this, {"PostGameStart", MC_POST_GAME_STARTED}, isContinued); -} - -// 00861890 Runs MC_POST_KNIFE_INIT, filtered by the knife's subtype. -void LuaEngine::PostKnifeInit(Entity_Knife* knife) -{ - callback_notify(*this, {"PostKnifeInit", MC_POST_KNIFE_INIT, (int)knife->subtype}, - LuaObject{knife, LUA_CLASS_KNIFE}); -} - -// 00865260 Runs MC_POST_NEW_LEVEL once a floor is generated and its first room entered. -void LuaEngine::PostNewLevel() -{ - callback_notify(*this, {"PostNewLevel", MC_POST_NEW_LEVEL}); -} - -// 00865180 Runs MC_POST_NEW_ROOM once a room is loaded. -void LuaEngine::PostNewRoom() -{ - callback_notify(*this, {"PostNewRoom", MC_POST_NEW_ROOM}); -} - -// 00864050 Runs MC_POST_PLAYER_INIT, filtered by the player's variant. -void LuaEngine::PostPlayerInit(Entity_Player* player) -{ - callback_notify(*this, {"PostPlayerInit", MC_POST_PLAYER_INIT, (int)player->variant}, - LuaObject{player, LUA_CLASS_PLAYER}); -} - -// 00863680 Runs MC_POST_RENDER after the game renders. -void LuaEngine::PostRender() -{ - callback_notify(*this, {"PostRender", MC_POST_RENDER}); -} - -// 008638d0 Runs MC_USE_ITEM for an active item, filtered by its type. A table result sets Discharge, Remove and -// ShowAnim, any other result ShowAnim alone. Whether to show the use animation, false without a result. -bool LuaEngine::UseItem(LuaItemUse& use) -{ - CallbackRun run = {"PostUseItem", MC_USE_ITEM, use.collectibleType}; - if (!callback_run(*this, run, use.collectibleType, LuaObject{use.rng, LUA_CLASS_RNG}, - LuaObject{use.player, LUA_CLASS_PLAYER}, use.useFlags, use.activeSlot, use.customVarData)) - return false; - - bool isShowAnimation = false; - if (!lua_istable(state, -1)) isShowAnimation = lua_toboolean(state, -1); - else - { - field_read(state, "Discharge", use.isDischarge); - field_read(state, "Remove", use.isRemove); - field_read(state, "ShowAnim", isShowAnimation); - } - lua_pop(state, 1); - return isShowAnimation; -} - -// 00863da0 Runs MC_USE_PILL for a pill effect, filtered by it. -void LuaEngine::UsePill(int pillEffect, Entity_Player* player, unsigned int useFlags) -{ - callback_notify(*this, {"PostUsePillEffect", MC_USE_PILL, pillEffect}, pillEffect, - LuaObject{player, LUA_CLASS_PLAYER}, useFlags); -} diff --git a/src/lua_engine.h b/src/lua_engine.h index 3c9e52f..6957432 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -1,14 +1,17 @@ #pragma once +#include "lua_callbacks.h" #include #include #include #include +#include #include #include struct Entity; struct Entity_Bomb; +struct Entity_Effect; struct Entity_Familiar; struct Entity_Knife; struct Entity_NPC; @@ -16,45 +19,23 @@ struct Entity_Pickup; struct Entity_Player; struct Entity_Projectile; struct Entity_Tear; +struct EntitySpawn; struct RNG; +struct Vector; struct lua_State; -constexpr int LUA_CALLBACK_COUNT = 74; constexpr int LUA_GC_HISTORY_SIZE = 10; constexpr int LUA_GC_STEP_MIN = 50; constexpr int LUA_MEMORY_HISTORY_SIZE = 128; // Lua's LUA_NOREF: a registry reference to nothing. constexpr int LUA_REF_NONE = -2; -// The built-in callbacks the game runs mods' functions for, by their ModCallbacks ids in enums.lua. -enum LuaCallback -{ - MC_POST_RENDER = 2, - MC_USE_ITEM = 3, - MC_EVALUATE_CACHE = 8, - MC_POST_PLAYER_INIT = 9, - MC_USE_PILL = 10, - MC_POST_GAME_STARTED = 15, - MC_POST_NEW_LEVEL = 18, - MC_POST_NEW_ROOM = 19, - MC_PRE_FAMILIAR_COLLISION = 26, - MC_PRE_NPC_COLLISION = 30, - MC_PRE_PLAYER_COLLISION = 33, - MC_PRE_PICKUP_COLLISION = 38, - MC_PRE_TEAR_COLLISION = 42, - MC_PRE_PROJECTILE_COLLISION = 46, - MC_POST_KNIFE_INIT = 50, - MC_PRE_KNIFE_COLLISION = 53, - MC_PRE_BOMB_COLLISION = 60, - MC_GET_PILL_EFFECT = 65, - MC_POST_ENTITY_KILL = 68 -}; - // The game classes callbacks hand objects of to Lua, each with the registry key of the metatable the API gives it. enum LuaClass { LUA_CLASS_ENTITY, LUA_CLASS_BOMB, + LUA_CLASS_EFFECT, LUA_CLASS_FAMILIAR, LUA_CLASS_KNIFE, LUA_CLASS_NPC, @@ -63,6 +44,7 @@ enum LuaClass LUA_CLASS_PROJECTILE, LUA_CLASS_RNG, LUA_CLASS_TEAR, + LUA_CLASS_VECTOR, LUA_CLASS_COUNT }; @@ -73,14 +55,6 @@ enum LuaMode LUA_MODE_DEBUG }; -// What a callback returned that can be true, false or nothing, as the game's Pre*Collision checks read it. -enum LuaResult -{ - LUA_RESULT_FALSE = -1, - LUA_RESULT_NIL, - LUA_RESULT_TRUE -}; - // A mod a script registered with RegisterMod, kept until that script runs again or Lua resets. struct LuaMod { @@ -91,19 +65,6 @@ struct LuaMod int tableRef = LUA_REF_NONE; }; -// An active item's use as MC_USE_ITEM sees it. A table result sets isDischarge and isRemove when it has their keys. -struct LuaItemUse -{ - Entity_Player* player = nullptr; - RNG* rng = nullptr; - int activeSlot = 0; - int collectibleType = 0; - int customVarData = 0; - unsigned int useFlags = 0; - bool isDischarge = false; - bool isRemove = false; -}; - // The mod scripting host: the Lua 5.3 state, the game's scripts in resources/scripts/, the mods scripts register, and // the entry points that run mods' callbacks. A callback runs only while enabledCallbacks has its id, which the API's // SetBuiltInCallbackState sets once a mod adds a function for it. Lua errors are logged, never fatal. @@ -146,18 +107,53 @@ struct LuaEngine LuaResult PreProjectileCollision(Entity_Projectile* projectile, Entity* collider, bool isLow); LuaResult PreTearCollision(Entity_Tear* tear, Entity* collider, bool isLow); - void EvaluateItems(Entity_Player* player, int cacheFlag); + int GetCard(const LuaCardDraw& draw); + int GetPillColor(uint32_t seed); int GetPillEffect(int pillEffect, int pillColor); + int GetTrinket(int trinket, const RNG& rng); + std::optional InputAction(Entity* entity, int hook, int action); + int PostCurseEval(int curses); + int PostGetCollectible(const LuaCollectibleDraw& draw); + int PreGetCollectible(const LuaCollectibleDraw& draw); + bool PreNPCUpdate(Entity_NPC* npc); + void Callback_PreEntitySpawn(EntitySpawn& spawn); + void PostPickupSelection(Entity_Pickup* pickup, int& variant, int& subType); + bool UseItem(LuaItemUse& use); + + void EvaluateItems(Entity_Player* player, int cacheFlag); + void PostEffectInit(Entity_Effect* effect); + void PostEffectRender(Entity_Effect* effect, const Vector& offset); + void PostEffectUpdate(Entity_Effect* effect); void PostEntityKill(Entity* entity); + void PostEntityRemove(Entity* entity); + void PostFireTear(Entity_Tear* tear); void PostGameStart(bool isContinued); void PostKnifeInit(Entity_Knife* knife); void PostNewLevel(); void PostNewRoom(); + void PostNPCDeath(Entity_NPC* npc); + void PostNPCInit(Entity_NPC* npc); + void PostNPCRender(Entity_NPC* npc, const Vector& offset); + void PostNPCUpdate(Entity_NPC* npc); + void PostPickupInit(Entity_Pickup* pickup); + void PostPickupRender(Entity_Pickup* pickup, const Vector& offset); + void PostPickupUpdate(Entity_Pickup* pickup); void PostPlayerInit(Entity_Player* player); void PostRender(); - bool UseItem(LuaItemUse& use); + void PostTearInit(Entity_Tear* tear); + void PostTearRender(Entity_Tear* tear, const Vector& offset); + void PostTearUpdate(Entity_Tear* tear); + void PostUpdate(); void UsePill(int pillEffect, Entity_Player* player, unsigned int useFlags); }; +extern void* g_luaEngine; + const void* lua_class_key(LuaClass luaClass); -void lua_callback_check(int callback, const char* name); +void lua_error_log(lua_State* state, const char* name); + +// The game's Lua engine, which Manager creates at startup. +inline LuaEngine& lua_engine_get() +{ + return *static_cast(g_luaEngine); +} diff --git a/src/main.cpp b/src/main.cpp index d182502..4d65581 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -66,7 +66,7 @@ int IsaacMain(int argc, uint8_t** argv) // frees and EOS tick have nothing to run, and the log is flushed with every message. Manager::Update(); g_manager->Render(); - if (g_game) static_cast(g_luaEngine)->gc_update(); + if (g_game) lua_engine_get().gc_update(); if (platform.isQuitRequested) break; platform.frame_wait(); } diff --git a/src/manager_input.cpp b/src/manager_input.cpp index 8023d6d..95657f8 100644 --- a/src/manager_input.cpp +++ b/src/manager_input.cpp @@ -98,8 +98,8 @@ void Manager::update_ingame_input() game.console.Update(); if (game.console.state != CONSOLE_CLOSED) return; - if (!manager.popupQueue.is_blocking() && game.gameOver._state != 0) game_over_input(game); - if (game.gameOver._state != 0) return; + if (!manager.popupQueue.is_blocking() && game.gameOver.state != GAME_OVER_HIDDEN) game_over_input(game); + if (game.gameOver.state != GAME_OVER_HIDDEN) return; game.leaderboard.update_input(); if (game.leaderboard.displayState != LEADERBOARD_HIDDEN) return; diff --git a/src/menu_options.cpp b/src/menu_options.cpp index 0b00878..5b4743e 100644 --- a/src/menu_options.cpp +++ b/src/menu_options.cpp @@ -513,7 +513,7 @@ void Menu_Options::language_reload() { MenuManager* menus = g_menuManager; ModManager& mods = g_manager->modManager; - LuaEngine& lua = *static_cast(g_luaEngine); + LuaEngine& lua = lua_engine_get(); if (menus) menus->unload_graphics(); pause_screen_unload_sprites(); diff --git a/src/mod_manager.cpp b/src/mod_manager.cpp index 10c07e5..10d4ff5 100644 --- a/src/mod_manager.cpp +++ b/src/mod_manager.cpp @@ -70,8 +70,6 @@ constexpr KAGE::Graphics::VertexAttribute MOD_SHADER_ATTRIBUTES[] = { constexpr int WRAP_CLAMP = 1; // The floats of the sprite vertex before RenderData: position, color and texture coordinates. constexpr int SHADER_RENDER_DATA_OFFSET = 9; -// ModCallbacks.MC_GET_SHADER_PARAMS, run with a shader's name for the table of its parameters. -constexpr LuaCallback MC_GET_SHADER_PARAMS = (LuaCallback)21; constexpr int CALLBACK_PARAM_NONE = -1; constexpr KColor SHADER_QUAD_WHITE = kcolor_rgba(1, 1, 1, 1); constexpr KColor SHADER_QUAD_COLOR_UNSET = kcolor_rgba(-1, -1, -1, -1); @@ -330,12 +328,6 @@ static void shaders_load(std::string& path, ModEntry& mod) } } -// The game's Lua engine. -static LuaEngine& lua_engine_get() -{ - return *static_cast(g_luaEngine); -} - // Whether a Lua mod has registered (Isaac::RegisterMod counts them in REPENTOGON's g_Mods list). static bool is_lua_mod_registered() { diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 7d9419f..e9c4cfa 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -1,6 +1,7 @@ #include "npc_ai.h" #include "game.h" #include "manager.h" +#include "npc_fireplace.h" #include "sfx_manager.h" // The Beast's forms, by variant: its stalactites, rocks and soul, the four ultra horsemen and their summons, and @@ -150,7 +151,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 301: return (void)NpcAI::ENTITY_BRAIN(&npc); case 33: - return (void)NpcAI::ENTITY_FIREPLACE(&npc); + return npc_fireplace_update(npc); case 35: return (void)NpcAI::ENTITY_MRMAW(&npc); case 36: @@ -657,9 +658,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) // update callbacks around the update phase. void npc_ai_update(Entity_NPC& npc) { - if (npc.aiCallPhase == AI_PHASE_UPDATE) - lua_callback_check(CALLBACK_PRE_NPC_UPDATE, "npc_ai_update 006c2990: MC_PRE_NPC_UPDATE"); + if (npc.aiCallPhase == AI_PHASE_UPDATE && lua_engine_get().PreNPCUpdate(&npc)) return; npc_ai_routine_run(npc); - if (npc.aiCallPhase == AI_PHASE_UPDATE) - lua_callback_check(CALLBACK_NPC_UPDATE, "npc_ai_update 006c2990: MC_NPC_UPDATE"); + if (npc.aiCallPhase == AI_PHASE_UPDATE) lua_engine_get().PostNPCUpdate(&npc); } diff --git a/src/npc_ai.h b/src/npc_ai.h index 2920606..24f8a41 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -12,13 +12,6 @@ constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; constexpr float RANDOM_HALF_TURN = 3.14f; constexpr float DEGREES_TO_RADIANS = 0.017453292f; -// The mod callbacks the NPC code runs, by their ModCallbacks ids. -constexpr int CALLBACK_NPC_UPDATE = 0; -constexpr int CALLBACK_POST_NPC_INIT = 27; -constexpr int CALLBACK_POST_NPC_RENDER = 28; -constexpr int CALLBACK_POST_NPC_DEATH = 29; -constexpr int CALLBACK_PRE_NPC_UPDATE = 69; - // The sound ids the common enemies play (Lua's SoundEffect). enum NpcSound : int { diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp new file mode 100644 index 0000000..1498c04 --- /dev/null +++ b/src/npc_fireplace.cpp @@ -0,0 +1,438 @@ +#include "npc_fireplace.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "game.h" +#include "npc_ai.h" +#include "room.h" +#include + +// A fireplace's variants (entities2.xml's 33): the fires, the moveable ones and Coal. +enum FireplaceVariant : int +{ + FIRE_NORMAL = 0, + FIRE_RED = 1, + FIRE_BLUE = 2, + FIRE_PURPLE = 3, + FIRE_WHITE = 4, + FIRE_MOVEABLE = 10, + FIRE_COAL = 11, + FIRE_MOVEABLE_BLUE = 12, + FIRE_MOVEABLE_PURPLE = 13 +}; + +// A fire burns lit, is out, and is told to light again by others. +constexpr int FIRE_STATE_OUT = NPC_STATE_IDLE; +constexpr int FIRE_STATE_LIT = NPC_STATE_ATTACK; +constexpr int FIRE_STATE_RELIGHT = NPC_STATE_ATTACK2; + +// A fire's three looks (its subtype), each with its burning, burnt out and dying animation. +constexpr int FIRE_LOOKS = 3; +constexpr const char* FLICKERING[FIRE_LOOKS] = {"Flickering", "Flickering2", "Flickering3"}; +constexpr const char* NO_FIRE[FIRE_LOOKS] = {"NoFire", "NoFire2", "NoFire3"}; +constexpr const char* DISAPPEAR[FIRE_LOOKS] = {"Dissapear", "Dissapear2", "Dissapear3"}; + +// The layer of the flame, which shrinks with the fire's health, and how deep a fire that is out draws. +constexpr int FLAME_LAYER = 1; +constexpr int FIRE_OUT_DEPTH = -1000; + +// A fire's health: it burns above 1.5 and is out at 1. A hit of 1000 puts a normal fire out at once, and its hits cost +// it 2 or 3 above 10 damage, else 1 or 2. +constexpr float FIRE_LIT_HEALTH = 1.5f; +constexpr float FIRE_OUT_HEALTH = 1; +constexpr float FIRE_HUGE_HIT = 1000; +constexpr float FIRE_BIG_HIT = 10; +constexpr int FIRE_HIT_ODDS = 3; + +// Water douses normal fires: every 5 frames a fire takes a hit while the room's water is above 0.2. +constexpr float FIRE_WATER_LEVEL = 0.2f; +constexpr int FIRE_WATER_FRAMES = 5; +constexpr int FIRE_WATER_DAMAGE_COUNTDOWN = 30; + +// The odds a blue fire turns purple on the room's first frame, and a fire's grid path while lit. +constexpr uint32_t PURPLE_FIRE_ODDS = 100; +constexpr int FIRE_PATH = 950; + +// A fire's shot cooldown when placed and when lit again. +constexpr uint32_t FIRE_COOLDOWN_RANGE = 30; +constexpr int FIRE_COOLDOWN_MIN = 60; +constexpr uint32_t RELIGHT_COOLDOWN_RANGE = 60; +constexpr int RELIGHT_COOLDOWN_MIN = 90; + +// How red and purple fires spit: their mouth above them and a little toward the target, the range they see in, the +// odds of trying and of shooting, the cooldown, and the shot's speed and a purple shot's size. +constexpr float FIRE_MOUTH_HEIGHT = 15; +constexpr float FIRE_MOUTH_REACH = 25; +constexpr float FIRE_SIGHT = 160; +constexpr int FIRE_AIM_ODDS = 5; +constexpr int FIRE_SHOOT_ODDS = 15; +constexpr int FIRE_SHOOT_COOLDOWN = 84; +constexpr float FIRE_SHOT_SPEED = 5; +constexpr float PURPLE_SHOT_SCALE = 1.5f; +constexpr int CHECK_LINE_PROJECTILE = 3; +constexpr uint64_t PROJECTILE_SMART = 1; + +// The entities whose fires do not spit (Lua's ENTITY_HERETIC and the unused ENTITY_RAGLICH). +constexpr int ENTITY_HERETIC = 905; +constexpr int ENTITY_RAGLICH = 919; + +// The embers a lit fire throws: their odds, where over the flame they start, and how they drift up. +constexpr int EMBER_ODDS = 7; +constexpr float EMBER_SPREAD = 16; +constexpr float EMBER_HEIGHT = 15; +constexpr float EMBER_HEALTH_RISE = 6; +constexpr float EMBER_RISE_MIN = 0.8f; +constexpr float EMBER_RISE_RANGE = 1.6f; +constexpr float EMBER_DRIFT = 0.4f; +constexpr int EMBER_PRIORITY = 255; +constexpr ColorMod EMBER_RED = {{1, 0.5f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod EMBER_BLUE = {{1, 1, 1, 1}, {0.2f, 1, 1.5f, 1}, {0, 0, 0}}; +constexpr ColorMod EMBER_PURPLE = {{1, 1, 1, 1}, {1, 0.2f, 1, 1}, {0, 0, 0}}; +constexpr ColorMod EMBER_WHITE = {{1, 1, 1, 1}, {1.5f, 1.5f, 1.5f, 1}, {0, 0, 0}}; + +// The poof of a fire lit again, a little above it, and the colors it takes from a red or another fire. +constexpr float RELIGHT_POOF_HEIGHT = 6; +constexpr float RELIGHT_RED_OFFSET = 0.6f; +constexpr float RELIGHT_RED_BLUE = 0; +constexpr float RELIGHT_OFFSET = 0.35f; +constexpr float RELIGHT_BLUE = 0.5f; + +// The sounds of a fire: lit again, and put out. +constexpr int SOUND_CANDLE_LIGHT = 471; +constexpr int SOUND_STEAM_HALFSEC = 261; +constexpr float PUT_OUT_VOLUME = 0.85f; + +// The effects a fire spawns (Lua's EffectVariant). +constexpr int EFFECT_POOF01 = 15; +constexpr int EFFECT_EMBER_PARTICLE = 66; + +// What a fire drops: one time in four (one in ten on Hard), from normal fires a heart one time in four and else a +// coin, from blue fires a soul heart (a black heart past one Daemon's Tail). Daemon's Tail turns four hearts in five +// away, by its own RNG off the drop RNG. +constexpr int COLLECTIBLE_BLACK_POWDER = 420; +constexpr int TRINKET_DAEMONS_TAIL = 22; +constexpr float LOOT_CHANCE = 0.25f; +constexpr float LOOT_CHANCE_HARD = 0.1f; +constexpr float LOOT_HEART_CHANCE = 0.25f; +constexpr uint32_t DAEMONS_TAIL_ODDS = 5; + +// Plays the animation of the fire's look, past the third look the third. +static void fire_play(Entity_NPC& npc, const char* const (&names)[FIRE_LOOKS]) +{ + npc.sprite.Play(names[std::min((uint32_t)npc.subtype, (uint32_t)FIRE_LOOKS - 1)]); +} + +// Sizes the flame to the fire's health. +static void flame_size_set(Entity_NPC& npc) +{ + float share = npc.health / npc.maxHitPoints; + npc.sprite.GetLayer(FLAME_LAYER)->size = vector_make(share, share); +} + +// Sets the room's path on the fire's cell, unless it rides a minecart. +static void fire_path_set(Entity_NPC& npc, int value) +{ + if (npc.minecart) return; + + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(npc.pos), value); +} + +// Lights the fire: flickering from a frame its seed picks, with the flame at its health's size. +static void fire_light(Entity_NPC& npc) +{ + npc.state = FIRE_STATE_LIT; + fire_play(npc, FLICKERING); + const AnimationData* data = npc.sprite.animState.animData; + if (data && data->length > 0) npc.sprite.animState.SetFrameFloat((float)(int)(npc.initSeed % (uint32_t)data->length)); + flame_size_set(npc); +} + +// Puts the fire out: it collides with nothing and draws under everything. +static void fire_put_out(Entity_NPC& npc) +{ + npc.state = FIRE_STATE_OUT; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + fire_play(npc, NO_FIRE); + npc.renderZOffset = FIRE_OUT_DEPTH; +} + +// Whether a fire is one water does not douse and that keeps burning in water: blue, purple and white ones. +static bool is_magic_fire(int variant) +{ + return variant == FIRE_BLUE || variant == FIRE_PURPLE || variant == FIRE_WHITE; +} + +// The first frame: a blue fire may turn purple and every fire takes a random look on the room's first frame. It +// stays put and, burning, claims its cell. Water douses normal fires and the Mausoleum's heart every fire. +static void fire_init(Entity_NPC& npc) +{ + Game& game = *g_game; + Room& room = *game.room; + RNG rng = {npc.initSeed, 5, 9, 7}; + + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + if (room.isInitialized && game.frameCount == room.enterFrame) + { + if (npc.variant == FIRE_BLUE && rng.RandomInt(PURPLE_FIRE_ODDS) == 0) npc.Morph(npc.type, FIRE_PURPLE, npc.subtype, -1); + npc.subtype = (int)rng.RandomInt(FIRE_LOOKS); + } + npc.targetPosition = npc.pos; + npc.projectileCooldown = (int)(Random() % FIRE_COOLDOWN_RANGE) + FIRE_COOLDOWN_MIN; + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | + FLAG_NO_DEATH_TRIGGER | FLAG_NO_FLASH_ON_DAMAGE | FLAG_NO_PHYSICS_KNOCKBACK; + + bool isDoused = (room.waterAmount > 0 && !is_magic_fire(npc.variant) && !npc.minecart) || game.IsMausoleumHeartStage(); + if (npc.health > FIRE_LIT_HEALTH && isDoused) npc.health = FIRE_OUT_HEALTH; + if (npc.health > FIRE_LIT_HEALTH) + { + fire_path_set(npc, FIRE_PATH); + fire_light(npc); + } + else + { + fire_path_set(npc, GRID_PATH_FREED); + fire_put_out(npc); + } + npc.UpdatePickupGhosts(); +} + +// Lights a fire that was out again, at full health, with a colored poof and a sound. +static void fire_relight(Entity_NPC& npc) +{ + npc.health = npc.maxHitPoints; + fire_light(npc); + npc.entityCollisionClass = ENTCOLL_ALL; + npc.renderZOffset = 0; + fire_path_set(npc, FIRE_PATH); + + Entity* poof = g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + bool isRed = npc.variant == FIRE_RED; + poof->posOffset = vector_make(0, -RELIGHT_POOF_HEIGHT); + poof->sprite.color._offset[0] = isRed ? RELIGHT_RED_OFFSET : RELIGHT_OFFSET; + poof->sprite.color._offset[1] = 0; + poof->sprite.color._offset[2] = isRed ? RELIGHT_RED_BLUE : RELIGHT_BLUE; + npc.PlaySound(SOUND_CANDLE_LIGHT, 1, 2, false, 1); + npc.projectileCooldown = (int)(Random() % RELIGHT_COOLDOWN_RANGE) + RELIGHT_COOLDOWN_MIN; +} + +// What a hit costs a normal fire: 2 or 3 past 10 damage, else 1 or 2. +static float hit_cost_get(float damage) +{ + bool isBig = damage > FIRE_BIG_HIT; + bool isMore = Random() % FIRE_HIT_ODDS == 0; + return (float)(isBig + isMore + 1); +} + +// The player whose hit, the last one, put the fire out. +static Entity_Player* fire_putter_get(Entity_NPC& npc) +{ + Entity* source = npc.damageEvents.empty() ? nullptr : npc.damageEvents.back().source.entity; + return source ? static_cast(source->GetPlayerAncestor()) : nullptr; +} + +// Entity_NPC::fireplace_get_loot (006d1580, which needs a LootList), advancing the drop RNG, with each drop spawned +// and updated at once: what a fire put out drops, nothing from white, moveable or Coal fires or without rewards. +static void fire_loot_spawn(Entity_NPC& npc) +{ + PlayerManager& players = g_game->playerManager; + RNG& rng = npc.dropRNG; + int variant = npc.variant; + bool isLootless = npc.HasEntityFlags(FLAG_NO_REWARD) || variant == FIRE_WHITE || variant >= FIRE_MOVEABLE; + auto isTailed = [&] { + RNG tail = {rng._seed, 1, 11, 6}; + return players.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) && tail.RandomInt(DAEMONS_TAIL_ODDS) != 0; + }; + + if (isLootless || rng.RandomFloat() >= (game_is_hard_mode() ? LOOT_CHANCE_HARD : LOOT_CHANCE)) return; + int pickup = PICKUP_HEART; + int subtype = 0; + if (variant == FIRE_BLUE || variant == FIRE_PURPLE) + { + if (isTailed()) return; + subtype = players.GetTrinketMultiplier(TRINKET_DAEMONS_TAIL) < 2 ? HEART_SOUL : HEART_BLACK; + } + else if (rng.RandomFloat() >= LOOT_HEART_CHANCE || isTailed()) pickup = PICKUP_COIN; + + uint32_t seed = rng.Next(); + Entity* drop = g_game->Spawn({.position = npc.pos, .subType = subtype, .type = ENTITY_PICKUP, .variant = pickup, .seed = seed}); + drop->Update(); + g_game->room->isPickupVisionInvalid = true; +} + +// The fire's hits this frame. A normal or red fire loses health to each and goes out at the last of it, or at once to +// an explosion, its death or a huge hit, with a hiss. Blue and purple fires go out only to explosions or death, in +// a poof. A fire put out drops its loot, and Black Powder's owner blows it up. A fire never dies. +static void fire_damage_update(Entity_NPC& npc) +{ + bool isExploded = npc.pendingDamageFlags & DAMAGE_EXPLOSION; + bool isLit = npc.state == FIRE_STATE_LIT; + + if (npc.pendingDamage <= 0 && !npc.isDead) return; + if ((npc.variant == FIRE_NORMAL || npc.variant == FIRE_RED) && isLit) + { + bool isQuenched = npc.isDead || isExploded || npc.pendingDamage >= FIRE_HUGE_HIT; + for (DamageEvent& event : npc.damageEvents) + if (event.damage > 0) npc.health -= hit_cost_get(event.damage); + npc.health = std::max(npc.health, FIRE_OUT_HEALTH); + flame_size_set(npc); + if (npc.health >= FIRE_LIT_HEALTH && !isQuenched) return; + + fire_path_set(npc, GRID_PATH_FREED); + npc.health = FIRE_OUT_HEALTH; + fire_put_out(npc); + npc.PlaySound(SOUND_STEAM_HALFSEC, PUT_OUT_VOLUME, 2, false, 1); + fire_play(npc, DISAPPEAR); + Entity_Player* player = fire_putter_get(npc); + if (player && player->HasCollectible(COLLECTIBLE_BLACK_POWDER)) + reconstruction_missing("NpcAI::ENTITY_FIREPLACE 006d18d0: Black Powder's blast (Game::BombExplosionEffects)"); + } + else if ((npc.variant == FIRE_BLUE || npc.variant == FIRE_PURPLE) && isLit) + { + if (!isExploded && !npc.isDead) return; + + npc.health = FIRE_OUT_HEALTH; + fire_put_out(npc); + npc.PlaySound(SOUND_STEAM_HALFSEC, PUT_OUT_VOLUME, 2, false, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + } + else + { + if (npc.isDead) npc.health = FIRE_OUT_HEALTH; + npc.isDead = false; + return; + } + // The online stats tally of fires put out (Player_stats_add 00425ac0) is not written yet. + fire_loot_spawn(npc); + npc.UpdatePickupGhosts(); + if (npc.isDead) npc.health = FIRE_OUT_HEALTH; + npc.isDead = false; +} + +// Where a fire aims: from its mouth at the nearest player, starting a little out toward it. +struct FireAim +{ + Vector start{}; + Vector target{}; + Vector direction{}; + float distance = 0; +}; + +static FireAim fire_aim_get(Entity_NPC& npc) +{ + FireAim aim; + Vector mouth = vector_make(npc.pos.x, npc.pos.y - FIRE_MOUTH_HEIGHT); + aim.target = game_nearest_player(npc.pos)->pos; + Vector toTarget = vector_sub(aim.target, mouth); + + aim.direction = vector_normalized(toTarget); + aim.distance = vector_length(toTarget); + aim.start = vector_add(mouth, vector_scale(aim.direction, FIRE_MOUTH_REACH)); + return aim; +} + +// Whether the fire spits: red and purple fires, unless the Heretic or Raglich made them. +static bool is_spitting_fire(Entity_NPC& npc) +{ + return (npc.variant == FIRE_RED || npc.variant == FIRE_PURPLE) && npc.spawnerType != ENTITY_HERETIC && + npc.spawnerType != ENTITY_RAGLICH; +} + +// A spitting fire now and then readies a shot at the nearest player in sight and range. The shot leaves on its +// overlay's Shoot event, a purple one homing and bigger, while the overlay carries the flame along. +static void fire_shoot_update(Entity_NPC& npc) +{ + if (is_spitting_fire(npc) && npc.projectileCooldown < 1 && npc.state == FIRE_STATE_LIT && Random() % FIRE_AIM_ODDS == 0) + { + FireAim aim = fire_aim_get(npc); + if (aim.distance < FIRE_SIGHT && room_check_line(aim.start, aim.target, CHECK_LINE_PROJECTILE, 0) && + Random() % FIRE_SHOOT_ODDS == 0) + { + npc.sprite.PlayOverlay("Shoot"); + npc.projectileCooldown = FIRE_SHOOT_COOLDOWN; + } + } + else if (npc.projectileCooldown > 0) npc.projectileCooldown--; + if (!npc.sprite.overlayAnimState.isPlaying) return; + + if (const NullFrame* frame = npc.sprite.overlayAnimState.GetNullFrameById(0)) + { + LayerState* flame = npc.sprite.GetLayer(FLAME_LAYER); + float share = npc.health / npc.maxHitPoints; + flame->pos = frame->pos; + flame->size = vector_make(frame->scale.x * share, share * frame->scale.y); + } + if (!npc.sprite.overlayAnimState.IsEventTriggered("Shoot") || npc.spawnerType == ENTITY_HERETIC || + npc.spawnerType == ENTITY_RAGLICH) + return; + + FireAim aim = fire_aim_get(npc); + uint32_t seed = Random(); + Entity* shot = g_game->Spawn({.position = aim.start, + .velocity = vector_scale(aim.direction, FIRE_SHOT_SPEED), + .spawner = &npc, + .type = ENTITY_PROJECTILE, + .seed = seed}); + if (npc.variant != FIRE_PURPLE) return; + + Entity_Projectile& projectile = static_cast(*shot); + projectile.projectileFlags |= PROJECTILE_SMART; + projectile.scale = PURPLE_SHOT_SCALE; +} + +// A lit fire now and then throws an ember up out of its flame, in its fire's color. +static void fire_ember_update(Entity_NPC& npc) +{ + if (npc.state != FIRE_STATE_LIT || Random() % EMBER_ODDS != 0) return; + + float height = random_unit(); + float x = random_unit() * EMBER_SPREAD - EMBER_SPREAD / 2 + npc.pos.x; + float y = -EMBER_HEIGHT - npc.health * EMBER_HEIGHT / EMBER_HEALTH_RISE - height * EMBER_HEIGHT + npc.pos.y; + float rise = random_unit() * -EMBER_RISE_RANGE - EMBER_RISE_MIN; + float drift = random_unit() * EMBER_DRIFT - EMBER_DRIFT / 2; + Entity* ember = g_game->Spawn({.position = vector_make(x, y), + .velocity = vector_make(drift, rise), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_EMBER_PARTICLE, + .seed = Random()}); + const ColorMod* color = nullptr; + switch (npc.variant) + { + case FIRE_RED: color = &EMBER_RED; break; + case FIRE_BLUE: color = &EMBER_BLUE; break; + case FIRE_PURPLE: color = &EMBER_PURPLE; break; + case FIRE_WHITE: color = &EMBER_WHITE; break; + } + if (color) ember->SetColor(*color, -1, EMBER_PRIORITY, false, true); +} + +// 006d18d0 The fireplace's AI: normal fires are doused by water and put out by shots, red ones spit, blue and purple +// ones go out only to explosions, white ones never. A lit fire hurts what touches it, throws embers and drops loot +// when put out. A fire that is out and finds a grid entity under it, off a minecart, is removed. Moveable fires and +// Coal have their own AIs. +void npc_fireplace_update(Entity_NPC& npc) +{ + if (!is_magic_fire(npc.variant) && g_game->room->waterAmount > FIRE_WATER_LEVEL && npc.IsFrame(FIRE_WATER_FRAMES, (int)npc.index)) + npc.TakeDamage(1, 0, EntityRef(), FIRE_WATER_DAMAGE_COUNTDOWN); + if (npc.variant == FIRE_COAL) return NpcAI::ENTITY_ROCK_SPIDER(&npc); + if (npc.variant == FIRE_MOVEABLE || npc.variant == FIRE_MOVEABLE_BLUE || npc.variant == FIRE_MOVEABLE_PURPLE) + return NpcHelper::fireplace_moveable_update(&npc); + + if (npc.state == NPC_STATE_INIT) return fire_init(npc); + if (npc.state == FIRE_STATE_RELIGHT) fire_relight(npc); + if (npc.state == FIRE_STATE_LIT && !npc.sprite.IsPlaying()) fire_play(npc, FLICKERING); + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + + fire_damage_update(npc); + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + fire_shoot_update(npc); + fire_ember_update(npc); + + Room& room = *g_game->room; + if (npc.state == FIRE_STATE_OUT && room.GetGridCollision(room.GetGridIndex(npc.pos)) != COLLISION_NONE && !npc.minecart) + npc.Remove(); +} diff --git a/src/npc_fireplace.h b/src/npc_fireplace.h new file mode 100644 index 0000000..785edcf --- /dev/null +++ b/src/npc_fireplace.h @@ -0,0 +1,5 @@ +#pragma once + +struct Entity_NPC; + +void npc_fireplace_update(Entity_NPC& npc); diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index 652f09f..415d73c 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -1,62 +1,408 @@ #include "npc_ai.h" +#include "entity_effect.h" #include "game.h" +#include "room.h" +// The gaper's kin this AI runs, and the enemies they get up as. constexpr int ENTITY_GAPER = 10; constexpr int ENTITY_GUSHER = 11; +constexpr int ENTITY_FATTY = 208; +constexpr int ENTITY_BLUBBER = 210; +constexpr int ENTITY_NULLS = 252; +constexpr int ENTITY_CONJOINED_FATTY = 257; +constexpr int ENTITY_CYCLOPIA = 284; +constexpr int ENTITY_STONEY = 302; + constexpr int GAPER_FROWNING = 1; constexpr int GAPER_FLAMING = 2; constexpr int GAPER_ROTTEN = 3; constexpr int GUSHER_PACER = 1; -constexpr int GAPER_SOUND_DELAY = 40; -constexpr int GAPER_SOUND_ODDS = 3; -constexpr int GUSHER_ODDS = 3; -constexpr int GUSHER_COOLDOWN_MIN = 20; -constexpr int GUSHER_COOLDOWN_RANGE = 20; -constexpr float GAPER_OVERKILL = -25; -constexpr int GAPER_PATH_MARKER = 900; -constexpr float WALK_THRESHOLD = 0.1f; -constexpr float FLEE_FRICTION = 0.8f; -constexpr int CONTROLLER_ACTION_GROAN = 10; +constexpr int FATTY_PALE = 1; +constexpr int FATTY_FLAMING = 2; +constexpr int CONJOINED_FATTY_PLAIN = 0; +constexpr int STONEY_CROSS = 10; +constexpr int FIREPLACE_MOVING = 10; -// How fast each gaper walks: a plain one, faster once its head is up, the frowning and flaming ones. +constexpr int EFFECT_BLOOD_EXPLOSION = 2; +constexpr int EFFECT_BLOOD_SPLAT = 7; +constexpr int EFFECT_CREEP_RED = 22; +constexpr int EFFECT_CREEP_GREEN = 23; +constexpr int BLOOD_EXPLOSION_BEAM = 2; + +constexpr int SOUND_FART = 37; +constexpr int SOUND_STONE_WALKER = 50; +constexpr int SOUND_MONSTER_ROAR_2 = 116; +constexpr int SOUND_ANGRY_GURGLE = 167; +constexpr int SOUND_HEARTIN = 212; +constexpr int SOUND_HEARTOUT = 213; +constexpr int SOUND_STONESHOOT = 262; + +constexpr uint64_t PROJECTILE_SMART = 1ull << 0; +constexpr uint64_t PROJECTILE_EXPLODE = 1ull << 1; +constexpr int COLOR_PRIORITY_DEFAULT = 255; +constexpr int CONTROLLER_ACTION_ATTACK = 9; +constexpr int CONTROLLER_ACTION_GROAN = 10; +constexpr int LAYER_STONEY_CROSS = 1; +constexpr int NULL_STONEY_CROSS = 2; + +// How fast each walks its path: a plain gaper, one with its head up, the frowning ones and Cyclopia, the flaming +// ones, the fatties, the Cross Stoney and the Nulls. constexpr float GAPER_SPEED = 0.6f; constexpr float GAPER_SPEED_HEAD_UP = 0.72f; constexpr float GAPER_SPEED_FROWNING = 0.498f; constexpr float GAPER_SPEED_FLAMING = 0.5478f; +constexpr float FATTY_SPEED = 0.3f; +constexpr float FATTY_SPEED_FLAMING = 0.33f; +constexpr float STONEY_SPEED_CROSS = 0.48000002f; +constexpr float NULLS_SPEED = 0.90000004f; -// A gaper's first frame: walking, with its head on the first frame of its overlay (a flaming one's head plays). -static void gaper_init(Entity_NPC& npc) +// The walk: the gap path marker each leaves (the Stoney's lower), the walk animation's threshold, and fleeing. +constexpr int PATH_MARKER = 900; +constexpr int PATH_MARKER_STONEY = 100; +constexpr float WALK_THRESHOLD = 0.1f; +constexpr float FLEE_FRICTION = 0.8f; +constexpr float ATTACK_FRICTION = 0.4f; +constexpr float CONTROLLER_DEADZONE = 0.1f; + +// A dying gaper that was not torn apart gets up one time in two, a Gusher pacing one time in three. +constexpr float GAPER_OVERKILL = -25; +constexpr int GUSHER_ODDS = 3; +constexpr int GUSHER_COOLDOWN_MIN = 20; +constexpr int GUSHER_COOLDOWN_RANGE = 20; + +// The groans: one time in three while it sees its target, each kind with its own delay. +constexpr int GROAN_ODDS = 3; +constexpr int GROAN_DELAY = 40; +constexpr int GROAN_DELAY_LONG = 60; +constexpr float STONEY_PITCH_MIN = 0.9f; +constexpr float STONEY_PITCH_RANGE = 0.1f; + +// A fatty winds up for 100 ticks, then attacks one time in 120 with its target within 200. +constexpr int FATTY_WINDUP = 100; +constexpr int FATTY_ATTACK_ODDS = 120; +constexpr float FATTY_ATTACK_RANGE_SQUARED = 40000; +constexpr float FATTY_SIDEWAYS_MIN_SQUARED = 0.01f; +constexpr float FATTY_SHOT_SPEED = 7; +constexpr float CONJOINED_SHOT_SCALE = 1.5f; +constexpr float PALE_FATTY_RING_SPEED = 8; +constexpr float PALE_FATTY_RING_SHOTS = 6; + +// The Conjoined Fatty's beam: a step of 25 a tick, creep growing from 0.9 by 0.07 a step, blood thrown back 5. +constexpr float BEAM_STEP = 25; +constexpr float BEAM_SCALE_BASE = 0.9f; +constexpr float BEAM_SCALE_STEP = 0.07f; +constexpr int BEAM_CREEP_FRAMES = 15; +constexpr float BEAM_SOUND_VOLUME = 0.7f; +constexpr float BEAM_BLOOD_BACK = 5; +constexpr float BEAM_BLOOD_RISE = -16; +constexpr float BEAM_BLOOD_DEPTH = 10; +constexpr float FULL_TURN_DEGREES = 360; +constexpr ColorMod BEAM_BLOOD_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; +constexpr ColorMod BEAM_SPLAT_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; + +// Cyclopia trails creep every 7 ticks and shoots one time in 30 from within 200. +constexpr int CYCLOPIA_TRAIL_TICKS = 7; +constexpr int CYCLOPIA_TRAIL_FRAMES = 20; +constexpr float CYCLOPIA_TRAIL_SCALE_MIN = 0.2f; +constexpr float CYCLOPIA_TRAIL_SCALE_RANGE = 0.3f; +constexpr int CYCLOPIA_SHOT_ODDS = 30; +constexpr float CYCLOPIA_RANGE_SQUARED = 40000; +constexpr int CYCLOPIA_COOLDOWN = 60; +constexpr int CYCLOPIA_COOLDOWN_CONTROLLED = 45; +constexpr float CYCLOPIA_SHOT_SPEED = 7; + +// The Stoney walks 90 to 149 ticks, pants 42 to 105, and dies with the room's last enemy, once its plates allow. +constexpr int STONEY_WALK_MIN = 90; +constexpr int STONEY_WALK_RANGE = 60; +constexpr int STONEY_PANT_UNIT = 21; +constexpr int STONEY_PANT_MIN_UNITS = 2; +constexpr uint32_t STONEY_PANT_UNIT_MASK = 3; +constexpr int STONEY_PLATE_DELAY = 9; +constexpr float STONEY_SHOT_SPEED = 10; +constexpr float STONEY_SHOT_HEIGHT = -15; +constexpr float STONEY_SHOT_FALL = 0.3f; +constexpr ColorMod NULLS_SPLAT_COLOR = {{0.1f, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod STONEY_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + +static bool is_fatty(Entity_NPC& npc) { - npc.state = NPC_STATE_MOVE; - npc.stateFrame = 0; - if (npc.variant == GAPER_FLAMING) npc.sprite.PlayOverlay("Head"); - else if (npc.sprite.SetOverlayAnimation("Head", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) - npc.sprite.overlayAnimState.SetFrameFloat(0); - - if (npc.sprite.SetAnimation("WalkVert", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) - { - npc.sprite.animState.SetFrameFloat(0); - npc.sprite.animState.isPlaying = false; - } + return npc.type == ENTITY_FATTY || npc.type == ENTITY_CONJOINED_FATTY; } -// A dying gaper that was not torn apart may get up as a Gusher (a pacer one time in three). +// Lays a sprite layer over a null's keyframe. +static void layer_fit(LayerState& layer, const NullFrame& frame) +{ + layer.pos = frame.pos; + layer.size = frame.scale; +} + +// The original's spawn_blood_explosion: a tinted blood explosion with its sprite offset, drawn just in front. +static Entity* blood_explosion_spawn(const EntitySpawn& spawn, const ColorMod& color, const Vector& spriteOffset) +{ + Entity* explosion = g_game->Spawn(spawn); + explosion->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + explosion->sprite.offset = spriteOffset; + explosion->renderDepthOffset = BEAM_BLOOD_DEPTH; + return explosion; +} + +// Creep of the npc's that lasts a number of frames. +static Entity_Effect* creep_spawn(Entity_NPC& npc, const Vector& position, int variant, int frames) +{ + Entity_Effect* creep = static_cast(g_game->Spawn( + {.position = position, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()})); + creep->timeout = frames; + creep->lifespan = frames; + return creep; +} + +// A Flaming Fatty's moving fire, left where it stands. +static void fire_spawn(Entity_NPC& npc) +{ + Entity* fire = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_FIREPLACE, + .variant = FIREPLACE_MOVING, + .seed = Random()}); + fire->targetPosition = fire->pos; +} + +// The first frame: walking, the gapers' heads on the first frame of their overlay (a flaming one's head plays), the +// Stoney untouchable and the Nulls and the Stoney with their own blood. +static void gaper_init(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + if (npc.type == ENTITY_STONEY) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR); + npc.isInvincible = true; + } + else if (!is_fatty(npc)) + { + if (npc.type == ENTITY_GAPER && npc.variant == GAPER_FLAMING) sprite.PlayOverlay("Head"); + else if (sprite.SetOverlayAnimation("Head", SWITCH_KEEP_FRAME) && sprite.overlayAnimState.animData) + sprite.overlayAnimState.SetFrameFloat(0); + } + if (npc.type == ENTITY_FATTY && npc.variant == FATTY_FLAMING) + { + sprite.isOverlayRenderFirst = true; + sprite.PlayOverlay("Fire"); + } + + if (sprite.SetAnimation("WalkVert", SWITCH_KEEP_FRAME) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + + if (npc.type == ENTITY_NULLS) npc.splatColor = NULLS_SPLAT_COLOR; + if (npc.type != ENTITY_STONEY) return; + + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.splatColor = STONEY_SPLAT_COLOR; + npc.i1 = (int)(Random() % STONEY_WALK_RANGE) + STONEY_WALK_MIN; + if (npc.variant != STONEY_CROSS) return; + + sprite.PlayOverlay("HeadIdle"); + if (const NullFrame* frame = sprite.GetNullFrameById(NULL_STONEY_CROSS)) + layer_fit(*sprite.GetLayer(LAYER_STONEY_CROSS), *frame); +} + +// A Flaming Fatty's fire follows the "FirePos" null. +static void flaming_fatty_fire_update(Entity_NPC& npc) +{ + if (!npc.sprite.animState.animData) return; + + const NullFrame* frame = npc.sprite.animState.GetNullFrame("FirePos"); + LayerState* layer = frame && frame->isVisible ? npc.sprite.GetLayer("Fire") : nullptr; + if (layer) layer_fit(*layer, *frame); +} + +// Gets back up as another enemy, at full health. +static void gaper_revive(Entity_NPC& npc, int type, int variant) +{ + npc.Morph(type, variant, 0, -1); + npc.isDead = false; + npc.health = npc.maxHitPoints; +} + +// One time in two one not torn apart lives on: a gaper as a Gusher, a Pale Fatty as a Blubber, a Conjoined Fatty as +// a Fatty. A Flaming Fatty leaves its fire. static void gaper_death_update(Entity_NPC& npc) { if (npc.health <= GAPER_OVERKILL || (Random() & 1) != 0) return; - bool isPacer = Random() % GUSHER_ODDS == 0 && npc.variant != GAPER_FLAMING; - npc.Morph(ENTITY_GUSHER, isPacer ? GUSHER_PACER : 0, 0, -1); - npc.isDead = false; - uint32_t cooldown = Random(); - npc.health = npc.maxHitPoints; - npc.projectileCooldown = (int)(cooldown % GUSHER_COOLDOWN_RANGE) + GUSHER_COOLDOWN_MIN; + if (npc.type == ENTITY_GAPER) + { + bool isPacer = Random() % GUSHER_ODDS == 0 && npc.variant != GAPER_FLAMING; + gaper_revive(npc, ENTITY_GUSHER, isPacer ? GUSHER_PACER : 0); + npc.projectileCooldown = (int)(Random() % GUSHER_COOLDOWN_RANGE) + GUSHER_COOLDOWN_MIN; + } + else if (npc.type == ENTITY_FATTY && npc.variant == FATTY_PALE) gaper_revive(npc, ENTITY_BLUBBER, 0); + else if (npc.type == ENTITY_FATTY && npc.variant == FATTY_FLAMING) fire_spawn(npc); + else if (npc.type == ENTITY_CONJOINED_FATTY && npc.variant == CONJOINED_FATTY_PLAIN) + gaper_revive(npc, ENTITY_FATTY, 0); } -// The speed a gaper walks its path at. +// Whether a walking fatty, wound up, attacks now: its target hostile and near one time in 120, or its player's +// attack or movement. +static bool fatty_attack_check(Entity_NPC& npc) +{ + if (npc.stateFrame < FATTY_WINDUP) npc.stateFrame += npc.update_ticks_get(); + + Entity* target = npc.GetPlayerTarget(); + if (npc.controllerID == -1) + { + if (!npc.IsHostileTo(target)) return false; + if (vector_length_squared(vector_sub(target->pos, npc.pos)) >= FATTY_ATTACK_RANGE_SQUARED) return false; + if (Random() % FATTY_ATTACK_ODDS != 0) return false; + } + else if (!npc.IsControllerActionPressed(CONTROLLER_ACTION_ATTACK) && + vector_is_zero(npc.GetControllerMovementInput(CONTROLLER_DEADZONE))) + return false; + return npc.stateFrame >= FATTY_WINDUP; +} + +// Starts a fatty's attack with a gurgle, sideways when it moves more across than down. +static void fatty_attack_start(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_ANGRY_GURGLE, 1, 5, false, 1); + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + + Vector velocity = npc.velocity; + bool isSideways = std::abs(velocity.y) < std::abs(velocity.x) && + vector_length_squared(velocity) > FATTY_SIDEWAYS_MIN_SQUARED; + npc.sprite.Play(isSideways ? "AttackHori" : "AttackVert"); + if (isSideways) npc.sprite.isFlipX = velocity.x < 0; + npc.UpdateControllerMovement(true); +} + +// The blood the Conjoined Fatty's beam throws where it lands: an explosion flung along the beam and a dark splat. +static void beam_blood_spawn(Entity_NPC& npc, const Vector& at, float scale) +{ + Vector velocity = vector_scale(vector_scale(npc.targetPosition, random_unit()), 2); + Vector spriteOffset = vector_make(0, random_unit() * BEAM_BLOOD_RISE); + Vector from = vector_sub(at, vector_scale(npc.targetPosition, BEAM_BLOOD_BACK)); + Entity* explosion = blood_explosion_spawn({.position = from, + .velocity = velocity, + .subType = BLOOD_EXPLOSION_BEAM, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}, + BEAM_BLOOD_COLOR, spriteOffset); + explosion->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + + Entity* splat = + g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->sizeMulti = vector_make(scale, scale); + splat->SetColor(BEAM_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); +} + +// The Conjoined Fatty's beam: aimed at its target on "Target" (or by its player on "Shoot"), it lays creep and blood +// a step further along each tick from "Shoot" until "Stop". +static void conjoined_beam_update(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + if (sprite.IsEventTriggered("Target")) + npc.targetPosition = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (sprite.IsEventTriggered("Shoot") && npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) + npc.targetPosition = vector_normalized(npc.controllerMovement); + if (!sprite.WasEventTriggered("Shoot") || sprite.WasEventTriggered("Stop")) return; + + if (npc.stateFrame == 0) + { + npc_sound_play(SOUND_HEARTIN, BEAM_SOUND_VOLUME, 2, 1); + npc_sound_play(SOUND_FART, 1, 2, 1); + } + Vector at = vector_add(vector_scale(npc.targetPosition, (float)npc.stateFrame * BEAM_STEP), npc.pos); + Entity_Effect* creep = creep_spawn(npc, at, EFFECT_CREEP_GREEN, BEAM_CREEP_FRAMES); + float scale = (float)npc.stateFrame * BEAM_SCALE_STEP + BEAM_SCALE_BASE; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + + if (g_game->room->IsPositionInRoom(at, 0)) beam_blood_spawn(npc, at, scale); + npc.stateFrame += npc.update_ticks_get(); +} + +// A fatty's "Shoot": the Blue Conjoined Fatty spits an exploding homing shot, the others fart (the Pale Fatty with a +// ring of shots, the Flaming Fatty with a fire). +static void fatty_shoot(Entity_NPC& npc) +{ + if (npc.type == ENTITY_CONJOINED_FATTY) + { + npc_sound_play(SOUND_HEARTOUT, 1, 2, 1); + ProjectileParams params; + params.bulletFlags |= PROJECTILE_SMART | PROJECTILE_EXPLODE; + params.scale = CONJOINED_SHOT_SCALE; + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + npc.FireProjectiles(npc.pos, vector_resized(aim, FATTY_SHOT_SPEED), PROJECTILES_SINGLE, params); + return; + } + + reconstruction_missing("npc_gaper_update 00508f40: the Fatty's fart (Game::ButterBeanFart 00704360, radius 120)"); + Vector ring = vector_make(PALE_FATTY_RING_SPEED, PALE_FATTY_RING_SHOTS); + if (npc.variant == FATTY_PALE) npc.FireProjectiles(npc.pos, ring, PROJECTILES_RING, ProjectileParams()); + else if (npc.variant == FATTY_FLAMING) fire_spawn(npc); +} + +// A fatty's own states: winding up while it walks, then its attack until the animation ends. True when the attack +// took the frame. +static bool fatty_update(Entity_NPC& npc) +{ + AnimationState& animation = npc.sprite.animState; + if (npc.state == NPC_STATE_MOVE) + { + if (!fatty_attack_check(npc)) return false; + fatty_attack_start(npc); + return true; + } + if (npc.state != NPC_STATE_ATTACK) return false; + + npc.UpdateControllerMovement(false); + if (npc.type == ENTITY_CONJOINED_FATTY && npc.variant == CONJOINED_FATTY_PLAIN) conjoined_beam_update(npc); + else if (animation.animData && animation.IsEventTriggered("Shoot")) fatty_shoot(npc); + if (!animation.animData || !animation.isPlaying) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + } + npc.friction *= ATTACK_FRICTION; + return true; +} + +// Cyclopia's attack: a shot at its target (or its player's aim) on "Shoot", back to walking when the overlay ends. +static void cyclopia_attack_update(Entity_NPC& npc) +{ + AnimationState& overlay = npc.sprite.overlayAnimState; + npc.UpdateControllerMovement(false); + if (overlay.IsEventTriggered("Shoot")) + { + Vector aim = npc.controllerID == -1 ? vector_sub(npc.GetPlayerTarget()->pos, npc.pos) : npc.controllerMovement; + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_resized(aim, CYCLOPIA_SHOT_SPEED), PROJECTILES_SINGLE, params); + } + if (!overlay.animData || !overlay.isPlaying) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.sprite.SetOverlayFrame("Head", 0); + } + npc.friction *= ATTACK_FRICTION; +} + +// The speed it walks its path at. A flaming gaper's head keeps playing. static float gaper_speed_get(Entity_NPC& npc) { - if (npc.variant == GAPER_FROWNING) return GAPER_SPEED_FROWNING; + if (is_fatty(npc)) + return npc.type == ENTITY_FATTY && npc.variant == FATTY_FLAMING ? FATTY_SPEED_FLAMING : FATTY_SPEED; + if (npc.type == ENTITY_STONEY) return npc.variant == STONEY_CROSS ? STONEY_SPEED_CROSS : GAPER_SPEED; + if (npc.type == ENTITY_NULLS) return NULLS_SPEED; + if (npc.variant == GAPER_FROWNING || npc.type == ENTITY_CYCLOPIA) return GAPER_SPEED_FROWNING; if (npc.variant == GAPER_FLAMING) { npc.sprite.PlayOverlay("Head"); @@ -65,33 +411,158 @@ static float gaper_speed_get(Entity_NPC& npc) return npc.sprite.GetOverlayFrame() > 0 ? GAPER_SPEED_HEAD_UP : GAPER_SPEED; } -// 00508f40 The gaper's AI (with the rotten gaper's own, and Fatty and the rest of its kin left to come): it walks -// its path to its target, groans now and then when it sees it, lifts its head, and its kin do not hurt it. +// Its groan: a fatty's roar, a walking Stoney's grind at a random pitch (the Cross Stoney is silent), else the gaper's. +static void gaper_groan(Entity_NPC& npc) +{ + if (is_fatty(npc)) npc.PlaySound(SOUND_MONSTER_ROAR_2, 1, GROAN_DELAY_LONG, false, 1); + else if (npc.type != ENTITY_STONEY) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, GROAN_DELAY, false, 1); + else if (npc.state != NPC_STATE_SPECIAL && npc.variant != STONEY_CROSS) + npc.PlaySound(SOUND_STONE_WALKER, 1, GROAN_DELAY_LONG, false, + random_unit() * STONEY_PITCH_RANGE + STONEY_PITCH_MIN); +} + +// Starts Cyclopia's attack, its cooldown set. +static void cyclopia_attack_start(Entity_NPC& npc, int cooldown) +{ + npc.projectileCooldown = cooldown; + npc.state = NPC_STATE_ATTACK; + npc.sprite.PlayOverlay("Attack"); +} + +// Cyclopia leaves a trail of creep, and attacks off cooldown: one time in 30 with its target in sight and near, or +// when its player moves. +static void cyclopia_update(Entity_NPC& npc) +{ + if (npc.GetIntervalTicks(CYCLOPIA_TRAIL_TICKS, (float)(npc.index % CYCLOPIA_TRAIL_TICKS))) + { + Entity_Effect* creep = creep_spawn(npc, npc.pos, EFFECT_CREEP_RED, CYCLOPIA_TRAIL_FRAMES); + float scale = random_unit() * CYCLOPIA_TRAIL_SCALE_RANGE + CYCLOPIA_TRAIL_SCALE_MIN; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + } + + if (npc.state == NPC_STATE_MOVE && npc.projectileCooldown < 1) + { + if (npc.controllerID == -1) + { + if (npc.pathfinder.hasDirectPath && Random() % CYCLOPIA_SHOT_ODDS == 0 && + vector_length_squared(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)) < CYCLOPIA_RANGE_SQUARED) + cyclopia_attack_start(npc, CYCLOPIA_COOLDOWN); + } + else + { + npc.UpdateControllerMovement(true); + if (!vector_is_zero(npc.controllerMovement)) cyclopia_attack_start(npc, CYCLOPIA_COOLDOWN_CONTROLLED); + } + } + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc.update_ticks_get(); +} + +// The Cross Stoney spins, shooting a plus and a cross by turns. +static void cross_stoney_update(Entity_NPC& npc) +{ + AnimationState& overlay = npc.sprite.overlayAnimState; + npc.sprite.PlayOverlay(npc.i2 != 1 ? "ShootAndRotate2" : "ShootAndRotate1"); + if (overlay.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_STONESHOOT, 1, 0, false, 1); + ProjectileParams params; + params.heightModifier = STONEY_SHOT_HEIGHT; + params.fallingAccelModifier = STONEY_SHOT_FALL; + Vector from = vector_add(vector_add(npc.velocity, npc.velocity), npc.pos); + ProjectilesMode mode = npc.i2 != 1 ? PROJECTILES_CROSS : PROJECTILES_PLUS; + npc.FireProjectiles(from, vector_make(STONEY_SHOT_SPEED, 0), mode, params); + } + if (!overlay.animData || !overlay.isPlaying) npc.i2 = 1 - npc.i2; +} + +// The Stoney crumbles with the room's last enemy (its plates done), else walks and pants by turns. The Cross Stoney's +// cross follows its null. +static void stoney_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + bool isRoomDone = npc.GetAliveEnemyCount() < 1 && + (!room.isTriggerPressurePlates || room.roomClearDelay < STONEY_PLATE_DELAY); + if (npc.state == NPC_STATE_DEATH) return; + if (isRoomDone) + { + npc.state = NPC_STATE_DEATH; + npc.stateFrame = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + if (npc.variant != STONEY_CROSS) return; + + npc.sprite.overlayAnimState.SetAnimationData(nullptr); + npc.sprite.GetLayer(LAYER_STONEY_CROSS)->pos = {}; + npc.sprite.GetLayer(LAYER_STONEY_CROSS)->size = vector_make(1, 1); + return; + } + + int ticks = npc.update_ticks_get(); + if (npc.state == NPC_STATE_MOVE && npc.variant == STONEY_CROSS) cross_stoney_update(npc); + else if (npc.state == NPC_STATE_MOVE && (npc.i1 < 1 || (npc.i1 -= ticks) < 1)) + { + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("Pant"); + npc.i1 = (int)((Random() & STONEY_PANT_UNIT_MASK) + STONEY_PANT_MIN_UNITS) * STONEY_PANT_UNIT; + } + else if (npc.state == NPC_STATE_SPECIAL) + { + npc.velocity = vector_scale(npc.velocity, 0); + if (npc.i1 > 0) npc.i1 -= ticks; + if (npc.i1 < 1) + { + npc.state = NPC_STATE_MOVE; + npc.i1 = (int)(Random() % STONEY_WALK_RANGE) + STONEY_WALK_MIN; + } + } + if (npc.variant != STONEY_CROSS) return; + + const NullFrame* frame = npc.sprite.GetNullFrameById(NULL_STONEY_CROSS); + LayerState& cross = *npc.sprite.GetLayer(LAYER_STONEY_CROSS); + cross.isVisible = frame && frame->isVisible; + if (cross.isVisible) layer_fit(cross, *frame); +} + +// 00508f40 The AI of the gaper and its kin (the rotten gaper has its own): Fatty, Conjoined Fatty, Nulls, Cyclopia, +// Stoney and Wraith. Each walks its path to its target groaning when it sees it, and its kin do not hurt it. The +// fatties wind up and attack, Cyclopia shoots and trails creep, the Stoney pants and crumbles with the room. void npc_gaper_update(Entity_NPC& npc) { if (npc.type == ENTITY_GAPER && npc.variant == GAPER_ROTTEN) return NpcAI::ENTITY_ROTTEN_GAPER(&npc); - if (npc.type != ENTITY_GAPER) reconstruction_missing("npc_gaper_update 00508f40: Fatty and the gaper's kin"); if (npc.pendingDamage > 0) for (DamageEvent& event : npc.damageEvents) if (event.source.spawnerType == npc.type) event.damage = 0; if (npc.state == NPC_STATE_INIT) gaper_init(npc); + if (npc.type == ENTITY_FATTY && npc.variant == FATTY_FLAMING) flaming_fatty_fire_update(npc); if (npc.isDead) return gaper_death_update(npc); - npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + if (is_fatty(npc) && fatty_update(npc)) return; + if (npc.type == ENTITY_CYCLOPIA && npc.state == NPC_STATE_ATTACK) cyclopia_attack_update(npc); + + if (npc.type != ENTITY_STONEY || npc.state != NPC_STATE_SPECIAL) + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); npc.aiFloat = gaper_speed_get(npc); if (!npc.HasEntityFlags(FLAG_SHRINK | FLAG_FEAR)) - npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), npc.aiFloat, GAPER_PATH_MARKER, true); + { + int marker = npc.type == ENTITY_STONEY ? PATH_MARKER_STONEY : PATH_MARKER; + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), npc.aiFloat, marker, DIRECT_PATH_FAR); + } else { npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); npc.friction *= FLEE_FRICTION; + if (is_fatty(npc) && npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= FLEE_FRICTION; } bool isGroaning = npc.controllerID == -1 ? npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && - Random() % GAPER_SOUND_ODDS == 0 + Random() % GROAN_ODDS == 0 : npc.IsControllerActionTriggered(CONTROLLER_ACTION_GROAN); - if (isGroaning) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, GAPER_SOUND_DELAY, false, 1); - if (npc.variant == 0 && npc.pathfinder.hasDirectPath && npc.sprite.GetOverlayFrame() < 1) + if (isGroaning) gaper_groan(npc); + if (npc.variant == 0 && npc.pathfinder.hasDirectPath && !is_fatty(npc) && npc.type != ENTITY_STONEY && + npc.sprite.GetOverlayFrame() < 1) npc.sprite.PlayOverlay("Head", PLAY_FORCED); + + if (npc.type == ENTITY_CYCLOPIA) cyclopia_update(npc); + if (npc.type == ENTITY_STONEY) stoney_update(npc); } diff --git a/src/path_finder.cpp b/src/path_finder.cpp index e2709e5..9b16697 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -1,26 +1,87 @@ #include "path_finder.h" -#include "entity_npc.h" #include "game.h" -#include "log.h" +#include "npc_ai.h" #include "room.h" +#include +#include +#include + +static_assert(PATH_GRID_CELLS == ROOM_GRID_CELLS); -constexpr float GRID_CELL = 40; -constexpr float GRID_TOP = 120; -constexpr float HALF = 0.5f; constexpr int PATH_ENEMY_TYPE_LAST = 999; +// The grid paths a cell's cost means: a pit band and a blocked band some grid collisions ignore, the highest cost a +// path still crosses, and what a rock crusher pays to walk through rocks and through hazards. +constexpr uint32_t GRID_PATH_BAND = 1000; +constexpr uint32_t GRID_PATH_PIT = 3000; +constexpr int GRID_PATH_IMPASSABLE = 950; +constexpr int GRID_PATH_SLOWING_MAX = 949; +constexpr int CRUSH_COST_EASY = 1; +constexpr int CRUSH_COST_DANGEROUS = 800; + +// A body wider than a cell paths with its collision points, and one an odd number of cells wide shifts by about half. +constexpr float LARGE_BODY_PERIOD = 80; +constexpr float ODD_BODY_SHIFT = 19.96f; + +// How the cell its owner counts itself in lags behind: 10 a tick, 50 while walking straight, refilled to 20 / speed. +constexpr int CELL_DELAY_TICK = 10; +constexpr int CELL_DELAY_DIRECT_TICK = 50; +constexpr float CELL_DELAY = 20; +constexpr float CELL_DELAY_SPEED_MIN = 0.2f; + +// Every 10 to 19 ticks the cost map is flooded again, each step costing 1, or 7 into a cell with a cost. +constexpr int REPATH_MIN = 10; +constexpr int REPATH_RANGE = 10; +constexpr int STEP_COST = 1; +constexpr int STEP_COST_ROUGH = 7; + +// How often it looks ahead for slowing cells and for a clear line, and how far straight walking reaches. +constexpr int SLOW_PROBE_FRAMES = 3; +constexpr float SLOWDOWN = 0.7f; +constexpr int LINE_CHECK_FRAMES = 10; +constexpr int LINE_CHECK_GROUND = 0; +constexpr float DIRECT_RANGE_NEAR = 70; +constexpr float DIRECT_RANGE_FAR = 750; + +// The steering: no target brakes, an arrival brakes harder, else a push of a tenth of the distance up to 2. +constexpr float FRICTION_IDLE = 0.85f; +constexpr float FRICTION_ARRIVED = 0.5f; +constexpr float FRICTION_MOVING = 0.7f; +constexpr float ARRIVE_DISTANCE = 1; +constexpr float PUSH_PER_DISTANCE = 0.1f; +constexpr float PUSH_MAX = 2; + +// The cells left of, above, right of and below a cell, each -1 off the grid. +static std::array grid_neighbors_get(Room& room, int gridIndex) +{ + int column = gridIndex % room.gridWidth; + int row = gridIndex / room.gridWidth; + return {room.GetGridIndexByTile(column - 1, row), room.GetGridIndexByTile(column, row - 1), + room.GetGridIndexByTile(column + 1, row), room.GetGridIndexByTile(column, row + 1)}; +} + +// 004cdd30 Raises a cell's path marker (its cost below the thousands) to marker, never past the impassable ones. +bool room_grid_path_mark(Room& room, int gridIndex, int marker) +{ + if ((uint32_t)gridIndex >= ROOM_GRID_CELLS || marker > GRID_PATH_IMPASSABLE) return false; + + int& path = room.gridPaths[gridIndex]; + if (path % (int)GRID_PATH_BAND < marker) path = path - path % (int)GRID_PATH_BAND + marker; + return true; +} + // 007e3260 Forgets every path, target and evasion, and its grid cell. void PathFinder::Reset() { gridIndex = -1; - pathStep = 0; + gridIndexDelay = 0; moveCountdown = 0; hasDirectPath = false; isPathFound = false; gridPathTarget = {}; evadeMovementCountdown = 0; - evadeDistance = 0; stuckFrames = 0; + evadeDistance = 0; visitedGridIndices.clear(); direction = PATH_DIRECTION_NONE; directionTimer = 0; @@ -40,11 +101,7 @@ void PathFinder::ResetMovementTarget() // 007e6ff0 Notes the grid cell its owner stands in, or -1 outside the grid. void PathFinder::UpdateGridIndex() { - Room& room = *g_game->room; - int column = (int)((entity->pos.x - GRID_CELL) / GRID_CELL + HALF); - int row = (int)((entity->pos.y - GRID_TOP) / GRID_CELL + HALF); - bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; - gridIndex = isInside ? room.gridWidth * row + column : -1; + gridIndex = g_game->room->GetGridIndex(entity->pos); } // 007e3340 Whether its owner paths as the players' side: charmed, the Blood Puppy, after a baited target, or an @@ -60,10 +117,244 @@ bool PathFinder::is_entity_friendly() return npc->controllerID != -1 || npc->forcedTarget; } -// 007e33c0 -void PathFinder::FindGridPath(const Vector&, float, int, bool) +// 007e7fb0 A grid path as its owner's grid collision feels it: flying over pits drops the pit band, walking on the +// ground keeps all, and anything else drops both the blocked and the pit bands. +int PathFinder::grid_path_felt(uint32_t gridPath) { - reconstruction_missing("PathFinder::FindGridPath 007e33c0"); + if (!entity || entity->entityGridCollisionClass == GRIDCOLL_GROUND) return (int)gridPath; + if (entity->entityGridCollisionClass == GRIDCOLL_NOPITS) + return (int)(gridPath - GRID_PATH_PIT < GRID_PATH_BAND ? gridPath - GRID_PATH_PIT : gridPath); + + uint32_t felt = gridPath - GRID_PATH_BAND < GRID_PATH_BAND ? gridPath - GRID_PATH_BAND : gridPath; + return (int)(felt - GRID_PATH_PIT < GRID_PATH_BAND ? felt - GRID_PATH_PIT : felt); +} + +// Whether a target's cell is worth remembering: one that is not solid, or for a rock crusher a grid entity that is +// neither easy nor dangerous to crush. +bool PathFinder::is_target_kept(Room& room, int targetIndex) +{ + if (!canCrushRocks) return targetIndex >= 0 && room.GetGridPath(targetIndex) < GRID_PATH_SOLID; + + GridEntity* grid = room.GetGridEntity(targetIndex); + return grid && !grid->IsEasyCrushableOrWalkable() && !grid->IsDangerousCrushableOrWalkable(); +} + +// The cost map: the room's grid paths, or for a large body each cell's cost under the first half of its collision +// points (the most blocked of them, a rock crusher paying less for rocks and hazards). +void PathFinder::grid_costs_fill(Room& room, const Vector& offset, bool isLarge) +{ + if (!isLarge) + { + gridCosts = room.gridPaths; + return; + } + + std::vector offsets{offset}; + for (const Vector& point : entity->collisionPoints) offsets.push_back(vector_add(offset, point)); + gridCosts.fill(0); + + for (int cell = 0; cell < room.gridWidth * room.gridHeight; cell++) + { + Vector center = room.GetGridPosition(cell); + for (size_t i = 0; i < offsets.size() / 2; i++) + { + int covered = room.GetGridIndex(vector_add(center, offsets[i])); + int path = room.GetGridPath(covered); + int cost = path; + GridEntity* grid = canCrushRocks ? room.GetGridEntity(covered) : nullptr; + if (grid) + { + if (grid->IsEasyCrushableOrWalkable()) cost = CRUSH_COST_EASY; + if (grid->IsDangerousCrushableOrWalkable()) cost = CRUSH_COST_DANGEROUS; + cost = std::min(cost, path); + } + if (i == 0 || (path > gridCosts[cell] && path > GRID_PATH_FREED)) gridCosts[cell] = cost; + } + } +} + +// A large body aiming at a cell it cannot fit into aims at the cheapest cell its collision points reach from there. +// The original reads its countdown as the cost of a point off the grid. Such points are skipped here. +int PathFinder::large_target_get(Room& room, const Vector& position, int targetIndex) +{ + if (targetIndex < 0 || gridCosts[targetIndex] <= GRID_PATH_FREED) return targetIndex; + if (room.GetGridPath(targetIndex) > GRID_PATH_FREED) return targetIndex; + + Vector center = room.GetGridPosition(room.GetGridIndex(position)); + int best = gridCosts[targetIndex]; + for (size_t i = 0; i < entity->collisionPoints.size() / 2; i++) + { + int cell = room.GetGridIndex(vector_sub(center, entity->collisionPoints[i])); + if (cell < 0 || gridCosts[cell] >= best) continue; + best = gridCosts[cell]; + targetIndex = cell; + } + return targetIndex; +} + +// (007e4860, 007e85a0) Floods the cost map from the target, cheapest first, marking each reached cell with its +// negated cost until it reaches its own cell or half the room's cells in cost. +void PathFinder::grid_costs_flood(Room& room, int targetIndex, bool isFriendly) +{ + auto isCostlier = [](const PathNode& first, const PathNode& second) { + return first.cost > second.cost; + }; + std::priority_queue, decltype(isCostlier)> open(isCostlier); + open.push({targetIndex, 0}); + isPathFound = false; + + while (!open.empty() && !isPathFound) + { + PathNode node = open.top(); + if (node.cost >= room.gridWidth * room.gridHeight / 2) break; + open.pop(); + + for (int next : grid_neighbors_get(room, node.gridIndex)) + { + if (next < 0 || gridCosts[next] < 0 || gridCosts[next] >= GRID_PATH_IMPASSABLE) continue; + + int cost = node.cost + (gridCosts[next] > 0 && !isFriendly ? STEP_COST_ROUGH : STEP_COST); + gridCosts[next] = -cost; + if (next == gridIndex) isPathFound = true; + open.push({next, cost}); + } + } +} + +// The neighbour of its cell the flood reached cheapest, or its own cell. A crawlspace ladder above is never taken. +int PathFinder::path_next_get(Room& room) +{ + std::array neighbors = grid_neighbors_get(room, gridIndex); + int next = gridIndex; + int best = -GRID_PATH_SOLID; + + for (int direction = 0; direction < PATH_DIRECTION_COUNT; direction++) + { + int cell = neighbors[direction]; + GridEntity* grid = room.GetGridEntity(cell); + bool isLadder = room.roomType == ROOM_DUNGEON && direction == PATH_DIRECTION_UP && grid && + grid->type == GRID_GRAVITY; + if (isLadder || cell < 0 || gridCosts[cell] >= 0 || gridCosts[cell] <= best) continue; + + best = gridCosts[cell]; + next = cell; + } + return next; +} + +// Pushes its owner from where it stands toward the spot, braking when there is none or it has arrived. +void PathFinder::path_steer(const Vector& moveTarget, const Vector& from, float speed) +{ + if (vector_is_zero(moveTarget)) + { + entity->friction *= FRICTION_IDLE; + return; + } + + Vector delta = vector_sub(moveTarget, from); + float distance = vector_length(delta); + if (distance <= ARRIVE_DISTANCE) + { + entity->friction *= FRICTION_ARRIVED; + return; + } + + float push = std::min(distance * PUSH_PER_DISTANCE, PUSH_MAX) * speed; + entity->friction *= FRICTION_MOVING; + entity->AddVelocity_divided(vector_make(delta.x / distance * push, delta.y / distance * push), false); +} + +// 007e33c0 Steers its owner toward position: straight at it when the line is clear and near enough, else down the +// cost map it floods from the target every 10 to 19 ticks. A controlled enemy moves by its player's input instead. +// A versus match's player never paths, so only enemies are tested for a controller. +void PathFinder::FindGridPath(const Vector& position, float speed, int pathMarker, DirectPathMode mode) +{ + bool isEnemy = entity->type >= ENTITY_FIRST_ENEMY && entity->type <= PATH_ENEMY_TYPE_LAST; + if (isEnemy && static_cast(entity)->controllerID != -1) + { + SimulatePlayerMovement(static_cast(entity)->GetControllerInput(0), 1); + UpdateGridIndex(); + hasDirectPath = true; + return; + } + if (entity->HasEntityFlags(FLAG_CONFUSION) && !entity->HasEntityFlags(FLAG_CHARM)) + { + MoveRandomly(STATUS_IGNORED); + Vector heading = vector_normalized(entity->velocity); + entity->velocity = {}; + entity->AddVelocity_divided(vector_scale(heading, speed), false); + } + + Vector body = vector_scale(entity->sizeMulti, entity->size * 2); + bool isLarge = body.x > GRID_CELL_SIZE || body.y > GRID_CELL_SIZE; + bool isFamiliar = entity->type == ENTITY_FAMILIAR && pathMarker <= 0; + bool isFriendly = is_entity_friendly() || pathMarker < 0; + Vector offset{}; + if (std::fmod(body.x, LARGE_BODY_PERIOD) > GRID_CELL_SIZE) offset.x = ODD_BODY_SHIFT; + if (std::fmod(body.y, LARGE_BODY_PERIOD) > GRID_CELL_SIZE) offset.y = ODD_BODY_SHIFT; + Vector from = vector_sub(entity->pos, offset); + + Room& room = *g_game->room; + int targetIndex = room.GetGridIndex(position); + if (is_target_kept(room, targetIndex)) gridPathTarget = position; + else if (!vector_is_zero(gridPathTarget)) targetIndex = room.GetGridIndex(gridPathTarget); + + int ticks = entity->update_ticks_get(); + int ownIndex = room.GetGridIndex(from); + Vector ownCenter = room.GetGridPosition(ownIndex); + if (ownIndex != gridIndex && (gridIndexDelay -= ticks * CELL_DELAY_TICK) < 0) + { + gridIndex = ownIndex; + gridIndexDelay = (int)(CELL_DELAY / std::max(speed, CELL_DELAY_SPEED_MIN)); + } + + float slowdown = 1; + if (!isFamiliar) + { + if (entity->IsFrame(SLOW_PROBE_FRAMES, 1)) + { + Vector ahead = vector_add(vector_scale(vector_normalized(entity->velocity), GRID_CELL_SIZE), from); + int felt = grid_path_felt(room.GetGridPath(room.GetGridIndex(ahead))); + if ((uint32_t)(felt - 1) < GRID_PATH_SLOWING_MAX) slowdown = SLOWDOWN; + } + if (pathMarker >= 0 && room.GetGridPath(gridIndex) < GRID_PATH_IMPASSABLE) + room_grid_path_mark(room, gridIndex, pathMarker); + } + + if (entity->IsFrame(LINE_CHECK_FRAMES, entity->index)) + { + Vector targetCenter = room.GetGridPosition(room.GetGridIndex(position)); + int threshold = isFriendly || isFamiliar ? GRID_PATH_FREED : 0; + if (entity->entityGridCollisionClass == GRIDCOLL_WALLS) hasDirectPath = true; + else if (canCrushRocks) + reconstruction_missing("Room::CheckLine 007f0df0: the rocks a rock crusher sees through"); + else hasDirectPath = room_check_line(ownCenter, targetCenter, LINE_CHECK_GROUND, threshold); + } + + float directRange = mode == DIRECT_PATH_FAR ? DIRECT_RANGE_FAR : DIRECT_RANGE_NEAR; + if (isLarge && mode == DIRECT_PATH_NEAR) + directRange += std::max(entity->size * entity->sizeMulti.x, entity->size * entity->sizeMulti.y); + + Vector moveTarget{}; + if ((hasDirectPath && vector_length(vector_sub(position, entity->pos)) < directRange) || gridIndex == targetIndex) + { + moveTarget = vector_sub(position, offset); + moveCountdown -= ticks * CELL_DELAY_TICK; + gridIndexDelay -= ticks * CELL_DELAY_DIRECT_TICK; + } + else + { + if (room.GetGridPath(gridIndex) == GRID_PATH_SOLID || moveCountdown > 0) moveCountdown -= ticks; + else + { + moveCountdown = (int)(Random() % REPATH_RANGE) + REPATH_MIN; + grid_costs_fill(room, offset, isLarge); + if (isLarge) targetIndex = large_target_get(room, position, targetIndex); + grid_costs_flood(room, targetIndex, isFriendly); + } + if (isPathFound) moveTarget = room.GetGridPosition(path_next_get(room)); + } + path_steer(moveTarget, from, slowdown * speed); } // 007e4940 @@ -103,7 +394,7 @@ bool PathFinder::HasPathToPos(const Vector&, bool) } // 007e8010 -void PathFinder::SimulatePlayerMovement(float*) +void PathFinder::SimulatePlayerMovement(const Vector&, float) { reconstruction_missing("PathFinder::SimulatePlayerMovement 007e8010"); } diff --git a/src/path_finder.h b/src/path_finder.h index be415d6..d841cda 100644 --- a/src/path_finder.h +++ b/src/path_finder.h @@ -1,18 +1,23 @@ #pragma once #include "classes.h" +#include #include struct Entity; -// Lua's Direction, the way SimulatePlayerMovement reads a movement. +// The cells of the largest room grid (ROOM_GRID_CELLS), one cost each in a pathfinder's map. +constexpr int PATH_GRID_CELLS = 448; + +// Lua's Direction, the way SimulatePlayerMovement reads a movement and FindGridPath orders a cell's neighbours. enum PathDirection : int { PATH_DIRECTION_NONE = -1, PATH_DIRECTION_LEFT, PATH_DIRECTION_UP, PATH_DIRECTION_RIGHT, - PATH_DIRECTION_DOWN + PATH_DIRECTION_DOWN, + PATH_DIRECTION_COUNT }; // Whether a movement call steers even while its owner is feared, confused or charmed. @@ -22,12 +27,29 @@ enum StatusMode STATUS_IGNORED }; +// How far FindGridPath walks straight at a target in plain sight: only near it, or from anywhere in the room. +enum DirectPathMode +{ + DIRECT_PATH_NEAR, + DIRECT_PATH_FAR +}; + +// Copies (007e48b0) are the defaults. The original also gave each node a path, which nothing ever filled. +// A cell queued by FindGridPath's flood, at the cost of reaching it from the target. +struct PathNode +{ + int gridIndex = -1; + int cost = 0; +}; + // Construction (007e31a0) is the default, with the owner given by its holder. // Field accessors (00456370, 00456740, 00499dc0, 004be6e0) are the public fields. -// How an NPC finds its way around the room (Lua's PathFinder, the original's NPCAI_Pathfinder): the grid path it -// follows to a target, the spot it wanders to, and the evasion it keeps up. +// How an NPC finds its way around the room (Lua's PathFinder, the original's NPCAI_Pathfinder): the cost map it floods +// from a target and walks down, the spot it wanders to, and the evasion it keeps up. +// gridIndex is the cell it counts itself in, which follows its owner only after gridIndexDelay runs out. struct PathFinder { + std::array gridCosts{}; std::set visitedGridIndices; Entity* entity = nullptr; Vector gridPathTarget{}; @@ -38,9 +60,8 @@ struct PathFinder int directionTimer = 0; int evadeMovementCountdown = 0; int gridIndex = -1; + int gridIndexDelay = 0; int moveCountdown = 0; - int pathLength = 0; - int pathStep = 0; int stuckFrames = 0; int targetGridIndex = -1; bool canCrushRocks = false; @@ -53,12 +74,23 @@ struct PathFinder void ResetMovementTarget(); void UpdateGridIndex(); bool is_entity_friendly(); - void FindGridPath(const Vector& position, float speed, int pathMarker, bool isUseDirectPath); + int grid_path_felt(uint32_t gridPath); + void FindGridPath(const Vector& position, float speed, int pathMarker, DirectPathMode mode); void EvadeTarget(const Vector& targetPos, StatusMode mode); bool MoveRandomly(StatusMode mode); void MoveRandomlyAxisAligned(float speed, StatusMode mode); void MoveRandomlyBoss(StatusMode mode); void update_chase_movement(); bool HasPathToPos(const Vector& position, bool isIgnorePoop); - void SimulatePlayerMovement(float* inputs); + void SimulatePlayerMovement(const Vector& input, float speed); + +private: + bool is_target_kept(Room& room, int targetIndex); + void grid_costs_fill(Room& room, const Vector& offset, bool isLarge); + int large_target_get(Room& room, const Vector& position, int targetIndex); + void grid_costs_flood(Room& room, int targetIndex, bool isFriendly); + int path_next_get(Room& room); + void path_steer(const Vector& moveTarget, const Vector& from, float push); }; + +bool room_grid_path_mark(Room& room, int gridIndex, int marker); diff --git a/src/pause_screen.cpp b/src/pause_screen.cpp index 4261450..c508146 100644 --- a/src/pause_screen.cpp +++ b/src/pause_screen.cpp @@ -55,7 +55,6 @@ constexpr float FADE_SPEED = 0.08f; constexpr int FADE_TARGET_MENU = 2; constexpr int KEYBOARD = 0; constexpr int COLLECTIBLE_GLITCHED_CROWN = 689; -constexpr unsigned int PICKUP_COLLECTIBLE = 100; // Whether an action holds on one device, as KAGE's input manager asks. bool is_controller_action(int deviceId, ButtonAction action, ActionTest test) @@ -337,7 +336,7 @@ void PauseScreen::selection_confirm(int controller) menuSprite.overlayAnimState.SetAnimationData(nullptr); Entity_Player* player = g_game->GetPlayer(0); if (player->isDead && player->GetExtraLives() < 1) - reconstruction_missing("Game::DeleteSaveState 00959130: GameState::Delete on Manager's game state"); + game_save_delete(); game_fade_out(); break; } diff --git a/src/player_manager.cpp b/src/player_manager.cpp index f321945..708cf0c 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -1017,10 +1017,6 @@ void PlayerManager::Update() } void PlayerManager::trigger_room_clear() { reconstruction_missing("PlayerManager::trigger_room_clear 009bb840"); } -void PlayerManager::trigger_coop_baby_death(Entity_Player*) -{ - reconstruction_missing("PlayerManager::trigger_coop_baby_death 009bc120"); -} Vector PlayerManager::find_safe_spawn_position(Vector) { reconstruction_missing("PlayerManager::find_safe_spawn_position 009bc280"); diff --git a/src/room.cpp b/src/room.cpp index b595af1..5fc3008 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -63,9 +63,6 @@ constexpr ColorMod ASCENT_COLOR = {{1, 1, 1, 1}, {1.2f, 1.2f, 1.2f, 0.6f}, {0.07 constexpr ColorMod GREY_COLOR = {{1, 1, 1, 1}, {1, 1, 1, -1}, {0, 0, 0}}; // The entity types, variants and subtypes Room checks. -constexpr int PICKUP_COLLECTIBLE = 100; -constexpr int PICKUP_OLD_CHEST = 55; -constexpr int PICKUP_TROPHY = 370; constexpr int EFFECT_TINY_BUG = 21; constexpr int EFFECT_TINY_FLY = 33; constexpr int EFFECT_HEAVEN_LIGHT_DOOR = 39; @@ -1133,7 +1130,7 @@ void Room::init_first_visit_items() { RNG rng = {descriptor->decorationSeed, 9, 21, 16}; Vector center = GetCenterPos(); - entity_spawn(ENTITY_PICKUP, PICKUP_OLD_CHEST, vector_make(center.x + 0, center.y - 40), 0, rng.Next()); + entity_spawn(ENTITY_PICKUP, PICKUP_OLDCHEST, vector_make(center.x + 0, center.y - 40), 0, rng.Next()); } if (g_game->seedEffects.HasSeedEffect(SEED_EFFECT_PRE_ITEMS)) { @@ -2644,35 +2641,6 @@ void Room::attach_minecarts() } } -// 007eff50 Respawns the entities a past visit saved, then forgets them. A cleared Mausoleum II secret exit loses its -// inner walls and doors. -void Room::RestoreState() -{ - if (!descriptor->savedEntities.empty()) - reconstruction_missing("Room::RestoreState 007eff50: the saved entities (EntitySaveState has no layout yet)"); - descriptor->savedEntities.clear(); - - bool isOpenedExit = descriptor->gridIndex == ROOM_SECRET_EXIT_IDX && g_game->stage == STAGE_MAUSOLEUM_II && - descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; - if (!isOpenedExit) return; - - for (int y = 1; y < gridHeight - 1; y++) - for (int x = 1; x < gridWidth - 1; x++) - { - int gridIndex = GetGridIndexByTile(x, y); - GridEntity* wall = gridIndex >= 0 ? gridEntities[gridIndex] : nullptr; - if (!wall || wall->type != GRID_WALL || wall->gridIndex >= ROOM_GRID_CELLS) continue; - - GridEntity* linked = gridEntities[wall->gridIndex]; - if (!linked || linked->type == GRID_DECORATION) continue; - - gridPaths[wall->gridIndex] = GRID_PATH_RESET; - gridEntities[wall->gridIndex] = nullptr; - delete linked; - } - for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) RemoveDoor(slot); -} - // How bright the lighting layer is at a point of the room, the light rain falls in: none without the layer. // Reading it needs the layer image's pixels, which the renderer does not keep. static float fx_light_get(Room& room) @@ -3375,53 +3343,3 @@ void Room::card_against_humanity_fill() reconstruction_missing("Room::card_against_humanity_fill 007fe220"); } -// The last frames of a clear's delay that leaving the room still counts the clear in. -constexpr int ROOM_CLEAR_DELAY_PENDING = 8; - -// Whether the room keeps an entity when the players leave, as Entity_Pickup::CanFlip (007eeeb0) checks before saving -// it: alive, not persistent, off any minecart (unless it rides the one saved with it), and of a kept type. -static bool is_entity_kept(Room& room, Entity& entity, bool isRiding) -{ - if (entity.isDead || (entity.flags & FLAG_PERSISTENT) || (entity.minecart && !isRiding)) return false; - return entity_type_is_saved(entity.type, entity.variant, (uint32_t)entity.subtype, entity.spawnerType, room.IsClear()); -} - -// 007efa50 Stores the room in its descriptor as the players leave: a partial shop restock comes due, and a clear still -// pending counts (the score, the players' room clear, the award and Greed's wave). Then, outside the debug room and -// once visited, its grid cells and the entities it keeps (a minecart only with its rider) are saved. -void Room::on_leave() -{ - Game& game = *g_game; - - if (shopRestockTimer > 0) - { - shopRestockTimer = -1; - reconstruction_missing("Room::ShopRestockPartial 008158a0"); - } - if (game.currentRoomIdx == ROOM_DEBUG_IDX || descriptor->visitedCount == 0) return; - if (roomClearDelay >= 1 && roomClearDelay <= ROOM_CLEAR_DELAY_PENDING && !IsClear()) - { - bool isGreedWave = game.IsGreedMode() && roomType == ROOM_DEFAULT; - - roomClearDelay = 0; - descriptor->flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; - descriptor->clearCount++; - 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"); - if (isGreedWave) game.greedLastBeatenWave = game.greedModeWave; - } - - descriptor->savedEntities.clear(); - for (int i = 0; i < gridWidth * gridHeight; i++) - descriptor->savedGridEntities[i] = gridEntities[i] ? gridEntities[i]->desc_save() : GRID_SAVE_EMPTY; - for (Entity* entity : entityList.updateEL) - { - bool isCart = entity->type == ENTITY_MINECART && entity->variant == 0; - Entity* rider = entity->child.get(); - bool isKept = isCart ? rider && is_entity_kept(*this, *rider, true) && is_entity_kept(*this, *entity, false) - : is_entity_kept(*this, *entity, false); - if (isKept) reconstruction_missing("Room::on_leave 007efa50: saving an entity (EntitySaveState has no layout yet)"); - } -} diff --git a/src/room_render.cpp b/src/room_render.cpp index b728651..78c9cb9 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -88,6 +88,34 @@ constexpr float PLATE_PRESSED_ALPHA = 0.25f; constexpr float NIGHT_LIGHT_ANGLE = 90; constexpr float PIXELATION_EASE_FRAMES = 15; +// A fireplace's light: how it fades and shrinks as the fire burns down, how far it flickers, how small Coal glows, +// and the colors of the fires by variant (blue and purple moveable ones too), white past the named ones. +constexpr float FIRE_LIGHT_FADE = 0.5f; +constexpr float FIRE_LIGHT_SCALE = 1.2f; +constexpr float FIRE_LIGHT_SHRINK = 0.2f; +constexpr float FIRE_LIGHT_FLICKER = 3; +constexpr float COAL_LIGHT_SCALE = 0.4f; +constexpr int FIRE_RED = 1; +constexpr int FIRE_BLUE = 2; +constexpr int FIRE_PURPLE = 3; +constexpr int FIRE_WHITE = 4; +constexpr int FIRE_COAL = 11; +constexpr int FIRE_MOVEABLE_BLUE = 12; +constexpr int FIRE_MOVEABLE_PURPLE = 13; +constexpr ColorMod FIRE_LIGHT_RED = {{1, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FIRE_LIGHT_BLUE = {{0.4f, 0.8f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FIRE_LIGHT_PURPLE = {{0.8f, 0.4f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FIRE_LIGHT_COAL = {{1, 0.6f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FIRE_LIGHT = {{1, 1, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The flicker of entity lights: its RNG's shifts, and the seed it takes for a zero one. +constexpr uint32_t FLICKER_SHIFTS[] = {5, 27, 25}; +constexpr uint32_t FLICKER_SEED_ZERO = 1; + +// RandomVector's own xorshift and the scale of its angle. +constexpr float RANDOM_VECTOR_SCALE = 2.3283062e-10f; +constexpr float RANDOM_VECTOR_HALF_TURN = 3.14f; + // The lighting overlay: how much a lightning flash lifts it, and how much darker some rooms are. constexpr float LIGHTNING_LIGHT = 0.2f; constexpr float LIGHTNING_FLASH = 0.5f; @@ -726,9 +754,8 @@ static void entity_glow_render(Room& room, Entity& entity, Vector offset) Vector ember = vector_add(render_position_get(vector_make(entity.pos.x, entity.pos.y - WILLO_HEIGHT), RENDER_SNAPPED), base); - Vector direction{}; light.color = WILLO_GLOW_COLOR; - RandomVector(&direction, rng.Next()); + Vector direction = RandomVector(rng.Next()); float distance = rng.RandomFloat(); light.scale = vector_make(WILLO_SCALE, WILLO_SCALE); sprite_draw(light, vector_make(ember.x + distance * direction.x, ember.y + distance * direction.y)); @@ -758,8 +785,7 @@ static void entity_glow_render(Room& room, Entity& entity, Vector offset) player.HasCollectible(COLLECTIBLE_FIRE_MIND); if (!isFireMind && !is_item_costume_visible(player, items.GetNullItem(NULL_ITEM_BRIMSTONE_FLAME), 0)) return; - Vector direction{}; - RandomVector(&direction, rng.Next()); + Vector direction = RandomVector(rng.Next()); float distance = rng.RandomFloat() * FLAME_FLICKER; light.color = isFireMind ? FIRE_MIND_GLOW_COLOR : FLAME_GLOW_COLOR; light.scale = vector_make(1, 1); @@ -870,7 +896,6 @@ static bool is_entity_lit(Room& room, Entity& entity) case ENTITY_EFFECT: return std::ranges::find(EFFECT_LIGHT_VARIANTS, variant) != std::end(EFFECT_LIGHT_VARIANTS); case LIGHT_TYPE_EMBER_FLY: return variant == 3 && room.backdropType == BACKDROP_ASHPIT; - case ENTITY_FIREPLACE: return entity.health > 1; case LIGHT_TYPE_SPIDER: return room.bossId == BOSS_LIGHT_SPIDER || isPitchBlack; case LIGHT_TYPE_GLOWING: return true; case LIGHT_TYPE_VARIANT_10: return variant == 10; @@ -945,14 +970,60 @@ static void player_light_render(Room& room, Entity_Player& player, Vector offset sprite_draw(light, position); } +// 0067f0d0 A unit direction from a seed, through RandomVector's own xorshift. A zero seed, which the original stops +// on, points right. +Vector RandomVector(uint32_t seed) +{ + seed ^= seed >> 3; + seed ^= seed << 1; + seed ^= seed >> 14; + float angle = (float)seed * RANDOM_VECTOR_SCALE * RANDOM_VECTOR_HALF_TURN; + angle += angle; + return vector_make(std::cos(angle), std::sin(angle)); +} + +// A burning fireplace's glow: its fire's color, fading and shrinking as it burns down (Coal small), flickering about +// the fire. +static void fireplace_light_render(Room& room, Entity& fire, Vector offset, RNG& flicker) +{ + if (fire.health <= 1) return; + + ANM2& light = room.lightSprite; + float burnt = 1 - fire.health / fire.maxHitPoints; + float scale = FIRE_LIGHT_SCALE - burnt * FIRE_LIGHT_SHRINK; + switch (fire.variant) + { + case FIRE_PURPLE: + case FIRE_MOVEABLE_PURPLE: light.color = FIRE_LIGHT_PURPLE; break; + case FIRE_BLUE: + case FIRE_MOVEABLE_BLUE: light.color = FIRE_LIGHT_BLUE; break; + case FIRE_RED: light.color = FIRE_LIGHT_RED; break; + case FIRE_WHITE: light.color = COLOR_DEFAULT; break; + case FIRE_COAL: + light.color = FIRE_LIGHT_COAL; + scale *= COAL_LIGHT_SCALE; + break; + default: light.color = FIRE_LIGHT; break; + } + light.color._tint[3] = 1 - burnt * FIRE_LIGHT_FADE; + light.scale = vector_make(scale, scale); + + Vector direction = RandomVector(flicker.Next()); + float distance = flicker.RandomFloat() * FIRE_LIGHT_FLICKER; + Vector position = vector_add(render_position_get(fire.pos, RENDER_SNAPPED), offset); + sprite_draw(light, vector_make(position.x + distance * direction.x, position.y + distance * direction.y)); +} + // 00806c20 Draws an entity's light into the light overlay, flickering by the frame and the entity's seed: the players' // lights, and those of the glowing tears, familiars, bombs, lasers, projectiles, enemies and effects. A minecart's // rider lights from the cart's null. -// Only the players' lights and the cases that draw nothing are reconstructed yet: the sprites with light layers and -// the other lit entities stop. +// Only the players' and fireplaces' lights and the cases that draw nothing are reconstructed yet: the sprites with +// light layers and the other lit entities stop. static void entity_light_render(Room& room, Entity& entity, Vector offset) { Vector base = vector_add(offset, minecart_offset(entity)); + uint32_t seed = (uint32_t)g_game->frameCount + entity.initSeed; + RNG flicker = {seed ? seed : FLICKER_SEED_ZERO, FLICKER_SHIFTS[0], FLICKER_SHIFTS[1], FLICKER_SHIFTS[2]}; DAT_00c7977e = 1; if (entity.isVisible && entity.sprite.bitflags & (ANIM_RENDER_ENABLE_LAYER_LIGHTING | ANIM_RENDER_ENABLE_NULL_LAYER_LIGHTING)) @@ -961,6 +1032,7 @@ static void entity_light_render(Room& room, Entity& entity, Vector offset) { if (entity.isExists) player_light_render(room, static_cast(entity), base); } + else if (entity.type == ENTITY_FIREPLACE) fireplace_light_render(room, entity, base, flicker); else if (is_entity_lit(room, entity)) reconstruction_missing("Room::render_entity_light 00806c20: the lights of entities but the players"); diff --git a/src/room_render.h b/src/room_render.h index 580f4d2..bf29086 100644 --- a/src/room_render.h +++ b/src/room_render.h @@ -50,4 +50,5 @@ extern RoomSurfaces roomSurfaces; extern std::array roomShockwaves; void room_surfaces_init(); +Vector RandomVector(uint32_t seed); KColor kcolor_apply(const ColorMod& color, const KColor& input); diff --git a/src/room_state.cpp b/src/room_state.cpp new file mode 100644 index 0000000..a2c3e02 --- /dev/null +++ b/src/room_state.cpp @@ -0,0 +1,463 @@ +#include "room_state.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_slot.h" +#include "game.h" +#include "log.h" +#include "npc_ai.h" +#include "room.h" +#include +#include +#include + +// The last frames of a clear's delay that leaving the room still counts the clear in. +constexpr int ROOM_CLEAR_DELAY_PENDING = 8; +constexpr int GRID_PATH_RESET = 900; +constexpr int STAGE_MAUSOLEUM_II = 8; + +// The effects, slots and enemies whose saves keep more than the common fields. +constexpr int EFFECT_TINY_BUG = 21; +constexpr int EFFECT_TINY_FLY = 33; +constexpr int EFFECT_HEAVEN_LIGHT_DOOR = 39; +constexpr int EFFECT_WORM = 63; +constexpr int EFFECT_BEETLE = 64; +constexpr int EFFECT_WISP = 65; +constexpr int EFFECT_WALL_BUG = 68; +constexpr int EFFECT_BUTTERFLY = 69; +constexpr int EFFECT_DIRT_PATCH = 116; +constexpr int EFFECT_SPAWNER = 120; +constexpr int EFFECT_TADPOLE = 158; +constexpr int EFFECT_LIL_GHOST = 159; +constexpr int HEAVEN_LIGHT_MOONLIGHT = 1; +constexpr int GIDEON_TYPE = 907; +constexpr int SLOT_DONATION_MACHINE = 8; +constexpr int SLOT_SHOP_RESTOCK_MACHINE = 10; +constexpr int SLOT_STATE_BROKEN = 3; +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. +constexpr std::array PICKUPS_SAVING_TARGET = {PICKUP_COLLECTIBLE, PICKUP_BED, PICKUP_BIGCHEST, + PICKUP_TROPHY, PICKUP_MOMSCHEST, PICKUP_MEGACHEST}; + +// The critters that come back anywhere in the room. +constexpr std::array EFFECTS_PLACED_RANDOMLY = {EFFECT_TINY_BUG, EFFECT_TINY_FLY, EFFECT_WORM, EFFECT_BEETLE, + EFFECT_WISP, EFFECT_BUTTERFLY, EFFECT_TADPOLE}; + +// Saves a pickup: its charge, price and shop, its timeout, look and pedestal, its pool, the collectibles it cycles +// (in the extra bytes) and Flip's other item. Empty chests and pedestals, a haunted chest in flight and a pickup +// about to vanish are not kept. +static bool pickup_state_save(Entity_Pickup& pickup, EntitySaveState& state) +{ + if (pickup.variant == PICKUP_ETERNALCHEST && pickup.chestReCloseTimer > 0) state.subtype = CHEST_RECLOSED_SUBTYPE; + + bool isEmpty = (Entity_Pickup::IsChest(pickup.variant) || pickup.variant == PICKUP_COLLECTIBLE) && state.subtype == 0; + bool isThrown = pickup.variant == PICKUP_HAUNTEDCHEST && pickup.HasEntityFlags(FLAG_HELD | FLAG_THROWN); + if (isEmpty || isThrown || pickup.timeout >= 0) return false; + + state.intStorage2 = pickup.charge; + state.intStorage3 = pickup.price; + state.byteStorage = pickup.isAutoUpdatePrice; + state.intStorage4 = pickup.shopItemId; + state.boolStorage1 = pickup.isTouched; + state.intStorage6 = pickup.coopDuplicateIndex; + state.intStorage7 = pickup.optionsPickupIndex; + state.intStorage5 = pickup.timeout; + state.floatStorage2 = pickup.sprite.scale.x; + state.boolStorage2 = pickup.isForceBlind; + state.intStorage1 = pickup.GetAlternatePedestal(); + state.intStorage8 = pickup.varData; + state.floatStorage1 = std::bit_cast(pickup.itemPoolType); + + if (pickup.cycleCollectibleCount) + { + std::array cycle{}; + std::copy_n(pickup.cycleCollectibleList.begin(), std::min(pickup.cycleCollectibleCount, cycle.size()), + cycle.begin()); + state.extraData = std::bit_cast(cycle); + } + if (pickup.flipSaveState) state.child = std::make_shared(*pickup.flipSaveState); + return true; +} + +// Saves a slot's donations and prize, and a restock machine's timer. A broken or gone slot is not kept, but for the +// donation machine. +static bool slot_state_save(Entity_Slot& slot, EntitySaveState& state) +{ + bool isGone = slot.state == SLOT_STATE_BROKEN || slot.state == SLOT_STATE_GONE; + if (isGone && slot.variant != SLOT_DONATION_MACHINE) return false; + + state.intStorage1 = slot.donationValue; + state.intStorage7 = slot.prizeCollectible; + if (slot.variant == SLOT_SHOP_RESTOCK_MACHINE) state.intStorage2 = slot.triggerTimer; + return true; +} + +// Saves a bomb: its tear effects but Hydrobounce, whether it is a fetus, its damage, radius and size, and the index of +// the player that placed it. An invisible bomb is not kept. +static bool bomb_state_save(Entity_Bomb& bomb, EntitySaveState& state) +{ + if (!bomb.isVisible) return false; + + TearFlags flags = bomb.tearFlags; + std::array words = {&state.intStorage2, &state.intStorage3, + (uint32_t*)&state.intStorage4, (uint32_t*)&state.intStorage5}; + flags.reset(TEAR_HYDROBOUNCE); + for (int i = 0; i < TEAR_FLAG_WORDS; i++) + *words[i] = (uint32_t)(flags >> i * TEAR_FLAG_WORD_BITS & TearFlags(UINT32_MAX)).to_ulong(); + + state.boolStorage2 = bomb.isFetus; + state.floatStorage1 = bomb.explosionDamage; + state.floatStorage2 = bomb.radiusMultiplier; + state.byteStorage = BOMB_NO_PLAYER; + Entity* spawner = bomb.GetLastSpawner(); + if (spawner && spawner->is_player()) state.byteStorage = (uint8_t)static_cast(spawner)->playerIndex; + state.intStorage1 = std::bit_cast(bomb.scale); + return true; +} + +// Saves an effect's state: a dirt patch's (whose effect child it stops at once), a spawner's with its data, and Lil +// Ghost's. Moonlight is kept only while lit and spawned by nothing. +static bool effect_state_save(Entity_Effect& effect, EntitySaveState& state) +{ + Entity* child = effect.child.get(); + + switch (effect.variant) + { + case EFFECT_DIRT_PATCH: + state.intStorage1 = effect.state; + if (!child || child->type != ENTITY_EFFECT) return true; + static_cast(child)->state = -1; + child->Update(); + return true; + case EFFECT_SPAWNER: + state.intStorage4 = (int)effect.varData[0]; + state.intStorage2 = effect.varData[1]; + [[fallthrough]]; + case EFFECT_LIL_GHOST: + state.intStorage1 = effect.state; + return true; + case EFFECT_HEAVEN_LIGHT_DOOR: + if (effect.subtype != HEAVEN_LIGHT_MOONLIGHT) return true; + return effect.state >= 0 && effect.spawnerType == 0; + } + return true; +} + +// 007eeeb0 Saves an entity the room keeps when the players leave (Entity_Pickup::CanFlip in the dump), or refuses a +// dead, persistent or unkept one: its kind, place, seeds and spawner, then what its class keeps. +bool entity_state_save(Room& room, Entity& entity, EntitySaveState& state, MinecartCheck check) +{ + if (entity.isDead || entity.HasEntityFlags(FLAG_PERSISTENT)) return false; + if (entity.minecart && check == MINECART_REFUSED) return false; + if (!entity_type_is_saved(entity.type, entity.variant, (uint32_t)entity.subtype, entity.spawnerType, room.IsClear())) + return false; + + state.type = entity.type; + state.variant = entity.variant; + state.subtype = entity.subtype; + state.targetPosition = entity.pos; + state.initSeed = entity.initSeed; + state.dropSeed = entity.dropRNG._seed; + state.spawnerType = entity.spawnerType; + state.spawnerVariant = (int)entity.spawnerVariant; + state.gridSpawnIdx = (int16_t)entity.spawnGridIndex; + state.floatStorage3 = entity.scoreMultiplier; + + bool isPickupTarget = entity.is_pickup() && std::ranges::count(PICKUPS_SAVING_TARGET, entity.variant); + bool isTargetSaved = isPickupTarget || entity.is_slot() || entity.type == ENTITY_GENERIC_PROP; + bool isTargetSet = entity.targetPosition.x != 0 || entity.targetPosition.y != 0; + if (isTargetSaved && isTargetSet) state.targetPosition = entity.targetPosition; + + switch (entity.type) + { + case ENTITY_PICKUP: + return pickup_state_save(static_cast(entity), state); + case ENTITY_SLOT: + return slot_state_save(static_cast(entity), state); + case ENTITY_FIREPLACE: + case ENTITY_MOVABLE_TNT: + state.intStorage1 = (uint32_t)std::max(entity.health, 0.0f); + return true; + case ENTITY_BOMB: + return bomb_state_save(static_cast(entity), state); + case ENTITY_EFFECT: + return effect_state_save(static_cast(entity), state); + case ENTITY_MINECART: + state.floatStorage1 = std::atan2(entity.targetPosition.y, entity.targetPosition.x) * RADIANS_TO_DEGREES; + return true; + } + return true; +} + +// Restores a pickup: its charge, price and shop, its look, pedestal and pool, the collectibles it cycles and Flip's +// other item. A Genesis item of a continued run stays and holds the Genesis room's timer. +static void pickup_state_restore(Room& room, Entity_Pickup& pickup, const EntitySaveState& state) +{ + Game& game = *g_game; + + if (state.subtype != 0) pickup.charge = (int)state.intStorage2; + pickup.update_price_sprite((int)state.intStorage3); + pickup.isAutoUpdatePrice = state.byteStorage; + pickup.shopItemId = std::clamp(state.intStorage4, SHOP_ITEM_ID_MIN, SHOP_ITEM_ID_MAX); + pickup.isTouched = state.boolStorage1; + pickup.coopDuplicateIndex = (int)state.intStorage6; + if (pickup.coopDuplicateIndex != 0 && pickup.coopDuplicateIndex != -1) pickup.cycleCollectibleCount = 0; + + bool wasBlind = pickup.isForceBlind; + pickup.optionsPickupIndex = (int)state.intStorage7; + pickup.spawnerType = state.spawnerType; + pickup.spawnerVariant = (uint32_t)state.spawnerVariant; + pickup.timeout = state.intStorage5; + pickup.sprite.scale = vector_make(state.floatStorage2, state.floatStorage2); + pickup.isForceBlind = state.boolStorage2; + if (pickup.variant == PICKUP_COLLECTIBLE && pickup.subtype != 0 && wasBlind != pickup.isForceBlind) + pickup.UpdateSprite(false); + pickup.SetAlternatePedestal((int)state.intStorage1); + pickup.varData = (int)state.intStorage8; + pickup.itemPoolType = std::bit_cast(state.floatStorage1); + + if (state.extraData) + { + auto cycle = std::bit_cast>(*state.extraData); + pickup.cycleCollectibleCount = 0; + for (uint32_t id : cycle) + { + if (!id) break; + pickup.cycleCollectibleList[pickup.cycleCollectibleCount++] = id; + } + } + if (state.child) + { + pickup.flipSaveState = state.child; + pickup.altPedestalANM2.Reset(); + } + pickup.UpdateLootPreview(); + + bool isGenesisItem = game.currentRoomIdx == ROOM_GENESIS_IDX && game.isStartingFromState && + pickup.variant == PICKUP_COLLECTIBLE && pickup.spawnGridIndex >= 0; + if (!isGenesisItem) return; + pickup.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + room.genesisTimer = -1; +} + +// Restores a bomb's tear effects, look, damage and radius (its sprite scaled by the radius), and gives it back to the +// player that placed it, the first one when that player is gone. +static void bomb_state_restore(Entity_Bomb& bomb, const EntitySaveState& state) +{ + PlayerManager& players = g_game->playerManager; + std::array words = {state.intStorage2, state.intStorage3, (uint32_t)state.intStorage4, + (uint32_t)state.intStorage5}; + + bomb.tearFlags.reset(); + for (int i = TEAR_FLAG_WORDS - 1; i >= 0; i--) bomb.tearFlags = bomb.tearFlags << TEAR_FLAG_WORD_BITS | TearFlags(words[i]); + bomb.isLoadCostumes = true; + bomb.isFetus = state.boolStorage2; + bomb.explosionDamage = state.floatStorage1; + bomb.radiusMultiplier = state.floatStorage2; + bomb.sprite.scale = vector_make(state.floatStorage2, state.floatStorage2); + bomb.spawnerType = state.spawnerType; + bomb.scale = std::bit_cast(state.intStorage1); + + int playerIndex = (int8_t)state.byteStorage; + if (playerIndex < 0) return; + if (playerIndex >= (int)players.playerList.size()) playerIndex = 0; + bomb.spawnerEntity = g_game->GetPlayer(playerIndex); +} + +// Restores an effect: the critters scatter anywhere in the room, a wall bug updates at once, and a dirt patch and a +// spawner get their state back. +static void effect_state_restore(Room& room, Entity_Effect& effect, const EntitySaveState& state) +{ + if (std::ranges::count(EFFECTS_PLACED_RANDOMLY, effect.variant)) + { + float yUnit = random_unit(); + float xUnit = random_unit(); + Vector size = vector_sub(room.bottomRightPos, room.topLeftPos); + effect.pos = vector_make(xUnit * size.x + room.topLeftPos.x, yUnit * size.y + room.topLeftPos.y); + return; + } + + switch (effect.variant) + { + case EFFECT_WALL_BUG: + effect.Update(); + return; + case EFFECT_SPAWNER: + effect.varData[0] = (uint32_t)state.intStorage4; + effect.varData[1] = state.intStorage2; + [[fallthrough]]; + case EFFECT_DIRT_PATCH: + effect.state = (int)state.intStorage1; + return; + } +} + +// Restores an enemy's health and champion color. One saved without a place would go to a free spot near the center. +static void enemy_state_restore(Entity& entity, const EntitySaveState& state) +{ + if (!entity.IsEnemy() || entity.type == ENTITY_SHOPKEEPER || entity.type == GIDEON_TYPE) return; + + entity.health = state.floatStorage1; + if (state.intStorage4 >= 0) static_cast(entity).MakeChampion(state.initSeed, state.intStorage4, false); + if (state.targetPosition.x == 0 && state.targetPosition.y == 0) + reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520: a saved enemy without a place"); +} + +// 007ef420 Gives a respawned entity what its save kept (Entity_Pickup::RestoreState in the dump): its drop seed, grid +// cell and score, then what its class keeps. +void entity_state_restore(Room& room, Entity& entity, const EntitySaveState& state) +{ + if (entity.pos.x == 0 && entity.pos.y == 0) + reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520: a saved entity without a place"); + + entity.dropRNG = DROP_RNG_SAVED; + entity.dropRNG._seed = state.dropSeed; + entity.spawnGridIndex = state.gridSpawnIdx; + entity.scoreMultiplier = state.floatStorage3; + + switch (entity.type) + { + case ENTITY_PICKUP: + pickup_state_restore(room, static_cast(entity), state); + return; + case ENTITY_SLOT: + { + Entity_Slot& slot = static_cast(entity); + slot.donationValue = (int)state.intStorage1; + if (slot.variant == SLOT_SHOP_RESTOCK_MACHINE) slot.triggerTimer = state.intStorage2; + slot.SetPrizeType((int)state.intStorage7); + return; + } + case ENTITY_EFFECT: + effect_state_restore(room, static_cast(entity), state); + return; + case ENTITY_FIREPLACE: + case ENTITY_MOVABLE_TNT: + entity.health = (float)state.intStorage1; + return; + case ENTITY_BOMB: + bomb_state_restore(static_cast(entity), state); + return; + } + enemy_state_restore(entity, state); +} + +// 007efa50 Stores the room in its descriptor as the players leave: a partial shop restock comes due, and a clear still +// pending counts (the score, the players' room clear, the award and Greed's wave). Then, outside the debug room and +// once visited, its grid cells and the entities it keeps are saved, a minecart only with its rider, saved after it. +void Room::on_leave() +{ + Game& game = *g_game; + + if (shopRestockTimer > 0) + { + shopRestockTimer = -1; + reconstruction_missing("Room::ShopRestockPartial 008158a0"); + } + if (game.currentRoomIdx == ROOM_DEBUG_IDX || descriptor->visitedCount == 0) return; + if (roomClearDelay >= 1 && roomClearDelay <= ROOM_CLEAR_DELAY_PENDING && !IsClear()) + { + bool isGreedWave = game.IsGreedMode() && roomType == ROOM_DEFAULT; + + roomClearDelay = 0; + descriptor->flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; + descriptor->clearCount++; + 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"); + if (isGreedWave) game.greedLastBeatenWave = game.greedModeWave; + } + + std::vector& saved = descriptor->savedEntities; + saved.clear(); + for (int i = 0; i < gridWidth * gridHeight; i++) + descriptor->savedGridEntities[i] = gridEntities[i] ? gridEntities[i]->desc_save() : GRID_SAVE_EMPTY; + + for (size_t i = 0; i < entityList.updateEL.size(); i++) + { + Entity& entity = *entityList.updateEL[i]; + EntitySaveState state; + if (!entity.IsType(ENTITY_MINECART, 0, -1)) + { + if (entity_state_save(*this, entity, state, MINECART_REFUSED)) saved.push_back(std::move(state)); + continue; + } + + EntitySaveState riderState; + Entity* rider = entity.child.get(); + if (!rider || !entity_state_save(*this, *rider, riderState, MINECART_IGNORED)) continue; + if (!entity_state_save(*this, entity, state, MINECART_REFUSED)) continue; + saved.push_back(std::move(state)); + saved.push_back(std::move(riderState)); + } +} + +// Opens a cleared Mausoleum II secret exit: the cells the inner walls cover lose what they hold, and the doors go. +static void secret_exit_open(Room& room) +{ + for (int y = 1; y < room.gridHeight - 1; y++) + for (int x = 1; x < room.gridWidth - 1; x++) + { + int gridIndex = room.GetGridIndexByTile(x, y); + GridEntity* wall = gridIndex >= 0 ? room.gridEntities[gridIndex] : nullptr; + if (!wall || wall->type != GRID_WALL || wall->gridIndex >= ROOM_GRID_CELLS) continue; + + GridEntity* linked = room.gridEntities[wall->gridIndex]; + if (!linked || linked->type == GRID_DECORATION) continue; + + room.gridPaths[wall->gridIndex] = GRID_PATH_RESET; + room.gridEntities[wall->gridIndex] = nullptr; + delete linked; + } + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) room.RemoveDoor(slot); +} + +// 007eff50 Respawns the entities a past visit saved where they were, each given back what its save kept (a rider gets +// its minecart back on the cart's cell, facing its way), then forgets them. A cleared Mausoleum II secret exit opens. +// The pickups come back as they were, so drawing them ignores the modifiers that would change them. +// A minecart saved last has no rider, where the original would read past the list: it is skipped. +void Room::RestoreState() +{ + std::vector& saved = descriptor->savedEntities; + + g_pickupIgnoreModifiers++; + for (size_t i = 0; i < saved.size(); i++) + { + const EntitySaveState& cart = saved[i]; + bool isCart = cart.type == ENTITY_MINECART && cart.variant == 0; + if (isCart && ++i == saved.size()) break; + + const EntitySaveState& state = saved[i]; + Entity* entity = g_game->Spawn({.position = state.targetPosition, + .subType = state.subtype, + .type = state.type, + .variant = state.variant, + .seed = state.initSeed}); + if (!entity) continue; + entity_state_restore(*this, *entity, state); + if (!isCart) continue; + + float angle = cart.floatStorage1 * DEGREES_TO_RADIANS; + entity->GiveMinecart(GetGridPosition(cart.gridSpawnIdx), vector_make(std::cos(angle), std::sin(angle))); + } + saved.clear(); + + bool isOpenedExit = descriptor->gridIndex == ROOM_SECRET_EXIT_IDX && g_game->stage == STAGE_MAUSOLEUM_II && + descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; + if (isOpenedExit) secret_exit_open(*this); + g_pickupIgnoreModifiers--; +} diff --git a/src/room_state.h b/src/room_state.h new file mode 100644 index 0000000..f6f6525 --- /dev/null +++ b/src/room_state.h @@ -0,0 +1,15 @@ +#pragma once + +#include "entity_save_state.h" + +class Room; + +// Whether saving an entity that rides a minecart refuses it, or ignores the cart because the cart is saved with it. +enum MinecartCheck +{ + MINECART_REFUSED, + MINECART_IGNORED +}; + +bool entity_state_save(Room& room, Entity& entity, EntitySaveState& state, MinecartCheck check); +void entity_state_restore(Room& room, Entity& entity, const EntitySaveState& state); diff --git a/src/room_update.cpp b/src/room_update.cpp index cdfcc3b..8ddfcf7 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -1,4 +1,7 @@ +#include "entity_effect.h" +#include "entity_laser.h" #include "entity_npc.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" @@ -106,7 +109,6 @@ constexpr int COLLECTIBLE_BROKEN_SHOVEL = 550; constexpr int COLLECTIBLE_VADE_RETRO = 653; constexpr int COLLECTIBLE_ASTRAL_PROJECTION = 677; constexpr int NULL_EFFECT_POOP_CLOUD = 64; -constexpr int PICKUP_COLLECTIBLE = 100; constexpr int EFFECT_RAIN_DROP = 41; constexpr int EFFECT_BLOOD_PARTICLE = 5; constexpr int EFFECT_FALLING_EMBER = 87; @@ -144,11 +146,49 @@ constexpr int BACKDROP_CORPSE3 = 44; constexpr uint32_t RNG_SHIFT_COUPON_1 = 1; constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; -// The entities with ambient loops of their own: enemies by type, laser and effect variants. -constexpr int SOUND_NPC_TYPES[] = {13, 14, 18, 25, 33, 61, 80, 214, 222, 249, 256, 281, 296, - 306, 808, 819, 838, 868, 886, 893, 950, 951, 965}; -constexpr int SOUND_LASER_VARIANTS[] = {6, 15}; -constexpr int SOUND_EFFECT_VARIANTS[] = {168, 171, 178, 180, 193}; +// The entities with ambient loops of their own (Lua's EntityType, EffectVariant and laser variants). +constexpr int AMBIENT_FLY_TYPES[] = {13, 14, 18, 25, 61, 80, 214, 222, 249, 256, 281, 296, 808, 819, 838, 868}; +constexpr int ENTITY_HUSH_FLY = 296; +constexpr int ENTITY_PORTAL = 306; +constexpr int ENTITY_VIS_FATTY = 886; +constexpr int ENTITY_BALL_AND_CHAIN = 893; +constexpr int ENTITY_DOGMA = 950; +constexpr int BEAST_FLY_VARIANTS[] = {11, 21}; +constexpr int DOGMA_ANGEL = 2; +constexpr int DOGMA_ANGEL_STATE = 10; +constexpr int LASER_LOOP_VARIANTS[] = {6, 15}; +constexpr int EFFECT_COLOSTOMIA_PUDDLE = 168; +constexpr int EFFECT_DOGMA_BLACKHOLE = 171; +constexpr int EFFECT_URN_OF_SOULS = 178; +constexpr int EFFECT_RIFT = 180; +constexpr int EFFECT_ANIMA_CHAIN = 193; +constexpr int BLACKHOLE_STATE_OPEN = 1; + +// How the sources sound: the reach of the enemies' loops, the flies' buzz (Hush's flies quieter, the whole buzz capped), +// fire, portals and rifts, a laser, Vis Fatty's, the Urn of Souls', the black hole's and the ball and chain's reach, +// the minecarts' full speed, Dogma's reach and its angels' speed, the rain's share, and the anima chain's fade. +constexpr float AMBIENT_NPC_REACH = 450; +constexpr float FLY_VOLUME = 0.35f; +constexpr float HUSH_FLY_VOLUME = 0.05f; +constexpr float FLY_VOLUME_MAX = 1.5f; +constexpr float FIRE_VOLUME = 0.6f; +constexpr float PORTAL_VOLUME = 0.6f; +constexpr float RIFT_VOLUME = 0.2f; +constexpr float LASER_VOLUME = 1.2f; +constexpr float FATTY_LASER_VOLUME = 0.5f; +constexpr float URN_VOLUME = 1.6f; +constexpr float BLACKHOLE_REACH = 2000; +constexpr float CHAIN_REACH = 1200; +constexpr float CHAIN_VOLUME = 0.4f; +constexpr float MINECART_REACH = 1200; +constexpr float MINECART_FULL_SPEED = 30; +constexpr float DOGMA_REACH = 1500; +constexpr float DOGMA_VOLUME_MIN = 0.02f; +constexpr float ANGEL_SPEED_SCALE = 0.125f; +constexpr float RAIN_VOLUME = 0.6f; +constexpr int ANIMA_FADE_START = 90; +constexpr float ANIMA_FADE_FRAMES = 30; +constexpr float DOPPLER_SPEED = 100; // The ambient loops update_ambient_sounds plays, in the order it sets them, and each one's volume step and scale. struct AmbientSound @@ -164,18 +204,18 @@ enum AmbientLoop AMBIENT_FLIES, AMBIENT_LASER, AMBIENT_FATTY_LASER, - AMBIENT_WATER, - AMBIENT_RAIN_LOOP, + AMBIENT_TAR, + AMBIENT_RAIN, AMBIENT_CURRENT, AMBIENT_LAVA, AMBIENT_PORTAL, AMBIENT_MINECART, AMBIENT_BALL_AND_CHAIN, - AMBIENT_BEAM, - AMBIENT_BEAST, + AMBIENT_URN, + AMBIENT_BLACKHOLE, AMBIENT_DOGMA, AMBIENT_DOGMA_ANGEL, - AMBIENT_STATIC, + AMBIENT_ANIMA_CHAIN, AMBIENT_LOOP_COUNT }; @@ -190,6 +230,11 @@ constexpr AmbientSound AMBIENT_SOUNDS[AMBIENT_LOOP_COUNT] = { // The volumes the ambient loops played at last, each easing toward its new one (Room's in the original, 0x7084). static std::array ambientVolumes{}; +// The players' average velocity and the manager frame it was worked out on (the original's globals at 00c94374 and +// 00c5c4d8). +static Vector playersVelocity{}; +static uint32_t playersVelocityFrame = 0; + static bool is_greed() { return g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; @@ -809,24 +854,187 @@ void Room::Update() if (unknown7230 % BOMB_RAIN_FRAMES == 0) reconstruction_missing("Room::Update 00802980: the troll bomb rain"); unknown7230--; } - if (isPickupVisionInvalid) reconstruction_missing("Room::Update 00802980: the pickups' loot previews"); + if (isPickupVisionInvalid) + { + for (Entity* entity : entityList.updateEL) + { + if (entity->type == ENTITY_PICKUP) static_cast(entity)->UpdateLootPreview(); + else if (is_npc_type(entity->type)) + if (Entity_NPC* npc = dynamic_cast(entity)) npc->UpdatePickupGhosts(); + } + isPickupVisionInvalid = false; + } if (isUnknown7769) reconstruction_missing("Room::Update 00802980: the split collectible pedestals"); if (DAT_00c82674 != DAT_00c82678) reconstruction_missing("Room::Update 00802980: the enemies pending a split"); } -// Whether an entity plays an ambient loop: the enemies, lasers and effects with sounds of their own. -static bool is_ambient_source(Entity& entity) +// Whether a source's closeness is cut at zero past its reach before it is squared, or squared as it is. +enum FalloffMode { - if (is_npc_type(entity.type)) return !entity.isDead && contains(SOUND_NPC_TYPES, entity.type); - if (entity.type == ENTITY_LASER) return contains(SOUND_LASER_VARIANTS, entity.variant); - return entity.type == ENTITY_EFFECT && contains(SOUND_EFFECT_VARIANTS, entity.variant); + FALLOFF_CLAMPED, + FALLOFF_SQUARED +}; + +// How loud a source is at a distance from the players: its closeness within a reach, squared. +static float ambient_falloff(Vector source, Vector center, float reach = AMBIENT_RANGE, FalloffMode mode = FALLOFF_CLAMPED) +{ + float closeness = 1 - std::hypot(source.x - center.x, source.y - center.y) / reach; + if (mode == FALLOFF_CLAMPED) closeness = std::max(closeness, 0.0f); + return closeness * closeness; } -// How loud a source of the floor is at a distance from the players: fading out with its square at AMBIENT_RANGE. -static float ambient_falloff(Vector source, Vector center) +// The local players' average velocity, worked out once a manager frame. Co-op babies and Tainted Forgotten's body +// do not count. +static Vector players_velocity_get() { - float closeness = std::max(1 - std::hypot(source.x - center.x, source.y - center.y) / AMBIENT_RANGE, 0.0f); - return closeness * closeness; + if (g_manager->framecount == playersVelocityFrame) return playersVelocity; + + Vector sum{}; + int count = 0; + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0 || player->playerType == PLAYER_THE_FORGOTTEN_B || !player->IsLocalPlayer()) continue; + + sum = vector_make(sum.x + player->velocity.x, sum.y + player->velocity.y); + count++; + } + playersVelocityFrame = g_manager->framecount; + playersVelocity = count > 0 ? vector_make(sum.x / (float)count, sum.y / (float)count) : Vector{}; + return playersVelocity; +} + +// The pitch a moving source sounds at to the players moving at a velocity: higher as they close on each other. +static float doppler_pitch_get(Entity& source, Vector center, Vector playersVelocity) +{ + float x = source.pos.x - center.x; + float y = source.pos.y - center.y; + float length = std::sqrt(x * x + y * y); + + if (length > 0) + { + x *= 1 / length; + y *= 1 / length; + } + return (y * playersVelocity.y + x * playersVelocity.x + DOPPLER_SPEED) / + (source.velocity.y * y + source.velocity.x * x + DOPPLER_SPEED); +} + +// What the room's sources call the loops to this frame, and the summed pitches of the flies and Dogma's angels. +struct AmbientMix +{ + std::array volumes{}; + Vector center{}; + Vector playersVelocity{}; + float angelPitch = 0; + float flyPitch = 0; + int flyCount = 0; +}; + +// An effect's or laser's loop: a colostomia puddle's tar, the Urn of Souls' flame, a rift's hum, Dogma's open black +// hole, the anima chain's rattle as it fades in, and a beam laser's hum. +static void ambient_effect_add(AmbientMix& mix, Entity& entity) +{ + std::array& volumes = mix.volumes; + + if (entity.type == ENTITY_LASER) + { + if (contains(LASER_LOOP_VARIANTS, entity.variant) && static_cast(entity).timeout != 0) + volumes[AMBIENT_LASER] = LASER_VOLUME; + return; + } + if (entity.type != ENTITY_EFFECT) return; + + Entity_Effect& effect = static_cast(entity); + const AnimationData* animation = effect.sprite.animState.animData; + switch (effect.variant) + { + case EFFECT_COLOSTOMIA_PUDDLE: volumes[AMBIENT_TAR] = std::max(volumes[AMBIENT_TAR], 1.0f); return; + case EFFECT_URN_OF_SOULS: volumes[AMBIENT_URN] = std::max(volumes[AMBIENT_URN], effect.scale * URN_VOLUME); return; + case EFFECT_RIFT: + volumes[AMBIENT_PORTAL] += ambient_falloff(effect.pos, mix.center, AMBIENT_NPC_REACH, FALLOFF_SQUARED) * + RIFT_VOLUME * effect.sprite.scale.x; + return; + case EFFECT_DOGMA_BLACKHOLE: + if (effect.subtype == 0 && effect.state == BLACKHOLE_STATE_OPEN && animation && animation->isLooping) + volumes[AMBIENT_BLACKHOLE] += ambient_falloff(effect.pos, mix.center, BLACKHOLE_REACH, FALLOFF_SQUARED); + return; + case EFFECT_ANIMA_CHAIN: + if (effect.subtype == 0 && effect.timeout > 0 && effect.timeout < ANIMA_FADE_START) + { + float fade = std::min((float)(ANIMA_FADE_START - effect.timeout) / ANIMA_FADE_FRAMES, 1.0f); + volumes[AMBIENT_ANIMA_CHAIN] = std::max(volumes[AMBIENT_ANIMA_CHAIN], fade); + } + return; + } +} + +// Dogma's loops: its own static, louder as it shows, and its angels' rushing, louder as they fly fast. +static void ambient_dogma_add(AmbientMix& mix, Entity_NPC& dogma) +{ + std::array& volumes = mix.volumes; + + if (dogma.variant == 0) + { + float shown = std::min(dogma.sprite.GetLayer(0)->color._colorize[2], 1.0f); + volumes[AMBIENT_DOGMA] = std::max(volumes[AMBIENT_DOGMA] + shown * ambient_falloff(dogma.pos, mix.center, DOGMA_REACH), + DOGMA_VOLUME_MIN); + } + else if (dogma.variant == DOGMA_ANGEL && dogma.state == DOGMA_ANGEL_STATE) + { + float speed = std::min(std::hypot(dogma.velocity.x, dogma.velocity.y) * ANGEL_SPEED_SCALE, 1.0f); + volumes[AMBIENT_DOGMA_ANGEL] += speed * ambient_falloff(dogma.pos, mix.center, AMBIENT_NPC_REACH); + mix.angelPitch += doppler_pitch_get(dogma, mix.center, mix.playersVelocity); + } +} + +// An enemy's loop: flies buzz (pitched by their motion), lit fires crackle, portals hum, Vis Fatty's laser, the ball +// and chain rolling, Dogma, and a minecart's rumble as fast as it rolls. Only enemies near the players on either axis +// play, but minecarts at any distance, and none dead, regenerating, stopped, paused, frozen or held. +static void ambient_npc_add(AmbientMix& mix, Entity_NPC& npc) +{ + std::array& volumes = mix.volumes; + Vector center = mix.center; + bool isSilenced = npc.isDead || npc.championRegenTimer > 0 || npc.speedMultiplier <= 0 || npc.pauseTimer > 0 || + npc.HasEntityFlags(FLAG_FREEZE | FLAG_HELD); + + if (isSilenced) return; + if (npc.type == ENTITY_MINECART) + { + float speed = std::clamp(std::hypot(npc.velocity.x, npc.velocity.y) / MINECART_FULL_SPEED, 0.0f, 1.0f); + volumes[AMBIENT_MINECART] += speed * ambient_falloff(npc.pos, center, MINECART_REACH, FALLOFF_SQUARED); + return; + } + if (std::max(std::abs(npc.pos.y - center.y), std::abs(npc.pos.x - center.x)) > AMBIENT_NPC_REACH) return; + + float closeness = ambient_falloff(npc.pos, center, AMBIENT_NPC_REACH, FALLOFF_SQUARED); + bool isFly = contains(AMBIENT_FLY_TYPES, npc.type) || (npc.type == ENTITY_BEAST && contains(BEAST_FLY_VARIANTS, npc.variant)); + if (isFly) + { + mix.flyCount++; + float buzz = closeness * (npc.type == ENTITY_HUSH_FLY ? HUSH_FLY_VOLUME : FLY_VOLUME); + volumes[AMBIENT_FLIES] = std::min(volumes[AMBIENT_FLIES] + buzz, FLY_VOLUME_MAX); + mix.flyPitch += doppler_pitch_get(npc, center, mix.playersVelocity); + return; + } + switch (npc.type) + { + case ENTITY_FIREPLACE: + if (npc.entityCollisionClass != ENTCOLL_NONE) volumes[AMBIENT_FIRE] += closeness * FIRE_VOLUME; + return; + case ENTITY_PORTAL: volumes[AMBIENT_PORTAL] += closeness * PORTAL_VOLUME; return; + case ENTITY_VIS_FATTY: + { + Entity* laser = npc.entityRef.get(); + if (npc.variant == 0 && laser && laser->type == ENTITY_LASER) + volumes[AMBIENT_FATTY_LASER] = std::max(volumes[AMBIENT_FATTY_LASER], laser->sprite.scale.x * FATTY_LASER_VOLUME); + return; + } + case ENTITY_BALL_AND_CHAIN: + if (npc.targetPosition.x != 0 || npc.targetPosition.y != 0) + volumes[AMBIENT_BALL_AND_CHAIN] += ambient_falloff(npc.pos, center, CHAIN_REACH, FALLOFF_SQUARED) * CHAIN_VOLUME; + return; + case ENTITY_DOGMA: ambient_dogma_add(mix, npc); return; + } } // The pits' ambient volume: each pit near the players adds its share. @@ -839,29 +1047,33 @@ static float pits_volume(Room& room, Vector center) return volume; } -// 00800500 Plays the room's ambient loops at the volumes its sources call for near the players: fire, flies, lasers, -// the Dank Depths' and flooded Mines' pits, rain, a water current, lava, portals, minecarts and the bosses' own, each -// volume easing toward its target. Then the alarm a fast Basement I boss clear sets off, panned toward the starting -// room. -// The entities' own loops are not reconstructed yet. +// 00800500 Plays the room's ambient loops at the volumes their sources call for near the players: fire, flies, lasers, +// tar, rain, a water current, lava, portals, minecarts and the bosses' own, each volume easing toward its target, the +// flies and Dogma's angels pitched by their motion. Then the alarm a fast Basement I boss clear sets off, panned toward +// the starting room. void Room::update_ambient_sounds() { Game& game = *g_game; SFXManager& sfx = g_manager->sfxManager; - std::array volumes{}; + AmbientMix mix = {.center = game.playerManager.players_center_position(CENTER_CACHED), .playersVelocity = players_velocity_get()}; + std::array& volumes = mix.volumes; + Vector center = mix.center; float flyPitch = 0; - Vector center = game.playerManager.players_center_position(CENTER_CACHED); if (!game.IsPaused() || game.roomTransition.mode != TRANSITION_NONE) { for (Entity* entity : entityList.updateEL) - if (is_ambient_source(*entity)) reconstruction_missing("Room::update_ambient_sounds 00800500: the entities' loops"); + { + if (!is_npc_type(entity->type)) ambient_effect_add(mix, *entity); + else if (Entity_NPC* npc = dynamic_cast(entity)) ambient_npc_add(mix, *npc); + } float warble = 0; for (float period : FLY_WARBLE_PERIODS) warble += std::sin((float)game.frameCount / period); - flyPitch = warble * FLY_WARBLE + 1; - if (numRainSpawners > 0) - reconstruction_missing("Room::update_ambient_sounds 00800500: the rain (Room::init_rain's spawners)"); + flyPitch = warble * FLY_WARBLE + (mix.flyCount == 0 ? 1 : mix.flyPitch / (float)mix.flyCount); + for (int i = 0; i < numRainSpawners; i++) + volumes[AMBIENT_RAIN] += rainIntensity * ambient_falloff(rainSpawners[i].position, center) * RAIN_VOLUME; + if (numRainSpawners > 0) volumes[AMBIENT_RAIN] = std::min(volumes[AMBIENT_RAIN], 1.0f); if (waterCurrent.x != 0 || waterCurrent.y != 0) volumes[AMBIENT_CURRENT] = 1; RoomConfig_Room* config = descriptor->data; @@ -874,7 +1086,7 @@ void Room::update_ambient_sounds() else if (backdropType == BACKDROP_MINES && isFlooded) volumes[AMBIENT_LAVA] = std::min(pits_volume(*this, center) * lavaIntensity, 1.0f); if (backdropType == BACKDROP_DANK_DEPTHS && isFlooded) - volumes[AMBIENT_WATER] = std::min(pits_volume(*this, center), 1.0f); + volumes[AMBIENT_TAR] = std::min(volumes[AMBIENT_TAR] + pits_volume(*this, center), 1.0f); volumes[AMBIENT_MINECART] = std::min(volumes[AMBIENT_MINECART], MINECART_VOLUME_MAX); } @@ -884,7 +1096,8 @@ void Room::update_ambient_sounds() float last = ambientVolumes[i]; float volume = std::clamp(volumes[i], last - sound.step, last + sound.step); ambientVolumes[i] = volume; - sfx.SetAmbientSound(sound.soundId, volume * sound.scale, i == AMBIENT_FLIES ? flyPitch : 1); + float pitch = i == AMBIENT_FLIES ? flyPitch : i == AMBIENT_DOGMA_ANGEL ? mix.angelPitch : 1; + sfx.SetAmbientSound(sound.soundId, volume * sound.scale, pitch); } if (unknown72fc < 0) return;