From f8ce24fc6c6815151bad8490e9876d7ae3cf5b6a Mon Sep 17 00:00:00 2001 From: shweet Date: Fri, 20 Nov 2026 14:25:15 -0500 Subject: [PATCH] Curation round 12: basement enemies, projectiles, tear flags, lighting and blend modes, actives, boss deaths, familiars, shops and secret rooms --- generated-src/classes.h | 53 +- generated-src/item_overlay.cpp | 483 -------- generated-src/npc_helper.cpp | 2 +- generated-src/stubs.cpp | 29 - src/active_items.h | 30 + src/anm2.cpp | 23 +- src/anm2.h | 3 + src/backdrop.cpp | 3 - src/bomb_explosion.cpp | 12 +- src/boss_ai.h | 16 +- src/boss_death.cpp | 758 +++++++++++++ src/boss_death.h | 6 + src/boss_gemini.cpp | 3 +- src/boss_monstro.cpp | 292 +++++ src/boss_pool.cpp | 2 +- src/console.cpp | 2 +- src/entity.cpp | 49 +- src/entity.h | 85 +- src/entity_bomb.cpp | 11 - src/entity_collision.cpp | 17 +- src/entity_combat.cpp | 45 +- src/entity_config.cpp | 3 +- src/entity_effect.cpp | 6 +- src/entity_effect.h | 55 + src/entity_effect_ambient.cpp | 32 - src/entity_effect_combat.cpp | 3 - src/entity_factory.cpp | 34 - src/entity_familiar.cpp | 1397 ++++++++++++----------- src/entity_familiar.h | 294 ++++- src/entity_list.cpp | 11 +- src/entity_npc.cpp | 243 +--- src/entity_npc.h | 30 +- src/entity_npc_room.cpp | 3 +- src/entity_pickup.cpp | 129 +-- src/entity_pickup.h | 45 +- src/entity_pickup_morph.cpp | 113 ++ src/entity_pickup_shop.cpp | 406 +++++++ src/entity_player.cpp | 14 +- src/entity_player.h | 170 ++- src/entity_player_actives.cpp | 254 ++++- src/entity_player_bombs.cpp | 5 - src/entity_player_collectibles.cpp | 243 ++++ src/entity_player_damage.cpp | 40 +- src/entity_player_death.cpp | 41 +- src/entity_player_evaluate.cpp | 72 +- src/entity_player_frame.cpp | 35 +- src/entity_player_health.cpp | 3 +- src/entity_player_items.cpp | 21 +- src/entity_player_kills.cpp | 7 +- src/entity_player_missing.cpp | 42 - src/entity_player_pockets.cpp | 697 ++++++++++++ src/entity_player_room.cpp | 7 +- src/entity_player_tears.cpp | 916 +++++++++++++++ src/entity_player_weapons.cpp | 65 -- src/entity_projectile.cpp | 1693 +++++++++++++++++++++++++++- src/entity_projectile.h | 145 ++- src/entity_slot.cpp | 21 +- src/entity_tear.cpp | 894 ++++++++++++--- src/entity_tear.h | 83 +- src/familiar_ai.cpp | 660 +++++++++++ src/familiar_collision.cpp | 332 ++++++ src/familiar_evaluate.cpp | 286 +++++ src/familiar_follow.cpp | 526 +++++++++ src/familiar_missing.cpp | 400 +++++++ src/familiar_shoot.cpp | 557 +++++++++ src/game.cpp | 12 +- src/game.h | 2 + src/game_over.cpp | 2 +- src/game_restore.cpp | 5 - src/game_save.cpp | 7 +- src/game_transition.cpp | 2 - src/game_update.cpp | 7 +- src/grid_entity.cpp | 5 +- src/grid_entity_door.cpp | 28 - src/grid_entity_pressure_plate.cpp | 3 - src/grid_entity_rock.cpp | 15 +- src/grid_entity_spikes.cpp | 3 +- src/grid_entity_tnt.cpp | 2 - src/grid_entity_trap_door.cpp | 7 +- src/info_display.cpp | 3 - src/item_config.cpp | 14 +- src/item_config.h | 4 + src/item_overlay.cpp | 243 ++++ src/item_overlay.h | 44 + src/item_pickup.cpp | 62 +- src/item_pool.cpp | 14 - src/kage_sound.cpp | 13 +- src/level.cpp | 22 +- src/level.h | 20 + src/level_stage.cpp | 6 +- src/manager.cpp | 2 - src/menu_bestiary.cpp | 1 - src/menu_character.cpp | 1 - src/menu_collection.cpp | 2 +- src/menu_custom_challenge.cpp | 1 - src/menu_cutscenes.cpp | 1 - src/menu_key_config.cpp | 1 - src/menu_manager.cpp | 1 - src/menu_manager.h | 1 - src/menu_options.cpp | 1 - src/minimap.cpp | 2 - src/music_manager.cpp | 2 - src/music_manager.h | 41 + src/nightmare_scene.cpp | 2 - src/nightmare_scene.h | 3 + src/npc_ai.cpp | 15 +- src/npc_ai.h | 3 + src/npc_basement.h | 13 + src/npc_clotty.cpp | 7 +- src/npc_collision.cpp | 899 +++++++++++++++ src/npc_dip.cpp | 5 - src/npc_dirt.cpp | 84 ++ src/npc_embryo.cpp | 39 + src/npc_fireplace.cpp | 27 +- src/npc_fireplace.h | 14 + src/npc_fly.cpp | 516 +++++++-- src/npc_gaper.cpp | 13 - src/npc_gusher.cpp | 8 - src/npc_hive.cpp | 252 +++++ src/npc_hopper.cpp | 383 +++++++ src/npc_horf.cpp | 3 - src/npc_mulligan.cpp | 6 +- src/npc_spider.cpp | 279 +++++ src/path_finder.cpp | 197 +++- src/pause_screen.cpp | 1 - src/persistent_game_data.h | 2 + src/player_hud.cpp | 473 +++++++- src/player_manager.cpp | 4 +- src/revive_player_menu.cpp | 1 - src/room.cpp | 100 +- src/room.h | 13 + src/room_clear.cpp | 22 +- src/room_config.cpp | 2 - src/room_descriptor.h | 6 +- src/room_lighting.cpp | 1022 +++++++++++++++++ src/room_render.cpp | 279 +---- src/room_render.h | 9 + src/room_special.cpp | 1078 ++++++++++++++++++ src/room_special.h | 55 + src/room_state.cpp | 13 +- src/room_update.cpp | 32 +- src/seeds.cpp | 2 +- src/sfx_manager.h | 31 + src/stage_transition.cpp | 12 +- src/stat_hud.cpp | 2 - src/weapon.cpp | 7 - 146 files changed, 16389 insertions(+), 3104 deletions(-) delete mode 100644 generated-src/item_overlay.cpp create mode 100644 src/boss_death.cpp create mode 100644 src/boss_death.h create mode 100644 src/boss_monstro.cpp create mode 100644 src/entity_pickup_morph.cpp create mode 100644 src/entity_pickup_shop.cpp create mode 100644 src/entity_player_collectibles.cpp create mode 100644 src/entity_player_pockets.cpp create mode 100644 src/entity_player_tears.cpp create mode 100644 src/familiar_ai.cpp create mode 100644 src/familiar_collision.cpp create mode 100644 src/familiar_evaluate.cpp create mode 100644 src/familiar_follow.cpp create mode 100644 src/familiar_missing.cpp create mode 100644 src/familiar_shoot.cpp create mode 100644 src/item_overlay.cpp create mode 100644 src/item_overlay.h create mode 100644 src/npc_collision.cpp create mode 100644 src/npc_dirt.cpp create mode 100644 src/npc_embryo.cpp create mode 100644 src/npc_hive.cpp create mode 100644 src/npc_hopper.cpp create mode 100644 src/npc_spider.cpp create mode 100644 src/room_lighting.cpp create mode 100644 src/room_special.cpp create mode 100644 src/room_special.h diff --git a/generated-src/classes.h b/generated-src/classes.h index 86cf8eb..b3b1475 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -120,6 +120,7 @@ struct AbyssLocustData; struct AchievementEntry; struct AchievementOverlay; struct AchievementOverlay_Entry; +struct ActiveGain; struct ActiveItemDesc; struct ActiveUse; struct AfterbirthPersistentGameData; @@ -249,6 +250,7 @@ struct FXRay; struct FXRayGroup; struct FXTile; struct FXVein; +struct FamiliarCount; struct FamiliarData; struct File; struct FileSymbolInfo; @@ -499,6 +501,7 @@ struct ProceduralEffect; struct ProceduralItem; struct ProceduralItemManager; struct ProjectileParams; +struct ProjectileShooter; struct Quad; struct QueueItemData; struct RNG; @@ -551,6 +554,8 @@ struct SharedPtrPair; struct Shockwave; struct ShockwaveParams; struct ShootInput; +struct ShopOffer; +struct ShopRestock; struct SimpleString; struct Size; struct SmeltedTrinket; @@ -580,6 +585,7 @@ struct SteamCloudFile; struct StringTable; struct StringTableCategory; struct SubtitleCue; +struct TargetSearch; struct TearParams; struct TemporaryEffect; struct TemporaryEffects; @@ -1631,26 +1637,6 @@ struct Item { }; -struct ItemOverlay { - ~ItemOverlay(); // 009abd80 - void Update(uint8_t unk); // 009aca90 - void Render(); // 009acfe0 - void Show(int eOverlayID, int delay, Entity_Player *player); // 009ad210 - - int _state; - int _overlayID; - uint8_t _sprite[0x1194]; // ANM2 - int _delay; - uint8_t _player[0x4]; // EntityPtr - uint8_t _megaMushPlayerSprite[0x4]; // ANM2 -}; -LAYOUT32(offsetof(ItemOverlay, _state) == 0x0); -LAYOUT32(offsetof(ItemOverlay, _overlayID) == 0x4); -LAYOUT32(offsetof(ItemOverlay, _sprite) == 0x8); -LAYOUT32(offsetof(ItemOverlay, _delay) == 0x119c); -LAYOUT32(offsetof(ItemOverlay, _player) == 0x11a0); -LAYOUT32(offsetof(ItemOverlay, _megaMushPlayerSprite) == 0x11a4); - namespace KAGE { struct CommandQueue { virtual ~CommandQueue(); // 00a28d30 slot 0 ::FUN_00a28d30 @@ -6522,23 +6508,17 @@ void FUN_0060d0c0(); // 0060d0c0 void FUN_0060d0d0(uint32_t param_1); // 0060d0d0 void FUN_0060d0f0(uint32_t param_1); // 0060d0f0 uint32_t FUN_0060d110(); // 0060d110 -uint8_t FUN_0060d120(); // 0060d120 -uint8_t FUN_0060d130(); // 0060d130 bool FUN_0060d1c0(uint32_t param_1); // 0060d1c0 uint32_t FUN_0060d1e0(); // 0060d1e0 void FUN_0060d1f0(uint32_t param_1); // 0060d1f0 void FUN_0060d400(); // 0060d400 void FUN_0060d530(uint8_t param_1); // 0060d530 void FUN_0060d5e0(uint8_t param_1); // 0060d5e0 -int FUN_0060d6a0(); // 0060d6a0 -uint32_t FUN_0060d780(); // 0060d780 uint32_t FUN_0060dae0(); // 0060dae0 -uint32_t FUN_00612ad0(); // 00612ad0 void FUN_0062c8a0(); // 0062c8a0 void FUN_0062e0e0(int param_1); // 0062e0e0 void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3); // 00631a00 void familiar_wisp_pick_tear_color(RNG *rng, int *outVariant, BitSet128 *outFlags); // 00633990 -uint32_t FUN_00634920(); // 00634920 void FUN_00638e20(); // 00638e20 void spawn_blue_spider(Vector *position, Entity *spawner, Vector *target); // 00638e30 Entity * spawn_dip_at(int subType, Vector *position, Entity *spawner, Vector *targetPosition); // 006393a0 @@ -6584,8 +6564,6 @@ int FUN_00652a30(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint8_t p void FUN_00652a70(); // 00652a70 bool _has_flag_0x110(uint32_t param_1); // 00652a90 int FUN_00652ae0(); // 00652ae0 -void FUN_00652df0(); // 00652df0 -void FUN_00652f80(); // 00652f80 void reroll_entity_to_free_tile(int param_1); // 0065ad30 bool FUN_0065cfe0(uint32_t param_1); // 0065cfe0 int FUN_0065d010(); // 0065d010 @@ -6908,7 +6886,6 @@ void FUN_00718ed0(uint32_t param_1); // 00718ed0 uint32_t FUN_00718ee0(); // 00718ee0 void FUN_0071df70(uint8_t param_1); // 0071df70 int FUN_0071df80(); // 0071df80 -uint32_t FUN_00721b70(int param_1); // 00721b70 void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6); // 00721e60 void FUN_00721eb0(); // 00721eb0 void FUN_00722020(int param_1); // 00722020 @@ -7046,7 +7023,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 -void FUN_00763290(); // 00763290 void FUN_00770640(float *param_1); // 00770640 uint8_t is_trinket_unpickable_id(int trinketId); // 007716c0 void FUN_007792f0(uint32_t param_1, uint32_t param_2); // 007792f0 @@ -7063,7 +7039,6 @@ uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2); // 007ad720 void FUN_007b8c00(int param_1); // 007b8c00 void FUN_007b9a60(); // 007b9a60 void FUN_007b9aa0(); // 007b9aa0 -float get_tear_trinket_multiplier(Entity_Player *player, int tearVariant); // 007c2d50 void FUN_007c2e80(); // 007c2e80 uint8_t FUN_007c7b10(uint32_t param_1, int param_2); // 007c7b10 char FUN_007c9080(); // 007c9080 @@ -7078,11 +7053,9 @@ void FUN_007d3330(int param_1); // 007d3330 Game * damage_charge_scale(); // 007d3560 void FUN_007d3e00(); // 007d3e00 char FUN_007d4320(); // 007d4320 -void FUN_007d8630(int param_1); // 007d8630 void FUN_007d9360(); // 007d9360 uint32_t FUN_007d9ca0(); // 007d9ca0 uint32_t FUN_007da770(); // 007da770 -uint32_t FUN_007da7a0(uint32_t param_1); // 007da7a0 uint32_t FUN_007dac30(); // 007dac30 void FUN_007dad80(); // 007dad80 int FUN_007dafb0(); // 007dafb0 @@ -7190,7 +7163,6 @@ void FUN_007ebc40(); // 007ebc40 float get_angel_room_chance(); // 007f96f0 void FUN_00812ea0(float *param_1, int *param_2, int *param_3); // 00812ea0 uint32_t FUN_00813420(int param_1, int param_2); // 00813420 -void pickup_roll_random_variant(void *papersOwner, int shopItemId, int *variant, uint32_t *subType, uint32_t seed); // 00814a50 uint32_t FUN_0081e220(); // 0081e220 void FUN_0081fae0(uint32_t *param_1); // 0081fae0 void FUN_00821940(); // 00821940 @@ -7268,7 +7240,6 @@ void FUN_0083c480(); // 0083c480 void item_pool_icons_render(void *iconLayer, Vector *position, KColor *color); // 0083d8c0 char * FUN_00840510(); // 00840510 std_string * int_to_string(std_string *outString, int value); // 00840540 -void FUN_008452f0(SourceQuad *param_1, void *param_2, ColorMod *param_3); // 008452f0 void collectible_icon_render(void *param_1, ColorMod *param_2, int *param_3, int *param_4); // 00848c20 void FUN_0084a870(float *param_1); // 0084a870 void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4); // 0084abc0 @@ -9473,8 +9444,6 @@ int save_backup_find_latest(PersistentGameData *gameData); // 00926510 void FUN_00929660(char param_1); // 00929660 uint8_t * FUN_00929b00(); // 00929b00 uint32_t FUN_00929b20(); // 00929b20 -void FUN_0092a520(uint32_t param_1); // 0092a520 -void FUN_0092a5e0(int param_1); // 0092a5e0 uint32_t FUN_0092aaf0(int param_1, int param_2); // 0092aaf0 uint32_t FUN_0092ab40(int param_1); // 0092ab40 uint32_t FUN_0092abd0(int param_1, int param_2); // 0092abd0 @@ -21579,7 +21548,6 @@ void ENTITY_FISTULA_BIG(Entity_NPC *npc); // 00466600 void ENTITY_LOKI(Entity_NPC *npc); // 00467670 void ENTITY_DADDYLONGLEGS(Entity_NPC *npc); // 00468180 void ENTITY_LARRYJR(Entity_NPC *npc); // 0046a0f0 -void ENTITY_MONSTRO(Entity_NPC *npc); // 0046c0a0 void ENTITY_DUKE(Entity_NPC *npc); // 0046e290 void ENTITY_WIDOW(Entity_NPC *npc); // 0046fbe0 void ENTITY_BLASTOCYST_BIG(Entity_NPC *npc); // 00472c40 @@ -21686,9 +21654,7 @@ void ENTITY_DUSTY_DEATHS_HEAD(Entity_NPC *npc); // 00504a40 void ENTITY_NECRO(Entity_NPC *npc); // 005052a0 void ENTITY_STONE_EYE(Entity_NPC *npc); // 00505d00 void ENTITY_CONSTANT_STONE_SHOOTER(Entity_NPC *npc); // 00506320 -void ENTITY_EMBRYO(Entity_NPC *npc); // 0050a6b0 void ENTITY_ETERNALFLY(Entity_NPC *npc); // 0050a8a0 -void ENTITY_HIVE(Entity_NPC *npc); // 0050c370 void ENTITY_GLOBIN(Entity_NPC *npc); // 0050e4d0 uint32_t ENTITY_BOOMFLY(Entity_NPC *npc); // 0050f280 void ENTITY_MAW(Entity_NPC *npc); // 00510ae0 @@ -21713,8 +21679,6 @@ void ENTITY_EYE(Entity_NPC *npc); // 00522ef0 uint32_t ENTITY_PARA_BITE(Entity_NPC *npc); // 005240a0 void ENTITY_FRED(Entity_NPC *npc); // 00524a10 void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 -void ENTITY_HOPPER(Entity_NPC *npc); // 00526470 -void ENTITY_SPIDER(Entity_NPC *npc); // 00529da0 void ENTITY_BABY(Entity_NPC *npc); // 0052ae30 void ENTITY_VIS_chubber_projectile(Entity_NPC *npc); // 0052c2f0 void ENTITY_VIS(Entity_NPC *npc); // 0052c720 @@ -21737,7 +21701,6 @@ void ENTITY_BLACK_MAW(Entity_NPC *npc); // 0053b2f0 void ENTITY_RING_OF_FLIES(Entity_NPC *npc); // 0053bae0 void ENTITY_WALL_CREEP(Entity_NPC *npc); // 0053c0d0 int * ENTITY_ROUND_WORM(Entity_NPC *npc); // 0053e4a0 -void ENTITY_DART_FLY(Entity_NPC *npc); // 005400d0 void ENTITY_FAT_BAT(Entity_NPC *npc); // 00540510 void ENTITY_SWARM(Entity_NPC *npc); // 00540df0 void ENTITY_DUKIE(Entity_NPC *npc); // 00541810 @@ -21830,7 +21793,6 @@ void ENTITY_WORMWOOD_pick_pit(Entity_NPC *npc); // 005ae230 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_MOVABLE_TNT(Entity_NPC *npc); // 006d6690 } namespace OnlinePlayerInfo { @@ -21893,9 +21855,6 @@ uint32_t SpawnTrinketRandomPickup(); // 007dc2d0 namespace _NpcHelper { uint32_t spider_load_graphics(uint8_t *param_1); // 006baa70 } -namespace _Room { -int ResolveHeartSubType(uint32_t param_1, int param_2, Entity_Player *param_3); // 00816250 -} namespace luabridge::CFunc { uint32_t readOnlyError(uint32_t param_1); // 0085cad0 } diff --git a/generated-src/item_overlay.cpp b/generated-src/item_overlay.cpp deleted file mode 100644 index c2a2289..0000000 --- a/generated-src/item_overlay.cpp +++ /dev/null @@ -1,483 +0,0 @@ -#include "classes.h" - -// 009abd80 -ItemOverlay::~ItemOverlay() -{ - int *local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - uint32_t *playerRef; - - puStack_c = &LAB_00afa3c0; - local_10 = ExceptionList; - ExceptionList = &local_10; - local_8 = 0; - ANM2::Reset(&this->_megaMushPlayerSprite); - AnimationState::~AnimationState(&(this->_megaMushPlayerSprite)._overlayAnimState); - AnimationState::~AnimationState(&(this->_megaMushPlayerSprite)._animState); - (GHIDRA_CAST(((this->_megaMushPlayerSprite)._animDefaultName._buf)))->msvc::string::_Tidy_deallocate(); - (GHIDRA_CAST((GHIDRA_CAST(&this->_megaMushPlayerSprite))))->msvc::string::_Tidy_deallocate(); - playerRef = &this->_player; - if (*playerRef != 0) { - local_14 = playerRef; - msvc::multiset::erase(&local_14); - *playerRef = 0; - } - local_8 = 0xffffffff; - _eh_vector_destructor_iterator_(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x11c))),0x58,0x30,FUN_009abd50); - local_8 = 2; - ANM2::Reset(&this->_sprite); - AnimationState::~AnimationState(&(this->_sprite)._overlayAnimState); - AnimationState::~AnimationState(&(this->_sprite)._animState); - (GHIDRA_CAST(((this->_sprite)._animDefaultName._buf)))->msvc::string::_Tidy_deallocate(); - (GHIDRA_CAST((GHIDRA_CAST(&this->_sprite))))->msvc::string::_Tidy_deallocate(); - ExceptionList = local_10; - return; -} - -// 009aca90 -void ItemOverlay::Update(uint8_t unk) -{ - uint8_t bVar1; - int iVar2; - uint32_t *playerSlot; - int healthType; - void *playerListEnd; - Entity_Player *player; - Entity_Player *heartPlayer; - int extraout_EDX; - uint32_t uVar3; - uint8_t isFastForward; - uint32_t playerIndex; - PlayerManager *playerManager; - undefined3 in_stack_00000005; - float Pitch; - int soundId; - AnimationState *local_8; - Game *game; - Manager *manager; - int *roomDesc; - AnimationState *spriteAnimState; - - isFastForward = unk; - if (this->_state == 1) { - this->_delay = this->_delay + -1; - if (this->_delay < 1) { - this->_state = 2; - return; - } - return; - } - if (this->_state == 0) { - return; - } - if ((this->_megaMushPlayerSprite)._loaded != 0) { - if (unk == 0) { - ANM2::Update(&this->_megaMushPlayerSprite); - } - else if ((this->_megaMushPlayerSprite)._animState._animData != (void *)0x0) { - AnimationState::AdvancePosition - (&(this->_megaMushPlayerSprite)._animState, - *GHIDRA_CAST((GHIDRA_INT((this->_megaMushPlayerSprite)._animState._animData) + 0x30)) + -1); - } - if (((this->_player != 0) && - (bVar1 = ANM2::IsPlaying(&this->_megaMushPlayerSprite,GHIDRA_CAST("Transform")), bVar1 != 0)) && - (isFastForward == 0)) { - iVar2 = ANM2::GetFrame(&this->_megaMushPlayerSprite); - manager = g_manager; - if (iVar2 == 1) { - local_8 = GHIDRA_CAST(0x9d); - seed_fart_sound_override(GHIDRA_CAST(&local_8)); - Pitch = 1.0; - iVar2 = 2; - } - else { - if (iVar2 == 6) { - local_8 = GHIDRA_CAST(0x10c); - seed_fart_sound_override(GHIDRA_CAST(&local_8)); - Pitch = 0.8; - } - else if (iVar2 == 0xb) { - local_8 = GHIDRA_CAST(0x10c); - seed_fart_sound_override(GHIDRA_CAST(&local_8)); - Pitch = 1.0; - } - else { - if (iVar2 != 0x10) goto LAB_009acc1b; - local_8 = GHIDRA_CAST(0x10c); - seed_fart_sound_override(GHIDRA_CAST(&local_8)); - Pitch = 1.2; - } - iVar2 = 1; - } - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_8),1.0,iVar2,0,Pitch,0.0); - } - } -LAB_009acc1b: - if ((this->_sprite)._loaded == 0) { - if (this->_state != 2) { - return; - } - if (((this->_megaMushPlayerSprite)._animState._animData != (void *)0x0) && - ((this->_megaMushPlayerSprite)._animState._isPlaying != 0)) { - return; - } - if (this->_player != 0) { - *GHIDRA_CAST((this->_player + 0x171)) = 1; - } - this->_state = 0; - return; - } - if ((this->_state == 2) && - (((this->_sprite)._animState._animData == (void *)0x0 || - ((this->_sprite)._animState._isPlaying == 0)))) { - this->_state = 0; - } - if (isFastForward == 0) { - ANM2::Update(&this->_sprite); - } - else { - if ((this->_sprite)._animState._animData == (void *)0x0) goto LAB_009accdf; - AnimationState::AdvancePosition - (&(this->_sprite)._animState, - *GHIDRA_CAST((GHIDRA_INT((this->_sprite)._animState._animData) + 0x30)) + -1); - } - if ((((this->_sprite)._animState._animData != (void *)0x0) && - (bVar1 = AnimationState::IsEventTriggered(&(this->_sprite)._animState,GHIDRA_CAST("Sound")), - manager = g_manager, bVar1 != 0)) && (this->_overlayID == 0x27)) { - local_8 = GHIDRA_CAST(0x51); - seed_fart_sound_override(GHIDRA_CAST(&local_8)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_8),1.0,2,0,1.0,0.0); - } -LAB_009accdf: - local_8 = &(this->_sprite)._animState; - if (((this->_sprite)._animState._animData != (void *)0x0) && - (bVar1 = AnimationState::IsEventTriggered(local_8,GHIDRA_CAST("SleepFillHP")), bVar1 != 0)) { - playerIndex = 0; - playerManager = &g_game->_playerManager; - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - GHIDRA_INT((playerManager->_playerList)._begin) >> - 2 != 0) { - do { - playerListEnd = (playerManager->_playerList)._end; - if (GHIDRA_INT(playerListEnd) - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("PlayerManager::GetPlayer() : There are no players! \n")); - playerListEnd = (playerManager->_playerList)._end; - } - playerSlot = (playerManager->_playerList)._begin; - if (playerIndex < GHIDRA_UINT((GHIDRA_INT(playerListEnd) - GHIDRA_INT(playerSlot) >> 2))) { - playerSlot = playerSlot + playerIndex; - } - if ((GHIDRA_CAST(*playerSlot))->_playerType != 0x28) { - iVar2 = Entity_Player::GetHealthType(GHIDRA_CAST(*playerSlot)); - if ((iVar2 == 1) || (iVar2 == 2)) { - iVar2 = player->_maxHearts; - } - else { - iVar2 = player->_maxHearts + player->_boneHearts * 2; - } - if (iVar2 < 1) { - Entity_Player::AddSoulHearts(player,6,0); - } - else { - healthType = Entity_Player::GetHealthType(player); - iVar2 = extraout_EDX; - if ((healthType != 1) && (healthType != 2)) { - iVar2 = extraout_EDX + heartPlayer->_boneHearts * 2; - } - if (iVar2 <= heartPlayer->_redHearts) goto LAB_009ace00; - Entity_Player::SetFullHearts(heartPlayer); - } - manager = g_manager; - if (unk == 0) { - soundId = 0x80; - seed_fart_sound_override(&soundId); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(soundId,1.0,2,0,1.0,0.0); - } - } -LAB_009ace00: - playerIndex = playerIndex + 1; - playerManager = &g_game->_playerManager; - } while (playerIndex < - GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((playerManager->_playerList)._begin) >> 2))); - } - PersistentGameData::IncreaseEventCounter(&g_manager->_persistentGameData,0xca,1); - isFastForward = (uint8_t)_unk; - } - spriteAnimState = local_8; - if ((this->_overlayID == 0x2c) && ((this->_sprite)._animState._animData != (void *)0x0)) { - bVar1 = AnimationState::IsEventTriggered(local_8,GHIDRA_CAST("Transition")); - manager = g_manager; - game = g_game; - if (bVar1 == 0) { - if ((((this->_sprite)._animState._animData != (void *)0x0) && - (bVar1 = AnimationState::IsEventTriggered(spriteAnimState,GHIDRA_CAST("Static")), - manager = g_manager, bVar1 != 0)) && (isFastForward == 0)) { - _unk = 0x51; - seed_fart_sound_override(GHIDRA_CAST(&unk)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(_unk,1.0,2,0,1.0,0.0); - Room::PlayMusic(g_game->_room); - MusicManager::EnableLayer(&g_manager->_musicManager,0,1); - return; - } - } - else { - if (isFastForward == 0) { - (*GHIDRA_CAST((GHIDRA_CAST((g_manager)) + 0x21c10))) = 0; - if ((game->_difficulty == 2) || (game->_difficulty == 3)) { - uVar3 = 0x12; - } - else { - uVar3 = 0x1b; - (*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x21c10))) = 1; - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((manager->_nightmareScene))) + 0x3a0)))) = uVar3; - *GHIDRA_CAST(&manager->_isNightmarePending) = 0x101; - } - roomDesc = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(game->_room) + 4)) + 0x10)); - if (((roomDesc != GHIDRA_CAST(0x0)) && (game->_stage == 0xd)) && - ((game->_stageType == 0 && ((*roomDesc == 0x23 && (roomDesc[4] == 2)))))) { - Level::SetStage(GHIDRA_CAST(game),0xd,1); - Room::reload_backdrop(g_game->_room); - return; - } - } - } - return; -} - -// 009acfe0 -void ItemOverlay::Render() -{ - void *quad; - ItemOverlay *extraout_ECX; - ANM2 *sprite; - ItemOverlay *extraout_ECX_00; - ItemOverlay *unusedArg; - double dVar1; - Vector scratchVec; - float pixelScale; - KColor tintColor; - uint8_t renderQuad [172]; - int player; - - if (this->_state == 0) { - return; - } - if (this->_state == 1) { - return; - } - if ((this->_sprite)._loaded == 0) { - unusedArg = this; - if (this->_overlayID != 0x2d) goto LAB_009ad1ff; - set_blend_mode(&DAT_00c798e0,1); - tintColor._red = 0.0; - tintColor._green = 0.0; - tintColor._blue = 0.0; - tintColor._alpha = 0.4; - tintColor._unk = 0; - scratchVec.x = g_screenWidth; - scratchVec.y = g_screenHeight; - render_quad_set_rect(renderQuad,&g_vectorZero,&scratchVec,&tintColor); - render_color_shader_pass(quad); - FUN_00682260(); - unusedArg = extraout_ECX; - if (((this->_megaMushPlayerSprite)._loaded == 0) || (player = this->_player, player == 0)) - goto LAB_009ad1ff; - pixelScale = g_displayPixelRatio * g_screenPointScale; - dVar1 = floor((double)(((g_screenWidth - 338.0) * 0.5 + - (*GHIDRA_CAST((player + 0x33c)) - 60.0) * 0.65) * pixelScale + 0.5)); - scratchVec.x = (float)dVar1 / pixelScale; - dVar1 = floor((double)(((g_screenHeight - 182.0) * 0.5 + - (*GHIDRA_CAST((player + 0x340)) - 140.0) * 0.65) * pixelScale + 0.5)); - sprite = &this->_megaMushPlayerSprite; - scratchVec.y = (float)dVar1 / pixelScale + *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1208)); - scratchVec.x = scratchVec.x + *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1204)); - } - else { - sprite = &this->_sprite; - scratchVec.y = g_screenHeight * 0.5; - scratchVec.x = g_screenWidth * 0.5; - } - ANM2::Render(sprite,&scratchVec,&g_vectorZero,&g_vectorZero); - unusedArg = extraout_ECX_00; -LAB_009ad1ff: - shader_cache_find(GHIDRA_INT(unusedArg)); - return; -} - -// 009ad210 -void ItemOverlay::Show(int eOverlayID, int delay, Entity_Player *player) -{ - int iVar1; - float fVar2; - float fVar3; - float fVar4; - uint8_t bVar5; - LayerState *layer; - uint8_t *pbVar6; - uint32_t cmpResult; - uint8_t extraout_CL; - uint8_t extraout_CL_00; - int iVar7; - uint8_t *pbVar8; - int layerColors; - uint8_t *pbVar9; - uint8_t *pbVar10; - bool isLess; - uint32_t layerColorIndex; - uint8_t *layerName; - void *layerData; - Entity_Player *newPlayer; - uint32_t *playerRef; - ANM2 *sprite; - - if (0x2f < GHIDRA_UINT(eOverlayID)) { - return; - } - sprite = &this->_sprite; - if (*GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x14)) == 0) { - ANM2::Reset(sprite); - } - else { - ANM2::Load(sprite,GHIDRA_CAST((GHIDRA_INT((&this->_sprite + 1)) + eOverlayID * 0x58 + 4)),0); - bVar5 = extraout_CL; - if (*GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x44)) != 0) { - Sprite::ReplaceSpritesheet - (GHIDRA_CAST(sprite),0, - GHIDRA_CAST((GHIDRA_INT((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x34))); - bVar5 = extraout_CL_00; - } - ANM2::LoadGraphics(sprite,bVar5); - } - newPlayer = player; - this->_overlayID = eOverlayID; - playerRef = &this->_player; - if (GHIDRA_CAST(*playerRef) != player) { - if (GHIDRA_CAST(*playerRef) != GHIDRA_CAST(0x0)) { - player = GHIDRA_CAST(playerRef); - msvc::multiset::erase(&player); - } - *playerRef = newPlayer; - if (newPlayer != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(playerRef); - } - } - if ((this->_sprite)._loaded != 0) { - layerColorIndex = 0; - layerColors = *GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x4c)); - iVar7 = *GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x50)) - layerColors; - iVar1 = iVar7 >> 0x1f; - if (iVar7 / 0x44 + iVar1 != iVar1) { - player = GHIDRA_CAST(0x0); - do { - pbVar10 = GHIDRA_CAST((GHIDRA_INT((&(player->_sprite)._filename + -3)) + layerColors)); - layerName = pbVar10; - if (0xf < *GHIDRA_CAST(((player->_sprite)._filename._buf + layerColors + -0x34))) { - layerName = *GHIDRA_CAST(pbVar10); - } - pbVar9 = GHIDRA_CAST(0x0); - if ((this->_sprite)._layerCount != 0) { - do { - layer = ANM2::GetLayer(sprite,pbVar9); - layerData = layer->_layerData; - if (layerData == (void *)0x0) { - pbVar8 = &s_empty; - } - else { - pbVar8 = GHIDRA_CAST((GHIDRA_INT(layerData) + 8)); - if (0xf < *GHIDRA_CAST((GHIDRA_CAST(layerData) + 0x1c))) { - pbVar8 = *GHIDRA_CAST(pbVar8); - } - } - pbVar6 = layerName; - do { - bVar5 = *pbVar8; - isLess = bVar5 < *pbVar6; - if (bVar5 != *pbVar6) { -LAB_009ad360: - cmpResult = -GHIDRA_UINT(isLess) | 1; - goto LAB_009ad365; - } - if (bVar5 == 0) break; - bVar5 = pbVar8[1]; - isLess = bVar5 < pbVar6[1]; - if (bVar5 != pbVar6[1]) goto LAB_009ad360; - pbVar8 = pbVar8 + 2; - pbVar6 = pbVar6 + 2; - } while (bVar5 != 0); - cmpResult = 0; -LAB_009ad365: - if ((cmpResult == 0) && (&layer->_color != GHIDRA_CAST((pbVar10 + 0x18)))) { - fVar2 = *GHIDRA_CAST((pbVar10 + 0x1c)); - fVar3 = *GHIDRA_CAST((pbVar10 + 0x20)); - fVar4 = *GHIDRA_CAST((pbVar10 + 0x24)); - (layer->_color)._tint[0] = *GHIDRA_CAST((pbVar10 + 0x18)); - (layer->_color)._tint[1] = fVar2; - (layer->_color)._tint[2] = fVar3; - (layer->_color)._tint[3] = fVar4; - fVar2 = *GHIDRA_CAST((pbVar10 + 0x2c)); - fVar3 = *GHIDRA_CAST((pbVar10 + 0x30)); - fVar4 = *GHIDRA_CAST((pbVar10 + 0x34)); - (layer->_color)._colorize[0] = *GHIDRA_CAST((pbVar10 + 0x28)); - (layer->_color)._colorize[1] = fVar2; - (layer->_color)._colorize[2] = fVar3; - (layer->_color)._colorize[3] = fVar4; - fVar2 = *GHIDRA_CAST((pbVar10 + 0x3c)); - (layer->_color)._offset[0] = *GHIDRA_CAST((pbVar10 + 0x38)); - (layer->_color)._offset[1] = fVar2; - (layer->_color)._offset[2] = *GHIDRA_CAST((pbVar10 + 0x40)); - } - pbVar9 = pbVar9 + 1; - } while (pbVar9 < GHIDRA_CAST((this->_sprite)._layerCount)); - } - player = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((player)) + 0x44)))); - layerColorIndex = layerColorIndex + 1; - layerColors = *GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x4c)); - } while (layerColorIndex < - GHIDRA_UINT(((*GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x50)) - layerColors) - / 0x44))); - } - pbVar10 = GHIDRA_CAST((GHIDRA_INT((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x1c)); - if (0xf < *GHIDRA_CAST((GHIDRA_CAST((&this->_sprite + 1)) + eOverlayID * 0x58 + 0x30))) { - pbVar10 = *GHIDRA_CAST(pbVar10); - } - pbVar9 = (this->_sprite)._animState._animData; - if (pbVar9 != GHIDRA_CAST(0x0)) { - pbVar8 = pbVar9; - if (0xf < *GHIDRA_CAST((pbVar9 + 0x14))) { - pbVar8 = *GHIDRA_CAST(pbVar9); - } - pbVar6 = pbVar10; - do { - bVar5 = *pbVar8; - isLess = bVar5 < *pbVar6; - if (bVar5 != *pbVar6) { -LAB_009ad424: - cmpResult = -GHIDRA_UINT(isLess) | 1; - goto LAB_009ad429; - } - if (bVar5 == 0) break; - bVar5 = pbVar8[1]; - isLess = bVar5 < pbVar6[1]; - if (bVar5 != pbVar6[1]) goto LAB_009ad424; - pbVar8 = pbVar8 + 2; - pbVar6 = pbVar6 + 2; - } while (bVar5 != 0); - cmpResult = 0; -LAB_009ad429: - if ((cmpResult == 0) && ((pbVar9[0x34] == 0 || ((this->_sprite)._animState._isPlaying != 0)))) - goto LAB_009ad452; - } - bVar5 = ANM2::SetAnimation(&this->_sprite,pbVar10,1); - if (bVar5 != 0) { - AnimationState::Rewind(&(this->_sprite)._animState); - (this->_sprite)._animState._isPlaying = 1; - } - } -LAB_009ad452: - this->_state = 2 - GHIDRA_UINT((delay != 0)); - this->_delay = delay; - return; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 456d418..af8df1d 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -12647,7 +12647,7 @@ void NpcHelper::ChampionDrop(Entity_NPC *npc) nearestPlayer = Game::GetPlayer(g_game,0); } Entity_Player::UseActiveItem(nearestPlayer,GHIDRA_CAST(&local_12c),0x23,1,-1,0); - (GHIDRA_CAST((&g_game->_itemOverlay)))->ItemOverlay::Show(0xc,3,GHIDRA_CAST(0x0)); + ItemOverlay::Show(&g_game->_itemOverlay,0xc,3,GHIDRA_CAST(0x0)); return; case 0x19: local_130 = GHIDRA_CAST(0x0); diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 9a0c234..4de3ab6 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8420,10 +8420,6 @@ float InputManager::GetActionValue(int action, int controllerIndex, Entity *enti void InviteFriendsMenu::load_graphics() { generated_stub("InviteFriendsMenu::load_graphics 009c4100"); } void InviteFriendsMenu::Render() { generated_stub("InviteFriendsMenu::Render 009c51e0"); } IsaacsBodyData::~IsaacsBodyData() { generated_stub("IsaacsBodyData::~IsaacsBodyData 0060d530"); } -ItemOverlay::~ItemOverlay() { generated_stub("ItemOverlay::~ItemOverlay 009abd80"); } -void ItemOverlay::Update(uint8_t unk) { generated_stub("ItemOverlay::Update 009aca90"); } -void ItemOverlay::Render() { generated_stub("ItemOverlay::Render 009acfe0"); } -void ItemOverlay::Show(int eOverlayID, int delay, Entity_Player *player) { generated_stub("ItemOverlay::Show 009ad210"); } KAGE::CommandQueue::~CommandQueue() { generated_stub("KAGE::CommandQueue::~CommandQueue 00a28d30"); } KAGE::EosFriendManager::~EosFriendManager() { generated_stub("KAGE::EosFriendManager::~EosFriendManager 00a7e440"); } KAGE::ManagerBase::~ManagerBase() { generated_stub("KAGE::ManagerBase::~ManagerBase 00a61a80"); } @@ -10246,7 +10242,6 @@ void NpcAI::ENTITY_FISTULA_BIG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ void NpcAI::ENTITY_LOKI(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LOKI 00467670"); } void NpcAI::ENTITY_DADDYLONGLEGS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DADDYLONGLEGS 00468180"); } void NpcAI::ENTITY_LARRYJR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LARRYJR 0046a0f0"); } -void NpcAI::ENTITY_MONSTRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MONSTRO 0046c0a0"); } void NpcAI::ENTITY_DUKE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DUKE 0046e290"); } void NpcAI::ENTITY_WIDOW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WIDOW 0046fbe0"); } void NpcAI::ENTITY_BLASTOCYST_BIG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLASTOCYST_BIG 00472c40"); } @@ -10448,9 +10443,7 @@ 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"); } void NpcAI::ENTITY_CONSTANT_STONE_SHOOTER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CONSTANT_STONE_SHOOTER 00506320"); } -void NpcAI::ENTITY_EMBRYO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EMBRYO 0050a6b0"); } void NpcAI::ENTITY_ETERNALFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ETERNALFLY 0050a8a0"); } -void NpcAI::ENTITY_HIVE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HIVE 0050c370"); } void NpcAI::ENTITY_GLOBIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GLOBIN 0050e4d0"); } uint32_t NpcAI::ENTITY_BOOMFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOOMFLY 0050f280"); } void NpcAI::ENTITY_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAW 00510ae0"); } @@ -10478,8 +10471,6 @@ void NpcAI::ENTITY_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EYE 0052 uint32_t NpcAI::ENTITY_PARA_BITE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PARA_BITE 005240a0"); } void NpcAI::ENTITY_FRED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FRED 00524a10"); } void NpcAI::ENTITY_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 00525650"); } -void NpcAI::ENTITY_HOPPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HOPPER 00526470"); } -void NpcAI::ENTITY_SPIDER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SPIDER 00529da0"); } void NpcAI::ENTITY_BABY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY 0052ae30"); } void NpcAI::ENTITY_VIS_chubber_projectile(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS_chubber_projectile 0052c2f0"); } void NpcAI::ENTITY_VIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS 0052c720"); } @@ -10502,7 +10493,6 @@ void NpcAI::ENTITY_BLACK_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BL void NpcAI::ENTITY_RING_OF_FLIES(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RING_OF_FLIES 0053bae0"); } void NpcAI::ENTITY_WALL_CREEP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WALL_CREEP 0053c0d0"); } int * NpcAI::ENTITY_ROUND_WORM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROUND_WORM 0053e4a0"); } -void NpcAI::ENTITY_DART_FLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DART_FLY 005400d0"); } void NpcAI::ENTITY_FAT_BAT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FAT_BAT 00540510"); } void NpcAI::ENTITY_SWARM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWARM 00540df0"); } void NpcAI::ENTITY_DUKIE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DUKIE 00541810"); } @@ -10827,18 +10817,13 @@ void FUN_0060d0c0() { generated_stub("FUN_0060d0c0 0060d0c0"); } void FUN_0060d0d0(uint32_t param_1) { generated_stub("FUN_0060d0d0 0060d0d0"); } void FUN_0060d0f0(uint32_t param_1) { generated_stub("FUN_0060d0f0 0060d0f0"); } uint32_t FUN_0060d110() { generated_stub("FUN_0060d110 0060d110"); } -uint8_t FUN_0060d120() { generated_stub("FUN_0060d120 0060d120"); } -uint8_t FUN_0060d130() { generated_stub("FUN_0060d130 0060d130"); } bool FUN_0060d1c0(uint32_t param_1) { generated_stub("FUN_0060d1c0 0060d1c0"); } uint32_t FUN_0060d1e0() { generated_stub("FUN_0060d1e0 0060d1e0"); } void FUN_0060d1f0(uint32_t param_1) { generated_stub("FUN_0060d1f0 0060d1f0"); } void FUN_0060d400() { generated_stub("FUN_0060d400 0060d400"); } void FUN_0060d530(uint8_t param_1) { generated_stub("FUN_0060d530 0060d530"); } void FUN_0060d5e0(uint8_t param_1) { generated_stub("FUN_0060d5e0 0060d5e0"); } -int FUN_0060d6a0() { generated_stub("FUN_0060d6a0 0060d6a0"); } -uint32_t FUN_0060d780() { generated_stub("FUN_0060d780 0060d780"); } uint32_t FUN_0060dae0() { generated_stub("FUN_0060dae0 0060dae0"); } -uint32_t FUN_00612ad0() { generated_stub("FUN_00612ad0 00612ad0"); } void * FamiliarAI::blue_spider(Entity_Familiar *familiar) { generated_stub("FamiliarAI::blue_spider 00616050"); } void FamiliarAI::bobs_brain(Entity_Familiar *familiar) { generated_stub("FamiliarAI::bobs_brain 00616770"); } void FamiliarAI::gb_bug(Entity_Familiar *familiar) { generated_stub("FamiliarAI::gb_bug 00618b00"); } @@ -10853,7 +10838,6 @@ void FamiliarAI::bumbo(Entity_Familiar *familiar) { generated_stub("FamiliarAI:: void FamiliarAI::spider_mod(Entity_Familiar *familiar) { generated_stub("FamiliarAI::spider_mod 00630c90"); } void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3) { generated_stub("FUN_00631a00 00631a00"); } void familiar_wisp_pick_tear_color(RNG *rng, int *outVariant, BitSet128 *outFlags) { generated_stub("familiar_wisp_pick_tear_color 00633990"); } -uint32_t FUN_00634920() { generated_stub("FUN_00634920 00634920"); } void FamiliarAI::sprinkler(Entity_Familiar *familiar) { generated_stub("FamiliarAI::sprinkler 00635390"); } void FamiliarAI::mystery_egg(Entity_Familiar *familiar) { generated_stub("FamiliarAI::mystery_egg 00638170"); } void FamiliarAI::lil_spewer(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lil_spewer 006384a0"); } @@ -10915,8 +10899,6 @@ int FUN_00652a30(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint8_t p void FUN_00652a70() { generated_stub("FUN_00652a70 00652a70"); } bool _has_flag_0x110(uint32_t param_1) { generated_stub("_has_flag_0x110 00652a90"); } int FUN_00652ae0() { generated_stub("FUN_00652ae0 00652ae0"); } -void FUN_00652df0() { generated_stub("FUN_00652df0 00652df0"); } -void FUN_00652f80() { generated_stub("FUN_00652f80 00652f80"); } void reroll_entity_to_free_tile(int param_1) { generated_stub("reroll_entity_to_free_tile 0065ad30"); } bool FUN_0065cfe0(uint32_t param_1) { generated_stub("FUN_0065cfe0 0065cfe0"); } int FUN_0065d010() { generated_stub("FUN_0065d010 0065d010"); } @@ -11136,7 +11118,6 @@ void FUN_006b84c0() { generated_stub("FUN_006b84c0 006b84c0"); } void FUN_006b8580() { generated_stub("FUN_006b8580 006b8580"); } Entity * spawn_gfuel_explosion() { generated_stub("spawn_gfuel_explosion 006b9450"); } 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 FUN_006d6650() { generated_stub("FUN_006d6650 006d6650"); } void NpcAI::ENTITY_MOVABLE_TNT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOVABLE_TNT 006d6690"); } @@ -11248,7 +11229,6 @@ void FUN_00718ed0(uint32_t param_1) { generated_stub("FUN_00718ed0 00718ed0"); } uint32_t FUN_00718ee0() { generated_stub("FUN_00718ee0 00718ee0"); } void FUN_0071df70(uint8_t param_1) { generated_stub("FUN_0071df70 0071df70"); } int FUN_0071df80() { generated_stub("FUN_0071df80 0071df80"); } -uint32_t FUN_00721b70(int param_1) { generated_stub("FUN_00721b70 00721b70"); } void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6) { generated_stub("FUN_00721e60 00721e60"); } void FUN_00721eb0() { generated_stub("FUN_00721eb0 00721eb0"); } void FUN_00722020(int param_1) { generated_stub("FUN_00722020 00722020"); } @@ -11386,7 +11366,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"); } -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"); } void FUN_007792f0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_007792f0 007792f0"); } @@ -11403,7 +11382,6 @@ uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_ void FUN_007b8c00(int param_1) { generated_stub("FUN_007b8c00 007b8c00"); } void FUN_007b9a60() { generated_stub("FUN_007b9a60 007b9a60"); } void FUN_007b9aa0() { generated_stub("FUN_007b9aa0 007b9aa0"); } -float get_tear_trinket_multiplier(Entity_Player *player, int tearVariant) { generated_stub("get_tear_trinket_multiplier 007c2d50"); } void FUN_007c2e80() { generated_stub("FUN_007c2e80 007c2e80"); } uint8_t FUN_007c7b10(uint32_t param_1, int param_2) { generated_stub("FUN_007c7b10 007c7b10"); } char FUN_007c9080() { generated_stub("FUN_007c9080 007c9080"); } @@ -11418,11 +11396,9 @@ void FUN_007d3330(int param_1) { generated_stub("FUN_007d3330 007d3330"); } Game * damage_charge_scale() { generated_stub("damage_charge_scale 007d3560"); } void FUN_007d3e00() { generated_stub("FUN_007d3e00 007d3e00"); } char FUN_007d4320() { generated_stub("FUN_007d4320 007d4320"); } -void FUN_007d8630(int param_1) { generated_stub("FUN_007d8630 007d8630"); } void FUN_007d9360() { generated_stub("FUN_007d9360 007d9360"); } uint32_t FUN_007d9ca0() { generated_stub("FUN_007d9ca0 007d9ca0"); } uint32_t FUN_007da770() { generated_stub("FUN_007da770 007da770"); } -uint32_t FUN_007da7a0(uint32_t param_1) { generated_stub("FUN_007da7a0 007da7a0"); } uint32_t FUN_007dac30() { generated_stub("FUN_007dac30 007dac30"); } void FUN_007dad80() { generated_stub("FUN_007dad80 007dad80"); } int FUN_007dafb0() { generated_stub("FUN_007dafb0 007dafb0"); } @@ -11531,8 +11507,6 @@ void FUN_007ebc40() { generated_stub("FUN_007ebc40 007ebc40"); } float get_angel_room_chance() { generated_stub("get_angel_room_chance 007f96f0"); } void FUN_00812ea0(float *param_1, int *param_2, int *param_3) { generated_stub("FUN_00812ea0 00812ea0"); } uint32_t FUN_00813420(int param_1, int param_2) { generated_stub("FUN_00813420 00813420"); } -void pickup_roll_random_variant(void *papersOwner, int shopItemId, int *variant, uint32_t *subType, uint32_t seed) { generated_stub("pickup_roll_random_variant 00814a50"); } -int _Room::ResolveHeartSubType(uint32_t param_1, int param_2, Entity_Player *param_3) { generated_stub("_Room::ResolveHeartSubType 00816250"); } uint32_t FUN_0081e220() { generated_stub("FUN_0081e220 0081e220"); } void FUN_0081fae0(uint32_t *param_1) { generated_stub("FUN_0081fae0 0081fae0"); } void FUN_00821940() { generated_stub("FUN_00821940 00821940"); } @@ -11617,7 +11591,6 @@ void ItemInfo::render_popup_callback(int param_1, uint32_t param_2) { generated_ void ItemInfo::render_line(uint8_t *param_1, Vector *param_2, int param_3) { generated_stub("ItemInfo::render_line 008404a0"); } char * FUN_00840510() { generated_stub("FUN_00840510 00840510"); } std_string * int_to_string(std_string *outString, int value) { generated_stub("int_to_string 00840540"); } -void FUN_008452f0(SourceQuad *param_1, void *param_2, ColorMod *param_3) { generated_stub("FUN_008452f0 008452f0"); } void collectible_icon_render(void *param_1, ColorMod *param_2, int *param_3, int *param_4) { generated_stub("collectible_icon_render 00848c20"); } void FUN_0084a870(float *param_1) { generated_stub("FUN_0084a870 0084a870"); } void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4) { generated_stub("FUN_0084abc0 0084abc0"); } @@ -13909,8 +13882,6 @@ int save_backup_find_latest(PersistentGameData *gameData) { generated_stub("save void FUN_00929660(char param_1) { generated_stub("FUN_00929660 00929660"); } uint8_t * FUN_00929b00() { generated_stub("FUN_00929b00 00929b00"); } uint32_t FUN_00929b20() { generated_stub("FUN_00929b20 00929b20"); } -void FUN_0092a520(uint32_t param_1) { generated_stub("FUN_0092a520 0092a520"); } -void FUN_0092a5e0(int param_1) { generated_stub("FUN_0092a5e0 0092a5e0"); } uint32_t FUN_0092aaf0(int param_1, int param_2) { generated_stub("FUN_0092aaf0 0092aaf0"); } uint32_t FUN_0092ab40(int param_1) { generated_stub("FUN_0092ab40 0092ab40"); } uint32_t FUN_0092abd0(int param_1, int param_2) { generated_stub("FUN_0092abd0 0092abd0"); } diff --git a/src/active_items.h b/src/active_items.h index 9c1ef1b..497ed0d 100644 --- a/src/active_items.h +++ b/src/active_items.h @@ -1,8 +1,15 @@ #pragma once #include "classes.h" +#include "item_config.h" #include +struct Entity_Pickup; +struct History; +struct HistoryItem; +struct ItemConfig_Item; +struct TemporaryEffect; + enum ButtonAction : int; enum ChargeType : int; @@ -33,6 +40,11 @@ enum UseFlag : uint32_t USE_NOHUD = 1 << 11 }; +// The tears-up uses that unlock an achievement, and the stats the bulb trinkets reread. +constexpr int TEARS_UP_UNLOCK_COUNT = 10; +constexpr uint32_t BULB_CACHE_FLAGS = + CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_SHOTSPEED | CACHE_RANGE | CACHE_SPEED | CACHE_LUCK; + // One use of an active item: the item, how it was triggered, the slot it came from and the data its slot keeps. struct ActiveUse { @@ -49,7 +61,25 @@ struct UseResult bool isRemove = false; }; +// An active item AddCollectible puts in a slot: the item, its charge (negative for its initial or full charge), the +// slot and the data the slot keeps. +struct ActiveGain +{ + int item = 0; + int charge = -1; + int slot = ACTIVE_SLOT_PRIMARY; + int varData = 0; +}; + bool input_is_action_pressed(ButtonAction action, int controllerIndex, Entity* entity); bool input_is_action_triggered(ButtonAction action, int controllerIndex, Entity* entity); bool is_active_usable(Entity_Player& player, int item, int slot); ChargeType active_charge_type(Entity_Player& player, int slot); +bool is_active_slot_kept(Entity_Player& player, int slot); +void active_collectible_add(Entity_Player& player, ItemConfig_Item& item, const ActiveGain& gain); +bool active_pedestal_swap(Entity_Pickup& pickup, Entity_Player& player); +bool battery_collect(Entity_Pickup& battery, Entity_Player& player); +bool is_temporary_effect_plain(const TemporaryEffect& effect); +bool history_item_remove(History& history, const HistoryItem& item); +bool pocket_item_collect(Entity_Pickup& pocket, Entity_Player& player); +void tears_up_unlock_check(Entity_Player& player); diff --git a/src/anm2.cpp b/src/anm2.cpp index c1728fa..2198cc1 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -31,8 +31,6 @@ constexpr float DEGREES_TURN = 360; constexpr float RADIANS_PER_DEGREE = 0.017453292f; constexpr float GLITCH_TURN = 90; constexpr int SHIMMER_STEPS = 256; -constexpr uint32_t GRAPHICS_PREMULTIPLIED_ALPHA = 4; -constexpr char LIGHT_LAYER_PREFIX = '*'; constexpr std::string_view SHADOW_LAYER_NAME = "shadow"; constexpr std::string_view APPEAR_ANIMATION = "Appear"; constexpr std::string_view IDLE_ANIMATION = "Idle"; @@ -969,7 +967,7 @@ LayerState::LayerState() // 00408310 Points a layer at its layer data and resets its spritesheet, transform, colour, blending and render flags. void LayerState::Init(const LayerData* data) { - bool isPremultiplied = g_graphicsManager_flags & GRAPHICS_PREMULTIPLIED_ALPHA; + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; layerData = data; spriteSheetPath = data ? data->spriteSheetPath : ""; @@ -1200,6 +1198,15 @@ static void procedural_item_turn(SourceQuad& source, const AnimationFrame& frame if (rng.RandomInt(2) != 0) quad_columns_swap(source); } +// A layer's blend mode as KAGE draws with it. +static KAGE::Graphics::BlendMode layer_blend_get(const LayerState& layer) +{ + using Factor = KAGE::Graphics::BlendFactor; + const std::array& mode = layer.blendMode; + return {(KAGE::Graphics::BlendEquation)mode[BLEND_EQUATION], (Factor)mode[BLEND_RGB_SOURCE], + (Factor)mode[BLEND_RGB_DEST], (Factor)mode[BLEND_ALPHA_SOURCE], (Factor)mode[BLEND_ALPHA_DEST]}; +} + // 00409120 Draws one keyframe of a layer track with the layer's spritesheet, colour, blending and shader. // The original reads past the sprite's layers for a track keying a missing layer. Here it draws nothing. void AnimationLayer::RenderFrame(const SpriteDraw& draw, int frameIndex, const ANM2& animation) const @@ -1213,9 +1220,9 @@ void AnimationLayer::RenderFrame(const SpriteDraw& draw, int frameIndex, const A unsigned int flags = animation.bitflags | layer.bitflags; if (!layer.isVisible || !layer.spriteSheet || ((flags & ANIM_RENDER_LIGHT_PASS_ONLY) && !is_light_pass())) return; - std::array savedBlendMode; - std::copy_n(g_graphicsManager_blendMode, BLEND_PART_COUNT, savedBlendMode.begin()); - std::copy(layer.blendMode.begin(), layer.blendMode.end(), g_graphicsManager_blendMode); + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + KAGE::Graphics::BlendMode savedBlend = graphics.blendMode; + graphics.blendMode = layer_blend_get(layer); ColorMod color = layer_color_get(frame, layer, animation, flags); SourceQuad source = GetSourceQuad(frame, layer, draw, animation); @@ -1244,8 +1251,8 @@ void AnimationLayer::RenderFrame(const SpriteDraw& draw, int frameIndex, const A &animation.championColor); layer.spriteSheet->Render(source, KAGE::Graphics::ColorQuad(dest, tint), tint); - std::copy(savedBlendMode.begin(), savedBlendMode.end(), g_graphicsManager_blendMode); - KAGE::Graphics::manager.shader_default_set(); + graphics.blendMode = savedBlend; + graphics.shader_default_set(); } // 00407690 Copies a sprite, sharing its file and spritesheets. The copy starts with no offset and no render flags. diff --git a/src/anm2.h b/src/anm2.h index e722a51..b6e92ad 100644 --- a/src/anm2.h +++ b/src/anm2.h @@ -100,6 +100,9 @@ inline Vector vector_make(float x, float y) return vector; } +// The name prefix of a light pass layer. +constexpr char LIGHT_LAYER_PREFIX = '*'; + // A null or root keyframe after loading: interpolation baked into one-tick frames and the root multiplied in. // startFrame and endFrame bound the ticks it shows on, end excluded. struct NullFrame diff --git a/src/backdrop.cpp b/src/backdrop.cpp index b23dadb..c4d780c 100644 --- a/src/backdrop.cpp +++ b/src/backdrop.cpp @@ -180,9 +180,6 @@ constexpr int NARROW_ROW_INSET = 2; constexpr int L_CORNER_SHEET_X = 18; // The blood splats a room may start with: on world cells 40 apart, kept 20 from the walls or 100 from the middle. -constexpr int EFFECT_BLOOD_SPLAT = 7; -constexpr int EFFECT_LIGHT = 121; -constexpr int EFFECT_BACKDROP_DECORATION = 140; constexpr float WORLD_CELL = 40; constexpr float WORLD_ORIGIN_X = 40; constexpr float WORLD_ORIGIN_Y = 120; diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index f3623f3..e56a54d 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -1,6 +1,7 @@ #include "entity_bomb.h" #include "boss_ai.h" #include "entity_combat.h" +#include "entity_effect.h" #include "entity_player.h" #include "entity_save_state.h" #include "entity_tear.h" @@ -24,7 +25,6 @@ constexpr float DAMAGE_MEDIUM = 140; constexpr float DAMAGE_LARGE = 175; // Safety Scissors shrink the explosions no player set off: by a quarter for two, by half for more. -constexpr int TRINKET_SAFETY_SCISSORS = 63; constexpr float SCISSORS_DOUBLE_SCALE = 0.75f; constexpr float SCISSORS_MORE_SCALE = 0.5f; @@ -49,19 +49,15 @@ constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; // The grid an explosion breaks: rays cast every so far around its reach, stepping so far, and a line walked in steps. constexpr float RAY_DENSITY = 8; constexpr float RAY_STEP = 20; -constexpr float LINE_STEP = 10; // The entities and effects an explosion treats apart. -constexpr int ENTITY_MEGA_SATAN = 274; constexpr int CHALLENGE_BLUE_BOMBER = 23; -constexpr int EFFECT_ISAACS_CARPET = 74; constexpr int CARPET_BLOWN = 1000; constexpr std::array EFFECTS_BLOWN_AWAY = {21, 33, 63, 64, 158, 159}; constexpr int BOMB_EXPLOSION_EFFECT = 1; constexpr int BOMB_CRATER_EFFECT = 18; constexpr int FIREWORKS_EFFECT = 104; constexpr int SPECIAL_DAILY_FIREWORKS = 12; -constexpr int TRINKET_BROKEN_PADLOCK = 136; constexpr size_t SAVED_EFFECTS_MAX = 128; // The colors poison, butt and brimstone bombs tint the explosion with. @@ -69,10 +65,6 @@ constexpr ColorMod POISON_COLOR = {{0.4f, 0.97f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, constexpr ColorMod BUTT_COLOR = {{0.4431373f, 0.2901961f, 0.06666667f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod BRIMSTONE_COLOR = {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -// The Mom's Shovel quest: a bomb in the first floor's start room while the quest is on digs the shovel up. -constexpr uint32_t LEVEL_STATE_SHOVEL_QUEST = 1u << 16; -constexpr int COLLECTIBLE_BROKEN_SHOVEL = 550; - // Whether Safety Scissors shrink an explosion: one no player or player's entity set off. static bool is_scissored(Entity* source) { @@ -284,7 +276,7 @@ void explosion_tear_flag_effects(const Explosion& explosion) static void shovel_quest_dig() { Game& game = *g_game; - bool isQuestRoom = game.stage == 1 && (game.levelStateFlags & LEVEL_STATE_SHOVEL_QUEST) && + bool isQuestRoom = game.stage == 1 && (game.levelStateFlags & 1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED) && game.currentRoomIdx == game.startingRoomIdx; if (isQuestRoom && !game.itemPool.removedCollectibles[COLLECTIBLE_BROKEN_SHOVEL]) reconstruction_missing("Room 008207a0: Mom's Shovel dug up by a bomb"); diff --git a/src/boss_ai.h b/src/boss_ai.h index 3c52d38..e769629 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -1,21 +1,11 @@ #pragma once +#include "entity_effect.h" #include "game.h" #include "npc_ai.h" #include "room.h" #include -// The flags the boss AIs test that entity.h leaves unnamed: a Delirium form keeps its health and its calm. -constexpr uint64_t FLAG_DELIRIUM_FORM = 1ull << 60; - -// The effects and projectile looks the bosses leave. -constexpr int EFFECT_BLOOD_EXPLOSION = 2; -constexpr int EFFECT_CREEP_RED = 22; -constexpr int PROJECTILE_FCUK = 12; -constexpr uint64_t PROJECTILE_SMART = 1ull << 0; -constexpr uint64_t PROJECTILE_NO_WALL_COLLIDE = 1ull << 13; - -constexpr int COLOR_PRIORITY_DEFAULT = 255; constexpr float BOSS_BLOOD_DEPTH = 10; // EntityList::QuerySublist uncached: the updated entities of a type (and variant unless -1) a query may see. @@ -60,3 +50,7 @@ inline bool room_is_clear() } void boss_gemini_update(Entity_NPC& npc); +void boss_monstro_update(Entity_NPC& npc); + +// Gemini's baby, the variant its twin is tied to. +constexpr int GEMINI_BABY = 10; diff --git a/src/boss_death.cpp b/src/boss_death.cpp new file mode 100644 index 0000000..f8b2e75 --- /dev/null +++ b/src/boss_death.cpp @@ -0,0 +1,758 @@ +#include "boss_death.h" +#include "boss_ai.h" +#include "entity_combat.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "item_config.h" +#include "item_overlay.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "options_config.h" +#include "persistent_game_data.h" +#include "room.h" +#include "room_descriptor.h" +#include "room_grid.h" +#include "room_render.h" +#include +#include +#include + +constexpr int ENTITY_SLOTH = 46; +constexpr int ENTITY_ENVY = 51; +constexpr int ENTITY_PRIDE = 52; +constexpr int ENTITY_FALLEN = 81; +constexpr int ENTITY_POLYCEPHALUS = 269; +constexpr int VARIANT_SUPER = 1; +constexpr int VARIANT_ULTRA_PRIDE = 2; +constexpr int VARIANT_KRAMPUS = 1; +constexpr int VARIANT_THE_PILE = 1; +constexpr int VARIANT_MOTHER_PHASE_TWO = 10; +constexpr int BIG_HORN_SMALL_HOLE = 1; +constexpr int BIG_HORN_BIG_HOLE = 2; +constexpr int ENVY_SIZES = 10; +constexpr int ROTGUT_BOSS_ROOM_SUBTYPE = 3; +constexpr int DUNGEON_BOSS_SUBTYPE_FIRST = 2; +constexpr int MINIBOSS_PRIDE = 6; +constexpr int MINIBOSS_ULTRA_PRIDE = 14; +constexpr int MINIBOSS_ID_LIMIT = 16; + +constexpr int EFFECT_POOF04 = 17; +constexpr int EFFECT_BLOOD_GUSH = 42; +constexpr int EFFECT_LARGE_BLOOD_EXPLOSION = 77; + +constexpr int COLLECTIBLE_LUMP_OF_COAL = 132; +constexpr int COLLECTIBLE_HEAD_OF_KRAMPUS = 293; +constexpr int COLLECTIBLE_QUARTER = 74; +constexpr int COLLECTIBLE_FOREVER_ALONE = 128; +constexpr int NULL_ITEM_SOL = 56; +constexpr int GIANTBOOK_SOL = 5; +constexpr int BOMB_TROLL_SUBTYPE = 3; +constexpr std::array HORNFEL_ITEMS = {256, 220, 19, 137, 646}; + +constexpr int ACHIEVEMENT_A_QUARTER = 10; +constexpr int ACHIEVEMENT_LOKIS_HORNS = 15; +constexpr int ACHIEVEMENT_BOOK_OF_SIN = 22; +constexpr int ACHIEVEMENT_EVERYTHING_TERRIBLE = 33; +constexpr int ACHIEVEMENT_LEFT_HAND = 77; +constexpr int ACHIEVEMENT_CELLAR = 86; +constexpr int ACHIEVEMENT_CATACOMBS = 87; +constexpr int ACHIEVEMENT_NECROPOLIS = 88; +constexpr int ACHIEVEMENT_HEAD_OF_KRAMPUS = 143; +constexpr int ACHIEVEMENT_SEVEN_SEALS = 372; +constexpr int ACHIEVEMENT_DROSS = 412; +constexpr int ACHIEVEMENT_ASHPIT = 413; +constexpr int ACHIEVEMENT_GEHENNA = 414; +constexpr int ACHIEVEMENT_BRIMSTONE_BOMBS = 546; +constexpr int EVENT_BABY_PLUM_KILLS = 493; + +constexpr int MUSIC_JINGLE_BOSS_OVER = 83; +constexpr int MUSIC_JINGLE_BOSS_OVER2 = 97; +constexpr int MUSIC_JINGLE_BOSS_OVER3 = 42; +constexpr int MUSIC_JINGLE_MINIBOSS_OVER = 92; +constexpr int STAGE_HOME = 13; +constexpr int GAME_STATE_PERFECTION_SPAWNED = 45; + +constexpr RNG DEATH_RNG_SHIFTS = {0, 4, 3, 17}; +constexpr RNG HEART_RNG_SHIFTS = {0, 2, 9, 15}; +constexpr RNG HEART_DIRECTION_SHIFTS = {0, 3, 13, 7}; +constexpr RNG COLOR_HEART_SHIFTS = {0, 3, 5, 22}; +constexpr RNG CONSOLATION_SHIFTS = {0, 3, 3, 29}; +constexpr RNG SOL_SHIFTS = {0, 5, 27, 25}; +constexpr int DEATH_SEED_SHIFT_INDEX = 4; +constexpr int HORNFEL_SHIFT_INDEX = 23; +constexpr int PERFECTION_SHIFT_INDEX = 24; +constexpr int HORNFEL_CHEST_ODDS = 7; +constexpr int HORNFEL_CHESTS = 3; +constexpr int SIN_ITEM_ODDS = 4; +constexpr int SUPER_SIN_ITEM_ODDS = 7; +constexpr int ULTRA_PRIDE_ITEM_ODDS = 4; +constexpr int SIN_COINS_MIN = 4; +constexpr int SIN_COINS_SPAN = 5; +constexpr float SIN_COIN_SPEED = 2; +constexpr float SIN_COIN_SPEED_SPAN = 5; +constexpr float DROP_SPEED = 7; +constexpr float SIN_DROP_SPEED = 5; +constexpr float SOL_DAMAGE = 100; +constexpr int SOL_DAMAGE_COUNTDOWN = 30; +constexpr size_t LOG_LINE = 128; + +constexpr int GUIDE_SHAKE_INTERVAL = 3; +constexpr int GUIDE_SHAKE_FRAMES = 5; +constexpr int GUIDE_GIB_INTERVAL = 10; +constexpr int GUIDE_GIB_MIN = 6; +constexpr uint32_t GUIDE_GIB_MASK = 3; +constexpr float GUIDE_GIB_SPREAD = 60; +constexpr uint32_t GUIDE_GIB_FLAGS = GIB_FLAG_BLOOD | GIB_FLAG_BONE | GIB_FLAG_GUT | GIB_FLAG_WORM; +constexpr int GUIDE_EXPLOSION_MIN = 3; +constexpr float GUIDE_REACH = 4; +constexpr float GUIDE_PERSPECTIVE = 0.65f; +constexpr float GUIDE_VOLUME = 0.5f; +constexpr float GUIDE_VOLUME_SPAN = 0.2f; +constexpr float GUIDE_POOF_DEPTH = 50; +constexpr float GUIDE_POOF_TURN = 90; +constexpr uint32_t GUIDE_POOF_TURNS = 3; +constexpr float GUIDE_POOF_SHRINK = 0.4f; +constexpr int GUIDE_GUSHES = 4; +constexpr float GUIDE_GUSH_REACH = 3.8f; +constexpr float GUIDE_GUSH_DEPTH = 50; +constexpr int SOUND_DEATH_BURST_HUGE = 141; +constexpr int SOUND_DEATH_BURST_GUIDED = 72; +constexpr float GFUEL_EARLY_FRAMES = 10; +constexpr int GFUEL_DELAYED_COUNT = 2; +constexpr uint32_t GFUEL_SEED_MASK = 0xfffff; +constexpr uint32_t GFUEL_BABY_PLUM_SEED = 0xdedbb; + +// The blood explosion sizes a death's Explosion event bursts in, by the dying boss's size and shadow. +constexpr int EXPLOSION_SMALL = 1; +constexpr int EXPLOSION_MEDIUM = 2; +constexpr int EXPLOSION_LARGE = 3; +constexpr int EXPLOSION_HUGE = 4; +constexpr float EXPLOSION_SMALL_SIZE = 13; +constexpr float EXPLOSION_LARGE_SIZE = 18; +constexpr float EXPLOSION_LARGE_SHADOW = 30; +constexpr float EXPLOSION_HUGE_SIZE = 40; +constexpr float EXPLOSION_HUGE_SHADOW = 50; + +// The bosses each set of kills completes, and the unlock it gives. +struct BossSet +{ + std::array bosses{}; + int achievement = 0; +}; + +constexpr std::array BOSS_SETS = {{ + {{1, 2, 13, 17, 44, 56}, ACHIEVEMENT_CELLAR}, + {{3, 4, 14, 28, 47, 45}, ACHIEVEMENT_CATACOMBS}, + {{5, 6, 15, 48, 46}, ACHIEVEMENT_NECROPOLIS}, + {{31}, ACHIEVEMENT_LOKIS_HORNS}, + {{9, 10, 11, 12, 38}, ACHIEVEMENT_SEVEN_SEALS}, + {{77, 75, 76, 91}, ACHIEVEMENT_DROSS}, + {{83, 80, 74, 82}, ACHIEVEMENT_ASHPIT}, + {{6, 79, 81}, ACHIEVEMENT_GEHENNA}, +}}; + +// A sin's own collectible when it drops one, and its super form's. +struct SinItem +{ + int item = 0; + int superItem = 0; +}; + +constexpr std::array SIN_ITEMS = {{{42, 140}, {13, 45}, {37, 106}, {15, 129}, {0, 0}, {0, 0}, {65, 81}}}; + +// What a sin leaves without its collectible, sloth to pride: a card, a pill, two bombs, two hearts, coins, a troll bomb +// or a key. +enum SinDrop +{ + SIN_DROP_PICKUP, + SIN_DROP_PAIR, + SIN_DROP_COINS, + SIN_DROP_IN_PLACE +}; + +struct SinConsolation +{ + SinDrop drop = SIN_DROP_PICKUP; + int variant = 0; + int subType = 0; +}; + +constexpr std::array SIN_CONSOLATIONS = {{ + {SIN_DROP_PICKUP, PICKUP_TAROTCARD}, + {SIN_DROP_PICKUP, PICKUP_PILL}, + {SIN_DROP_PAIR, PICKUP_BOMB}, + {SIN_DROP_PAIR, PICKUP_HEART}, + {SIN_DROP_COINS, PICKUP_COIN}, + {SIN_DROP_IN_PLACE, PICKUP_BOMB, BOMB_TROLL_SUBTYPE}, + {SIN_DROP_PICKUP, PICKUP_KEY}, +}}; + +// Logs a line with one number, as KAGE_LogMessage's callers format it. +static void boss_log(const char* format, int value) +{ + char line[LOG_LINE]; + std::snprintf(line, sizeof(line), format, value); + KAGE_LogMessage(LOG_INFO, (uint8_t*)line); +} + +// An RNG with a shift triple and a seed. +static RNG rng_make(const RNG& shifts, uint32_t seed) +{ + RNG rng = shifts; + rng._seed = seed; + return rng; +} + +// Room::FindFreePickupSpawnPosition at the default step. +static Vector free_spot_get(const Vector& position) +{ + return room_free_pickup_position_find({.position = position}); +} + +// A pickup the boss drops. +static Entity* drop_spawn(Entity_NPC& boss, const Vector& position, const Vector& velocity, int variant, int subType, + uint32_t seed) +{ + return g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &boss, + .subType = subType, + .type = ENTITY_PICKUP, + .variant = variant, + .seed = seed}); +} + +// Whether Daemon's Tail lets a heart through: always without it, one roll in five with it. +static bool is_heart_allowed(uint32_t roll) +{ + return !g_game->playerManager.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) || roll % DAEMONS_TAIL_ODDS == 0; +} + +// Plays the room's victory jingle (and queues the boss over music after it), unless it plays already when asked. +static void victory_jingle_play(Room& room, bool isSkippedWhenPlaying) +{ + MusicManager& music = g_manager->musicManager; + int jingle = (int)room.GetBossVictoryJingle(); + + if (jingle == 0 || (isSkippedWhenPlaying && music.currentMusicId == jingle)) return; + music.Play(jingle, g_manager->optionsConfig.musicVolume); + if (music.tracks.size() > MUSIC_BOSS_OVER) music.queuedMusicId = MUSIC_BOSS_OVER; +} + +// 0092a5e0 Marks a boss as killed in the save and gives the floors every boss of a set unlocks. Ids outside the boss +// list are ignored, where the original wrote before it for a negative one. +void PersistentGameData::AddBoss(int bossId) +{ + if (isReadOnly || bossId < 0 || bossId >= BOSS_COUNT) return; + + bosses[bossId] = true; + isChangesMade = true; + boss_log("Boss %d added to SaveState\n", bossId); + for (const BossSet& set : BOSS_SETS) + if (std::ranges::all_of(set.bosses, [&](int id) { return id == 0 || bosses[id]; })) TryUnlock(set.achievement); +} + +// 0092a520 Marks a sin as killed in the save (the ids seven up as their sins, Ultra Pride's as Pride), and gives The +// Book of Sin once all seven are. +void PersistentGameData::AddMiniBoss(int miniBossId) +{ + if (isReadOnly) return; + if (miniBossId < 0 || miniBossId >= MINIBOSS_ID_LIMIT) + { + boss_log("[warn] AddMiniBoss: invalid miniboss id %d\n", miniBossId); + return; + } + + int sin = miniBossId == MINIBOSS_ULTRA_PRIDE ? MINIBOSS_PRIDE : miniBossId; + if (sin >= MINIBOSS_COUNT) sin -= MINIBOSS_COUNT; + if (sin >= MINIBOSS_COUNT) return; + miniBosses[sin] = true; + isChangesMade = true; + boss_log("MiniBoss %d added to SaveState\n", sin); + if (std::ranges::all_of(miniBosses, [](bool isKilled) { return isKilled; })) TryUnlock(ACHIEVEMENT_BOOK_OF_SIN); +} + +// 00820720 The jingle a boss's death plays: none at Home's night or in the Mom's Heart secret exit, the miniboss one +// for minibosses, Repentance's on the alt floors, and the room's own (its alt music flag) elsewhere. +uint32_t Room::GetBossVictoryJingle() +{ + Game& game = *g_game; + if (game.stage == STAGE_HOME && game.stageType == STAGE_TYPE_HOME_NIGHT) return 0; + if (game.get_secret_exit_kind() == SECRET_EXIT_MOMS_HEART && game.currentRoomIdx == ROOM_SECRET_EXIT_IDX) return 0; + + if (game.room->roomType == ROOM_MINIBOSS || game.room->isSurpriseMiniboss) return MUSIC_JINGLE_MINIBOSS_OVER; + if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) + return MUSIC_JINGLE_BOSS_OVER3; + return descriptor->flags & ROOM_DESCRIPTOR_FLAG_ALT_BOSS_MUSIC ? MUSIC_JINGLE_BOSS_OVER2 : MUSIC_JINGLE_BOSS_OVER; +} + +// The hearts a boss room's (or Boss Rush's) last boss drops: two, one once Everything is Terrible is unlocked, Boss +// Rush at most one, and Hard mode may take one away. Daemon's Tail lets one in five through. +static void boss_hearts_drop(Room& room, Entity_NPC& boss, RNG& rng) +{ + PersistentGameData& save = g_manager->persistentGameData; + RNG heartRng = rng_make(HEART_RNG_SHIFTS, rng.Next()); + RNG directionRng = rng_make(HEART_DIRECTION_SHIFTS, boss.initSeed); + bool isTerrible = save.Unlocked(ACHIEVEMENT_EVERYTHING_TERRIBLE); + int hearts = isTerrible ? 1 : 2; + + if (room.roomType == ROOM_BOSSRUSH) hearts = isTerrible ? 1 - (int)heartRng.RandomInt(2) : 1; + if (game_is_hard_mode()) hearts -= (int)heartRng.RandomInt(2); + + for (int i = 0; i < hearts; i++) + { + if (!is_heart_allowed(rng.Next())) continue; + + uint32_t seed = heartRng.Next(); + Vector velocity = vector_scale(RandomVector(directionRng.Next()), DROP_SPEED); + drop_spawn(boss, free_spot_get(boss.pos), velocity, PICKUP_HEART, 0, seed); + } +} + +// The heart a boss in one of its colors drops: a soul heart for a few colors (Larry Jr's, Mom's, Famine's, Gemini's, +// Gurdy Jr's), any heart otherwise. +static void boss_color_heart_drop(Entity_NPC& boss, RNG& rng) +{ + int color = boss.bosscoloridx; + bool isSoul = false; + + switch (boss.type) + { + case ENTITY_LARRYJR: + isSoul = boss.variant == 0 && color == 1; + break; + case ENTITY_MOM: + isSoul = true; + break; + case ENTITY_FAMINE: + isSoul = boss.variant == 0 && color == 0; + break; + case ENTITY_GEMINI: + isSoul = (boss.variant == 0 || boss.variant == GEMINI_BABY) && color == 1; + break; + case ENTITY_GURDY_JR: + isSoul = color == 0; + break; + } + if (!is_heart_allowed(rng.Next())) return; + + RNG directionRng = rng_make(COLOR_HEART_SHIFTS, boss.initSeed); + uint32_t seed = rng.Next(); + Vector velocity = vector_scale(RandomVector(directionRng.Next()), DROP_SPEED); + drop_spawn(boss, free_spot_get(boss.pos), velocity, PICKUP_HEART, isSoul ? HEART_SOUL : 0, seed); +} + +// Sol on the floor's last boss: every vulnerable enemy takes 100 from a Sol holder, every player is healed and charged +// (a holder also gets Sol's effect), the curses lift, the map shows, the rain stops and the giant book plays. +static void sol_trigger(Room& room, uint32_t seed) +{ + Game& game = *g_game; + RNG solRng = rng_make(SOL_SHIFTS, seed); + + EntityList_EL& enemies = room.entityList.updateEL; + for (size_t i = 0; i < enemies.size(); i++) + { + Entity* enemy = enemies[i]; + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + + Entity_Player* owner = game.playerManager.RandomCollectibleOwner(COLLECTIBLE_SOL, solRng.Next(), nullptr); + enemy->TakeDamage(SOL_DAMAGE, 0, EntityRef(owner), SOL_DAMAGE_COUNTDOWN); + } + + for (size_t i = 0; i < game.playerManager.playerList.size(); i++) + { + Entity_Player* player = game.GetPlayer((int)i); + player->SetFullHearts(); + player->FullCharge(-1, false, false); + ItemConfig_Item* sol = g_manager->itemConfig.GetNullItem(NULL_ITEM_SOL); + if (player->HasCollectible(COLLECTIBLE_SOL) && sol) + player->temporaryEffects.AddEffect(TemporaryEffect(sol), true, 1); + } + game.RemoveCurses(UINT32_MAX); + game.ShowMap(); + game.room->isRainStopped = true; + game.itemOverlay.Show(GIANTBOOK_SOL, 0, nullptr); +} + +// Hornfel's death unlocks Brimstone Bombs and leaves a bomb collectible one time in seven, three bombs otherwise. +static void hornfel_drop(Entity_NPC& boss, RNG& rng) +{ + Game& game = *g_game; + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_BRIMSTONE_BOMBS); + + int item = game.itemPool.GetCollectibleFromList(HORNFEL_ITEMS, rng.Next(), 0, 0); + if (item == 0 || rng.RandomInt(HORNFEL_CHEST_ODDS) != 0) + { + RNG chestRng; + chestRng.game_constructor(boss.initSeed, HORNFEL_SHIFT_INDEX); + for (int i = 0; i < HORNFEL_CHESTS; i++) + { + uint32_t seed = rng.Next(); + Vector velocity = vector_scale(RandomVector(chestRng.Next()), DROP_SPEED); + drop_spawn(boss, boss.pos, velocity, PICKUP_BOMB, 0, seed); + } + return; + } + + Vector spot = free_spot_get(boss.pos); + drop_spawn(boss, spot, {}, PICKUP_COLLECTIBLE, item, rng.Next()); + game.itemPool.removedCollectibles[item] = true; +} + +// The last boss of a floor killed without a hit for two floors drops Perfection, once a run. +static void perfection_drop(Entity_NPC& boss, RNG& rng) +{ + Game& game = *g_game; + game.gameStateFlags |= 1ull << GAME_STATE_PERFECTION_SPAWNED; + + RNG directionRng; + directionRng.game_constructor(boss.initSeed, PERFECTION_SHIFT_INDEX); + uint32_t seed = rng.Next(); + Vector velocity = vector_scale(RandomVector(directionRng.Next()), DROP_SPEED); + drop_spawn(boss, boss.pos, velocity, PICKUP_TRINKET, TRINKET_PERFECTION, seed); +} + +// The rewards of the last boss of a room but the minibosses: the victory jingle, the boss room's hearts, a boss color's +// heart, Sol, Hornfel's drop and Perfection, then the boss is marked killed in the save. A dungeon's boss rooms only +// mark Rotgut's return room as done. +static void boss_death_rewards(Room& room, Entity_NPC& boss, RNG& rng, bool isGreedWave) +{ + Game& game = *g_game; + RoomType roomType = room.roomType; + RoomDescriptor* descriptor = room.descriptor; + bool isDungeonBoss = roomType == ROOM_DUNGEON && descriptor->data->subtype >= DUNGEON_BOSS_SUBTYPE_FIRST && + descriptor->data->subtype <= ROTGUT_BOSS_ROOM_SUBTYPE; + if (isDungeonBoss) + { + if (boss.type != ENTITY_ROTGUT || descriptor->data->subtype != ROTGUT_BOSS_ROOM_SUBTYPE) return; + RoomDescriptor* returnRoom = game.GetRoomByIdx(game.dungeonReturnRoomIndex, -1); + if (returnRoom->data && returnRoom->data->type == ROOM_BOSS) + returnRoom->flags |= ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED; + return; + } + + boss_log("deathspawn_boss, color idx %d\n", boss.bosscoloridx); + int music = g_manager->musicManager.currentMusicId; + bool isBossMusic = music == MUSIC_BOSS || music == MUSIC_BOSS2 || music == MUSIC_BOSS3; + if ((roomType == ROOM_BOSS || roomType == ROOM_ANGEL || isBossMusic) && !game.ambush._isActive && + (!game.IsGreedMode() || roomType != ROOM_DEFAULT)) + victory_jingle_play(room, true); + + if (roomType == ROOM_BOSS || roomType == ROOM_BOSSRUSH) boss_hearts_drop(room, boss, rng); + if (boss.subtype != 0 && !isGreedWave) boss_color_heart_drop(boss, rng); + + bool isLastBossRoom = descriptor->listIndex == game.lastBossRoomListIdx; + if (isLastBossRoom && game.playerManager.FirstCollectibleOwner(COLLECTIBLE_SOL, LAZARUS_SHARE_CHECK)) + sol_trigger(room, rng._seed); + if (boss.type == ENTITY_HORNFEL && boss.isDead) hornfel_drop(boss, rng); + if (isLastBossRoom && game.stagesWithoutDamage > 1 && !(game.levelStateFlags >> LEVEL_STATE_DAMAGED & 1) && + !(game.gameStateFlags >> GAME_STATE_PERFECTION_SPAWNED & 1)) + perfection_drop(boss, rng); + + g_manager->persistentGameData.AddBoss(boss.GetBossID()); + if (boss.type == ENTITY_BABY_PLUM) g_manager->persistentGameData.IncreaseEventCounter(EVENT_BABY_PLUM_KILLS, 1); +} + +// A sin's collectible, one time in four (a super sin's also one time in seven more): Greed's Quarter once unlocked, a +// super Envy's Forever Alone. Whether it dropped. +static bool sin_item_drop(Entity_NPC& sin, RNG& rng) +{ + const SinItem& items = SIN_ITEMS[sin.type - ENTITY_SLOTH]; + bool isSuper = sin.variant == VARIANT_SUPER; + int item = isSuper ? items.superItem : items.item; + if (sin.type == ENTITY_GREED) + item = isSuper && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_A_QUARTER) ? COLLECTIBLE_QUARTER + : COLLECTIBLE_STEAM_SALE; + if (sin.type == ENTITY_ENVY) + item = sin.variant % ENVY_SIZES == VARIANT_SUPER ? COLLECTIBLE_FOREVER_ALONE : COLLECTIBLE_SHOOP_DA_WHOOP; + + ItemPool& pool = g_game->itemPool; + if (!pool.is_collectible_available(item, UNLOCK_CHECKED) || !pool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY)) + return false; + Vector spot = free_spot_get(sin.pos); + drop_spawn(sin, spot, {}, PICKUP_COLLECTIBLE, item, rng.Next()); + return true; +} + +// What a sin leaves without its collectible (see SIN_CONSOLATIONS). The second heart of a pair also passes Daemon's +// Tail, one time in two. +static void sin_consolation_drop(Entity_NPC& sin, RNG& rng) +{ + const SinConsolation& drop = SIN_CONSOLATIONS[sin.type - ENTITY_SLOTH]; + RNG directionRng = rng_make(CONSOLATION_SHIFTS, sin.initSeed); + + switch (drop.drop) + { + case SIN_DROP_PICKUP: + { + Vector spot = free_spot_get(sin.pos); + drop_spawn(sin, spot, {}, drop.variant, 0, rng.Next()); + return; + } + case SIN_DROP_PAIR: + { + Vector velocity = vector_scale(RandomVector(directionRng.Next()), SIN_DROP_SPEED); + drop_spawn(sin, sin.pos, velocity, drop.variant, 0, rng.Next()); + uint32_t roll = rng.Next(); + bool isTailed = + drop.variant == PICKUP_HEART && g_game->playerManager.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL); + if (!isTailed || (roll & 1) == 0) + drop_spawn(sin, sin.pos, vector_scale(velocity, -1), drop.variant, 0, rng.Next()); + return; + } + case SIN_DROP_COINS: + { + int coins = (int)rng.RandomInt(SIN_COINS_SPAN) + SIN_COINS_MIN; + for (int i = 0; i < coins; i++) + { + Vector direction = RandomVector(directionRng.Next()); + float speed = random_unit() * SIN_COIN_SPEED_SPAN + SIN_COIN_SPEED; + drop_spawn(sin, sin.pos, vector_scale(direction, speed), drop.variant, 0, rng.Next()); + } + return; + } + case SIN_DROP_IN_PLACE: + { + uint32_t seed = rng.Next(); + drop_spawn(sin, sin.pos, {}, drop.variant, drop.subType, seed); + return; + } + } +} + +// The rewards of the last of a room's minibosses (the sins, Krampus, Ultra Pride and its baby): the jingle, their own +// drop (Ultra Pride's Left Hand, Krampus's coal or head, the baby's Eternal D6 or a key, a sin's collectible or its +// consolation), then the sin marked killed in the save and the unlocks. +static void miniboss_death_rewards(Room& room, Entity_NPC& boss, RNG& rng, bool isGreedWave) +{ + PersistentGameData& save = g_manager->persistentGameData; + ItemPool& pool = g_game->itemPool; + bool isUltraPride = boss.type == ENTITY_SLOTH && boss.variant == VARIANT_ULTRA_PRIDE; + bool isUltraPrideBaby = boss.type == ENTITY_BABY && boss.variant == VARIANT_ULTRA_PRIDE; + bool isKrampus = boss.type == ENTITY_FALLEN && boss.variant == VARIANT_KRAMPUS; + + if (room.roomType == ROOM_MINIBOSS || room.isSurpriseMiniboss || + (room.roomType == ROOM_BOSS && g_game->IsGreedMode())) + victory_jingle_play(room, false); + + if (!isGreedWave) + { + if (isUltraPride) + { + uint32_t seed = rng.Next(); + drop_spawn(boss, free_spot_get(boss.pos), {}, PICKUP_TRINKET, TRINKET_LEFT_HAND, seed); + save.TryUnlock(ACHIEVEMENT_LEFT_HAND); + } + else if (isKrampus) + { + Vector spot = free_spot_get(boss.pos); + int item = COLLECTIBLE_LUMP_OF_COAL; + if (pool.is_collectible_available(COLLECTIBLE_HEAD_OF_KRAMPUS, UNLOCK_IGNORED) && rng.RandomInt(2) != 0) + item = COLLECTIBLE_HEAD_OF_KRAMPUS; + drop_spawn(boss, spot, {}, PICKUP_COLLECTIBLE, item, rng.Next()); + pool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY); + } + else if (isUltraPrideBaby) + { + bool isItem = rng.RandomInt(ULTRA_PRIDE_ITEM_ODDS) == 0 && + pool.is_collectible_available(COLLECTIBLE_ETERNAL_D6, UNLOCK_CHECKED) && + pool.RemoveCollectible(COLLECTIBLE_ETERNAL_D6, REMOVE_ANY, REMOVE_APPLY); + Vector spot = free_spot_get(boss.pos); + if (isItem) drop_spawn(boss, spot, {}, PICKUP_COLLECTIBLE, COLLECTIBLE_ETERNAL_D6, rng.Next()); + else drop_spawn(boss, spot, {}, PICKUP_KEY, 0, rng.Next()); + } + else + { + bool isItemRolled = rng.RandomInt(SIN_ITEM_ODDS) == 0 || + (rng.RandomInt(SUPER_SIN_ITEM_ODDS) == 0 && boss.variant == VARIANT_SUPER); + if (!(isItemRolled && sin_item_drop(boss, rng))) sin_consolation_drop(boss, rng); + } + } + + if (isUltraPride || isUltraPrideBaby) save.AddMiniBoss(MINIBOSS_PRIDE); + else if (boss.type >= ENTITY_SLOTH && boss.type <= ENTITY_PRIDE) save.AddMiniBoss(boss.type - ENTITY_SLOTH); + else if (isKrampus) save.TryUnlock(ACHIEVEMENT_HEAD_OF_KRAMPUS); +} + +// 007fec00 A boss leaving for good: counts it off the room's bosses (once, never a friendly one or one that does not +// count), and the last one gives the room's rewards, a miniboss's or a boss's, then moves the room's death seed on. +// Big Horn's holes never count. Uriel's and Gabriel's key pieces are not reconstructed yet. +void Room::TriggerBossDeath(Entity_NPC& boss) +{ + Game& game = *g_game; + if (boss.type == ENTITY_BIG_HORN && (boss.variant == BIG_HORN_SMALL_HOLE || boss.variant == BIG_HORN_BIG_HOLE)) + return; + + bool isGreedWave = + (game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER) && roomType == ROOM_DEFAULT; + if (boss.HasEntityFlags(FLAG_BOSSDEATH_TRIGGERED | FLAG_DONT_COUNT_BOSS_HP)) return; + boss.AddEntityFlags(FLAG_BOSSDEATH_TRIGGERED); + if (boss.HasEntityFlags(FLAG_FRIENDLY)) return; + + boss_log("TriggerBossDeath: %d bosses remaining.\n", bossesRemaining - 1); + bossesRemaining--; + if (bossesRemaining <= 0) + { + if (game.ambush._isActive) reconstruction_missing("Room::TriggerBossDeath 007fec00: an ambush's death seed"); + + RNG rng = rng_make(DEATH_RNG_SHIFTS, descriptor->bossDeathSeed); + bool isMiniboss = (boss.type >= ENTITY_SLOTH && boss.type <= ENTITY_PRIDE) || + (boss.type == ENTITY_FALLEN && boss.variant == VARIANT_KRAMPUS) || + (boss.type == ENTITY_BABY && boss.variant == VARIANT_ULTRA_PRIDE); + if (isMiniboss) miniboss_death_rewards(*this, boss, rng, isGreedWave); + else boss_death_rewards(*this, boss, rng, isGreedWave); + + RNG seedRng; + seedRng.game_constructor(descriptor->bossDeathSeed, DEATH_SEED_SHIFT_INDEX); + descriptor->bossDeathSeed = seedRng.Next(); + } + + bool isAngel = boss.type == ENTITY_URIEL || boss.type == ENTITY_GABRIEL; + RoomType currentType = game.room->roomType; + bool isAngelRoom = currentType == ROOM_ANGEL || currentType == ROOM_SACRIFICE || currentType == ROOM_SUPERSECRET; + if (isAngel && isAngelRoom) reconstruction_missing("Room::TriggerBossDeath 007fec00: the angels' key pieces"); +} + +// 006d7520 A death animation's blood guide between its BloodStart and BloodStop (or Explosion) events: a huge boss +// (and Mother's second phase) shakes the screen and throws gibs and blood about the guide, the rest puff blood poofs +// there. Satan's guide starts four gushes that follow him, which BloodStop and Explosion end. G-Fuel's poofs are not +// reconstructed yet. +void Entity_NPC::update_blood_guide_gibs(const NullFrame& guide) +{ + bool isBleeding = sprite.WasEventTriggered("BloodStart") && !sprite.WasEventTriggered("BloodStop") && + !sprite.WasEventTriggered("Explosion"); + bool isHuge = (type == ENTITY_MOTHER && variant == VARIANT_MOTHER_PHASE_TWO) || (config->gibFlags & GIB_FLAG_HUGE); + auto guideSpot = [&](float reach) { + Vector direction = random_direction(); + float distance = random_unit(); + return vector_make(distance * direction.x * guide.scale.x * reach + guide.pos.x, + distance * direction.y * guide.scale.y * reach + guide.pos.y); + }; + + if (isBleeding && isHuge) + { + if (GetIntervalTicks(GUIDE_SHAKE_INTERVAL, 0)) game_shake_screen(GUIDE_SHAKE_FRAMES); + if (GetIntervalTicks(GUIDE_GIB_INTERVAL, 0)) + { + Vector offset = vector_scale(guideSpot(GUIDE_REACH), 1 / GUIDE_PERSPECTIVE); + gibs_spawn({.color = splatColor, + .position = vector_add(pos, offset), + .spawner = this, + .spread = GUIDE_GIB_SPREAD, + .amount = (int)(Random() & GUIDE_GIB_MASK) + GUIDE_GIB_MIN, + .gibFlags = GUIDE_GIB_FLAGS}); + blood_explosion_spawn((int)(Random() & 1) + GUIDE_EXPLOSION_MIN, pos, offset, splatColor, {}); + PlaySound(SOUND_DEATH_BURST_HUGE, random_unit() * GUIDE_VOLUME_SPAN + GUIDE_VOLUME, 2, false, 1); + } + } + else if (isBleeding && (Random() & 1) == 0) + { + if (g_game->playerManager.GetGFuelCount() > 0) + reconstruction_missing("Entity_NPC::update_blood_guide_gibs 006d7520: G-Fuel's explosions"); + + auto* poof = static_cast(g_game->Spawn( + {.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_POOF04, .seed = Random()})); + poof->renderDepthOffset = GUIDE_POOF_DEPTH; + poof->sprite.offset = guideSpot(GUIDE_REACH); + poof->sprite.rotation = (float)(Random() & GUIDE_POOF_TURNS) * GUIDE_POOF_TURN; + float flipY = (Random() & 1) == 0 ? 1.0f : -1.0f; + float flipX = (Random() & 1) == 0 ? 1.0f : -1.0f; + float shrink = 1 - random_unit() * GUIDE_POOF_SHRINK; + poof->sprite.scale = vector_make(shrink * flipX, shrink * flipY); + poof->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + PlaySound(SOUND_DEATH_BURST_GUIDED, random_unit() * GUIDE_VOLUME_SPAN + GUIDE_VOLUME, 2, false, 1); + } + + if (type == ENTITY_SATAN && sprite.IsEventTriggered("BloodStart")) + { + for (int i = 0; i < GUIDE_GUSHES; i++) + { + auto* gush = static_cast(g_game->Spawn({.position = pos, + .spawner = this, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_GUSH, + .seed = Random()})); + gush->FollowParent(this); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float distance = random_unit(); + gush->sprite.offset = + vector_make(std::cos(angle) * distance * guide.scale.x * GUIDE_GUSH_REACH + guide.pos.x, + distance * std::sin(angle) * guide.scale.y * GUIDE_GUSH_REACH + guide.pos.y); + gush->renderDepthOffset = (Random() & 1) == 0 ? GUIDE_GUSH_DEPTH : -GUIDE_GUSH_DEPTH; + gush->timeout = -1; + gush->lifespan = -1; + if ((Random() & 1) == 0) gush->sprite.isFlipX = true; + gush->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + } + + if (!sprite.IsEventTriggered("BloodStop") && !sprite.IsEventTriggered("Explosion")) return; + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + if (entity && entity->type == ENTITY_EFFECT && entity->variant == EFFECT_BLOOD_GUSH && entity->parent == this) + entity->Remove(); +} + +// The blood explosion size a dying boss bursts in. +static int explosion_size_get(Entity_NPC& npc) +{ + int size = npc.size < EXPLOSION_SMALL_SIZE ? EXPLOSION_SMALL : EXPLOSION_MEDIUM; + if (npc.size >= EXPLOSION_LARGE_SIZE || npc.shadowSize > EXPLOSION_LARGE_SHADOW) size = EXPLOSION_LARGE; + if (npc.size >= EXPLOSION_HUGE_SIZE || npc.shadowSize > EXPLOSION_HUGE_SHADOW) size = EXPLOSION_HUGE; + return size; +} + +// Part of 006c4b30: a death animation with a blood guide bleeds along it (update_blood_guide_gibs), and its Explosion +// event bursts the boss: a blood explosion at the guide sized to it (with a large one for a boss with large gibs, but +// Pin's tail), its shadow gone and its gibs thrown. G-Fuel's explosions, Mom's Heart's shots and The Pile's chunks are +// not reconstructed yet. +void npc_blood_guide_update(Entity_NPC& npc, const NullFrame& bloodGuide) +{ + npc.update_blood_guide_gibs(bloodGuide); + + bool isBabyPlumGfuel = npc.type == ENTITY_BABY_PLUM && (npc.initSeed & GFUEL_SEED_MASK) == GFUEL_BABY_PLUM_SEED; + bool isGfuelDelayed = !npc.HasEntityFlags(FLAG_NO_BLOOD_SPLASH) && + (g_game->playerManager.GetGFuelCount() > GFUEL_DELAYED_COUNT || isBabyPlumGfuel) && + ((npc.initSeed & 1) == 0 || npc.type == ENTITY_BABY_PLUM); + if (isGfuelDelayed) + { + float frame = npc.sprite.animState.animFrame; + float next = (float)npc.sprite.animState.NextEventTrigger("Explosion"); + float step = npc.sprite.playbackSpeed * npc.speedMultiplier; + if (frame + GFUEL_EARLY_FRAMES <= next && next < frame + step + GFUEL_EARLY_FRAMES) + reconstruction_missing("Entity_NPC::Update 006c4b30: G-Fuel's delayed explosion"); + } + + if (!npc.sprite.IsEventTriggered("Explosion")) return; + if (!npc.HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) + { + if (g_game->playerManager.GetGFuelCount() > 0) + reconstruction_missing("Entity_NPC::Update 006c4b30: G-Fuel's death explosions"); + + Entity* explosion = g_game->Spawn({.position = npc.pos, + .subType = explosion_size_get(npc), + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + explosion->sprite.offset = bloodGuide.pos; + explosion->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (npc.IsBoss() && (npc.config->gibFlags & GIB_FLAG_LARGE) && (npc.type != ENTITY_PIN || !npc.parent)) + { + Entity* large = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_LARGE_BLOOD_EXPLOSION, + .seed = Random()}); + large->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + } + if (npc.type == ENTITY_MOMS_HEART) reconstruction_missing("Entity_NPC::Update 006c4b30: Mom's Heart's death shots"); + if (npc.type == ENTITY_POLYCEPHALUS && npc.variant == VARIANT_THE_PILE) + reconstruction_missing("Entity_NPC::Update 006c4b30: The Pile's chunks"); + npc.shadowSize = 0; + npc.BloodExplode(); +} diff --git a/src/boss_death.h b/src/boss_death.h new file mode 100644 index 0000000..7e70e33 --- /dev/null +++ b/src/boss_death.h @@ -0,0 +1,6 @@ +#pragma once + +#include "anm2.h" +#include "entity_npc.h" + +void npc_blood_guide_update(Entity_NPC& npc, const NullFrame& bloodGuide); diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp index 3423ba7..ec62bda 100644 --- a/src/boss_gemini.cpp +++ b/src/boss_gemini.cpp @@ -1,5 +1,6 @@ #include "boss_ai.h" #include "camera.h" +#include "entity_effect.h" #include "entity_laser.h" #include "room_descriptor.h" #include @@ -8,7 +9,6 @@ // umbilical cord's segments. constexpr int GEMINI_STEVEN = 1; constexpr int GEMINI_BLIGHTED_OVUM = 2; -constexpr int GEMINI_BABY = 10; constexpr int GEMINI_STEVEN_BABY = 11; constexpr int GEMINI_BLIGHTED_OVUM_BABY = 12; constexpr int GEMINI_CORD = 20; @@ -89,7 +89,6 @@ constexpr float STEVEN_DEATH_SCALE = 2; constexpr int SOUND_CUTE_GRUNT = 25; constexpr int SOUND_MONSTER_YELL_B = 122; -constexpr int SOUND_BLOODSHOOT = 178; constexpr int SOUND_WORM_SPIT = 318; constexpr int SOUND_STEVEN_DEATH_BIG = 961; constexpr int SOUND_STEVEN_DEATH_SMALL = 962; diff --git a/src/boss_monstro.cpp b/src/boss_monstro.cpp new file mode 100644 index 0000000..77a9692 --- /dev/null +++ b/src/boss_monstro.cpp @@ -0,0 +1,292 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "grid_entity_trap_door.h" +#include "room_descriptor.h" + +constexpr int ENTITY_MONSTRO = 20; +constexpr int MONSTRO_TWINS = 1; +constexpr int MONSTRO_NO_JUMP = 2; +constexpr int STAGE_ID_JUMP_DOWN = 25; +constexpr float TWIN_OFFSET = 24; + +// What Monstro does next from its idle pose, rolled in thirds. +enum MonstroAttack +{ + MONSTRO_HOP, + MONSTRO_SPIT, + MONSTRO_JUMP +}; + +// i1 of a Monstro dropping into the room from above, which lands on its target's way. +constexpr int JUMP_DROP_IN = 2; + +constexpr float FRICTION = 0.9f; +constexpr float LANDED_FRICTION = 0.8f; +constexpr float HOP_PULL = 1.2f; +constexpr float HOP_MIN_DISTANCE = 0.001f; +constexpr float JUMP_PULL = 0.006f; +constexpr float JUMP_PUSH = 0.3f; +constexpr float SPIT_CLOUD_HEIGHT = -29; +constexpr float HOP_DUST_HEIGHT = 15; +constexpr int SPIT_SHOTS = 13; +constexpr int STOMP_SHOTS = 18; + +constexpr int POOF02_DUST = 2; +constexpr int SOUND_MONSTER_ROAR_0 = 14; +constexpr int SOUND_BOSS_SPIT = 16; +constexpr float HOP_VOLUME = 0.5f; +constexpr float REHOP_VOLUME = 0.4f; +constexpr float HOP_LAND_VOLUME = 0.5f; +constexpr float SHOCKWAVE_AMPLITUDE = 0.035f; +constexpr float SHOCKWAVE_SPEED = 0.025f; +constexpr int SHOCKWAVE_FRAMES = 10; + +constexpr ColorMod HOP_DUST_COLOR = {{0.8f, 0.8f, 0.8f, 0.7f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SPIT_CLOUD_COLOR = {{1, 1, 1, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Restarts an animation from its first frame, as the AIs switch to one (SetAnimation keeping the frame, then Rewind). +static void anim_restart(ANM2& sprite, std::string_view name) +{ + if (!sprite.SetAnimation(name, SWITCH_KEEP_FRAME)) return; + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; +} + +// Aims at the center of the cell under a position, unless the cell is blocked. Whether it did. +static bool target_cell_set(Entity_NPC& npc, const Vector& position) +{ + Room& room = *g_game->room; + if (room_grid_collision_at(position) != 0) return false; + npc.targetPosition = room.GetGridPosition(room.GetGridIndex(position)); + return true; +} + +// The first frame: a twin Monstro (subtype 1) brings its brother 24 to its right, and on stage 25 Monstro drops in. +static void monstro_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + npc.i1 = 0; + if (npc.subtype == MONSTRO_TWINS && npc.spawnerType != ENTITY_MONSTRO) + { + g_game->Spawn({.position = vector_make(npc.pos.x + TWIN_OFFSET, npc.pos.y), + .velocity = npc.velocity, + .spawner = &npc, + .subType = npc.subtype, + .type = npc.type, + .variant = npc.variant, + .seed = Random()}); + npc.pos.x -= TWIN_OFFSET; + } + if (g_game->GetStageID() != STAGE_ID_JUMP_DOWN) return; + + npc.ClearEntityFlags(FLAG_APPEAR); + npc.state = NPC_STATE_STOMP; + npc.i1 = JUMP_DROP_IN; + const AnimationData* shown = npc.sprite.animState.animData; + if (shown && shown->name == "JumpDown" && (!shown->isLooping || npc.sprite.animState.isPlaying)) return; + anim_restart(npc.sprite, "JumpDown"); +} + +// The idle pose rolls the next attack: a hop, a spit or a jump (never a jump for subtype 2), only hops for a calm +// Delirium form. +static void monstro_idle(Entity_NPC& npc) +{ + if (npc.sprite.SetAnimation("Walk", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + + int attack = (int)(Random() % 3); + if (npc.subtype == MONSTRO_NO_JUMP && attack == MONSTRO_JUMP) attack = MONSTRO_SPIT; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) attack = MONSTRO_HOP; + npc.i2 = attack; + + switch (attack) + { + case MONSTRO_HOP: + npc.state = NPC_STATE_MOVE; + npc.PlaySound(SOUND_MONSTER_ROAR_0, HOP_VOLUME, 2, false, 1); + return anim_restart(npc.sprite, "Walk"); + case MONSTRO_SPIT: + npc.state = NPC_STATE_ATTACK; + anim_restart(npc.sprite, "Taunt"); + npc.sprite.isFlipX = npc.pos.x - npc.GetPlayerTarget()->pos.x < 0; + return; + case MONSTRO_JUMP: + npc.state = NPC_STATE_JUMP; + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + return anim_restart(npc.sprite, "JumpUp"); + } +} + +// A hop toward its target's cell: pulled there while airborne, dust where it lands, and once the hop ends, another +// one time in two, else back to idle. +static void monstro_hop(Entity_NPC& npc, const Vector& target) +{ + if (vector_is_zero(npc.targetPosition)) target_cell_set(npc, target); + if (vector_is_zero(npc.targetPosition)) + { + npc.friction *= LANDED_FRICTION; + return; + } + + bool isJumped = npc.sprite.WasEventTriggered("Jump"); + bool isLanded = npc.sprite.WasEventTriggered("Land"); + bool isAirborne = isJumped && !isLanded; + npc.entityCollisionClass = isAirborne ? ENTCOLL_NONE : ENTCOLL_ALL; + npc.entityGridCollisionClass = isAirborne ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, HOP_LAND_VOLUME, 2, false, 1); + auto* dust = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = POOF02_DUST, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()})); + dust->sprite.offset = vector_make(0, HOP_DUST_HEIGHT); + dust->sprite.isFlipX = (Random() & 1) == 0; + dust->SetColor(HOP_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->FollowParent(&npc); + dust->Update(); + } + + if (!isLanded) + { + Vector toward = vector_sub(npc.targetPosition, npc.pos); + float distance = vector_length(toward); + if (distance == 0) distance = HOP_MIN_DISTANCE; + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, + vector_scale(toward, HOP_PULL / distance * npc.speedMultiplier / npc.friction)); + npc.friction *= FRICTION; + npc.sprite.isFlipX = npc.velocity.x > 0; + return; + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) + { + npc.friction *= LANDED_FRICTION; + return; + } + + npc.targetPosition = {}; + if (Random() & 1) + { + npc.PlaySound(SOUND_MONSTER_ROAR_0, REHOP_VOLUME, 2, false, 1); + return anim_restart(npc.sprite, "Walk"); + } + npc.sprite.playbackSpeed = 1; + npc.state = NPC_STATE_IDLE; +} + +// The big jump's takeoff: untouchable once it leaves the ground, then falling (JumpDown). +static void monstro_jump(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + if (!npc.sprite.animState.animData || !npc.sprite.WasEventTriggered("Jump")) return; + + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = NPC_STATE_STOMP; + npc.targetPosition = {}; + anim_restart(npc.sprite, "JumpDown"); +} + +// The fall onto its target's cell (a drop-in lands where the target is heading from): steered there in the air, then +// the landing shakes the ground, poofs blood and sprays 18 shots, and it rests. +static void monstro_stomp(Entity_NPC& npc, Vector target) +{ + if (vector_is_zero(npc.targetPosition)) + { + if (npc.i1 == JUMP_DROP_IN) + { + Entity* prey = npc.GetPlayerTarget(); + float gap = prey->size + npc.size + 5; + target = vector_sub(target, vector_scale(vector_normalized(prey->velocity), gap)); + } + if (target_cell_set(npc, target) && npc.i1 == JUMP_DROP_IN) npc.pos = npc.targetPosition; + } + + bool isLanded = npc.sprite.WasEventTriggered("Land"); + if (vector_is_zero(npc.targetPosition) || isLanded) npc.friction *= LANDED_FRICTION; + else + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + Vector toward = vector_sub(npc.targetPosition, npc.pos); + Vector pull = vector_add(vector_scale(toward, JUMP_PULL), vector_scale(vector_normalized(toward), JUMP_PUSH)); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(pull, npc.speedMultiplier / npc.friction)); + } + + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) + { + if (!isLanded) return; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + shockwave_make(npc.pos, SHOCKWAVE_AMPLITUDE, SHOCKWAVE_SPEED, SHOCKWAVE_FRAMES); + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, 1); + } + if (npc.sprite.IsEventTriggered("Shoot")) npc.FireBossProjectiles(STOMP_SHOTS, {}, 0, ProjectileParams()); + return; + } + + npc.targetPosition = {}; + npc.i1 = 0; + npc.state = NPC_STATE_IDLE; + npc.sprite.playbackSpeed = 1; +} + +// The spit: 13 shots lobbed at its target on Shoot with a blood cloud from its mouth, then idle once the taunt ends. +static void monstro_spit(Entity_NPC& npc) +{ + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_SPIT, 1, 2, false, 1); + ProjectileParams params; + npc.FireBossProjectiles(SPIT_SHOTS, npc.GetPlayerTarget()->pos, 0, params); + Entity_Effect* cloud = npc.MakeBloodCloud(npc.pos, SPIT_CLOUD_COLOR); + cloud->posOffset = vector_make(0, SPIT_CLOUD_HEIGHT); + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + } + npc.state = NPC_STATE_IDLE; +} + +// 0046c0a0 NpcAI::ENTITY_MONSTRO: Monstro hops after its target, spits a spray of shots, or jumps off screen and +// stomps down in a ring of shots. Monstro II and Gish (type 43), which share it, and a Monstro a player controls are +// not reconstructed yet. +void boss_monstro_update(Entity_NPC& npc) +{ + if (npc.type != ENTITY_MONSTRO) reconstruction_missing("NpcAI::ENTITY_MONSTRO 0046c0a0: Monstro II and Gish"); + if (npc.controllerID != -1) reconstruction_missing("NpcAI::ENTITY_MONSTRO 0046c0a0: a controlled Monstro"); + + npc.friction *= FRICTION; + Vector target = npc.CalcTargetPosition(0); + + switch (npc.state) + { + case NPC_STATE_INIT: + return monstro_init(npc); + case NPC_STATE_IDLE: + return monstro_idle(npc); + case NPC_STATE_MOVE: + return monstro_hop(npc, target); + case NPC_STATE_JUMP: + return monstro_jump(npc); + case NPC_STATE_STOMP: + return monstro_stomp(npc, target); + case NPC_STATE_ATTACK: + return monstro_spit(npc); + } +} diff --git a/src/boss_pool.cpp b/src/boss_pool.cpp index 8c3ac97..d7eb7e6 100644 --- a/src/boss_pool.cpp +++ b/src/boss_pool.cpp @@ -4,6 +4,7 @@ #include "log.h" #include "manager.h" #include "platform.h" +#include #include #include @@ -60,7 +61,6 @@ constexpr int STAGE_MOM = 6; constexpr int STAGE_CHAPTER_4 = 7; constexpr int STAGE_MOMS_HEART = 8; constexpr int STAGE_SHEOL = 10; -constexpr int STAGE_DARK_ROOM = 11; constexpr int STAGE_VOID = 12; constexpr int CHALLENGE_APRILS_FOOL = 32; diff --git a/src/console.cpp b/src/console.cpp index 30f8bc4..cd1beb5 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -1,5 +1,6 @@ #include "console.h" #include "entity_pickup.h" +#include "entity_player.h" #include "font.h" #include "game.h" #include "kage_graphics.h" @@ -51,7 +52,6 @@ constexpr size_t HISTORY_LOAD_MAX = 64; // The Lua input hook and ButtonAction a mod can open the console with. constexpr int INPUT_HOOK_TRIGGERED = 1; constexpr int ACTION_CONSOLE = 33; -constexpr int COLLECTIBLE_GLITCHED_CROWN = 689; constexpr int SLIDE_FRAMES = 14; constexpr int BLINK_FRAMES = 30; diff --git a/src/entity.cpp b/src/entity.cpp index 071081a..272a292 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -77,11 +77,14 @@ constexpr int STATUS_DAMAGE_PHASE = 1; constexpr float BLEED_FLICKER_SCALE = 0.02f; constexpr int STATUS_COLOR_PRIORITY = 255; constexpr int STATUS_COLOR_FRAMES = 2; +// How long a boss shrugs off status effects after one, and the trinket that doubles their durations. +constexpr int BOSS_STATUS_COOLDOWN = 240; +constexpr int SLOW_BRIEF_FRAMES = 2; +constexpr int TRINKET_SECOND_HAND = 78; // A hit flashes the entity for a third of its damage in frames, from one to six. 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 float POSITION_LIMIT = 10000; // The debug flags PostRender draws for: entity positions, collision shapes and grid collision points. constexpr uint32_t DEBUG_ENTITY_POSITIONS = 1 << 0; @@ -1236,10 +1239,18 @@ void Entity::convert_shot_for_enemy_owner(Entity*) reconstruction_missing("Entity::convert_shot_for_enemy_owner 0064bb70"); } -// 006ad350 -int Entity::apply_second_hand_duration(int, const EntityRef&) +// 006ad350 A status effect's duration, twice per copy of Second Hand the player behind its source holds. A player is +// only affected so in versus. +int Entity::apply_second_hand_duration(int duration, const EntityRef& source) { - reconstruction_missing("Entity::apply_second_hand_duration 006ad350"); + if ((type == ENTITY_PLAYER && !g_game->deathmatchManager.is_active()) || !source.entity) return duration; + + Entity* root = source.entity; + while (root->spawnerEntity) root = root->spawnerEntity; + if (root->type != ENTITY_PLAYER) return duration; + Entity_Player& player = *static_cast(root); + if (!player.HasTrinket(TRINKET_SECOND_HAND)) return duration; + return player.GetTrinketMultiplier(TRINKET_SECOND_HAND) * duration * 2; } // 006ad3c0 @@ -1254,10 +1265,34 @@ void Entity::AddPoison(const EntityRef&, int, float, bool) reconstruction_missing("Entity::AddPoison 006ad500"); } -// 006ad750 -void Entity::AddSlowing(const EntityRef&, int, float, ColorMod, bool) +// 006ad750 Slows the entity (the head of a body sharing its status) unless a friend did it: a negative duration for +// two frames, a positive one added up and tinted, then bosses shrug status off for a while. The amount is set either +// way, and the segments copy it. +void Entity::AddSlowing(const EntityRef& source, int duration, float amount, ColorMod slowColor, + bool isIgnoreBossCooldown) { - reconstruction_missing("Entity::AddSlowing 006ad750"); + if (IsDamageSourceFriendly(source)) return; + duration = apply_second_hand_duration(duration, source); + Entity* head = this; + if (DoesEntityShareStatus()) + while (head->parent) head = head->parent; + + bool isImmune = head->HasEntityFlags(FLAG_NO_STATUS_EFFECTS); + if (duration < 0 && !isImmune) + { + head->slowingCountdown = SLOW_BRIEF_FRAMES; + head->AddEntityFlags(FLAG_SLOW); + } + else if (duration > 0 && !isImmune && (head->bossStatusEffectCooldown < 1 || isIgnoreBossCooldown)) + { + head->slowingCountdown += duration; + head->AddEntityFlags(FLAG_SLOW); + head->SetColor(slowColor, duration, STATUS_COLOR_PRIORITY, false, true); + bool isBossLike = head->IsBoss() || (g_game->deathmatchManager.is_active() && head->type == ENTITY_PLAYER); + if (!isIgnoreBossCooldown && isBossLike) head->bossStatusEffectCooldown = BOSS_STATUS_COOLDOWN; + } + head->slowingAmount = amount; + head->CopyStatusEffects(); } // 006ad870 diff --git a/src/entity.h b/src/entity.h index 01c6444..1b5ecdd 100644 --- a/src/entity.h +++ b/src/entity.h @@ -21,33 +21,99 @@ enum EntityType : int ENTITY_LASER = 7, ENTITY_KNIFE = 8, ENTITY_PROJECTILE = 9, + ENTITY_GAPER = 10, + ENTITY_GUSHER = 11, + ENTITY_FLY = 13, + ENTITY_POOTER = 14, + ENTITY_CLOTTY = 15, + ENTITY_MULLIGAN = 16, ENTITY_SHOPKEEPER = 17, + ENTITY_ATTACKFLY = 18, ENTITY_LARRYJR = 19, + ENTITY_HIVE = 22, + ENTITY_CHARGER = 23, + ENTITY_BOOMFLY = 25, ENTITY_CHUB = 28, + ENTITY_HOPPER = 29, + ENTITY_BOIL = 30, ENTITY_FIREPLACE = 33, + ENTITY_LEAPER = 34, ENTITY_MRMAW = 35, + ENTITY_GURDY = 36, + ENTITY_BABY = 38, + ENTITY_VIS = 39, + ENTITY_GUTS = 40, + ENTITY_KNIGHT = 41, + ENTITY_POKY = 44, + ENTITY_MOM = 45, + ENTITY_GREED = 50, + ENTITY_FLAMING_HOPPER = 54, + ENTITY_LEECH = 55, + ENTITY_SUCKER = 61, ENTITY_PIN = 62, + ENTITY_FAMINE = 63, + ENTITY_MOMS_HEART = 78, ENTITY_GEMINI = 79, + ENTITY_SATAN = 84, + ENTITY_SPIDER = 85, ENTITY_BUTTLICKER = 89, ENTITY_HEART = 92, ENTITY_MASK = 93, + ENTITY_BIG_SPIDER = 94, ENTITY_MASK_OF_INFAMY = 97, ENTITY_HEART_OF_INFAMY = 98, + ENTITY_GURDY_JR = 99, + ENTITY_ISAAC_BOSS = 102, + ENTITY_BABY_LONG_LEGS = 206, + ENTITY_CRAZY_LONG_LEGS = 207, + ENTITY_FATTY = 208, + ENTITY_BLUBBER = 210, + ENTITY_DEATHS_HEAD = 212, ENTITY_SWINGER = 216, + ENTITY_DIP = 217, + ENTITY_WALL_HUGGER = 218, + ENTITY_SQUIRT = 220, ENTITY_RING_OF_FLIES = 222, ENTITY_GRUB = 239, ENTITY_ROUND_WORM = 244, ENTITY_POOP = 245, + ENTITY_GATE = 263, ENTITY_URIEL = 271, ENTITY_GABRIEL = 272, + ENTITY_MEGA_SATAN = 274, + ENTITY_PITFALL = 291, ENTITY_MOVABLE_TNT = 292, + ENTITY_HUSH_FLY = 296, + ENTITY_STONEY = 302, + ENTITY_LITTLE_HORN = 404, + ENTITY_ULTRA_GREED = 406, ENTITY_HUSH = 407, + ENTITY_BIG_HORN = 411, + ENTITY_DELIRIUM = 412, ENTITY_BLOOD_PUPPY = 802, + ENTITY_BISHOP = 805, + ENTITY_WILLO = 808, + ENTITY_SMALL_LEECH = 810, + ENTITY_ROCK_SPIDER = 818, + ENTITY_FLY_BOMB = 819, ENTITY_DARK_ESAU = 866, + ENTITY_ORBIT_SPAWNER = 873, + ENTITY_GRUDGE = 877, ENTITY_CULTIST = 885, + ENTITY_BALL_AND_CHAIN = 893, + ENTITY_VISAGE = 903, + ENTITY_HERETIC = 905, + ENTITY_HORNFEL = 906, + ENTITY_GIDEON = 907, + ENTITY_BABY_PLUM = 908, ENTITY_SCOURGE = 909, + ENTITY_ROTGUT = 911, ENTITY_MOTHER = 912, + ENTITY_SINGE = 915, + ENTITY_BUMBINO = 916, ENTITY_TURDLET = 918, + ENTITY_RAGLICH = 919, + ENTITY_DOGMA = 950, ENTITY_BEAST = 951, ENTITY_GENERIC_PROP = 960, ENTITY_FROZEN_ENEMY = 963, @@ -122,7 +188,8 @@ enum EntityFlag : uint64_t FLAG_BRIMSTONE_MARKED = 1ull << 56, FLAG_HELD = 1ull << 57, FLAG_THROWN = 1ull << 58, - FLAG_FRIENDLY_BALL = 1ull << 59 + FLAG_FRIENDLY_BALL = 1ull << 59, + FLAG_DELIRIUM_FORM = 1ull << 60 }; // Lua's DamageFlag: what kind of damage a hit deals. @@ -131,8 +198,19 @@ enum DamageFlag : uint64_t DAMAGE_NOKILL = 1ull << 0, DAMAGE_FIRE = 1ull << 1, DAMAGE_EXPLOSION = 1ull << 2, + DAMAGE_ACID = 1ull << 4, + DAMAGE_COUNTDOWN = 1ull << 6, + DAMAGE_SPIKES = 1ull << 7, DAMAGE_POOP = 1ull << 9, - DAMAGE_POISON_BURN = 1ull << 15 + DAMAGE_INVINCIBLE = 1ull << 13, + DAMAGE_SPAWN_FLY = 1ull << 14, + DAMAGE_POISON_BURN = 1ull << 15, + DAMAGE_SPAWN_BLACK_HEART = 1ull << 23, + DAMAGE_SPAWN_RED_HEART = 1ull << 26, + DAMAGE_SPAWN_COIN = 1ull << 27, + DAMAGE_IGNORE_ARMOR = 1ull << 30, + DAMAGE_SPAWN_CARD = 1ull << 31, + DAMAGE_SPAWN_RUNE = 1ull << 32 }; // Lua's EntityGridCollisionClass: what of the room's grid an entity collides with. @@ -204,6 +282,9 @@ constexpr RNG DROP_RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; struct Entity; struct lua_State; +// The priority SetColor gives a color nothing outranks. +constexpr int COLOR_PRIORITY_DEFAULT = 255; + // Reading and clearing (0040c3a0, 00a0fe80) are the pointer's own. // A pointer to an entity that the entity clears when it goes away (REPENTOGON's EntityPtr). It registers itself with // the entity it points to, which nulls every such pointer in ClearReferences. diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index 3179110..e9691f1 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -17,8 +17,6 @@ #include #include -constexpr uint64_t DAMAGE_IGNORE_ARMOR = 1ull << 30; - // A bomb's fuse and damage, and the brimstone and giga bombs' own. Troll bombs light a random part of a second longer. constexpr int FUSE_FRAMES = 45; constexpr int FUSE_TROLL_EXTRA = 30; @@ -75,9 +73,6 @@ constexpr int BOMB_PICKUP_GIGA = 7; constexpr int BLASTING_CAP_CHANCE = 10; // The sounds a bomb makes, and the size its costume sprites are picked by. -constexpr int SOUND_FETUS_LAND = 40; -constexpr int SOUND_BEEP = 171; -constexpr int SOUND_GOLD_HEART_DROP = 466; constexpr int SOUND_SAFETY_SCISSORS = 900; constexpr float GOLDEN_VOLUME = 0.8f; constexpr float GIGA_DROP_PITCH = 0.8f; @@ -90,17 +85,11 @@ constexpr size_t ANM2_EXTENSION_SIZE = 5; // The items and entities a bomb asks about (Lua's names). constexpr int COLLECTIBLE_REMOTE_DETONATOR = 137; -constexpr int TRINKET_SAFETY_SCISSORS = 63; constexpr int TRINKET_BLASTING_CAP = 73; constexpr int PICKUP_BOMB = 40; constexpr int PICKUP_BOMBCHEST = 51; constexpr int POOF01_EFFECT = 15; -constexpr int ENTITY_VISAGE = 903; -constexpr int ENTITY_HORNFEL = 906; constexpr int ENTITY_COLOSTOMIA = 917; -constexpr int ENTITY_LITTLE_HORN = 404; -constexpr int ENTITY_BIG_HORN = 411; -constexpr int ENTITY_PITFALL = 291; constexpr int VISAGE_MASK_VARIANT = 10; // Pushes and slowdowns of a bomb that collides with something low. diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 271bcec..81a47bf 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -1,4 +1,6 @@ #include "entity_collision.h" +#include "entity_familiar.h" +#include "entity_npc.h" #include "entity_player.h" #include "entity_projectile.h" #include "game.h" @@ -11,7 +13,6 @@ #include // What crushes rocks on contact: The Nail, Leo (worn or rolled by Zodiac), Thunder Thighs, Stompy and Mega Mush. -constexpr int COLLECTIBLE_THE_NAIL = 83; constexpr int COLLECTIBLE_LEO = 302; constexpr int COLLECTIBLE_THUNDER_THIGHS = 314; constexpr int PLAYERFORM_STOMPY = 13; @@ -47,15 +48,8 @@ constexpr int PUSH_OUT_STEPS = 6; constexpr float HALF_CELL = GRID_CELL_SIZE / 2; // The enemies that bounce harder off walls, with the sounds some make. -constexpr int ENTITY_GURDY_JR = 99; -constexpr int ENTITY_DIP = 217; -constexpr int ENTITY_SQUIRT = 220; -constexpr int ENTITY_BALL_AND_CHAIN = 893; -constexpr int ENTITY_SINGE = 915; -constexpr int SINGE_BALL = 1; constexpr float REBOUND_GURDY_JR = 1.4f; constexpr float REBOUND_BOUNCER = 1.2f; -constexpr int SOUND_DEATH_BURST_LARGE = 28; constexpr int SOUND_STONE_IMPACT = 487; constexpr int SOUND_BALL_AND_CHAIN_HIT = 581; constexpr float BOUNCE_VOLUME_SCALE = 0.05f; @@ -81,15 +75,12 @@ constexpr int ROOM_TYPE_SUPERSECRET = 8; constexpr float MASS_HEAVY = 10; constexpr float MASS_ANCHORED = 100; constexpr float MASS_PROJECTILE_PROOF = 20; -constexpr int FAMILIAR_CUBE_BABY = 239; -constexpr int COLLECTIBLE_ISAACS_HEART = 276; constexpr int NULL_TOOTH_AND_NAIL = 59; // Charger, Boom Fly, Knight, Leech, Pin, Swarmer, Floating Knight, Bone Knight, Poop and Movable TNT. constexpr std::array SHOT_ANCHORED_TYPES = {23, 25, 41, 55, 62, 91, 254, 283, 245, 292}; // Two entities closer than this are not pushed apart. A player or the Punching Bag is not pushed into a wall. constexpr float PUSH_MIN_DISTANCE = 0.0001f; -constexpr int FAMILIAR_PUNCHING_BAG = 67; constexpr float PLAYER_PUSH_SHARE = 0.5f; constexpr float BEAST_PUSH_DAMPING = 0.25f; @@ -638,7 +629,7 @@ float Entity::collision_mass_get(Entity* other) if (HasEntityFlags(FLAG_MAGNETIZED) && is_enemy_type(other->type)) weight *= MASS_HEAVY; if (type == ENTITY_PLAYER) { - if (other->type == ENTITY_FAMILIAR && other->variant == FAMILIAR_CUBE_BABY) weight *= MASS_HEAVY; + if (other->type == ENTITY_FAMILIAR && other->variant == Entity_Familiar::CUBE_BABY) weight *= MASS_HEAVY; if (static_cast(this)->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) weight *= MASS_HEAVY; } @@ -709,7 +700,7 @@ bool Entity::push_apart_circle(Entity* other) float firstShare = 1 - secondShare; float overlap = (reach - distance) / distance; bool isWallBound = first.type == ENTITY_PLAYER || - (first.type == ENTITY_FAMILIAR && first.variant == FAMILIAR_PUNCHING_BAG); + (first.type == ENTITY_FAMILIAR && first.variant == Entity_Familiar::PUNCHING_BAG); if (isWallBound && first.is_grid_collision_at(vector_make(-delta.x * firstShare * overlap, -delta.y * firstShare * overlap))) { diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 480ffb4..03dee9d 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -25,19 +25,11 @@ 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; @@ -45,11 +37,7 @@ 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; @@ -71,20 +59,9 @@ constexpr std::array STATIC_OBSTACLE_TYPES = {292, 245, 302, 42, 201, 20 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; @@ -93,31 +70,20 @@ 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; @@ -150,7 +116,6 @@ 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; @@ -829,7 +794,7 @@ static TearContact tear_contact_get(Entity_Tear& tear, Entity& collider, Entity* if (collider.type == ENTITY_PROJECTILE) { Entity_Projectile& shot = static_cast(collider); - bool isUnstoppable = !tear.tearFlags[TEAR_SHIELDED] || (shot.projectileFlags & PROJECTILE_CANT_BE_STOPPED); + bool isUnstoppable = !tear.tearFlags[TEAR_SHIELDED] || (shot.projectileFlags & PROJECTILE_CANT_HIT_PLAYER); if (isUnstoppable && !(shot.projectileFlags & PROJECTILE_SHIELDED)) return TEAR_CONTACT_PASS; shot.projectileFlags = 0; shot.isDead = true; @@ -1008,14 +973,6 @@ bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) 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) diff --git a/src/entity_config.cpp b/src/entity_config.cpp index 572ec3e..91653f7 100644 --- a/src/entity_config.cpp +++ b/src/entity_config.cpp @@ -1,5 +1,6 @@ #include "entity_config.h" #include "data.h" +#include "entity.h" #include "manager.h" #include "texture_cache.h" #include @@ -19,8 +20,6 @@ constexpr float BOSS_PORTRAIT_ORIGIN_X = 96; constexpr float BOSS_PORTRAIT_ORIGIN_Y = 132; // Types that share one id by variant, so a mod's clashing entity takes the next variant instead of the next type. -constexpr int ENTITY_EFFECT = 1000; -constexpr int ENTITY_TEXT = 9001; constexpr int ENTITY_FIRST_NPC = 10; // What tags and gibFlags read, each name standing for its index's bit. diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index a1ae2d9..9c20a99 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -2,6 +2,7 @@ #include "entity_effect_ambient.h" #include "entity_effect_combat.h" #include "entity_list.h" +#include "entity_player.h" #include "game.h" #include "log.h" #include "lua_engine.h" @@ -23,20 +24,15 @@ constexpr std::array CRAWLSPACE_HIDDEN_EFFECTS = {7, 18, 22, 23, 24, 2 constexpr std::array WAVE_CHAIN_CREEPS = {53, 44, 46, 45, 32, 204}; constexpr int FAMILIAR_CREEP_WAVE = 125; -constexpr int EFFECT_BLOOD_PARTICLE = 5; constexpr int EFFECT_HUSH_LASER = 96; constexpr int EFFECT_HUSH_LASER_UP = 101; constexpr int EFFECT_BLACK_POWDER = 92; constexpr int EFFECT_BOOMERANG = 60; -constexpr int EFFECT_PORTAL_TELEPORT = 161; constexpr int EFFECT_TIMER = 119; constexpr int EFFECT_ENEMY_SOUL = 179; -constexpr int EFFECT_ANIMA_CHAIN = 193; constexpr int EFFECT_REDEMPTION = 185; -constexpr int EFFECT_LIGHT = 121; // The Hourglass slows Hush's lasers from full speed to half as its effect's cooldown runs from 0 to 30. -constexpr int COLLECTIBLE_HOURGLASS = 66; constexpr float HOURGLASS_COOLDOWN_SPAN = 30; constexpr float HOURGLASS_SLOWEST = 0.5f; diff --git a/src/entity_effect.h b/src/entity_effect.h index 40dc5fe..0f430cb 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -16,6 +16,61 @@ enum EffectUpdateEnd EFFECT_UPDATE_RETURN }; +// The effect variants several files name (Lua's EffectVariant). +enum EffectVariant : int +{ + EFFECT_BOMB_EXPLOSION = 1, + EFFECT_BLOOD_EXPLOSION = 2, + EFFECT_FLY_EXPLOSION = 3, + EFFECT_ROCK_PARTICLE = 4, + EFFECT_BLOOD_PARTICLE = 5, + EFFECT_BLOOD_SPLAT = 7, + EFFECT_BULLET_POOF = 11, + EFFECT_TEAR_POOF_A = 12, + EFFECT_TEAR_POOF_B = 13, + EFFECT_POOF01 = 15, + EFFECT_POOF02 = 16, + EFFECT_TINY_BUG = 21, + EFFECT_CREEP_RED = 22, + EFFECT_CREEP_GREEN = 23, + EFFECT_CREEP_WHITE = 25, + EFFECT_CREEP_BLACK = 26, + EFFECT_WOOD_PARTICLE = 27, + EFFECT_TINY_FLY = 33, + EFFECT_SPIDER_EXPLOSION = 38, + EFFECT_HEAVEN_LIGHT_DOOR = 39, + EFFECT_WATER_DROPLET = 41, + EFFECT_PLAYER_CREEP_RED = 46, + EFFECT_HEART = 49, + EFFECT_PLAYER_CREEP_GREEN = 53, + EFFECT_CREEP_BROWN = 56, + EFFECT_DUST_CLOUD = 59, + EFFECT_WORM = 63, + EFFECT_BEETLE = 64, + EFFECT_WISP = 65, + EFFECT_EMBER_PARTICLE = 66, + EFFECT_WALL_BUG = 68, + EFFECT_ISAACS_CARPET = 74, + EFFECT_DICE_FLOOR = 76, + EFFECT_TEAR_POOF_SMALL = 79, + EFFECT_TEAR_POOF_VERYSMALL = 80, + EFFECT_FALLING_EMBER = 87, + EFFECT_PENTAGRAM_BLACKPOWDER = 93, + EFFECT_WATER_SPLASH = 99, + EFFECT_BRIMSTONE_BALL = 113, + EFFECT_BROKEN_SHOVEL_SHADOW = 115, + EFFECT_SPAWNER = 120, + EFFECT_LIGHT = 121, + EFFECT_BACKDROP_DECORATION = 140, + EFFECT_SMOKE_CLOUD = 141, + EFFECT_DOOR_OUTLINE = 154, + EFFECT_TALL_LADDER = 156, + EFFECT_TADPOLE = 158, + EFFECT_LIL_GHOST = 159, + EFFECT_PORTAL_TELEPORT = 161, + EFFECT_ANIMA_CHAIN = 193 +}; + // Construction and destruction (005cd9f0, 005cd960) are the defaults, the extra data shared with its other holders. // Field accessors (00435e60, 00435eb0, 004d7770, 005784c0, 0060ce20) are the public fields. // An effect (Lua's EntityEffect): a visual or a hazard such as creep, a poof or a light beam, with its timeout, its diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp index 6f96e3e..9990b43 100644 --- a/src/entity_effect_ambient.cpp +++ b/src/entity_effect_ambient.cpp @@ -24,46 +24,17 @@ // The ambient and environment variants (Lua's EffectVariant). enum AmbientVariant : int { - EFFECT_BLOOD_EXPLOSION = 2, - EFFECT_BLOOD_SPLAT = 7, - EFFECT_TINY_BUG = 21, - EFFECT_TINY_FLY = 33, - EFFECT_WATER_DROPLET = 41, - EFFECT_BEETLE = 64, - EFFECT_EMBER_PARTICLE = 66, - EFFECT_WALL_BUG = 68, - EFFECT_ISAACS_CARPET = 74, - EFFECT_DICE_FLOOR = 76, - EFFECT_FALLING_EMBER = 87, - EFFECT_BROKEN_SHOVEL_SHADOW = 115, - EFFECT_SPAWNER = 120, - EFFECT_LIGHT = 121, EFFECT_WATER_RIPPLE = 133, EFFECT_RAIN_DROP = 135, - EFFECT_BACKDROP_DECORATION = 140, - EFFECT_DOOR_OUTLINE = 154, - EFFECT_TALL_LADDER = 156, - EFFECT_WISP = 65, - EFFECT_HEAVEN_LIGHT_DOOR = 39, - EFFECT_TADPOLE = 158, - EFFECT_LIL_GHOST = 159, - EFFECT_CREEP_RED = 22, - EFFECT_CREEP_GREEN = 23, EFFECT_CREEP_YELLOW = 24, - EFFECT_CREEP_WHITE = 25, - EFFECT_CREEP_BLACK = 26, EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, EFFECT_PLAYER_CREEP_HOLYWATER = 37, EFFECT_PLAYER_CREEP_WHITE = 44, EFFECT_PLAYER_CREEP_BLACK = 45, - EFFECT_PLAYER_CREEP_RED = 46, - EFFECT_PLAYER_CREEP_GREEN = 53, EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL = 54, - EFFECT_CREEP_BROWN = 56, EFFECT_PLAYER_CREEP_LEMON_PARTY = 78, EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90, EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, - EFFECT_PENTAGRAM_BLACKPOWDER = 93, EFFECT_CREEP_SLIPPERY_BROWN = 94, EFFECT_CREEP_STATIC = 169, EFFECT_PLAYER_CREEP_YELLOW = 204 @@ -1055,10 +1026,7 @@ constexpr std::array CORK_SMALL_GROWTH = {1, 1.25f, 1.5f}; constexpr std::array CORK_GROWTH = {1.65f, 1.9f, 2.15f}; // What spares a player creep: Callus, and the collectible 571 (Evil Charm's immunity is the player's). -constexpr uint32_t TRINKET_CALLUS = 14; constexpr int COLLECTIBLE_CREEP_IMMUNE = 571; -constexpr uint64_t DAMAGE_ACID = 1 << 4; -constexpr uint64_t DAMAGE_COUNTDOWN = 1 << 6; // The slowing creep: white slows more than the black and brown, for ten frames past touching it, tinted grey-blue. constexpr int PLAYER_SLOW_FRAMES = -10; diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index d583347..e6e636c 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -71,8 +71,6 @@ constexpr std::array ANIMATED_PARTICLES = { CombatEffect::TOOTH_PARTICLE, CombatEffect::DIAMOND_PARTICLE, CombatEffect::NAIL_PARTICLE, CombatEffect::GOLD_PARTICLE, CombatEffect::COIN_PARTICLE}; -constexpr int EFFECT_LIGHT = 121; - // The animations by subtype or at random. constexpr std::array BLOOD_EXPLOSION_ANIMATIONS = {"Poof_Large", "Poof_Small", "Poof", "Poof_Large1", "Poof_Large2", "Poof_Alt"}; @@ -216,7 +214,6 @@ constexpr float EXPLOSION_LARGE_VOLUME = 1.1f; constexpr int ENTITY_DUKE_OF_FLIES = 67; constexpr int ENTITY_RAG_MEGA = 409; constexpr const char* GFUEL_EXPLOSION_ANM2 = "gfx/promo/gfuel/effects/explosion3.anm2"; -constexpr int TRINKET_SAFETY_SCISSORS = 63; constexpr float SCISSORS_SCALE_DOUBLE = 0.75f; constexpr float SCISSORS_SCALE_TRIPLE = 0.5f; diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index 0f5ad83..d317a65 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -24,54 +24,27 @@ constexpr uint64_t NS_PER_MS = 1000000; // 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; constexpr int SPAWN_STATUS_FRAMES = 90; // The entity types, variants and boss ids spawning and layouts single out. -constexpr int ENTITY_GAPER = 10; -constexpr int ENTITY_GUSHER = 11; constexpr int ENTITY_HORF = 12; -constexpr int ENTITY_POOTER = 14; -constexpr int ENTITY_CLOTTY = 15; -constexpr int ENTITY_MULLIGAN = 16; -constexpr int ENTITY_HIVE = 22; -constexpr int ENTITY_CHARGER = 23; constexpr int ENTITY_GLOBIN = 24; -constexpr int ENTITY_BOOMFLY = 25; constexpr int ENTITY_MAW = 26; constexpr int ENTITY_HOST = 27; -constexpr int ENTITY_HOPPER = 29; -constexpr int ENTITY_BOIL = 30; -constexpr int ENTITY_BABY = 38; -constexpr int ENTITY_VIS = 39; -constexpr int ENTITY_GUTS = 40; -constexpr int ENTITY_KNIGHT = 41; constexpr int ENTITY_STONEHEAD = 42; constexpr int ENTITY_FLAMINGHOPPER = 54; -constexpr int ENTITY_LEECH = 55; constexpr int ENTITY_MEMBRAIN = 57; constexpr int ENTITY_PARA_BITE = 58; constexpr int ENTITY_EYE = 60; -constexpr int ENTITY_SUCKER = 61; -constexpr int ENTITY_SPIDER = 85; constexpr int ENTITY_WALKINGBOIL = 88; -constexpr int ENTITY_BABY_LONG_LEGS = 206; -constexpr int ENTITY_CRAZY_LONG_LEGS = 207; -constexpr int ENTITY_FATTY = 208; -constexpr int ENTITY_DEATHS_HEAD = 212; -constexpr int ENTITY_DIP = 217; -constexpr int ENTITY_SQUIRT = 220; constexpr int ENTITY_SKINNY = 226; constexpr int ENTITY_NERVE_ENDING = 231; constexpr int ENTITY_HUSH_GAPER = 297; constexpr int ENTITY_GREED_GAPER = 299; constexpr int ENTITY_MUSHROOM = 300; -constexpr int ENTITY_STONEY = 302; constexpr int ENTITY_SUB_HORF = 812; constexpr int ENTITY_STRIDER = 814; constexpr int ENTITY_GYRO = 824; -constexpr int ENTITY_ROTGUT = 911; -constexpr int ENTITY_DOGMA = 950; constexpr int EFFECT_CRAWLSPACE_LADDER = 192; constexpr int BOSS_SATAN = 24; @@ -79,11 +52,6 @@ constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_RUNE_CHANCE = 10; constexpr int PICKUP_RANDOM_CARD = 301; constexpr int COLLECTIBLE_DIRTY_MIND = 576; -constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; -constexpr int COLLECTIBLE_KNIFE_PIECE_2 = 627; -constexpr int COLLECTIBLE_INNER_CHILD = 688; -constexpr int COLLECTIBLE_FLIP = 711; -constexpr int TRINKET_MECONIUM = 91; constexpr int SLOT_MACHINE = 1; constexpr int SLOT_BEGGAR = 4; @@ -260,7 +228,6 @@ constexpr int STAGE_BACKWARDS_LAST = 6; constexpr int STAGE_WOMB_2 = 8; constexpr int STAGE_BLUE_WOMB = 9; constexpr int STAGE_SHEOL = 10; -constexpr int STAGE_DARK_ROOM = 11; constexpr int STAGE_VOID_ENTRY = 12; constexpr int STAGE_LABYRINTH_SHIFT = 1; constexpr uint32_t CURSE_LABYRINTH = 1 << 1; @@ -854,7 +821,6 @@ void room_trigger_output_cell_add(Room& room, int group, int column, int row) // The grimaces, stone shooters and other hazards a cleared room still spawns (Poky only past its first variant). constexpr std::array PERSISTENT_ENTITIES = { ENTITY_STONEHEAD, 202, 203, 218, 235, 236, 804, 809, 852, 877, 893}; -constexpr int ENTITY_POKY = 44; // 007ed2a0 Room::IsPersistentRoomEntity: whether a cleared room still spawns the entity. bool room_entity_is_persistent(int type, int variant) diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index 0d24874..32a0a0d 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -1,21 +1,196 @@ #include "entity_familiar.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "game_state_player.h" #include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include -// The variants the familiar code tells apart by number, and the Lost Soul's state while it is dead. -constexpr int FAMILIAR_ISAACS_HEART = 62; -constexpr int FAMILIAR_PUNCHING_BAG = 67; -constexpr int FAMILIAR_MILK = 100; -constexpr int FAMILIAR_LOST_SOUL = 211; +// The familiars that join the following line, and the ones that trail the player's path instead (Init 0060de70). +constexpr int FOLLOWER_VARIANTS[] = {1, 2, 4, 5, 6, 7, 9, 10, 11, 20, 21, 22, 23, 40, 41, 3, + 25, 12, 51, 52, 54, 61, 57, 55, 59, 74, 26, 27, 28, 76, 80, 81, + 82, 86, 91, 92, 89, 95, 97, 100, 104, 103, 105, 108, 112, 114, 109, 119, + 124, 125, 129, 130, 93, 203, 208, 209, 221, 230, 220, 232, 213, 214, 223, 242}; +constexpr int DELAYED_VARIANTS[] = {98, 101, 106, 99}; + +// The familiars that skip the appear flag, and the ones that start on the player. +constexpr int NO_APPEAR_VARIANTS[] = {17, 96, 207}; +constexpr int PLAYER_PINNED_VARIANTS[] = {98, 99, 101, 131, 106}; + +// The orbit layers of the orbitals, by variant. +constexpr std::pair ORBIT_LAYERS[] = { + {30, 3}, {60, 3}, {31, 2}, {218, 2}, {32, 0}, {33, 0}, {35, 0}, {44, 0}, {45, 0}, {50, 0}, + {69, 0}, {70, 0}, {83, 0}, {126, 0}, {226, 0}, {43, 1}, {65, 5}, {68, 5}, {116, 5}, {117, 5}, + {121, 5}, {128, 5}, {84, 4}, {123, 4}, {204, 6}, {216, 6}, {217, 6}, {229, 10}, {237, 8}}; + +// The familiars whose setup, drawing and links wait for their takeovers. +constexpr int UNWRITTEN_INIT_VARIANTS[] = {48, 62, 121, 122, 128, 131, 206, 228, 231, + 233, 234, 236, 237, 238, 239, 240, 900}; +constexpr int UNWRITTEN_RENDER_VARIANTS[] = {48, 68, 75, 78, 79, 231, 237, 240, 243}; + +// The familiars that walk, Init's grid collision for them, and the ones whose hit list survives the reset. +constexpr int GROUND_VARIANTS[] = {46, 47, 71, 72, 48, 56, 73}; +constexpr int KEEP_HIT_LIST_VARIANTS[] = {24, 102}; + +// The sacks, which spawn their pickups and float down again. +constexpr int SACK_VARIANTS[] = {20, 21, 22, 23, 57, 82, 91, 114}; +constexpr int FLOAT_DOWN_VARIANTS[] = {20, 21, 22, 57, 82, 91, 114}; + +// The followers that shoot, and the orbitals that only circle. +constexpr int SHOOTER_VARIANTS[] = {1, 4, 5, 6, 7, 9, 10, 11, 12, 54, 81, 92, 97, 209, 220}; +constexpr int ORBITAL_VARIANTS[] = {30, 31, 32, 33, 35, 44, 60, 65, 69, 84, 117, 121, 126}; + +// The familiars that stop enemy shots whatever their state. +constexpr int BLOCKING_VARIANTS[] = {17, 32, 33, 35, 42, 44, 45, 51, 65, 67, 68, 69, 70, + 75, 83, 95, 100, 103, 116, 117, 121, 128, 130, 201, 204, 207, + 211, 216, 217, 224, 226, 228, 229, 234, 237, 238, 239, 243, 900}; + +// The poof an appearing familiar shows, and when. +constexpr int APPEAR_TIMER_START = 5; +constexpr int APPEAR_POOF_FRAME = 3; + +// How many familiars the innermost orbit holds before the orbiting flies make way. +constexpr int FLY_RING_LIMIT = 3; + +// The subtype a permanent familiar (Lua's 55555) spawns with, and the collectible it shows. +constexpr int SUBTYPE_PERMANENT = 55555; +constexpr int COLLECTIBLE_PERMANENT_FAMILIAR = 661; +constexpr ColorMod PERMANENT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + +// The charge bars a familiar may show, where, and the shots that fill it. +constexpr std::string_view CHARGE_BAR_ANM2 = "gfx/chargebar.anm2"; +constexpr std::string_view CHARGE_BAR_MAW_ANM2 = "gfx/chargebar_maw.anm2"; +constexpr float CHARGE_BAR_OFFSET_X = 12; +constexpr float CHARGE_BAR_OFFSET_Y = -35; +constexpr int CHARGE_FRAMES = 30; +constexpr float LIL_GURDY_CHARGE_FRAMES = 90; +constexpr float ISAACS_HEART_CHARGE_FRAMES = 30; +constexpr int CHARGE_BAR_DELAY = 7; + +// The blue fly's locust looks, by subtype. +constexpr std::string_view LOCUST_ANIMS[] = { + "", "LocustWrath", "LocustPestilence", "LocustFamine", "LocustDeath", "LocustConquest"}; + +// What some variants start with. +constexpr float BBF_DAMAGE = 10; +constexpr float PUNCHING_BAG_HEALTH = 100; +constexpr float MILK_HEALTH = 9999; +constexpr float DAGGER_ORBIT_SCALE = 1.5f; +constexpr int SOUND_BUMBO = 842; +constexpr int SOUND_SPRINKLER = 1070; +constexpr float ANGRY_FLY_HEIGHT = -24; +constexpr float SPIN_SIZE_BONUS = 5; +constexpr int NULLITEM_SPIN_TO_WIN_EFFECT = 50; + +// Dip's splat colours by subtype (offsets on a cleared tint, Stone Dip's tint cleared too), and Corn Dip's double +// damage. +struct DipSplat +{ + int subtype = 0; + float red = 0; + float green = 0; + float blue = 0; +}; +constexpr DipSplat DIP_SPLATS[] = {{0, 0.25490198f, 0.16078432f, 0.13725491f}, + {2, 0.25490198f, 0.16078432f, 0.13725491f}, + {4, 0.25490198f, 0.16078432f, 0.13725491f}, + {1, 0.5882353f, 0.10588236f, 0.18823531f}, + {3, 0.9176471f, 0.61960787f, 0}, + {5, 0.039215688f, 0.039215688f, 0.039215688f}, + {6, 0.7607844f, 0.94117653f, 0.94117653f}, + {13, 0.3137255f, 0.16078432f, 0.13725491f}, + {14, 0.25490198f, 0.50980395f, 0.13725491f}, + {20, 0.6f, 0.4f, 0}}; +constexpr int DIP_STONE = 12; + +// The spin of Spin to Win, and the wisps' spin with My Little Unicorn or Unicorn Stump. +constexpr float SPIN_ORBIT_STEP = 10; +constexpr float UNICORN_ORBIT_STEP = 0.5f; +constexpr float SPIN_INTERPOLATE_STEP = 5; +constexpr float UNICORN_INTERPOLATE_STEP = 0.25f; +constexpr int SPIN_FLASH_INTERVAL = 4; +constexpr int SPIN_HIT_INTERVAL = 8; +constexpr ColorMod SPIN_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.6f, 0.6f, 0.6f}}; +constexpr int ORBIT_LAYER_WISPS = 8; +constexpr int COLLECTIBLE_UNICORN_STUMP_ID = 298; +constexpr int VERSUS_PUNCHING_INTERVAL = 16; + +// How much bigger the familiars of BFFS! and Hive Mind look. +constexpr float LOCUST_MULTIPLIED_SCALE = 1.1f; +constexpr float MULTIPLIED_SCALE = 1.25f; + +// The crawlspace's pull on a walking familiar: the fall, and the push off a ledge. +constexpr float FORGOTTEN_BODY_FALL = 0.8f; +constexpr float CRAWLSPACE_LEDGE_PROBE = 0.5f; +constexpr float CRAWLSPACE_FALL = 3.5f; + +// A thrown Dip or Cube Baby: its lift, the Dip's speed and state, and how long the cube flies. +constexpr float THROWN_HEIGHT = -15; +constexpr float THROWN_LIFT = 0.7f; +constexpr float DIP_THROWN_SPEED = 0.8f; +constexpr int DIP_THROWN = 2; +constexpr int CUBE_BABY_THROWN_FRAMES = 30; + +// The Lost Soul's state while it is dead, and a wisp that never blocks. constexpr int LOST_SOUL_DEAD = 2; -constexpr int FAMILIAR_VANISHING_TWIN = 242; -// A formation mode of none, which asks for a new place. -constexpr uint8_t FORMATION_NONE = 0xff; +constexpr int WISP_UNBLOCKING = 702; + +// EntityList::QuerySublist for familiars: the ones of a variant (any for -1) the room updates and queries see. +std::vector familiar_query(int queryVariant) +{ + std::vector found; + + for (Entity* entity : entity_query(ENTITY_FAMILIAR, queryVariant)) + if (Entity_Familiar* familiar = dynamic_cast(entity)) found.push_back(familiar); + return found; +} + +// Whether a versus match runs, where familiars fight each other. +bool familiar_versus() +{ + return (int)g_game->deathmatchManager.state > 1; +} + +// Plays a sound through the fart seeds. +void familiar_sound_play(int sound, SoundPlay play) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, play); +} + +// normalize_angle_degrees 00682740: an angle brought into -180 to 180. +float angle_wrap(float angle) +{ + if (std::fabs(angle) > 360) angle = std::fmod(angle, 360.0f); + if (angle > 180) return angle - 360; + if (angle < -180) return angle + 360; + return angle; +} + +// Whether My Little Unicorn or Unicorn Stump spins the player's wisps. +bool familiar_unicorn_active(Entity_Player& owner) +{ + return owner.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN) || + owner.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_UNICORN_STUMP_ID); +} + +// Isaac::GetAxisAlignedUnitVectorFromDir 0067f1d0: the unit step of a direction, none for no direction. +Vector direction_unit(int direction) +{ + constexpr float STEPS[][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; + return (uint32_t)direction < 4 ? vector_make(STEPS[direction][0], STEPS[direction][1]) : Vector{}; +} // 00651890 Rewinds with the Glowing Hourglass: a dead Lost Soul comes back, and it remembers the rewind for its next // room. void Entity_Familiar::TriggerGlowingHourglass() { - if (variant == FAMILIAR_LOST_SOUL && state == LOST_SOUL_DEAD) + if (variant == LOST_SOUL && state == LOST_SOUL_DEAD) { state = 0; Update(); @@ -32,722 +207,620 @@ void Entity_Familiar::hourglass_rewind_clear() // 0060dab0 Only a visible Vanishing Twin that took a boss's form holds the doors shut. bool Entity_Familiar::CanShutDoors() { - return variant == FAMILIAR_VANISHING_TWIN && coins != 0 && isVisible; + return variant == VANISHING_TWIN && coins != 0 && isVisible; } // 0060d8c0 Whether enemies can hurt it: only the familiars that take hits. bool Entity_Familiar::CanBeDamagedByEnemy() { - return variant == FAMILIAR_ISAACS_HEART || variant == FAMILIAR_PUNCHING_BAG || variant == FAMILIAR_LOST_SOUL || - variant == FAMILIAR_MILK; -} - -// 00612820 Leaves its orbit, the rest of the orbit closing the gap. -void Entity_Familiar::RemoveFromOrbit() -{ - if (orbitLayer < 0) return; - - RecalculateOrbitOffset(orbitLayer, false); - orbitLayer = -1; + return variant == ISAACS_HEART || variant == PUNCHING_BAG || variant == LOST_SOUL || variant == MILK; } // 0062aaa0 Counts hearts it collected. void Entity_Familiar::AddHearts(int amount) { - hearts = hearts + amount; + hearts += amount; } // 00630440 Counts keys it collected. void Entity_Familiar::AddKeys(int amount) { - keys = keys + amount; + keys += amount; } -// 006348d0 Drops its place in the following line, to be given a new one. -void Entity_Familiar::reset_follow_target() +// 0060de70 Sets a familiar up: its player (the spawning player or the first), sprite and charge bar, its place in the +// following line, the delayed line or an orbit, and what its variant starts with. A subtype of 55555 makes a permanent +// familiar that stays where it spawned. +void Entity_Familiar::Init(int initType, int initVariant, int initSubtype, uint32_t seed) { + extraData.reset(); + isSubtype55555 = initSubtype == SUBTYPE_PERMANENT; + isHourglassRewound = false; + int kept = isSubtype55555 ? 0 : initSubtype; + Entity::Init(initType, initVariant, kept, seed); + + Entity* spawner = spawnerEntity; + player = spawner && spawner->type == ENTITY_PLAYER ? static_cast(spawner) : g_game->GetPlayer(0); + if (config) + { + sprite.Load(config->anm2Path, GRAPHICS_LOAD); + sprite.Play(sprite.GetDefaultAnimationName()); + } + + fireCooldown = 0; + headFrameDelay = 0; + orbitAngleOffset = 0; + sirenOriginalPlayer = nullptr; + orbitDistance = {}; + orbitSpeed = 0; + orbitLayer = -1; + isLilDelirium = false; + isNotCountedAsFollower = false; + isFollower = familiar_listed(FOLLOWER_VARIANTS, initVariant); + isDelayed = familiar_listed(DELAYED_VARIANTS, initVariant); + moveDirection = -1; + shootDirection = -1; + lastDirection = -1; + counter = 0; + state = 0; + appearTimer = APPEAR_TIMER_START; + if (!familiar_listed(NO_APPEAR_VARIANTS, initVariant)) flags |= FLAG_APPEAR; + + coins = 0; + hearts = 0; + keys = 0; + roomClearCount = 0; + linkedEntity = nullptr; + weapon.reset(); + item = nullptr; + sirenCharmFrames = 0; + moveDelayNum = -1; + wispTimer = (int)(Random() % 60) + 60; + wispState = 0; + wispCharge = 1; + wispDamageMultiplier = 1; + wispScale = 1; + formationTargetOffset = {}; - formationOffset = formationTargetOffset; + formationOffset = {}; formationAngle = 0; formationMode = FORMATION_NONE; + UpdateFollowPosition(); + formationOffset = formationTargetOffset; + sirenHelper = nullptr; + if (isSubtype55555) + { + formationTargetOffset = pos; + formationOffset = pos; + item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_PERMANENT_FAMILIAR); + isNotCountedAsFollower = true; + SetColor(PERMANENT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + flags &= ~FLAG_APPEAR; + } + if (!chargeBarSprite.isLoaded) + chargeBarSprite.Load(variant == LIL_ABADDON ? CHARGE_BAR_MAW_ANM2 : CHARGE_BAR_ANM2, GRAPHICS_LOAD); + + entityGridCollisionClass = GRIDCOLL_NONE; + if (familiar_listed(GROUND_VARIANTS, initVariant)) entityGridCollisionClass = GRIDCOLL_GROUND; + else if (initVariant == SAMSONS_CHAINS) entityGridCollisionClass = GRIDCOLL_NOPITS; + else if (initVariant == LIL_GURDY) entityGridCollisionClass = GRIDCOLL_WALLS; + else if (variant == SPIDER_MOD || variant == SPIDER_BABY) + { + entityCollisionClass = ENTCOLL_ENEMIES; + entityGridCollisionClass = GRIDCOLL_GROUND; + } + + if (isFollower || variant == TWISTED_BABY) AddToFollowers(); + else if (isDelayed) AddToDelayed(); + else + { + for (auto [orbitVariant, layer] : ORBIT_LAYERS) + if (orbitVariant == initVariant) orbitLayer = layer; + if (initVariant == WISP) reconstruction_missing("Entity_Familiar::Init 0060de70 (a wisp's orbit layer)"); + if (isSubtype55555) orbitLayer = -1; + else if (orbitLayer >= 0 && isExists) + { + RecalculateOrbitOffset(orbitLayer, ORBIT_JOIN); + orbitDistance = GetOrbitDistance(orbitLayer); + } + } + + variant_init(kept); + if (overwrite_limit() < 0) flags |= FLAG_DONT_OVERWRITE; + if (familiar_versus()) reconstruction_missing("Entity_Familiar::Init 0060de70 (a versus match's familiar)"); + if (variant == BUM_FRIEND || variant == DARK_BUM || variant == KEY_BUM || variant == SUPER_BUM) + sprite.Play("FloatDown"); + if (variant == SAMSONS_CHAINS) entityCollisionClass = ENTCOLL_ALL; + if (player->temporaryEffects.HasNullEffect(NULLITEM_SPIN_TO_WIN_EFFECT)) + { + flags |= FLAG_SPIN; + if (orbitLayer >= 0) size = config->collisionRadius + SPIN_SIZE_BONUS; + } + variant_finish(); } -// The rest of Entity_Familiar is not reconstructed yet. - -// 0060de70 -void Entity_Familiar::Init(int, int, int, uint32_t) +// Part of 0060de70: what each variant starts with. The rarer familiars stop the game. +void Entity_Familiar::variant_init(int initSubtype) { - reconstruction_missing("Entity_Familiar::Init 0060de70"); + if (familiar_listed(UNWRITTEN_INIT_VARIANTS, variant)) + return reconstruction_missing("Entity_Familiar::Init 0060de70 (this familiar's setup)"); + if (familiar_listed(FLOAT_DOWN_VARIANTS, variant)) return sprite.Play("FloatDown"); + + switch (variant) + { + case BLUE_FLY: + collisionDamage = player->meleeDamage + player->meleeDamage; + if (initSubtype >= 1 && initSubtype <= 5) sprite.Play(LOCUST_ANIMS[initSubtype]); + break; + case BLUE_SPIDER: + counter = 0; + collisionDamage = player->meleeDamage + player->meleeDamage; + sprite.Play("Appear"); + break; + case SACRIFICIAL_DAGGER: + case SLIPPED_RIB: orbitDistance = vector_scale(GetOrbitDistance(orbitLayer), DAGGER_ORBIT_SCALE); break; + case BBF: collisionDamage = BBF_DAMAGE; break; + case PUNCHING_BAG: + maxHitPoints = PUNCHING_BAG_HEALTH; + health = PUNCHING_BAG_HEALTH; + isInvincible = !familiar_versus(); + break; + case RELIC: + case TONSIL: sprite.Play("Float"); break; + case LIL_SPEWER: lastDirection = -1; [[fallthrough]]; + case LIL_BRIMSTONE: + case LIL_MONSTRO: + case LIL_ABADDON: fireCooldown = familiar_lullaby_delay(*this, CHARGE_FRAMES); break; + case LOST_FLY: + moveDirection = DIRECTION_DOWN; + targetPosition = {}; + break; + case KEY_BUM: state = (int)dropRNG.RandomInt(4); break; + case BUMBO: familiar_sound_play(SOUND_BUMBO); break; + case BROWN_NUGGET_POOTER: sprite.Play("Appear"); break; + case BLOODSHOT_EYE: sprite.animState.isPlaying = false; break; + case ANGRY_FLY: posOffset.y = ANGRY_FLY_HEIGHT; break; + case BUDDY_IN_A_BOX: subtype = 0; break; + case SPRINKLER: + entityCollisionClass = ENTCOLL_NONE; + entityGridCollisionClass = GRIDCOLL_NONE; + familiar_sound_play(SOUND_SPRINKLER); + break; + case MILK: + maxHitPoints = MILK_HEALTH; + health = MILK_HEALTH; + break; + } } -// 0061da10 +// The end of 0060de70: Dip's splat colour and damage, and the few variants that pick an animation or state. +void Entity_Familiar::variant_finish() +{ + switch (variant) + { + case DIP: + for (const DipSplat& splat : DIP_SPLATS) + if (splat.subtype == subtype) + splatColor = {{0, 0, 0, 1}, {0, 0, 0, 0}, {splat.red, splat.green, splat.blue}}; + if (subtype == DIP_STONE) + for (float& channel : splatColor._tint) channel = 0; + collisionDamage = (subtype == DIP_CORN ? 2.0f : 1.0f) * player->meleeDamage; + break; + case BOILED_BABY: sprite.Play("FloatDown"); break; + case BOT_FLY: sprite.Play("Fly"); break; + case BABY_PLUM: + sprite.Play("Descend"); + entityCollisionClass = ENTCOLL_NONE; + state = 0; + break; + case BLOOD_PUPPY: state = 0; break; + } + if ((variant == CENSER || variant == SUCCUBUS) && sprite.layerStates.size() > 1) sprite.GetLayer(1)->bitflags = 1; +} + +// Part of 0061da10: an appearing familiar waits invisible for five frames, a poof showing on the third. +bool Entity_Familiar::update_appearing() +{ + if (appearTimer <= 0 || !HasEntityFlags(FLAG_APPEAR)) return false; + + if (--appearTimer == APPEAR_POOF_FRAME) + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()})->Update(); + isVisible = appearTimer == 0; + if ((variant == WISP || variant == ITEM_WISP) && g_game->frameCount == spawnFrame) ai_wisp(); + Entity::Update(); + return true; +} + +// 0061da10 A familiar's frame: its size, the first frames' fixes (the delayed ones start on the player, a fourth +// familiar in the innermost orbit pushes an orbiting fly out), the appearing poof, then its variant's behaviour and the +// shared tail. void Entity_Familiar::Update() { - reconstruction_missing("Entity_Familiar::Update 0061da10"); + if (variant != FORGOTTEN_BODY) + { + if (variant == ABYSS_LOCUST) reconstruction_missing("Entity_Familiar::Update 0061da10 (a locust's size)"); + sprite.scale = vector_make(1, 1); + } + + if (g_game->frameCount - spawnFrame < 2) + { + if (familiar_listed(PLAYER_PINNED_VARIANTS, variant)) pos = player->pos; + if (orbitLayer == 0) + { + int ringCount = 0; + Entity_Familiar* ringFly = nullptr; + for (Entity_Familiar* other : familiar_query(-1)) + { + if (other->player != player || !other->isExists || other->orbitLayer != 0) continue; + + ringCount++; + if (!ringFly && other->variant == FLY_ORBITAL) ringFly = other; + } + if (ringCount > FLY_RING_LIMIT) + { + if (variant == FLY_ORBITAL) Remove(); + else if (ringFly) ringFly->Remove(); + } + } + if (!isExists) return Entity::Update(); + } + if (update_appearing()) return; + + if (sirenCharmFrames > 0) sirenCharmFrames++; + if (isLilDelirium && IsFrame(300, index)) delirium_morph(); + if (state == 0 && updateTime == 0) ResolveOrbitConflict(); + + variant_update(); + update_tail(); } -// 00624a80 +// The behaviours of 0061da10 by variant. The familiars not reconstructed yet stop the game. +void Entity_Familiar::variant_update() +{ + if (familiar_listed(SHOOTER_VARIANTS, variant)) + { + FollowParent(); + return Shoot(); + } + if (familiar_listed(ORBITAL_VARIANTS, variant)) + { + velocity = vector_sub(GetOrbitPosition(player->pos), pos); + return; + } + if (familiar_listed(SACK_VARIANTS, variant)) + { + FollowParent(); + if (sprite.IsFinished("Spawn")) sprite.Play(variant == RELIC ? "Float" : "FloatDown"); + return; + } + + switch (variant) + { + case DEMON_BABY: return ai_auto_shooter(); + case LITTLE_CHUBBY: + case BOBS_BRAIN: return ai_charger(); + case DEAD_BIRD: return ai_flying_bird(); + case BLUE_FLY: return ai_blue_fly(); + default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); + } +} + +// Part of 0061da10: the spin of Spin to Win and the unicorn wisps, the hit list's reset, BFFS!'s size, a crawlspace's +// pull, the entity's own update, and the frames spent chasing each target (which a versus match's walkers give up on). +void Entity_Familiar::update_tail() +{ + if (!vector_is_zero(orbitDistance)) + { + if (HasEntityFlags(FLAG_SPIN)) + { + orbitAngleOffset = angle_wrap(orbitAngleOffset - orbitSpeed * SPIN_ORBIT_STEP); + if (orbitLayer >= 0 && IsFrame(SPIN_FLASH_INTERVAL, 0)) + SetColor(SPIN_FLASH, SPIN_FLASH_INTERVAL, COLOR_PRIORITY_DEFAULT, true, true); + } + if (orbitLayer == ORBIT_LAYER_WISPS && familiar_unicorn_active(*player)) + orbitAngleOffset = angle_wrap(orbitAngleOffset - orbitSpeed * UNICORN_ORBIT_STEP); + } + + int interval = hit_list_interval(); + if (interval > 0 && IsFrame(interval, index) && !familiar_listed(KEEP_HIT_LIST_VARIANTS, variant)) hitList.clear(); + + if (GetMultiplier() > 1) + { + if (variant == ABYSS_LOCUST) sprite.scale = vector_scale(sprite.scale, LOCUST_MULTIPLIED_SCALE); + else if (variant != FORGOTTEN_BODY && variant != ISAACS_HEART && variant != LOST_SOUL) + sprite.scale = vector_scale(sprite.scale, MULTIPLIED_SCALE); + } + + Room& room = *g_game->room; + if (room.roomType == ROOM_DUNGEON && !IsFlying()) + { + GridEntity* grid = room_grid_entity_at(pos); + if ((grid && grid->type == GRID_GRAVITY) || variant == SAMSONS_CHAINS || variant == FORGOTTEN_BODY) + { + if (variant == FORGOTTEN_BODY) velocity.y += FORGOTTEN_BODY_FALL; + else + { + velocity.x = velocity.x > 0 ? vector_length(velocity) : velocity.x < 0 ? -vector_length(velocity) : 0; + velocity.y = 0; + Vector below = vector_add(pos, vector_make(0, sizeMulti.y * size + CRAWLSPACE_LEDGE_PROBE)); + if (room.GetGridCollision(room.GetGridIndex(below)) != COLLISION_WALL) + AddVelocity_divided(vector_make(0, CRAWLSPACE_FALL), false); + } + } + } + + Entity::Update(); + chargeBarSprite.Update(); + if (isDead) Remove(); + + if (target) targetFrames[target->index]++; + for (auto it = targetFrames.begin(); it != targetFrames.end();) + { + if (it->second < 0) it->second++; + it = it->second == 0 ? targetFrames.erase(it) : std::next(it); + } +} + +// 00624a80 Moves between frames: the orbit's spin carried for the move only. The variants that act on interpolation +// stop the game. void Entity_Familiar::Interpolate() { - reconstruction_missing("Entity_Familiar::Interpolate 00624a80"); + if (variant == LIL_BRIMSTONE || variant == INCUBUS || variant == DAMOCLES || variant == BLOOD_BABY || + variant == UMBILICAL_BABY) + reconstruction_missing("Entity_Familiar::Interpolate 00624a80 (this " + "familiar's interpolation)"); + + float savedAngle = orbitAngleOffset; + if (orbitLayer >= 0) + { + float angle = savedAngle; + if (HasEntityFlags(FLAG_SPIN)) + { + angle = angle_wrap(angle - orbitSpeed * SPIN_INTERPOLATE_STEP); + orbitAngleOffset = angle; + } + if (orbitLayer == ORBIT_LAYER_WISPS && familiar_unicorn_active(*player)) + orbitAngleOffset = angle_wrap(angle - orbitSpeed * UNICORN_INTERPOLATE_STEP); + } + Entity::Interpolate(); + if (variant == DECAP_ATTACK) posOffset.y += targetPosition.y * 0.5f * speedMultiplier; + orbitAngleOffset = savedAngle; } -// 00624e10 -void Entity_Familiar::Render(const Vector&) +// 00624e10 Draws a familiar with its charge bar. The familiars drawn their own way (Isaac's body, Samson's chains, the +// locusts, item wisps, the co-op babies) and Tainted Lazarus's hologram stop the game. +void Entity_Familiar::Render(const Vector& offset) { - reconstruction_missing("Entity_Familiar::Render 00624e10"); + if (IsLilithBirthrightIncubus()) + { + Entity* whip = get_incubus_umbilical_whip(); + if (!whip || !whip->isVisible) return; + } + if (player && player->IsHologram()) + return reconstruction_missing("Entity_Familiar::Render 00624e10 (Tainted Lazarus's hologram)"); + if (familiar_listed(UNWRITTEN_RENDER_VARIANTS, variant)) + return reconstruction_missing("Entity_Familiar::Render 00624e10 (this familiar's drawing)"); + + ColorMod saved = sprite.color; + Entity::Render(offset); + render_charge_indicator(renderPosition); + sprite.color = saved; } -// 00624dd0 -bool Entity_Familiar::RenderShadowLayer(const Vector&) +// 00624dd0 Its shadow, which Tainted Lilith's hidden Incubus does not cast. +bool Entity_Familiar::RenderShadowLayer(const Vector& offset) { - reconstruction_missing("Entity_Familiar::RenderShadowLayer 00624dd0"); + if (IsLilithBirthrightIncubus()) + { + Entity* whip = get_incubus_umbilical_whip(); + if (!whip || !whip->isVisible) return false; + } + return Entity::RenderShadowLayer(offset); } -// 0062cdc0 -bool Entity_Familiar::TakeDamage(float, uint64_t, const EntityRef&, int) +// How full a familiar's charge is in percent, or 0 for none (part of 006324d0). +static int charge_percent(Entity_Familiar& familiar) { - reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0"); + float percent = 0; + switch (familiar.variant) + { + case Entity_Familiar::INCUBUS: + return familiar.weapon && familiar.weapon->GetChargeBarAmount() > 0 + ? (int)(familiar.weapon->GetChargeBarAmount() * 100) + : 0; + case Entity_Familiar::LIL_BRIMSTONE: + case Entity_Familiar::LIL_MONSTRO: + case Entity_Familiar::LIL_ABADDON: + { + int full = familiar_lullaby_delay(familiar, CHARGE_FRAMES); + if (familiar.fireCooldown == full) return 0; + percent = 1 - (float)(familiar.fireCooldown + 1) / (float)full; + break; + } + case Entity_Familiar::LIL_GURDY: + if (familiar.state != 0) return 0; + percent = (float)familiar.fireCooldown / LIL_GURDY_CHARGE_FRAMES; + break; + case Entity_Familiar::LIL_SPEWER: + if (familiar.fireCooldown < 0) return 0; + percent = 1 - (float)familiar.fireCooldown / (float)familiar_lullaby_delay(familiar, CHARGE_FRAMES); + break; + case Entity_Familiar::ISAACS_HEART: percent = (float)familiar.fireCooldown / ISAACS_HEART_CHARGE_FRAMES; break; + default: return 0; + } + return (int)std::clamp(percent * 100, 0.0f, 100.0f); } -// 00610540 -void Entity_Familiar::Kill(const EntityRef&) +// 006324d0 Shows the charge bar of a charging familiar above it, when the options show charge bars: filling while +// charging, flashing once full, and fading out when the charge goes. +void Entity_Familiar::render_charge_indicator(const Vector& renderPos) { - reconstruction_missing("Entity_Familiar::Kill 00610540"); + if (!g_manager->optionsConfig.isChargeBarsEnabled) return; + + ANM2& bar = chargeBarSprite; + int percent = charge_percent(*this); + const AnimationData* shown = bar.animState.animData; + if (percent == 0) + { + if (shown) bar.Play("Disappear"); + } + else if (percent == 100) + { + if (!shown || (!shown->isLooping && !bar.animState.isPlaying)) + { + bar.Play("StartCharged"); + if (!bar.animState.animData || !bar.animState.isPlaying) bar.Play("Charged"); + } + } + else bar.SetFrame("Charging", percent); + + bool isPlaying = bar.animState.animData && bar.animState.isPlaying; + if (!isPlaying && (percent < 1 || g_game->frameCount - spawnFrame < CHARGE_BAR_DELAY)) return; + bar.Render({.position = vector_add(renderPos, vector_make(CHARGE_BAR_OFFSET_X, CHARGE_BAR_OFFSET_Y))}); } -// 00610470 +// 00610470 Removes it, leaving its orbit and lines, and its player's counts of blue flies and spiders. void Entity_Familiar::Remove() { - reconstruction_missing("Entity_Familiar::Remove 00610470"); + Entity::Remove(); + RemoveFromOrbit(); + RemoveFromFollowers(); + RemoveFromDelayed(); + if (variant == BLUE_FLY && subtype == 0) player->numBlueFlies--; + else if (variant == BLUE_SPIDER) player->numBlueSpiders--; + if (variant == GUILLOTINE || variant == SCISSORS || variant == DECAP_ATTACK) + reconstruction_missing("Entity_Familiar::Remove 00610470 (the player's detached head)"); + ResolveOrbitConflict(); } -// 006121d0 +// 006121d0 Drops its links and its weapon. The Forgotten's body, the wisps and Gello's cord stop the game. void Entity_Familiar::ClearReferences() { - reconstruction_missing("Entity_Familiar::ClearReferences 006121d0"); + if (variant == FORGOTTEN_BODY || variant == WISP || variant == ITEM_WISP || variant == UMBILICAL_BABY) + reconstruction_missing("Entity_Familiar::ClearReferences 006121d0 (this familiar's links)"); + linkedEntity = nullptr; + Entity::ClearReferences(); + hitList = {}; + extraData.reset(); + weapon.reset(); } -// 0063c0a0 -bool Entity_Familiar::TryThrow(const EntityRef&, const Vector&, float) +// 0062e020 Moves it to another player, leaving and rejoining its orbit and lines. +void Entity_Familiar::set_player(Entity_Player* newPlayer) { - reconstruction_missing("Entity_Familiar::TryThrow 0063c0a0"); + bool isOrbiting = !isFollower && orbitLayer >= 0 && isExists; + bool isRefollowing = isFollower || variant == TWISTED_BABY; + bool wasDelayed = isDelayed; + if (isOrbiting) RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + if (isRefollowing) RemoveFromFollowers(); + if (wasDelayed) RemoveFromDelayed(); + + player = newPlayer; + if (isOrbiting) RecalculateOrbitOffset(orbitLayer, ORBIT_JOIN); + if (isRefollowing) AddToFollowers(); + if (wasDelayed) AddToDelayed(); } -// 006261f0 -bool Entity_Familiar::HandleCollision(Entity*, bool) +// 0060d780 How many of it the room keeps before spawns overwrite the oldest, or -1 for a familiar never overwritten. +int Entity_Familiar::overwrite_limit() { - reconstruction_missing("Entity_Familiar::HandleCollision 006261f0"); + switch (variant) + { + case BLUE_FLY: + case BLUE_SPIDER: + case BONE_SPUR: return 100; + case BROWN_NUGGET_POOTER: return 50; + case LEPROSY: + case BONE_ORBITAL: + case SWARM_FLY_ORBITAL: return 25; + case DIP: + case MINISAAC: return 10; + case WISP: return 8; + case ITEM_WISP: return 6; + case BLOOD_BABY: return 1; + default: return isNotCountedAsFollower ? 100 : -1; + } } -// 00431be0 -void Entity_Familiar::ai_umbilical_baby(bool) +// 0060d6a0 How often its hit list resets, letting it hit an enemy again: its config's interval, eight frames while +// spinning, two for the Lemegeton wisp that never blocks, never for Gello, and longer ones in a versus match. Locusts, +// Blood Babies and Decap Attack's head stop the game. +int Entity_Familiar::hit_list_interval() { - reconstruction_missing("Entity_Familiar::ai_umbilical_baby 00431be0"); + if (variant == ABYSS_LOCUST || variant == BLOOD_BABY || variant == DECAP_ATTACK) + reconstruction_missing("Entity_Familiar::hit_list_interval 0060d6a0 (this " + "familiar's interval)"); + if (variant == UMBILICAL_BABY) return 0; + + int interval = (int)config->collisionInterval; + if (orbitLayer >= 0 && HasEntityFlags(FLAG_SPIN)) interval = SPIN_HIT_INTERVAL; + if (variant == WISP && subtype == WISP_UNBLOCKING) interval = 2; + if (!familiar_versus()) return interval; + if (variant == LIL_HAUNT) return interval * 2; + if (variant == SWORN_PROTECTOR) return interval * 4; + if (variant == MY_SHADOW) return VERSUS_PUNCHING_INTERVAL; + return interval; } -// 004357e0 -void Entity_Familiar::set_extra_data(void*, void*) -{ - reconstruction_missing("Entity_Familiar::set_extra_data 004357e0"); -} - -// 00436330 -void Entity_Familiar::WispInit() -{ - reconstruction_missing("Entity_Familiar::WispInit 00436330"); -} - -// 00436fd0 -uint32_t Entity_Familiar::wisp_kill() -{ - reconstruction_missing("Entity_Familiar::wisp_kill 00436fd0"); -} - -// 004386f0 -Entity_Tear* Entity_Familiar::fire_wisp_projectile(Vector) -{ - reconstruction_missing("Entity_Familiar::fire_wisp_projectile 004386f0"); -} - -// 0043a5e0 -uint32_t Entity_Familiar::wisp_take_damage(float*, uint32_t*, int*) -{ - reconstruction_missing("Entity_Familiar::wisp_take_damage 0043a5e0"); -} - -// 0043aa90 -void Entity_Familiar::ai_wisp() -{ - reconstruction_missing("Entity_Familiar::ai_wisp 0043aa90"); -} - -// 0043db20 -void Entity_Familiar::ai_mr_me_wisp() -{ - reconstruction_missing("Entity_Familiar::ai_mr_me_wisp 0043db20"); -} - -// 0043e4a0 -void Entity_Familiar::ai_mega_blast_wisp() -{ - reconstruction_missing("Entity_Familiar::ai_mega_blast_wisp 0043e4a0"); -} - -// 0043eb10 -int Entity_Familiar::GetRandomWisp(RNG*) -{ - reconstruction_missing("Entity_Familiar::GetRandomWisp 0043eb10"); -} - -// 005ae490 -void Entity_Familiar::ai_buddy_inbox() -{ - reconstruction_missing("Entity_Familiar::ai_buddy_inbox 005ae490"); -} - -// 0060d180 -KColor* Entity_Familiar::GetPlayerSlot(KColor*, Entity_Player*) -{ - reconstruction_missing("Entity_Familiar::GetPlayerSlot 0060d180"); -} - -// 0060d8e0 +// 0060d8e0 Whether it stops enemy shots: the blocking orbitals and followers, a charging Big Chubby, the wisps and the +// rest by variant. A locust blocks when its item shields, which stops the game. bool Entity_Familiar::CanBlockProjectiles() { - reconstruction_missing("Entity_Familiar::CanBlockProjectiles 0060d8e0"); -} - -// 0060dc40 -float Entity_Familiar::apply_tear_modifiers() -{ - reconstruction_missing("Entity_Familiar::apply_tear_modifiers 0060dc40"); -} - -// 0060ddd0 -void Entity_Familiar::set_locust_config_index(int) -{ - reconstruction_missing("Entity_Familiar::set_locust_config_index 0060ddd0"); -} - -// 00612330 -Entity* Entity_Familiar::get_orbit_parent() -{ - reconstruction_missing("Entity_Familiar::get_orbit_parent 00612330"); -} - -// 00612440 -int Entity_Familiar::RecalculateOrbitOffset(int, bool) -{ - reconstruction_missing("Entity_Familiar::RecalculateOrbitOffset 00612440"); -} - -// 006127b0 -void Entity_Familiar::AddToOrbit(int) -{ - reconstruction_missing("Entity_Familiar::AddToOrbit 006127b0"); -} - -// 00612850 -Vector Entity_Familiar::GetOrbitDistance(int) -{ - reconstruction_missing("Entity_Familiar::GetOrbitDistance 00612850"); -} - -// 00612890 -bool Entity_Familiar::is_detached_from_follow() -{ - reconstruction_missing("Entity_Familiar::is_detached_from_follow 00612890"); -} - -// 00612970 -int Entity_Familiar::GetFollowerPriority() -{ - reconstruction_missing("Entity_Familiar::GetFollowerPriority 00612970"); -} - -// 00612af0 -bool Entity_Familiar::IsLilithBirthrightIncubus() -{ - reconstruction_missing("Entity_Familiar::IsLilithBirthrightIncubus 00612af0"); -} - -// 00612b50 -Entity* Entity_Familiar::get_incubus_umbilical_whip() -{ - reconstruction_missing("Entity_Familiar::get_incubus_umbilical_whip 00612b50"); -} - -// 00612bb0 -void Entity_Familiar::FollowParent() -{ - reconstruction_missing("Entity_Familiar::FollowParent 00612bb0"); -} - -// 00613910 -void Entity_Familiar::FollowPosition(const Vector&) -{ - reconstruction_missing("Entity_Familiar::FollowPosition 00613910"); -} - -// 006139b0 -Vector Entity_Familiar::GetOrbitPosition(const Vector&) -{ - reconstruction_missing("Entity_Familiar::GetOrbitPosition 006139b0"); -} - -// 00613c20 -Entity_Laser* Entity_Familiar::fire_robo_baby_laser(const Vector&) -{ - reconstruction_missing("Entity_Familiar::fire_robo_baby_laser 00613c20"); -} - -// 00613df0 -void Entity_Familiar::PlayFloatAnim(int) -{ - reconstruction_missing("Entity_Familiar::PlayFloatAnim 00613df0"); -} - -// 00613fe0 -void Entity_Familiar::AddToDelayed() -{ - reconstruction_missing("Entity_Familiar::AddToDelayed 00613fe0"); -} - -// 006141e0 -void Entity_Familiar::RemoveFromDelayed() -{ - reconstruction_missing("Entity_Familiar::RemoveFromDelayed 006141e0"); -} - -// 006142e0 -void Entity_Familiar::PlayChargeAnim(int) -{ - reconstruction_missing("Entity_Familiar::PlayChargeAnim 006142e0"); -} - -// 00614500 -void Entity_Familiar::PlayShootAnim(int) -{ - reconstruction_missing("Entity_Familiar::PlayShootAnim 00614500"); -} - -// 00614b10 -void Entity_Familiar::Shoot() -{ - reconstruction_missing("Entity_Familiar::Shoot 00614b10"); -} - -// 00615d80 -void Entity_Familiar::ai_blue_fly() -{ - reconstruction_missing("Entity_Familiar::ai_blue_fly 00615d80"); -} - -// 00616db0 -void Entity_Familiar::ai_walker() -{ - reconstruction_missing("Entity_Familiar::ai_walker 00616db0"); -} - -// 006174c0 -void Entity_Familiar::ai_charger() -{ - reconstruction_missing("Entity_Familiar::ai_charger 006174c0"); -} - -// 00619270 -void Entity_Familiar::ai_auto_shooter() -{ - reconstruction_missing("Entity_Familiar::ai_auto_shooter 00619270"); -} - -// 0061a240 -void Entity_Familiar::ai_blue_babys_only_friend() -{ - reconstruction_missing("Entity_Familiar::ai_blue_babys_only_friend 0061a240"); -} - -// 0061a4e0 -void Entity_Familiar::ai_pickup_sack() -{ - reconstruction_missing("Entity_Familiar::ai_pickup_sack 0061a4e0"); -} - -// 0061b8c0 -void Entity_Familiar::ai_flying_bird() -{ - reconstruction_missing("Entity_Familiar::ai_flying_bird 0061b8c0"); -} - -// 0061bd50 -void Entity_Familiar::ai_daddy_longlegs() -{ - reconstruction_missing("Entity_Familiar::ai_daddy_longlegs 0061bd50"); -} - -// 0061c150 -void Entity_Familiar::ai_orbital_variant_50() -{ - reconstruction_missing("Entity_Familiar::ai_orbital_variant_50 0061c150"); -} - -// 0061d6b0 -void Entity_Familiar::ai_key_full() -{ - reconstruction_missing("Entity_Familiar::ai_key_full 0061d6b0"); -} - -// 0062a8f0 -bool Entity_Familiar::CanPlayerFire() -{ - reconstruction_missing("Entity_Familiar::CanPlayerFire 0062a8f0"); -} - -// 0062a930 -void Entity_Familiar::AddCoins(int) -{ - reconstruction_missing("Entity_Familiar::AddCoins 0062a930"); -} - -// 0062aab0 -void Entity_Familiar::TriggerRoomClear() -{ - reconstruction_missing("Entity_Familiar::TriggerRoomClear 0062aab0"); -} - -// 0062b360 -void Entity_Familiar::level_start() -{ - reconstruction_missing("Entity_Familiar::level_start 0062b360"); -} - -// 0062bb70 -void Entity_Familiar::room_enter() -{ - reconstruction_missing("Entity_Familiar::room_enter 0062bb70"); -} - -// 0062c8d0 -void Entity_Familiar::farting_baby_fart() -{ - reconstruction_missing("Entity_Familiar::farting_baby_fart 0062c8d0"); -} - -// 0062d290 -void Entity_Familiar::mongo_baby_pick_next_mimic() -{ - reconstruction_missing("Entity_Familiar::mongo_baby_pick_next_mimic 0062d290"); -} - -// 0062d7e0 -void Entity_Familiar::RemoveFromFollowers() -{ - reconstruction_missing("Entity_Familiar::RemoveFromFollowers 0062d7e0"); -} - -// 0062db20 -void Entity_Familiar::AddToFollowers() -{ - reconstruction_missing("Entity_Familiar::AddToFollowers 0062db20"); -} - -// 0062e020 -void Entity_Familiar::set_player(Entity_Player*) -{ - reconstruction_missing("Entity_Familiar::set_player 0062e020"); -} - -// 0062e120 -void Entity_Familiar::ai_samsons_chains() -{ - reconstruction_missing("Entity_Familiar::ai_samsons_chains 0062e120"); -} - -// 0062e620 -void Entity_Familiar::update_weapon(bool) -{ - reconstruction_missing("Entity_Familiar::update_weapon 0062e620"); -} - -// 0062ee30 -void Entity_Familiar::ai_lil_gurdy() -{ - reconstruction_missing("Entity_Familiar::ai_lil_gurdy 0062ee30"); -} - -// 00630450 -void Entity_Familiar::store_backup(void*) -{ - reconstruction_missing("Entity_Familiar::store_backup 00630450"); -} - -// 00631050 -void Entity_Familiar::MoveDelayed(int) -{ - reconstruction_missing("Entity_Familiar::MoveDelayed 00631050"); -} - -// 006312f0 -void Entity_Familiar::MoveDiagonally(float) -{ - reconstruction_missing("Entity_Familiar::MoveDiagonally 006312f0"); -} - -// 00631850 -void Entity_Familiar::move_to_parent_offset() -{ - reconstruction_missing("Entity_Familiar::move_to_parent_offset 00631850"); -} - -// 00631b20 -void Entity_Familiar::delirium_morph() -{ - reconstruction_missing("Entity_Familiar::delirium_morph 00631b20"); -} - -// 006322f0 -void Entity_Familiar::init_lil_harbinger_sprite() -{ - reconstruction_missing("Entity_Familiar::init_lil_harbinger_sprite 006322f0"); -} - -// 006324d0 -void Entity_Familiar::render_charge_indicator(const Vector&) -{ - reconstruction_missing("Entity_Familiar::render_charge_indicator 006324d0"); -} - -// 00632820 -void Entity_Familiar::ai_lil_monstro() -{ - reconstruction_missing("Entity_Familiar::ai_lil_monstro 00632820"); -} - -// 00632d90 -void Entity_Familiar::ai_variant_111() -{ - reconstruction_missing("Entity_Familiar::ai_variant_111 00632d90"); -} - -// 00633500 -void Entity_Familiar::update_angry_fly() -{ - reconstruction_missing("Entity_Familiar::update_angry_fly 00633500"); -} - -// 00634000 -bool Entity_Familiar::TryFireTear(Entity_Tear*) -{ - reconstruction_missing("Entity_Familiar::TryFireTear 00634000"); -} - -// 006341a0 -uint8_t Entity_Familiar::apply_baby_bender(Entity_Tear*) -{ - reconstruction_missing("Entity_Familiar::apply_baby_bender 006341a0"); -} - -// 00634260 -Vector Entity_Familiar::UpdateFollowPosition() -{ - reconstruction_missing("Entity_Familiar::UpdateFollowPosition 00634260"); -} - -// 00634a40 -void Entity_Familiar::ResolveOrbitConflict() -{ - reconstruction_missing("Entity_Familiar::ResolveOrbitConflict 00634a40"); -} - -// 00634b10 -void Entity_Familiar::ai_lil_spewer() -{ - reconstruction_missing("Entity_Familiar::ai_lil_spewer 00634b10"); -} - -// 006378c0 -void Entity_Familiar::ai_lil_harbingers() -{ - reconstruction_missing("Entity_Familiar::ai_lil_harbingers 006378c0"); -} - -// 00638c10 -Entity_Laser* Entity_Familiar::FireBrimstone(const Vector&, uint8_t) -{ - reconstruction_missing("Entity_Familiar::FireBrimstone 00638c10"); -} - -// 00639000 -Entity* Entity_Familiar::ThrowDip(int, const Vector&, Entity*) -{ - reconstruction_missing("Entity_Familiar::ThrowDip 00639000"); -} - -// 00639750 -Entity_Tear* Entity_Familiar::FireProjectile(const Vector&, uint8_t) -{ - reconstruction_missing("Entity_Familiar::FireProjectile 00639750"); -} - -// 0063aef0 -Entity_Laser* Entity_Familiar::sprinkler_shoot_laser(float, float) -{ - reconstruction_missing("Entity_Familiar::sprinkler_shoot_laser 0063aef0"); -} - -// 0063b340 -void Entity_Familiar::update_idle_anim_by_size() -{ - reconstruction_missing("Entity_Familiar::update_idle_anim_by_size 0063b340"); -} - -// 0063b8b0 -void Entity_Familiar::RemoveFromPlayer(uint8_t) -{ - reconstruction_missing("Entity_Familiar::RemoveFromPlayer 0063b8b0"); -} - -// 0063c1c0 -void Entity_Familiar::ai_minisaac() -{ - reconstruction_missing("Entity_Familiar::ai_minisaac 0063c1c0"); -} - -// 0063ce20 -void Entity_Familiar::minisaac_fire() -{ - reconstruction_missing("Entity_Familiar::minisaac_fire 0063ce20"); -} - -// 0063dd60 -void Entity_Familiar::minisaac_find_target() -{ - reconstruction_missing("Entity_Familiar::minisaac_find_target 0063dd60"); -} - -// 0063f9f0 -void Entity_Familiar::ai_blood_oath() -{ - reconstruction_missing("Entity_Familiar::ai_blood_oath 0063f9f0"); -} - -// 006402f0 -void Entity_Familiar::paschal_candle_sync_effects() -{ - reconstruction_missing("Entity_Familiar::paschal_candle_sync_effects 006402f0"); -} - -// 00640ca0 -void Entity_Familiar::ai_boiled_baby() -{ - reconstruction_missing("Entity_Familiar::ai_boiled_baby 00640ca0"); -} - -// 006414c0 -void Entity_Familiar::zhl_misfit_006414c0() -{ - reconstruction_missing("Entity_Familiar::zhl_misfit_006414c0 006414c0"); -} - -// 006424d0 -void Entity_Familiar::ai_bird_cage() -{ - reconstruction_missing("Entity_Familiar::ai_bird_cage 006424d0"); -} - -// 006431d0 -void Entity_Familiar::ai_bot_fly() -{ - reconstruction_missing("Entity_Familiar::ai_bot_fly 006431d0"); -} - -// 006437a0 -void Entity_Familiar::ai_stitches() -{ - reconstruction_missing("Entity_Familiar::ai_stitches 006437a0"); -} - -// 006444d0 -Entity* Entity_Familiar::aim_reflected_projectile() -{ - reconstruction_missing("Entity_Familiar::aim_reflected_projectile 006444d0"); -} - -// 00644e80 -void Entity_Familiar::ai_shadow_intruder_damocles(bool) -{ - reconstruction_missing("Entity_Familiar::ai_shadow_intruder_damocles 00644e80"); -} - -// 006470c0 -void* Entity_Familiar::get_item_config_entry() -{ - reconstruction_missing("Entity_Familiar::get_item_config_entry 006470c0"); -} - -// 00647170 -uint8_t Entity_Familiar::abyss_locust_eat() -{ - reconstruction_missing("Entity_Familiar::abyss_locust_eat 00647170"); -} - -// 0064a2d0 -uint8_t Entity_Familiar::break_grid_ahead() -{ - reconstruction_missing("Entity_Familiar::break_grid_ahead 0064a2d0"); -} - -// 0064a830 -void Entity_Familiar::load_config_graphics() -{ - reconstruction_missing("Entity_Familiar::load_config_graphics 0064a830"); -} - -// 0064b6c0 -void Entity_Familiar::render_abyss_locust_sprite(ANM2*, float*) -{ - reconstruction_missing("Entity_Familiar::render_abyss_locust_sprite 0064b6c0"); -} - -// 0064b920 -void Entity_Familiar::siren_charm(Entity*, Entity_Player*) -{ - reconstruction_missing("Entity_Familiar::siren_charm 0064b920"); -} - -// 0064bab0 -void Entity_Familiar::RemoveFromPlayer() -{ - reconstruction_missing("Entity_Familiar::RemoveFromPlayer 0064bab0"); -} - -// 0064ca30 -void Entity_Familiar::UpdateDirtColor(uint8_t) -{ - reconstruction_missing("Entity_Familiar::UpdateDirtColor 0064ca30"); -} - -// 0064d1d0 -void Entity_Familiar::update_star_of_bethlehem_speed(bool) -{ - reconstruction_missing("Entity_Familiar::update_star_of_bethlehem_speed 0064d1d0"); -} - -// 0064e0c0 -void Entity_Familiar::ai_blood_clot(bool) -{ - reconstruction_missing("Entity_Familiar::ai_blood_clot 0064e0c0"); -} - -// 00650220 -void Entity_Familiar::predict_player_movement() -{ - reconstruction_missing("Entity_Familiar::predict_player_movement 00650220"); -} - -// 009615e0 -uint8_t Entity_Familiar::multidimensional_baby_copy_knife(Entity_Knife*, Entity*) -{ - reconstruction_missing("Entity_Familiar::multidimensional_baby_copy_knife 009615e0"); + switch (variant) + { + case SMART_FLY: return subtype == 0; + case HUSHY: return subtype == 1; + case BIG_CHUBBY: + case LIL_PORTAL: return fireCooldown < 0; + case WISP: return subtype != WISP_UNBLOCKING; + case ABYSS_LOCUST: + reconstruction_missing("Entity_Familiar::CanBlockProjectiles 0060d8e0 (a locust's shield)"); + return false; + default: return familiar_listed(BLOCKING_VARIANTS, variant); + } +} + +// 0063c0a0 Thrown by the player: a Dip (once) and the Cube Baby fly off the way it was thrown, the Dip bouncing. +bool Entity_Familiar::TryThrow(const EntityRef&, const Vector& direction, float force) +{ + if (variant == DIP && state != DIP_THROWN) + { + targetPosition = {}; + posOffset.y = THROWN_HEIGHT; + orbitSpeed = -force * THROWN_LIFT; + orbitDistance = vector_scale(direction, DIP_THROWN_SPEED); + state = DIP_THROWN; + velocity = vector_scale(direction, DIP_THROWN_SPEED); + return true; + } + if (variant != CUBE_BABY) return false; + + orbitSpeed = -force * THROWN_LIFT; + velocity = direction; + posOffset.y = THROWN_HEIGHT; + fireCooldown = CUBE_BABY_THROWN_FRAMES; + return true; +} + +// 00630450 Saves what a familiar keeps between rooms and runs: its seeds, variant, counters, formation spot and health +// (a wisp's orbit layer in place of its clears, Blood Puppy's health, the Star of Bethlehem's speed). +void Entity_Familiar::store_backup(FamiliarData* backup) +{ + if (variant == ABYSS_LOCUST) reconstruction_missing("Entity_Familiar::store_backup 00630450 (a locust)"); + + backup->initSeed = initSeed; + backup->dropSeed = dropRNG._seed; + backup->variant = variant; + backup->subtype = subtype; + backup->coins = coins; + backup->hearts = hearts; + backup->keys = keys; + backup->state = state; + backup->roomClearCount = variant == WISP || variant == ITEM_WISP ? orbitLayer : roomClearCount; + backup->formationTargetOffset = formationTargetOffset; + backup->health = health; + if (variant == BLOOD_PUPPY) backup->health = linkedEntity ? linkedEntity->health : 0; + if (variant == STAR_OF_BETHLEHEM) backup->health = orbitSpeed; + backup->isNotCountedAsFollower = isNotCountedAsFollower; + backup->isSubtype55555 = isSubtype55555; } diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 9ab1e85..4c18e24 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -1,18 +1,207 @@ #pragma once -#include "entity.h" #include "anm2.h" +#include "entity.h" #include "path_finder.h" +#include "sfx_manager.h" #include "weapon.h" +#include +#include #include #include -// Construction and destruction (0060d3d0, 0060d200) are the defaults, with the familiar owning its pathfinder. -// Field accessors (004361f0, 00505cf0, 0060d0e0, 0060d100) are the public fields. +struct FamiliarData; + +// Whether RecalculateOrbitOffset spaces a layer with the familiar joining it or leaving it. +enum OrbitChange +{ + ORBIT_LEAVE, + ORBIT_JOIN +}; + +// Whether GetFollowTargetPosition jitters the player's position, as a newly spawned familiar's is. +enum FollowSpot +{ + FOLLOW_EXACT, + FOLLOW_SCATTERED +}; + +// Whether FireProjectile adds the player's motion to the shot, which a shot aimed at a mark skips. +enum FireMode +{ + FIRE_INHERIT_MOTION, + FIRE_EXACT +}; + +// PickEnemyTarget's flags. +enum TargetFlag : uint32_t +{ + TARGET_RETARGET = 1 << 0, + TARGET_NOT_NEAR_PLAYER = 1 << 1, + TARGET_PREFER_HEALTHY = 1 << 2, + TARGET_PREFER_WEAK = 1 << 3, + TARGET_NO_STICKINESS = 1 << 4 +}; + +// The formation slot of a familiar outside any. +constexpr uint8_t FORMATION_NONE = 0xff; + +// A target search (PickEnemyTarget's arguments): how far, how often, how it ranks the enemies, and an optional cone. +struct TargetSearch +{ + Vector coneDirection{}; + float coneAngle = 15; + float range = 0; + int frameInterval = 1; + uint32_t flags = 0; +}; + +// Construction and destruction (0060d3d0, 0060d200) are the defaults, with the familiar owning its pathfinder, and +// set_extra_data (004357e0) is the extra data's reset. +// Field accessors (004361f0, 00505cf0, 0060d0e0, 0060d100, 0060d120, 0060d130) are the public fields. // A familiar (Lua's EntityFamiliar): its player, its place in the following line or an orbit, the consumables it // collects, its weapon, and the extra data some variants keep. struct Entity_Familiar : Entity { + // Lua's FamiliarVariant, the ones the familiar code tells apart. + enum Variant : int + { + BROTHER_BOBBY = 1, + DEMON_BABY = 2, + LITTLE_CHUBBY = 3, + LITTLE_GISH = 4, + LITTLE_STEVEN = 5, + ROBO_BABY = 6, + SISTER_MAGGY = 7, + ABEL = 8, + GHOST_BABY = 9, + HARLEQUIN_BABY = 10, + RAINBOW_BABY = 11, + ISAACS_HEAD = 12, + BLUE_BABY_SOUL = 13, + DEAD_BIRD = 14, + EVES_BIRD_FOOT = 15, + DADDY_LONGLEGS = 16, + PEEPER = 17, + LITTLE_CHAD = 22, + RELIC = 23, + BUM_FRIEND = 24, + HOLY_WATER = 25, + FLY_ORBITAL = 33, + SACRIFICIAL_DAGGER = 35, + DEAD_CAT = 40, + GUPPYS_HAIRBALL = 42, + BLUE_FLY = 43, + CUBE_OF_MEAT_1 = 44, + CUBE_OF_MEAT_2 = 45, + CUBE_OF_MEAT_3 = 46, + CUBE_OF_MEAT_4 = 47, + ISAACS_BODY = 48, + SMART_FLY = 50, + DRY_BABY = 51, + JUICY_SACK = 52, + ROBO_BABY_2 = 53, + ROTTEN_BABY = 54, + MYSTERY_SACK = 57, + BBF = 58, + BOBS_BRAIN = 59, + BEST_BUD = 60, + LIL_BRIMSTONE = 61, + ISAACS_HEART = 62, + LIL_HAUNT = 63, + DARK_BUM = 64, + SISSY_LONGLEGS = 66, + PUNCHING_BAG = 67, + GUILLOTINE = 68, + BALL_OF_BANDAGES_1 = 69, + BALL_OF_BANDAGES_2 = 70, + BALL_OF_BANDAGES_3 = 71, + BALL_OF_BANDAGES_4 = 72, + BLUE_SPIDER = 73, + MONGO_BABY = 74, + SAMSONS_CHAINS = 75, + CAINS_OTHER_EYE = 76, + SCISSORS = 78, + INCUBUS = 80, + FATES_REWARD = 81, + LIL_CHEST = 82, + SWORN_PROTECTOR = 83, + LOST_FLY = 85, + CHARGED_BABY = 86, + LIL_GURDY = 87, + BUMBO = 88, + CENSER = 89, + KEY_BUM = 90, + RUNE_BAG = 91, + SERAPHIM = 92, + GB_BUG = 93, + SPIDER_MOD = 94, + FARTING_BABY = 95, + SUCCUBUS = 96, + LIL_LOKI = 97, + OBSESSED_FAN = 98, + PAPA_FLY = 99, + MILK = 100, + MULTIDIMENSIONAL_BABY = 101, + SUPER_BUM = 102, + TONSIL = 103, + BIG_CHUBBY = 104, + SHADE = 106, + HUSHY = 107, + LIL_MONSTRO = 108, + KING_BABY = 109, + YO_LISTEN = 111, + SPIDER_BABY = 113, + BROWN_NUGGET_POOTER = 115, + BLOODSHOT_EYE = 116, + ANGRY_FLY = 118, + BUDDY_IN_A_BOX = 119, + SPRINKLER = 120, + LEPROSY = 121, + LIL_HARBINGERS = 122, + MYSTERY_EGG = 124, + LIL_SPEWER = 125, + SLIPPED_RIB = 126, + BONE_ORBITAL = 128, + HALLOWED_GROUND = 129, + JAW_BONE = 130, + MY_SHADOW = 131, + INTRUDER = 200, + DIP = 201, + DAMOCLES = 202, + BLOOD_OATH = 203, + WISP = 206, + PEEPER_2 = 207, + BOILED_BABY = 208, + FREEZER_BABY = 209, + BIRD_CAGE = 210, + LOST_SOUL = 211, + LIL_DUMPY = 212, + KNIFE_PIECE_1 = 213, + KNIFE_PIECE_2 = 214, + BOT_FLY = 218, + PASCHAL_CANDLE = 221, + KNIFE_FULL = 223, + BABY_PLUM = 224, + FRUITY_PLUM = 225, + MINISAAC = 228, + SWARM_FLY_ORBITAL = 229, + LIL_ABADDON = 230, + ABYSS_LOCUST = 231, + LIL_PORTAL = 232, + BONE_SPUR = 234, + TWISTED_BABY = 235, + STAR_OF_BETHLEHEM = 236, + ITEM_WISP = 237, + BLOOD_BABY = 238, + CUBE_BABY = 239, + UMBILICAL_BABY = 240, + BLOOD_PUPPY = 241, + VANISHING_TWIN = 242, + DECAP_ATTACK = 243, + FORGOTTEN_BODY = 900 + }; + // The base of the extra data some variants keep (AbyssLocustData, IsaacsBodyData, UmbilicalBabyData). struct ExtraData { @@ -21,6 +210,7 @@ struct Entity_Familiar : Entity ANM2 chargeBarSprite; PathFinder pathfinder{this}; + std::map targetFrames; std::unique_ptr extraData; std::vector hitList; ColorMod dirtColor = COLOR_DEFAULT; @@ -36,6 +226,9 @@ struct Entity_Familiar : Entity float formationAngle = 0; float orbitAngleOffset = 0; float orbitSpeed = 0; + float wispCharge = 1; + float wispDamageMultiplier = 1; + float wispScale = 1; int appearTimer = 0; int chargeLevel = 0; int coins = 0; @@ -45,6 +238,7 @@ struct Entity_Familiar : Entity int hearts = 0; int keys = 0; int lastDirection = 0; + int maxSubtype = 0; int moveDelayNum = 0; int moveDirection = 0; int orbitLayer = 0; @@ -53,6 +247,8 @@ struct Entity_Familiar : Entity int sirenCharmFrames = 0; int state = 0; int wispCollectibleType = 0; + int wispState = 0; + int wispTimer = 0; uint8_t formationMode = 0; bool isDelayed = false; bool isFollower = false; @@ -76,8 +272,12 @@ struct Entity_Familiar : Entity bool TryThrow(const EntityRef& source, const Vector& direction, float force) override; bool HandleCollision(Entity* collider, bool isLow) override; + void variant_init(int initSubtype); + void variant_finish(); + void variant_update(); + bool update_appearing(); + void update_tail(); void ai_umbilical_baby(bool isInterpolated); - static void set_extra_data(void* extraDataPtr, void* extraData); void WispInit(); uint32_t wisp_kill(); Entity_Tear* fire_wisp_projectile(Vector velocity); @@ -90,30 +290,53 @@ struct Entity_Familiar : Entity KColor* GetPlayerSlot(KColor* outColor, Entity_Player* player); bool CanBeDamagedByEnemy(); bool CanBlockProjectiles(); - float apply_tear_modifiers(); + float GetMultiplier(); + int overwrite_limit(); + int hit_list_interval(); void set_locust_config_index(int); Entity* get_orbit_parent(); - int RecalculateOrbitOffset(int layer, bool isAdd); - void AddToOrbit(int orbitLayer); + void RecalculateOrbitOffset(int layer, OrbitChange change); + void AddToOrbit(int layer); void RemoveFromOrbit(); static Vector GetOrbitDistance(int layer); - bool is_detached_from_follow(); + Vector GetOrbitPosition(const Vector& center); + void ResolveOrbitConflict(); + bool is_following(); + bool is_formation_exempt(); + bool is_counted_follower(); int GetFollowerPriority(); bool IsLilithBirthrightIncubus(); Entity* get_incubus_umbilical_whip(); void FollowParent(); void FollowPosition(const Vector& position); - Vector GetOrbitPosition(const Vector& offset); - Entity_Laser* fire_robo_baby_laser(const Vector& direction); - void PlayFloatAnim(int direction); + Vector UpdateFollowPosition(); + Vector GetFollowTargetPosition(FollowSpot spot); + void reset_follow_target(); + void AddToFollowers(); + void RemoveFromFollowers(); void AddToDelayed(); void RemoveFromDelayed(); + void set_player(Entity_Player* newPlayer); + bool TryAimAtMarkedTarget(Vector& aimDirection, int& direction, Vector* targetPosition); + void PickEnemyTarget(const TargetSearch& search); + Entity_Laser* fire_robo_baby_laser(const Vector& direction); + void PlayFloatAnim(int direction); void PlayChargeAnim(int direction); void PlayShootAnim(int direction); + void play_idle_anim(); void Shoot(); + Entity_Tear* FireProjectile(const Vector& aimDirection, FireMode mode); + bool TryFireTear(Entity_Tear* tear); + void shot_owner_convert(Entity* shot); + bool apply_baby_bender(Entity_Tear* tear); + bool apply_baby_bender_tear_params(TearFlags& flags, ColorMod& color, float* height, float* fallingSpeed, + float* range, bool isLaser); + bool CanPlayerFire(); void ai_blue_fly(); void ai_walker(); void ai_charger(); + void charger_dash(); + void charger_start(const Vector& aimDirection, int direction); void ai_auto_shooter(); void ai_blue_babys_only_friend(); void ai_pickup_sack(); @@ -121,41 +344,33 @@ struct Entity_Familiar : Entity void ai_daddy_longlegs(); void ai_orbital_variant_50(); void ai_key_full(); - bool CanPlayerFire(); void AddCoins(int count); void AddHearts(int amount); + void AddKeys(int amount); void TriggerRoomClear(); + void trigger_player_damage(const DamageEvent& hit); void level_start(); void room_enter(); void farting_baby_fart(); void mongo_baby_pick_next_mimic(); - void RemoveFromFollowers(); - void AddToFollowers(); - void set_player(Entity_Player* player); void ai_samsons_chains(); void update_weapon(bool isInterpolated); void ai_lil_gurdy(); - void AddKeys(int amount); - void store_backup(void* backup); + void store_backup(FamiliarData* backup); void MoveDelayed(int numFrames); void MoveDiagonally(float speed); void move_to_parent_offset(); + void predict_player_movement(); void delirium_morph(); void init_lil_harbinger_sprite(); void render_charge_indicator(const Vector& renderPos); void ai_lil_monstro(); void ai_variant_111(); void update_angry_fly(); - bool TryFireTear(Entity_Tear* tear); - uint8_t apply_baby_bender(Entity_Tear* tear); - Vector UpdateFollowPosition(); - void reset_follow_target(); - void ResolveOrbitConflict(); void ai_lil_spewer(); void ai_lil_harbingers(); Entity_Laser* FireBrimstone(const Vector& aimDirection, uint8_t unk); static Entity* ThrowDip(int subType, const Vector& position, Entity* spawner); - Entity_Tear* FireProjectile(const Vector& aimDirection, uint8_t unk); Entity_Laser* sprinkler_shoot_laser(float angle, float distance); void update_idle_anim_by_size(); void RemoveFromPlayer(uint8_t unusedRemoveFamiliar); @@ -181,6 +396,37 @@ struct Entity_Familiar : Entity void UpdateDirtColor(uint8_t immediate); void update_star_of_bethlehem_speed(bool isForce); void ai_blood_clot(bool isPostMove); - void predict_player_movement(); static uint8_t multidimensional_baby_copy_knife(Entity_Knife* knife, Entity* unused); + +private: + bool collision_block(Entity& collider, bool isIgnored); + bool collision_contact(Entity& collider, float damageMultiplier, float damage); + bool solid_check(Entity& collider, bool isIgnored); }; + +// How many of a familiar a player should have (Entity_Player::CheckFamiliar's arguments): the item behind them and the +// generator their spawns draw from, a subtype of -1 counting every subtype. +struct FamiliarCount +{ + ItemConfig_Item* item = nullptr; + RNG* rng = nullptr; + int count = 0; + int subtype = -1; + int variant = 0; +}; + +// Whether a variant is one of a list. +template bool familiar_listed(const List& list, int value) +{ + return std::ranges::find(list, value) != std::ranges::end(list); +} + +std::vector familiar_query(int queryVariant); +bool familiar_versus(); +void familiar_sound_play(int sound, SoundPlay play = {}); +bool familiar_unicorn_active(Entity_Player& owner); +float angle_wrap(float angle); +Vector direction_unit(int direction); +void familiar_check(Entity_Player& player, const FamiliarCount& familiars); +void familiars_evaluate(Entity_Player& player); +int familiar_lullaby_delay(Entity_Familiar& familiar, int fireDelay); diff --git a/src/entity_list.cpp b/src/entity_list.cpp index d5f0a74..9d64584 100644 --- a/src/entity_list.cpp +++ b/src/entity_list.cpp @@ -1,5 +1,6 @@ #include "entity_list.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_npc.h" #include "entity_player.h" #include "entity_projectile.h" @@ -14,12 +15,8 @@ #include constexpr const char* SHADOW_PNG = "gfx/shadow.png"; -constexpr int FAMILIAR_WISP = 206; -constexpr int FAMILIAR_CUBE_BABY = 239; constexpr int BOMB_ROCKET = 19; constexpr int BOMB_ROCKET_GIGA = 20; -constexpr int ENTITY_ULTRA_GREED = 406; -constexpr int ENTITY_BUMBINO = 916; constexpr int KNIFE_MAIN = 0; // The boss bar flashes for this many frames when the bosses' health changes. constexpr int BOSS_BAR_FLASH_FRAMES = 8; @@ -272,7 +269,7 @@ void EntityList::Reset() renderEL.push_back(entity); } for (Entity* entity : updateEL) - if (entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_WISP) wispEL.push_back(entity); + if (entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::WISP) wispEL.push_back(entity); renderCursor = 0; renderMode = RENDER_NULL; @@ -305,7 +302,7 @@ void EntityList::AddEntity(Entity* entity) size_t at = 0; while (at < renderEL.size() && entity->GetRenderZ() > renderEL[at]->GetRenderZ()) at++; renderEL.insert(renderEL.begin() + (long)at, entity); - if (entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_WISP) wispEL.push_back(entity); + if (entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::WISP) wispEL.push_back(entity); } else updateEL.remove(entity); @@ -568,7 +565,7 @@ void EntityList::rebuild_sublists() int type = entity->type; bool isIndexed = true; - if (type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_CUBE_BABY) + if (type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::CUBE_BABY) { partitions[PARTITION_ENEMIES].insert(*entity); partitions[PARTITION_ENEMY_TARGETS].insert(*entity); diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index 9cb803a..e85a4dd 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -1,6 +1,9 @@ #include "entity_npc.h" +#include "boss_death.h" #include "entity_config.h" #include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_pickup.h" #include "entity_player.h" #include "entity_projectile.h" #include "data.h" @@ -9,6 +12,7 @@ #include "log.h" #include "manager.h" #include "npc_ai.h" +#include "npc_basement.h" #include "persistent_game_data.h" #include "platform.h" #include "room.h" @@ -19,21 +23,11 @@ #include #include -constexpr int ENTITY_FLY = 13; -constexpr int ENTITY_POOTER = 14; -constexpr int ENTITY_ATTACKFLY = 18; -constexpr int ENTITY_MULLIGAN = 16; -constexpr int ENTITY_HIVE = 22; -constexpr int ENTITY_SPIDER = 85; constexpr int ENTITY_ETERNAL_FLY = 96; constexpr int ENTITY_FEAR_IMMUNE = 205; -constexpr int ENTITY_DEATHS_HEAD = 212; constexpr int ENTITY_NO_DECOY_TYPE = 213; -constexpr int ENTITY_COLLISION_SPAWNER_SPECIAL = 873; -constexpr int ENTITY_BIG_HORN = 411; constexpr int ENTITY_MOMS_HEART_PLAYER_PICK = 53; constexpr int ENTITY_DEATH_REWARD_EXEMPT = 885; -constexpr int ENTITY_ROTGUT = 911; constexpr int ENTITY_UNREACHABLE_EXEMPT = 886; constexpr int ENTITY_FLICKER_TYPE = 252; constexpr int ENTITY_DEATH_SPARK_TYPE = 882; @@ -56,11 +50,7 @@ constexpr int DEATH_HEAD_LAYER_TYPE = 405; constexpr int DEATH_NO_BURST_FIRST = 74; constexpr int DEATH_NO_BURST_LAST = 76; constexpr int MULLIGAN_VARIANT_FLEEING = 2; -constexpr int FAMILIAR_BLUE_FLY = 43; constexpr int CHALLENGE_KILL_CHARGE = 33; -constexpr int COLLECTIBLE_SKATOLE_ID = 9; -constexpr int COLLECTIBLE_BURSTING_SACK_ID = 377; -constexpr int COLLECTIBLE_E_COLI_ID = 236; constexpr int COLLECTIBLE_LIL_PORTAL_ID = 661; constexpr std::string_view BIG_HORN_SPIT_EVENT = "Item"; constexpr std::string_view DIRT_LAYER = "dirt"; @@ -71,7 +61,6 @@ constexpr int DIRT_SAMPLE_FRAMES = 15; constexpr float DIRT_GREEN = 0.9f; constexpr float DIRT_LERP = 0.1f; constexpr int MORPH_COLOR_PRIORITY = -1000; -constexpr int COLOR_PRIORITY_DEFAULT = 255; constexpr ColorMod COLOR_INVISIBLE = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int UNREACHABLE_CHECK_FRAMES = 60; constexpr int UNREACHABLE_GRACE_FRAMES = 900; @@ -89,10 +78,6 @@ constexpr int FEAR_RETARGET_RANGE = 15; constexpr int FEAR_RETARGET_MIN = 5; constexpr float MOVEMENT_DEADZONE = 0.1f; constexpr float ATTACK_PREDICT_FRAMES = 5; -constexpr int LINE_CHECK_PROJECTILE = 3; -constexpr int LINE_MODE_GROUND = 0; -constexpr int LINE_MODE_PROJECTILE = 3; -constexpr float LINE_STEP = 10; constexpr int LINE_BLOCKED_MAX = 8; // The corners of the band a line check samples around each step. struct LineCorner @@ -104,8 +89,6 @@ constexpr std::array LINE_CORNERS = {{{-5, -5}, {-5, 5}, {5, 5}, constexpr int GRID_PATH_PIT = 3000; constexpr uint32_t GRID_PATH_BAND = 1000; constexpr int STAGE_BEAST_DUNGEON = 35; -constexpr int LINE_CHECK_THRESHOLD = 999; -constexpr float KNOCKBACK_IMPACT_SPEED = 6; constexpr float SHIELD_SECOND = 30; constexpr float SHIELD_BASE = 0.09f; constexpr float SHIELD_FALLOFF = 0.18f; @@ -115,66 +98,27 @@ constexpr int SOUND_POOP_DEATH = 237; constexpr float POOP_DEATH_VOLUME = 0.9f; constexpr uint32_t DEBUG_HEALTH_VALUES = 1 << 6; constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; -constexpr uint64_t PROJECTILE_ANY_HEIGHT_ENTITY_HIT = 1ull << 17; // The burst effects a dead NPC leaves besides blood (Lua's EffectVariant). enum DeathBurst : int { - EFFECT_SPIDER_EXPLOSION = 38, EFFECT_POOP_EXPLOSION = 43, EFFECT_BURST_810 = 130, EFFECT_BURST_853 = 131, EFFECT_BURST_818 = 145 }; -// Lua's DamageFlag bits the NPC code reads beyond entity.h's. -enum NpcDamageFlag : uint64_t -{ - DAMAGE_ACID = 1ull << 4, - DAMAGE_INVINCIBLE = 1ull << 13, - DAMAGE_SPAWN_FLY = 1ull << 14, - DAMAGE_SPAWN_BLACK_HEART = 1ull << 23, - DAMAGE_SPAWN_RED_HEART = 1ull << 26, - DAMAGE_SPAWN_COIN = 1ull << 27, - DAMAGE_IGNORE_ARMOR = 1ull << 30, - DAMAGE_SPAWN_CARD = 1ull << 31, - DAMAGE_SPAWN_RUNE = 1ull << 32 -}; -constexpr int ENTITY_SUCKER = 61; constexpr int ENTITY_SIREN_HELPER = 966; -constexpr int ENTITY_BABY_PLUM = 908; constexpr int ENTITY_EXORCIST = 832; -constexpr int ENTITY_ISAAC_BOSS = 102; -constexpr int ENTITY_HORNFEL = 906; -constexpr int ENTITY_GIDEON = 907; constexpr int ENTITY_SHADOW_CHARGER = 23; constexpr int ENTITY_ULTRA_GREED_DOOR = 889; -constexpr int ENTITY_MONSTRO = 45; -constexpr int ENTITY_GURDY_JR = 78; constexpr int SUCKER_VARIANT_BULB = 5; -constexpr int FAMILIAR_PUNCHING_BAG = 67; constexpr int SHADOW_CHARGER_SUBTYPE = 1; constexpr int TYPE_NO_TICK_A = 274; constexpr int TYPE_NO_TICK_B = 275; -// The effects the NPC code spawns (Lua's EffectVariant). -enum NpcEffect : int -{ - EFFECT_BLOOD_EXPLOSION = 2, - EFFECT_FLY_EXPLOSION = 3, - EFFECT_BLOOD_SPLAT = 7, - EFFECT_POOF01 = 15, - EFFECT_POOF02 = 16, - EFFECT_TARGET = 19, - EFFECT_HEART = 49, - EFFECT_PLAYER_CREEP_GREEN = 53, - EFFECT_WATER_RIPPLE = 99 -}; - constexpr int ENTITY_KEY_TEAR_A = 43; constexpr int ENTITY_KEY_TEAR_B = 44; -constexpr int PICKUP_COIN = 20; -constexpr int COIN_PENNY = 1; // The items and seeds whose effects the NPC update reads, by Lua id. constexpr int COLLECTIBLE_HOURGLASS_ID = 66; @@ -421,7 +365,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool { for (Entity* decoy : g_game->room->entityList.mainEL) { - if (decoy->type != ENTITY_FAMILIAR || decoy->variant != FAMILIAR_PUNCHING_BAG) continue; + if (decoy->type != ENTITY_FAMILIAR || decoy->variant != Entity_Familiar::PUNCHING_BAG) continue; float distance = vector_length_squared(vector_sub(decoy->pos, position)); if (distance >= best) continue; best = distance; @@ -488,11 +432,12 @@ static int line_cell_collision(Room& room, int column, int row) } // 007f0df0 Whether a line from start to end is clear, walked in steps of 10: mode 0 checks a 10 wide band for grid -// collision and for more than 8 cells walked past their grid path threshold, mode 3 the same band for shots (which -// fly over pits). The other modes, crushable rocks and the stop position are left to come. +// collision and for more than 8 cells walked past their grid path threshold, mode 1 the same on the line's own cells, +// mode 3 the band for shots (which fly over pits). The other modes, crushable rocks and the stop position are left +// to come. bool room_check_line(const Vector& start, const Vector& end, int mode, int gridPathThreshold) { - if (mode != LINE_MODE_GROUND && mode != LINE_MODE_PROJECTILE) + if (mode != LINE_MODE_GROUND && mode != LINE_MODE_CELL && mode != LINE_MODE_PROJECTILE) reconstruction_missing("Room::CheckLine 007f0df0: the single cell modes"); Room& room = *g_game->room; @@ -515,6 +460,16 @@ bool room_check_line(const Vector& start, const Vector& end, int mode, int gridP for (float walked = 0; walked < length; walked += LINE_STEP) { at = vector_sub(at, step); + if (mode == LINE_MODE_CELL) + { + int column = cellOf(at.x, GRID_CELL); + int row = cellOf(at.y, GRID_TOP); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cellIndex = isInside ? row * room.gridWidth + column : -1; + if (room.GetGridCollision(cellIndex) != COLLISION_NONE) return false; + if (cellIndex != startIndex && cellIndex >= 0 && room.GetGridPath(cellIndex) > gridPathThreshold) blocked++; + continue; + } for (const LineCorner& corner : LINE_CORNERS) { int column = cellOf(at.x + corner.x, GRID_CELL); @@ -611,7 +566,7 @@ void Entity_NPC::Init(int entityType, int entityVariant, int entitySubType, uint hitList.clear(); secondaryHitList.clear(); pathfinder.Reset(); - if (isBoss) reconstruction_missing("Entity_NPC::Init 006b8b20: the room's boss count (Room+0x7224)"); + if (isBoss) g_game->room->bossesRemaining++; totalDamageTaken = 0; lua_engine_get().PostNPCInit(this); } @@ -646,12 +601,12 @@ void Entity_NPC::boss_color_roll() RoomDescriptor* descriptor = game.room->descriptor; RNG rng = {descriptor ? descriptor->spawnSeed : 0, 1, 11, 16}; if (rng.RandomFloat() < boss_color_chance_get()) subtype = (int)rng.RandomInt(colors) + 1; - if (config->id == ENTITY_MONSTRO && subtype == 2 && game.challenge == CHALLENGE_BEANS) subtype = 0; + if (config->id == ENTITY_MOM && subtype == 2 && game.challenge == CHALLENGE_BEANS) subtype = 0; } if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) { - if (config->id == ENTITY_MONSTRO) subtype = 3; - else if (config->id == ENTITY_GURDY_JR) subtype = 1; + if (config->id == ENTITY_MOM) subtype = 3; + else if (config->id == ENTITY_MOMS_HEART) subtype = 1; } if (subtype == 0 || subtype > colors) return; @@ -805,11 +760,11 @@ void Entity_NPC::UpdateDirtColor(bool isImmediate) { if (isImmediate || IsFrame(DIRT_SAMPLE_FRAMES, (int)index)) { - if (!isChampion || championColorIdx != CHAMPION_GREEN) - reconstruction_missing("Entity_NPC::UpdateDirtColor 006c04b0: Room::GetFloorColorAt"); - dirtColor._tint[0] = 0; - dirtColor._tint[1] = DIRT_GREEN; - dirtColor._tint[2] = 0; + KColor floor = kcolor_rgba(0, DIRT_GREEN / 2, 0, 1); + if (!isChampion || championColorIdx != CHAMPION_GREEN) floor = room_floor_color_get(*g_game->room, pos, size); + dirtColor._tint[0] = floor._red * 2; + dirtColor._tint[1] = floor._green * 2; + dirtColor._tint[2] = floor._blue * 2; dirtColor._tint[3] = 1; } @@ -927,13 +882,11 @@ 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}}; @@ -953,7 +906,7 @@ constexpr ColorMod PULLING_RED_COLOR = {{1, 0.2f, 0.2f, 1}, {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) +ColorMod champion_sprite_color_get(int championColor) { const ChampionLook& look = CHAMPION_LOOKS[championColor]; if (look.sheetColor._tint[3] <= 0) return look.spriteColor; @@ -1519,8 +1472,7 @@ void Entity_NPC::death_animation_update() if (std::ranges::find(DEATH_EVENT_TYPES, type) != DEATH_EVENT_TYPES.end()) reconstruction_missing("Entity_NPC::Update 006c4b30: a boss's death animation events"); - if (sprite.GetNullFrame("BloodGuide")) - reconstruction_missing("Entity_NPC::Update 006c4b30: the blood guided gibs of a death animation"); + if (const NullFrame* bloodGuide = sprite.GetNullFrame("BloodGuide")) npc_blood_guide_update(*this, *bloodGuide); if (type == ENTITY_HUSH && sprite.IsEventTriggered("ash")) reconstruction_missing("Entity_NPC::Update 006c4b30: the ash a boss leaves"); if (sprite.IsFinished() && isExists) trigger_kill_item_effects(); @@ -1566,7 +1518,7 @@ void Entity_NPC::decoy_update() else if (decoyTargetTimer < -DECOY_TIMER_MAX) decoyTargetTimer = 0; Entity* playerTarget = GetPlayerTarget(); - if (playerTarget->type == ENTITY_FAMILIAR && playerTarget->variant == FAMILIAR_PUNCHING_BAG) decoyTargetTimer++; + if (playerTarget->type == ENTITY_FAMILIAR && playerTarget->variant == Entity_Familiar::PUNCHING_BAG) decoyTargetTimer++; else if (decoyTargetTimer != 0) decoyTargetTimer--; } @@ -1821,7 +1773,7 @@ void Entity_NPC::ripple_spawn() if (!g_game->room->HasWater() || !IsFrame(RIPPLE_FRAMES, (int)index) || entityCollisionClass == ENTCOLL_NONE) return; - Entity* ripple = spawn_at(ENTITY_EFFECT, EFFECT_WATER_RIPPLE, 0, vector_add(pos, velocity), this); + Entity* ripple = spawn_at(ENTITY_EFFECT, EFFECT_WATER_SPLASH, 0, vector_add(pos, velocity), this); float rippleScale = size * RIPPLE_SCALE * scale; ripple->sprite.scale = vector_make(rippleScale, rippleScale); ripple->renderDepthOffset = RIPPLE_DEPTH; @@ -2011,109 +1963,6 @@ float Entity_NPC::compute_speed_multiplier() return speed; } -// The NPC types whose collisions the generic rules below do not cover: bosses, segmented and special enemies. -constexpr std::array COLLISION_SPECIAL_TYPES = { - 17, 19, 21, 23, 25, 28, 29, 30, 31, 32, 33, 35, 36, 39, 40, 41, 44, 55, 61, 62, 63, - 66, 89, 99, 206, 207, 212, 213, 216, 218, 222, 237, 239, 243, 245, 251, 256, 260, 261, 265, 274, 281, - 289, 291, 292, 293, 295, 296, 308, 401, 402, 404, 406, 407, 410, 412, 802, 808, 810, 815, 818, 819, 822, - 853, 866, 868, 873, 877, 878, 881, 889, 893, 903, 909, 910, 912, 915, 918, 919, 951, 964, 965}; -constexpr std::array COLLISION_SPECIAL_COLLIDERS = {21, 23, 28, 31, 35, 40, 55, 62, 89, - 212, 218, 239, 243, 260, 274, 281, 293, 918}; -constexpr int ENTITY_COLLISION_IGNORED = 291; -constexpr float SPAWN_GRACE_FRAMES = 10; - -// 006cd410 What it does on touching another entity, and whether that contact is ignored: it hurts a player it -// touches (but for Skatole's flies and Bursting Sack's spiders), a shrunk enemy is squished, its friends and -// shots pass, and enemies just spawned in a challenge or ambush do not touch yet. -bool Entity_NPC::HandleCollision(Entity* collider, bool isLow) -{ - LuaResult lua = static_cast(g_luaEngine)->PreNPCCollision(this, collider, isLow); - if (lua == LUA_RESULT_TRUE) return true; - if (lua == LUA_RESULT_FALSE) return false; - - bool isSpecial = - std::ranges::find(COLLISION_SPECIAL_TYPES, type) != COLLISION_SPECIAL_TYPES.end() || - std::ranges::find(COLLISION_SPECIAL_COLLIDERS, collider->type) != COLLISION_SPECIAL_COLLIDERS.end() || - minecart || spawnerType == ENTITY_COLLISION_SPAWNER_SPECIAL; - if (isSpecial) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a special enemy's contact"); - - bool isIgnored = true; - bool isMagnetized = HasEntityFlags(FLAG_MAGNETIZED) || collider->HasEntityFlags(FLAG_MAGNETIZED); - if (Entity::is_enemy_type(collider->type) && isMagnetized && - collider->GetStatusEffectTarget() != GetStatusEffectTarget()) - isIgnored = false; - - if (aiCallFlags & AI_CALL_COLLISION) - { - collisionEntity = collider; - isCollisionIsLow = isLow; - collisionResult = -1; - ai_call(AI_PHASE_COLLISION); - if (collisionResult > 0) return false; - if (collisionResult == 0) return isIgnored; - } - - if (HasEntityFlags(FLAG_SHRINK) && collider->type == ENTITY_PLAYER && !IsBoss()) - { - Kill(EntityRef()); - return isIgnored; - } - if (IsFriendly() && IsDamageSourceFriendly(EntityRef(collider))) - { - if (collider->type == ENTITY_PLAYER || collider->type == ENTITY_FAMILIAR) return isIgnored; - if (collider->IsEnemy() && collider->IsFriendly()) return isIgnored; - } - if (!isLow && collider->type == ENTITY_PROJECTILE) return isIgnored; - - Room& room = *g_game->room; - bool isGraceRoom = room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH || - (g_game->IsGreedMode() && room.roomType == ROOM_DEFAULT) || HasEntityFlags(FLAG_AMBUSH); - if (isGraceRoom && (state == NPC_STATE_APPEAR || g_game->frameCount - spawnFrame < SPAWN_GRACE_FRAMES)) - return isIgnored; - if (collider->type == ENTITY_COLLISION_IGNORED) return isIgnored; - - if (!isLow) - { - if (collider->type == ENTITY_PLAYER) player_contact(*static_cast(collider)); - else if (collider->type == ENTITY_FAMILIAR) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: an enemy hurting a familiar"); - } - enemy_contact(*collider); - if (HasEntityFlags(FLAG_KNOCKED_BACK) && vector_length(knockbackDirection) > KNOCKBACK_IMPACT_SPEED) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a knocked back enemy's impact"); - return false; -} - -// Part of 006cd410: touching a player hurts it by the collision damage, unless Skatole spares flies or Bursting -// Sack spiders. E. Coli turns the enemy to poop and a kill-on-touch enemy dies. -void Entity_NPC::player_contact(Entity_Player& player) -{ - PlayerManager& players = g_game->playerManager; - bool isSpared = ((config->tags & ENTITY_TAG_FLY) && players.AnyoneHasCollectible(COLLECTIBLE_SKATOLE_ID)) || - ((config->tags & ENTITY_TAG_SPIDER) && players.AnyoneHasCollectible(COLLECTIBLE_BURSTING_SACK_ID)); - if (!isSpared && collisionDamage > 0) - { - bool isHurt = player.TakeDamage(collisionDamage, 0, EntityRef(this), 0); - if (isHurt && isChampion && championColorIdx == CHAMPION_ORANGE && player.numCoins > 0) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: the orange champion's stolen coins"); - } - if (player.HasCollectible(COLLECTIBLE_E_COLI_ID)) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: E. Coli's poop"); - if (isKillOnTouch) Kill(EntityRef()); -} - -// Part of 006cd410: an active enemy meets another: a charmed one (or one targeting it) bumps it for damage once per -// hit list. -void Entity_NPC::enemy_contact(Entity& other) -{ - if (!other.IsEnemy() || !IsActiveEnemy(DEAD_EXCLUDED) || !other.IsActiveEnemy(DEAD_EXCLUDED)) return; - - bool isSameSide = HasEntityFlags(FLAG_CHARM) == other.HasEntityFlags(FLAG_CHARM); - bool isTargeted = target.get() == &other || forcedTarget.get() == &other; - if ((isSameSide && !isTargeted) || collisionDamage <= 0 || EntityList::HitListContains(hitList, other)) return; - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a charmed enemy hurting another"); -} - // 006d60a0 Takes a hit as any entity (Entity::TakeDamage) and lets the items that react to it act: a player's hit // ends Pacifist, Betrayal turns it on its attacker, the pulsing champion spawns its flies, and a hit taken spawns // a blue fly for a hit that spawns one, marks a player's kill for Jar of Flies, and triggers the attacker's @@ -2130,7 +1979,7 @@ bool Entity_NPC::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: Betrayal"); if (players.FirstCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES_ID, LAZARUS_SHARE_CHECK)) { - bool isBlueFly = source.type == ENTITY_FAMILIAR && source.variant == FAMILIAR_BLUE_FLY; + bool isBlueFly = source.type == ENTITY_FAMILIAR && source.variant == Entity_Familiar::BLUE_FLY; bool isPlayerKill = source.type == ENTITY_PLAYER || (source.spawnerType == ENTITY_PLAYER && !isBlueFly) || (damageFlags & ((uint64_t)DAMAGE_ACID | DAMAGE_POISON_BURN)) || source.type == ENTITY_EFFECT; @@ -2362,7 +2211,7 @@ bool Entity_NPC::IsTargetInAttackRange(float range, int frameInterval, bool isPr isPredictVelocity ? vector_add(other->pos, vector_scale(other->velocity, ATTACK_PREDICT_FRAMES)) : other->pos; if (frameInterval != 0 && !IsFrame(frameInterval, (int)index)) return false; if (vector_length_squared(vector_sub(aim, pos)) >= range * range) return false; - return room_check_line(pos, other->pos, LINE_CHECK_PROJECTILE, LINE_CHECK_THRESHOLD) || + return room_check_line(pos, other->pos, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD) || championColorIdx == CHAMPION_TRANSPARENT; } @@ -2551,15 +2400,13 @@ void Entity_NPC::projectile_params_apply(Entity_Projectile& projectile, const Pr projectile.renderDepthOffset = params.depthOffset - params.positionOffset.y; if (projectile.height < PROJECTILE_HEIGHT_LOW && !(projectile.projectileFlags & PROJECTILE_ANY_HEIGHT_ENTITY_HIT)) projectile.entityCollisionClass = ENTCOLL_NONE; - if (params.unknownA0 != 0) - reconstruction_missing("Entity_NPC::FireProjectiles 006cb2e0: the projectile field at 0x470"); + projectile.motionHook = params.motionHook; } // 006cb2a0 Hands a fired shot its shooter's champion color, scale and flags (Entity_Projectile::apply_spawn_flags). -void Entity_NPC::fire_projectile_from_params(Entity_Projectile*) +void Entity_NPC::fire_projectile_from_params(Entity_Projectile* projectile) { - reconstruction_missing( - "Entity_NPC::fire_projectile_from_params 006cb2a0: Entity_Projectile::apply_spawn_flags 006cb010"); + projectile->apply_spawn_flags({this, flags, scale, isChampion ? championColorIdx : -1}); } // The NPC types with their own interpolation or drawing, which the generic steps below do not cover. @@ -2715,8 +2562,8 @@ void Entity_NPC::update_damage_history() // rewards (sticky spiders, black hearts), Jar of Flies' count, its removal, the on-kill items and its record. void Entity_NPC::trigger_kill_item_effects() { - if (isBoss) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: Room::TriggerBossDeath"); - if (isChampion) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: NpcHelper::ChampionDrop"); + if (isBoss) g_game->room->TriggerBossDeath(*this); + else if (isChampion) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: NpcHelper::ChampionDrop"); if (type == ENTITY_ROTGUT && variant == 1) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: Rotgut's death"); if (HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) @@ -2991,12 +2838,6 @@ void Entity_NPC::KillUnique() reconstruction_missing("Entity_NPC::KillUnique 006be760"); } -// 006c1ac0 -void* Entity_NPC::shopkeeper_get_loot(void*, bool) -{ - reconstruction_missing("Entity_NPC::shopkeeper_get_loot 006c1ac0"); -} - // 006c2750 Entity_NPC* Entity_NPC::ThrowSpider(const Vector&, Entity*, Vector, bool, float) { @@ -3039,12 +2880,6 @@ bool Entity_NPC::CanReroll() reconstruction_missing("Entity_NPC::CanReroll 006d4db0"); } -// 006d7520 -void Entity_NPC::update_blood_guide_gibs(float*) -{ - reconstruction_missing("Entity_NPC::update_blood_guide_gibs 006d7520"); -} - // 006d88b0 void Entity_NPC::TransferControl(Entity_NPC*) { diff --git a/src/entity_npc.h b/src/entity_npc.h index 676af2f..b228238 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -2,6 +2,7 @@ #include "entity.h" #include "anm2.h" +#include "entity_projectile.h" #include "path_finder.h" #include #include @@ -97,11 +98,23 @@ enum ChampionColor : int CHAMPION_COUNT = 26 }; +// Mask of Infamy's hit color, and Singe's ball variant. +constexpr ColorMod INFAMY_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {64 / 255.0f, 64 / 255.0f, 128 / 255.0f}}; +constexpr int SINGE_BALL = 1; + +// How far apart a line check samples. +constexpr float LINE_STEP = 10; + +// The Sucker's Bulb and Bloodfly variants. +constexpr int SUCKER_BULB = 5; +constexpr int SUCKER_BLOODFLY = 7; + // Construction (0043ef30) is the default, but for the circle angle it draws at random. // How FireProjectiles shoots (Lua's ProjectileParams): the shots' variant, look, fall, homing and change, and the // spread they leave in. struct ProjectileParams { + ProjectileHook motionHook = nullptr; ColorMod color = COLOR_DEFAULT; Vector fireDirectionLimit{}; Vector positionOffset{}; @@ -121,7 +134,6 @@ struct ProjectileParams float homingStrength = 1; float scale = 1; float spread = 1; - float unknownA0 = 0; float velocityMulti = 1; int changeTimeout = 30; int variant = 0; @@ -277,7 +289,7 @@ struct Entity_NPC : Entity void update_physics(); void apply_velocity(char isInterpolated); void update_move_direction_anim(); - void update_blood_guide_gibs(float* nullFrame); + void update_blood_guide_gibs(const NullFrame& guide); void spawn_damage_numbers(); void update_damage_history(); void status_overlay_render(const Vector& offset); @@ -303,8 +315,6 @@ struct Entity_NPC : Entity static Entity_NPC* ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig, float yOffset); - void player_contact(Entity_Player& player); - void enemy_contact(Entity& other); void PlayDeathEffects(); int death_burst_get(); void trigger_kill_item_effects(); @@ -344,7 +354,6 @@ struct Entity_NPC : Entity void RenderSegmentLink(const Vector& offset, bool isShadow); void CreateBling(); void CreateGoldParticles(uint32_t count); - void* shopkeeper_get_loot(void* outLoot, bool isShouldAdvance); void* fireplace_get_loot(void* outLoot, bool isShouldAdvance); void on_player_damaged(); static int FindTargetPit(const Vector& pos1, const Vector& pos2, uint32_t pitIndex); @@ -356,6 +365,16 @@ struct Entity_NPC : Entity extern bool g_isChampionRollSkipped; +// Room::CheckLine's modes: a 10 wide band for walkers, the line's own cells, and the band for shots (over pits). +// A threshold of 999 lets any grid path pass. +enum LineCheckMode : int +{ + LINE_MODE_GROUND = 0, + LINE_MODE_CELL = 1, + LINE_MODE_PROJECTILE = 3 +}; +constexpr int LINE_CHECK_THRESHOLD = 999; + // Game's, Room's and PlayerManager's queries the enemies need, until those classes carry them. Entity_Player* game_nearest_player(const Vector& position); bool game_is_enemy_erased(Entity& entity); @@ -365,4 +384,5 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool void game_shake_screen(int timeout); bool game_is_hard_mode(); uint32_t room_grid_collision_at(const Vector& position); +ColorMod champion_sprite_color_get(int championColor); bool room_check_line(const Vector& start, const Vector& end, int mode, int gridPathThreshold); diff --git a/src/entity_npc_room.cpp b/src/entity_npc_room.cpp index cf5cf8e..5ab08b5 100644 --- a/src/entity_npc_room.cpp +++ b/src/entity_npc_room.cpp @@ -1,3 +1,4 @@ +#include "entity_effect.h" #include "entity_npc.h" #include "entity_player.h" #include "game.h" @@ -6,8 +7,6 @@ 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. diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 1cae137..4448126 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -1,4 +1,5 @@ #include "entity_pickup.h" +#include "active_items.h" #include "entity_config.h" #include "entity_effect.h" #include "entity_familiar.h" @@ -37,16 +38,6 @@ enum HeartSubType : int HEART_SCARED = 9, HEART_BLENDED = 10 }; -enum CoinSubType : int -{ - COIN_PENNY = 1, - COIN_NICKEL, - COIN_DIME, - COIN_DOUBLEPACK, - COIN_LUCKYPENNY, - COIN_STICKYNICKEL, - COIN_GOLDEN -}; enum KeySubType : int { KEY_NORMAL = 1, @@ -69,17 +60,9 @@ enum BombSubType : int constexpr int COLLECTIBLE_MAGNETO = 53; constexpr int COLLECTIBLE_HUMBLEING_BUNDLE = 203; constexpr int COLLECTIBLE_BOGO_BOMBS = 250; -constexpr int COLLECTIBLE_STARTER_DECK = 251; -constexpr int COLLECTIBLE_LITTLE_BAGGY = 252; -constexpr int COLLECTIBLE_THE_JAR = 290; constexpr int COLLECTIBLE_MAGGYS_BOW = 312; -constexpr int COLLECTIBLE_PAY_TO_PLAY = 380; constexpr int COLLECTIBLE_SACK_HEAD = 424; constexpr int COLLECTIBLE_GUPPYS_EYE = 665; -constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; -constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; -constexpr int COLLECTIBLE_KNIFE_PIECE_2 = 627; -constexpr int COLLECTIBLE_MOMS_SHOVEL = 668; constexpr int COLLECTIBLE_THE_POLAROID = 327; constexpr int COLLECTIBLE_THE_NEGATIVE = 328; constexpr int STAGE_VOID = 12; @@ -88,23 +71,17 @@ constexpr int OPTIONS_ITEM_TIMEOUT = 4; constexpr int TRINKET_BROKEN_MAGNET = 6; constexpr int TRINKET_BLACK_LIPSTICK = 17; constexpr int TRINKET_BIBLE_TRACT = 18; -constexpr int TRINKET_DAEMONS_TAIL = 22; constexpr int TRINKET_MOMS_PEARL = 38; constexpr int TRINKET_BLOODY_PENNY = 49; constexpr int TRINKET_BURNT_PENNY = 50; constexpr int TRINKET_FLAT_PENNY = 51; constexpr int TRINKET_COUNTERFEIT_PENNY = 52; -constexpr int TRINKET_LEFT_HAND = 61; constexpr int TRINKET_SUPER_MAGNET = 68; -constexpr int TRINKET_WATCH_BATTERY = 72; -constexpr int TRINKET_RIB_OF_GREED = 84; constexpr int TRINKET_MOMS_LOCKET = 87; constexpr int TRINKET_ROTTEN_PENNY = 126; constexpr int TRINKET_BLESSED_PENNY = 131; constexpr int TRINKET_APPLE_OF_SODOM = 140; constexpr int TRINKET_CHARGED_PENNY = 147; -constexpr int TRINKET_FLAT_FILE = 151; -constexpr int TRINKET_GILDED_KEY = 159; constexpr int TRINKET_NUH_UH = 165; constexpr int TRINKET_CURSED_PENNY = 172; constexpr int COLLECTIBLE_MITRE = 173; @@ -132,54 +109,37 @@ constexpr int ACHIEVEMENT_HAUNTED_CHEST = 611; constexpr int ACHIEVEMENT_GOLDEN_PENNY = 613; constexpr int ACHIEVEMENT_GOLDEN_BATTERY = 615; constexpr int STAGE_HOME = 35; -constexpr int GAME_STATE_HEART_BOMB_COIN_PICKED = 41; // The other entities and effects pickups spawn, meet and are saved with. -constexpr int ENTITY_PITFALL = 291; -constexpr int ENTITY_ULTRA_GREED = 406; constexpr int ENTITY_POLTY = 816; -constexpr int ENTITY_GIDEON = 907; -constexpr int ENTITY_BUMBINO = 916; constexpr int FAMILIAR_BUM_FRIEND = 24; constexpr int FAMILIAR_DARK_BUM = 64; constexpr int FAMILIAR_BUMBO = 88; constexpr int FAMILIAR_KEY_BUM = 90; constexpr int FAMILIAR_SUPER_BUM = 102; -constexpr int FAMILIAR_ABYSS_LOCUST = 231; -constexpr int FAMILIAR_LIL_PORTAL = 232; constexpr int FIREPLACE_VARIANT_COUNT = 10; constexpr int MINECART_UNSAVED_VARIANT = 10; constexpr int BOMB_THROWABLE = 13; constexpr int BOMB_ROCKET = 19; constexpr int BOMB_ROCKET_GIGA = 20; -constexpr int EFFECT_SMOKE_CLOUD = 141; -constexpr int EFFECT_PORTAL_TELEPORT = 161; -constexpr int EFFECT_TALL_LADDER = 156; constexpr uint32_t PORTAL_SAVED_SUBTYPE_MIN = 899; // The effects a room keeps when it or no spawner placed them (tiny bugs and flies, wall bugs, worms, wisps, beetles, // butterflies, tadpoles, lil ghosts), and the ones it always keeps (carpet, dice floor, heaven light, dirt patch, // spawner, fissure spawner). constexpr std::initializer_list SAVED_AMBIENT_EFFECTS = {21, 33, 68, 63, 65, 64, 69, 158, 159}; constexpr std::initializer_list SAVED_EFFECTS = {74, 76, 39, 116, 120, 192}; -constexpr int ENTITY_FLY = 13; constexpr int BOMB_VARIANT_TROLL = 3; constexpr int BOMB_VARIANT_SUPERTROLL = 4; constexpr int BOMB_VARIANT_GOLDENTROLL = 18; -constexpr int EFFECT_POOF01 = 15; -constexpr int EFFECT_POOF02 = 16; constexpr int POOF02_LAVA_SPLASH = 66; -constexpr int FAMILIAR_WISP = 206; constexpr int WISP_HEALED_BY_HEARTS = 296; // The sounds pickups play. constexpr int SOUND_CHEST_DROP = 21; constexpr int SOUND_FETUS_JUMP = 38; -constexpr int SOUND_FETUS_LAND = 40; -constexpr int SOUND_HOLY = 54; constexpr int SOUND_KEYPICKUP_GAUNTLET = 58; constexpr int SOUND_KEY_DROP0 = 59; constexpr int SOUND_MEAT_FEET_SLOW0 = 68; -constexpr int SOUND_BOOK_PAGE_TURN_12 = 8; constexpr int SOUND_BOSS2_BUBBLES = 185; constexpr int SOUND_DIMEDROP = 198; constexpr int SOUND_DIMEPICKUP = 199; @@ -191,14 +151,11 @@ constexpr int SOUND_NICKELPICKUP = 232; constexpr int SOUND_PENNYDROP = 233; constexpr int SOUND_PENNYPICKUP = 234; constexpr int SOUND_SCAMPER = 249; -constexpr int SOUND_SHELLGAME = 252; -constexpr int SOUND_SPLATTER = 258; constexpr int SOUND_SUPERHOLY = 266; constexpr int SOUND_PING_PONG = 458; constexpr int SOUND_BONE_HEART = 461; constexpr int SOUND_SHOVEL_DROP = 463; constexpr int SOUND_GOLD_HEART = 465; -constexpr int SOUND_GOLD_HEART_DROP = 466; constexpr int SOUND_BONE_DROP = 467; constexpr int SOUND_UNHOLY = 468; constexpr int SOUND_GOLDENBOMB = 470; @@ -209,7 +166,6 @@ constexpr float STICKY_NICKEL_VOLUME = 0.5f; constexpr float POOP_PITCH_MIN = 0.9f; constexpr float POOP_PITCH_RANGE = 0.3f; constexpr int PILL_GOLD = 14; -constexpr int PILL_COLOR_MASK = 0x7ff; constexpr int CARD_PLAYING_FLAG = 0x8000; constexpr float RANDOM_UNIT = 2.3283064e-10f; // The card pickup subtypes that sound like objects, not paper, when collected. @@ -814,7 +770,7 @@ bool entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerTy // 006e02f0 Starts a pickup: clears what a previous life left, chooses its kind (the pick seeded from its seed), loads // its sprite, makes it appear, and gives Pay To Play's chests a coin slot. -// Items, shop wares, the big chest, trophy and bed are not reconstructed yet. +// The big chest, trophy and bed are not reconstructed yet. void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { isUnknown176 = true; @@ -853,10 +809,9 @@ 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_BROKEN_SHOVEL, PICKUP_BIGCHEST, PICKUP_TROPHY, PICKUP_BED, - PICKUP_MOMSCHEST}, - choice.variant)) - reconstruction_missing("Entity_Pickup::Init 006e02f0: shop wares and the big pickups"); + if (choice.variant == PICKUP_SHOPITEM) shop_ware_choose(choice, seed); + if (is_listed({PICKUP_BROKEN_SHOVEL, PICKUP_BIGCHEST, PICKUP_TROPHY, PICKUP_BED, PICKUP_MOMSCHEST}, choice.variant)) + reconstruction_missing("Entity_Pickup::Init 006e02f0: the big pickups"); if (choice.variant == PICKUP_COLLECTIBLE) collectible_choose(choice.subType, seed); lua_engine_get().PostPickupSelection(this, choice.variant, choice.subType); @@ -953,22 +908,6 @@ void Entity_Pickup::UpdateSprite(bool isIgnoreBlind) sprite.LoadGraphics(); } -// 006e2570 Sets the price and its sprite. A free pickup drops the price sprite. -// Prices, which shops set, are not reconstructed yet. -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) - { - if (g_game->room->roomType == ROOM_DUNGEON) posOffset.y = 0; - sprite.Play("Idle"); - SetAlternatePedestal(0); - } - priceANM2.Reset(); - if (child) child->Remove(); -} - // 006e17c0 Shows a chest's or sack's contents to a holder of Guppy's Eye, and otherwise removes the preview. void Entity_Pickup::UpdateLootPreview() { @@ -1094,7 +1033,7 @@ void Entity_Pickup::Update() } else if (!HasEntityFlags(FLAG_THROWN)) friction *= PICKUP_FRICTION; update_magnet_attraction(); - if (isAutoUpdatePrice && price != 0) reconstruction_missing("Entity_Pickup::Update 006e3940: a price"); + if (isAutoUpdatePrice && price != 0) price_refresh(); appear_update(); bool isClosedChest = IsChest(variant) && subtype != 0; @@ -1267,8 +1206,8 @@ void Entity_Pickup::update_magnet_attraction() // 006e8ae0 A player touching the pickup collects it (hearts, coins, keys and bombs into their counters), plays its // pickup sound and animation and marks it dead. Coop ghosts, babies and players who cannot pick up take only a few // kinds. Whether the collision is solid: a priced or collected pickup and players' bombs pass through. -// Items, chests, sacks, cards, pills, trinkets, shops, familiars that collect and the rarer items and trinkets that -// change what a pickup gives are not reconstructed yet. +// A priced pickup is bought with the player's coins or health. Items, chests, sacks, cards, pills, trinkets, +// familiars that collect and the rarer items and trinkets that change what a pickup gives are not reconstructed yet. bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) { if (variant == PICKUP_COLLECTIBLE && (megaChestCollectible[0] || megaChestCollectible[1])) @@ -1308,7 +1247,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) bool isKeyBum = familiar == FAMILIAR_KEY_BUM || familiar == FAMILIAR_SUPER_BUM; bool isBum = !isLow && ((isCoinBum && variant == PICKUP_COIN) || (isHeartBum && variant == PICKUP_HEART) || (isKeyBum && variant == PICKUP_KEY && subtype != KEY_GOLDEN)); - bool isEater = !isLow && (familiar == FAMILIAR_ABYSS_LOCUST || familiar == FAMILIAR_LIL_PORTAL) && + bool isEater = !isLow && (familiar == Entity_Familiar::ABYSS_LOCUST || familiar == Entity_Familiar::LIL_PORTAL) && is_listed({PICKUP_HEART, PICKUP_COIN, PICKUP_KEY, PICKUP_BOMB, PICKUP_PILL, PICKUP_LIL_BATTERY, PICKUP_TAROTCARD, PICKUP_TRINKET}, variant); @@ -1344,7 +1283,8 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) 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"); + int paidPrice = price; + if (price != 0 && (player->IsHoldingItem() || !CanPickupShopItem(*player))) return true; bool isPickedUp = false; int collectedSubtype = subtype; @@ -1366,8 +1306,15 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_COLLECTIBLE: isPickedUp = collectible_collect(*player); break; + case PICKUP_LIL_BATTERY: + isPickedUp = battery_collect(*this, *player); + break; + case PICKUP_TAROTCARD: + case PICKUP_PILL: + isPickedUp = pocket_item_collect(*this, *player); + break; default: - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: chests, sacks, pocket items and trinkets"); + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: chests, sacks and trinkets"); } if (!isPickedUp) @@ -1386,12 +1333,10 @@ 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); - if (variant != PICKUP_COLLECTIBLE) - { - PlayPickupSound(); - collect_finish(player); - } - else if (!player->proceduralItems.empty()) + if (variant != PICKUP_COLLECTIBLE) PlayPickupSound(); + if (paidPrice != 0) purchase_finish(*player, paidPrice); + else if (variant != PICKUP_COLLECTIBLE) collect_finish(player); + if ((variant == PICKUP_COLLECTIBLE || paidPrice != 0) && !player->proceduralItems.empty()) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the procedural items' pickup trigger"); if (g_game->playerManager.IsCoopPlay() && coopDuplicateIndex != -1) @@ -1543,7 +1488,7 @@ bool Entity_Pickup::heart_collect(Entity_Player& player) isPickedUp = true; } for (Entity* entity : g_game->room->entityList.updateEL) - if (entity->IsType(ENTITY_FAMILIAR, FAMILIAR_WISP, WISP_HEALED_BY_HEARTS) && entity->isExists && + if (entity->IsType(ENTITY_FAMILIAR, Entity_Familiar::WISP, WISP_HEALED_BY_HEARTS) && entity->isExists && static_cast(entity)->player == &player) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a wisp healed by hearts"); @@ -1765,7 +1710,7 @@ bool Entity_Pickup::CanRerollVariant(int pickupVariant, int pickupSubType) if (is_listed({PICKUP_BED, PICKUP_TROPHY, PICKUP_BIGCHEST, PICKUP_THROWABLEBOMB, PICKUP_MOMSCHEST}, pickupVariant)) return false; if (pickupVariant != PICKUP_COLLECTIBLE) return true; - if (pickupSubType == COLLECTIBLE_MOMS_SHOVEL) return false; + if (pickupSubType == COLLECTIBLE_DADS_NOTE) return false; if (g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && pickupSubType == -1) return false; bool isChallenge = g_game->challenge != 0 || g_game->dailyChallenge._id != 0; @@ -1860,12 +1805,6 @@ void Entity_Pickup::GetLootList(const Vector&) reconstruction_missing("Entity_Pickup::GetLootList 005832c0"); } -// 005b19b0 -Vector Entity_Pickup::GetRandomPickupVelocity(const Vector&, RNG*, uint32_t) -{ - reconstruction_missing("Entity_Pickup::GetRandomPickupVelocity 005b19b0"); -} - // 006e1640 bool Entity_Pickup::TryFlip(Entity_Player*, uint32_t) { @@ -1890,30 +1829,12 @@ bool Entity_Pickup::TryOpenChest(Entity_Player*) reconstruction_missing("Entity_Pickup::TryOpenChest 006e6e40"); } -// 006e83a0 -uint32_t Entity_Pickup::can_player_buy(Entity_Player*) -{ - reconstruction_missing("Entity_Pickup::can_player_buy 006e83a0"); -} - -// 006e84d0 -void Entity_Pickup::CollectTrinket(Entity_Player*, uint32_t) -{ - reconstruction_missing("Entity_Pickup::CollectTrinket 006e84d0"); -} - // 006ee3f0 bool Entity_Pickup::CanJeraDuplicate() { reconstruction_missing("Entity_Pickup::CanJeraDuplicate 006ee3f0"); } -// 006eea30 -void Entity_Pickup::MakeShopItem(int) -{ - reconstruction_missing("Entity_Pickup::MakeShopItem 006eea30"); -} - // 006eed30 int Entity_Pickup::AssignOptionsIndex() { diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 05db3d4..5894d57 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -57,6 +57,38 @@ enum PickupSale PICKUP_FOR_SALE }; +// The prices the shops ask (Lua's PickupPrice and the spikes' offer). +enum PickupPrice : int +{ + PRICE_ONE_HEART = -1, + PRICE_TWO_HEARTS = -2, + PRICE_THREE_SOULHEARTS = -3, + PRICE_ONE_HEART_AND_TWO_SOULHEARTS = -4, + PRICE_SPIKES = -5, + PRICE_SOUL = -6, + PRICE_ONE_SOUL_HEART = -7, + PRICE_TWO_SOUL_HEARTS = -8, + PRICE_ONE_HEART_AND_ONE_SOUL_HEART = -9, + PRICE_SPIKES_OFFER = -10, + PRICE_FREE = -1000 +}; + +// A coin's subtypes (Lua's CoinSubType). +enum CoinSubType : int +{ + COIN_PENNY = 1, + COIN_NICKEL, + COIN_DIME, + COIN_DOUBLEPACK, + COIN_LUCKYPENNY, + COIN_STICKYNICKEL, + COIN_GOLDEN +}; + +// The game state bit set once a heart, bomb or coin is picked, and Daemon's Tail's 1 in 5 heart chance. +constexpr int GAME_STATE_HEART_BOMB_COIN_PICKED = 41; +constexpr int DAEMONS_TAIL_ODDS = 5; + // A pickup kind to choose (Pickup_PickVariant): a variant and subtype where 0 asks for a random one, the seed the // choice comes from, and how it draws from the pools. struct PickupChoice @@ -126,14 +158,16 @@ struct Entity_Pickup : Entity int GetAlternatePedestal(); void SetForceBlind(uint8_t setBlind); void UpdateSprite(bool isIgnoreBlind); + void Morph(int entityType, int entityVariant, int entitySubType, bool isKeepPrice, bool isKeepSeed, + bool isIgnoreModifiers); void update_price_sprite(int newPrice); void AppearFast(); bool TryOpenChest(Entity_Player* player); void PlayDropSound(); void PlayPickupSound(); int GetCoinValue(); - uint32_t can_player_buy(Entity_Player*); - void CollectTrinket(Entity_Player*, uint32_t); + bool CanPickupShopItem(Entity_Player& player); + void TriggerShopPurchase(Entity_Player& player, int spentMoney); uint8_t empty_pedestal(); void update_magnet_attraction(); void update_cycle_collectible(bool isForce); @@ -158,6 +192,13 @@ private: bool bomb_collect(Entity_Player& player); void collect_finish(Entity_Player* player); + // The shop's parts of Init, Update, update_price_sprite and HandleCollision (entity_pickup_shop.cpp). + void shop_ware_choose(PickupChoice& choice, uint32_t seed); + void price_sprite_load(); + void price_refresh(); + void other_deals_take(); + void purchase_finish(Entity_Player& player, int paidPrice); + // 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(); diff --git a/src/entity_pickup_morph.cpp b/src/entity_pickup_morph.cpp new file mode 100644 index 0000000..f4c493b --- /dev/null +++ b/src/entity_pickup_morph.cpp @@ -0,0 +1,113 @@ +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" + +constexpr int MORPH_RNG_SHIFT = 7; + +// What Morph keeps of a pickup across its Init. +struct MorphKept +{ + EntityPtr child; + EntityPtr parent; + EntityPtr target; + Vector pos{}; + Vector targetPosition{}; + Vector velocity{}; + uint64_t flags = 0; + uint32_t index = 0; + uint32_t state = 0; + int coopDuplicateIndex = 0; + int itemPoolType = 0; + int optionsPickupIndex = 0; + int pedestal = 0; + int shopItemId = 0; + int timeout = 0; + bool isForceBlind = false; + bool isTouched = false; + bool isUnknown52d = false; +}; + +// 006e30a0 Turns a pickup into another in place (Lua's EntityPickup:Morph): a new seed unless kept, its place, links, +// index, flags and timers kept, its price kept or dropped, an active's initial charge, and its pedestal. Entities +// pointing at it forget it. The deathmatch's swaps, a devil deal keeping its sacrifice item, a priced shop item's +// reroll, a Mega Chest's halves and Flip's other item are not written yet. +void Entity_Pickup::Morph(int entityType, int entityVariant, int entitySubType, bool isKeepPrice, bool isKeepSeed, + bool isIgnoreModifiers) +{ + if (!isKeepSeed) + { + RNG rng = rng_make(initSeed, MORPH_RNG_SHIFT); + initSeed = rng.Next(); + } + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Pickup::Morph 006e30a0 (the deathmatch's blacklist)"); + if (megaChestCollectible[0] || megaChestCollectible[1] || flipSaveState) + reconstruction_missing("Entity_Pickup::Morph 006e30a0 (a Mega Chest's halves or Flip's other item)"); + + MorphKept saved = {.child = child, + .parent = parent, + .target = target, + .pos = pos, + .targetPosition = targetPosition, + .velocity = velocity, + .flags = flags, + .index = index, + .state = state, + .coopDuplicateIndex = coopDuplicateIndex, + .itemPoolType = itemPoolType, + .optionsPickupIndex = optionsPickupIndex, + .pedestal = GetAlternatePedestal(), + .shopItemId = shopItemId, + .timeout = timeout, + .isForceBlind = isForceBlind, + .isTouched = isTouched, + .isUnknown52d = isUnknown52d}; + int savedIgnoreModifiers = g_pickupIgnoreModifiers; + if (isIgnoreModifiers) g_pickupIgnoreModifiers++; + + if (itemPoolType == POOL_DEVIL && price == 0 && ItemConfig::is_collectible_tagged(subtype, TAG_DEVIL_SACRIFICE) && + !ItemConfig::is_collectible_tagged(entitySubType, TAG_DEVIL_SACRIFICE)) + reconstruction_missing("Entity_Pickup::Morph 006e30a0 (a devil deal keeping its sacrifice item)"); + int newPrice = isKeepPrice ? price : 0; + if (price != 0 && isKeepPrice && entitySubType == 0) + reconstruction_missing("Entity_Pickup::Morph 006e30a0 (a priced shop item's reroll)"); + Init(entityType, entityVariant, entitySubType, initSeed); + + itemPoolType = saved.itemPoolType; + g_pickupIgnoreModifiers = savedIgnoreModifiers; + index = saved.index; + flags = saved.flags; + targetPosition = saved.targetPosition; + parent = saved.parent; + child = saved.child; + target = saved.target; + pos = saved.pos; + isTouched = saved.isTouched; + coopDuplicateIndex = saved.coopDuplicateIndex; + velocity = saved.velocity; + isUnknown52d = saved.isUnknown52d; + optionsPickupIndex = saved.optionsPickupIndex; + isVisible = true; + timeout = saved.timeout; + charge = 0; + varData = 0; + state = 0; + invisibleFrames = 0; + if (entityVariant == PICKUP_COLLECTIBLE && subtype != 0) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(subtype); + if (item && item->type == ITEM_ACTIVE) charge = item->initCharge; + state = saved.state; + } + + shopItemId = saved.shopItemId; + update_price_sprite(newPrice); + SetAlternatePedestal(saved.pedestal); + bool isBlindChanged = isForceBlind != saved.isForceBlind; + isForceBlind = saved.isForceBlind; + if (variant == PICKUP_COLLECTIBLE && subtype != 0 && isBlindChanged) UpdateSprite(false); + for (EntityPtr* referrer : referrers) referrer->forget(); + referrers.clear(); +} diff --git a/src/entity_pickup_shop.cpp b/src/entity_pickup_shop.cpp new file mode 100644 index 0000000..78e67e1 --- /dev/null +++ b/src/entity_pickup_shop.cpp @@ -0,0 +1,406 @@ +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_special.h" +#include +#include + +constexpr int COLLECTIBLE_KEEPERS_SACK = 716; +constexpr int GRID_SPIKES_OFFER = 28; +constexpr int EFFECT_SPIKE_PRICE = 174; +constexpr int ACHIEVEMENT_SHOP_SPENDING = 582; +constexpr int SHOP_SPENDING_UNLOCK = 39; +constexpr int EVENT_SHOP_PURCHASES = 197; +constexpr uint64_t DAMAGE_PURCHASE = 0x10002080; +constexpr uint64_t DAMAGE_DEVIL_DEAL = 0x400; +constexpr float SPIKES_PRICE_DAMAGE = 2; +constexpr int SPIKES_PRICE_COUNTDOWN = 30; +constexpr float DUNGEON_PRICE_LIFT = -20; +constexpr float YOUR_SOUL_KEEP_ONE = 1; +constexpr float YOUR_SOUL_KEEP_TWO = 0.9f; +constexpr float YOUR_SOUL_KEEP_THREE = 0.8f; +constexpr float PICKUP_VELOCITY_SPEED = 5; +constexpr float PICKUP_VELOCITY_CHALLENGE = 0.4f; +constexpr float PICKUP_VELOCITY_LOB = 0.2f; +constexpr float PICKUP_VELOCITY_LOB_BASE = 3; +constexpr float PICKUP_VELOCITY_REACH = 7; +constexpr float PICKUP_VELOCITY_ROUND = 3.14f; +constexpr float PICKUP_VELOCITY_SCALE = 2.3283062e-10f; +constexpr int PICKUP_VELOCITY_TRIES = 10; +constexpr int PRICE_DIGITS = 10; +constexpr int PRICE_COIN_FRAME = 10; +constexpr float DEVIL_DEAL_POOF_DROP = 10; +constexpr int DEVIL_DEAL_TIMEOUT = 4; +constexpr int DEVIL_TREASURE_RAISED_VARIANT = 27; +constexpr float DEVIL_TREASURE_RAISE = 80; + +// The price sprite's layers: the tens, the units and the coin symbol. +enum PriceLayer +{ + PRICE_LAYER_TENS, + PRICE_LAYER_UNITS, + PRICE_LAYER_SYMBOL +}; + +// The hearts each heart price takes, red and soul, by its negated price (Lua's PickupPrice). +struct HeartCost +{ + int red = 0; + int soul = 0; +}; + +constexpr std::array HEART_COSTS = { + {{}, {1, 0}, {2, 0}, {0, 3}, {1, 2}, {}, {}, {0, 1}, {0, 2}, {1, 1}}}; + +// (00703ab0) Game::GetNearestPlayerEx for the main players: the nearest one that is no co-op ghost, baby, held twin +// or hologram and still collides. +Entity_Player* player_nearest_find(const Vector& position) +{ + Entity_Player* nearest = nullptr; + float best = 1e10f; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = vector_length_squared(vector_sub(position, player->pos)); + if (distance >= best || player->variant != 0 || player->isCoopGhost || player->parent) continue; + if (player->IsHologram() || player->entityCollisionClass == ENTCOLL_NONE) continue; + nearest = player; + best = distance; + } + return nearest; +} + +// The ware a shop slot sells, the Init part of 006e02f0: the room rolls the slot's ware and price from the pickup's +// seed, the pick's modifiers may change it (pricing it again), and a devil treasure room's crawlspace ware stands +// higher. +void Entity_Pickup::shop_ware_choose(PickupChoice& choice, uint32_t seed) +{ + Room& room = *g_game->room; + RNG rng = {seed, 5, 9, 7}; + ShopOffer offer = {.seed = rng.Next()}; + + shopItemId = room_shop_ware_roll(room, offer); + price = offer.price; + choice = {offer.subType, offer.variant, offer.seed, POOL_DRAW_TAKE, PICKUP_FOR_SALE}; + if (pickup_variant_pick(choice) && (choice.variant != offer.variant || choice.subType != offer.subType)) + { + offer.variant = choice.variant; + offer.subType = choice.subType; + price = room_shop_discount(room, shopItemId, room_shop_item_price(room, offer, nullptr), nullptr); + } + + RoomDescriptor* desc = room.descriptor; + bool isRaised = desc && (desc->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE) && desc->data->type == ROOM_TREASURE && + desc->data->variant == DEVIL_TREASURE_RAISED_VARIANT; + if (isRaised) pos.y -= DEVIL_TREASURE_RAISE; +} + +// A price on its sprite: hearts by frame, spikes as a spike effect under the ware, free as a struck price, coins as +// two digits and the coin, red while discounted. +void Entity_Pickup::price_sprite_load() +{ + EntityConfig& configs = g_manager->entityConfig; + EntityConfig_Entity* priceConfig = configs.GetEntity(ENTITY_PICKUP, PICKUP_SHOPITEM, 0); + if (!priceConfig) priceConfig = configs.GetEntity(ENTITY_PICKUP, 0, 0); + priceANM2.Load(priceConfig->anm2Path, GRAPHICS_LOAD); + + bool isHearts = price < 0 && price != PRICE_FREE; + ShopOffer offer = {.shopItemId = shopItemId, .subType = subtype, .variant = variant}; + bool isDiscounted = + !isHearts && (price < room_shop_item_price(*g_game->room, offer, nullptr) || price == PRICE_FREE); + priceANM2.SetAnimation(isHearts ? "Hearts" : isDiscounted ? "NumbersRed" : "NumbersWhite"); + + if (price > 0) + { + if (price < PRICE_DIGITS) priceANM2.GetLayer(PRICE_LAYER_TENS)->isVisible = false; + else priceANM2.animState.SetLayerFrame(PRICE_LAYER_TENS, price / PRICE_DIGITS); + priceANM2.animState.SetLayerFrame(PRICE_LAYER_UNITS, price % PRICE_DIGITS); + priceANM2.animState.SetLayerFrame(PRICE_LAYER_SYMBOL, PRICE_COIN_FRAME); + return; + } + switch (price) + { + case PRICE_SPIKES_OFFER: return; + case PRICE_FREE: + priceANM2.GetLayer(PRICE_LAYER_TENS)->isVisible = false; + priceANM2.SetLayerFrame(PRICE_LAYER_UNITS, 0); + priceANM2.SetLayerFrame(PRICE_LAYER_SYMBOL, PRICE_COIN_FRAME); + return; + case PRICE_SPIKES: + for (int layer : {PRICE_LAYER_TENS, PRICE_LAYER_UNITS, PRICE_LAYER_SYMBOL}) + priceANM2.GetLayer(layer)->isVisible = false; + if (!child) + { + Entity* spikes = g_game->Spawn({.position = pos, + .spawner = this, + .type = ENTITY_EFFECT, + .variant = EFFECT_SPIKE_PRICE, + .seed = Random()}); + spikes->parent = this; + spikes->Update(); + child = spikes; + } + return; + } + + // The heart prices' frames: one heart, two, three soul hearts and so on, the soul's after the spikes'. + int frame = -price - 1; + if (price <= PRICE_SOUL) frame--; + if (priceANM2.animState.animData) priceANM2.animState.SetFrameFloat((float)frame); +} + +// 006e2570 Sets the price and its sprite. A free pickup drops the price sprite and plays idle, a priced one shows its +// price and stands still on its shop pedestal. Spike offers keep their price until bought or turned to a soul. +void Entity_Pickup::update_price_sprite(int newPrice) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(subtype); + int oldPrice = price; + bool isOfferKept = oldPrice == PRICE_SPIKES_OFFER && item && item->HasTags(TAG_DEVIL_SACRIFICE) && newPrice != 0 && + newPrice != PRICE_SOUL && newPrice != PRICE_SPIKES_OFFER; + if (isOfferKept) return; + + price = newPrice; + Room& room = *g_game->room; + if (price == 0) + { + if (variant == PICKUP_COLLECTIBLE) + { + if (room.roomType == ROOM_DUNGEON) posOffset.y = 0; + sprite.Play("Idle"); + SetAlternatePedestal(0); + } + priceANM2.Reset(); + } + else + { + sprite.overlayAnimState.SetAnimationData(nullptr); + if (room.roomType == ROOM_DUNGEON) posOffset.y = DUNGEON_PRICE_LIFT; + price_sprite_load(); + if (variant == PICKUP_COLLECTIBLE && sprite.SetAnimation("ShopIdle") && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + else if (variant != PICKUP_COLLECTIBLE) sprite.Play("Idle"); + entityCollisionClass = ENTCOLL_PLAYERONLY; + } + if (price != PRICE_SPIKES && child) child->Remove(); + + GridEntity* below = room.GetGridEntity((uint32_t)(room.GetGridIndex(pos) + room.gridWidth)); + bool isOfferSpikes = below && below->type == GRID_SPIKES_OFFER; + if (oldPrice == PRICE_SPIKES_OFFER || price == PRICE_SPIKES_OFFER || isOfferSpikes) + reconstruction_missing( + "Entity_Pickup::update_price_sprite 006e2570: a spike offer's spikes (GridEntity_Spikes)"); +} + +// The price part of 006e3940: a ware that follows the shop's prices takes the price the nearest player would pay. +void Entity_Pickup::price_refresh() +{ + Room& room = *g_game->room; + Entity_Player* player = player_nearest_find(pos); + ShopOffer offer = {.shopItemId = shopItemId, .subType = subtype, .variant = variant}; + int newPrice = room_shop_discount(room, shopItemId, room_shop_item_price(room, offer, player), player); + if (newPrice != price) update_price_sprite(newPrice); +} + +// 006eea30 Puts a free pickup up for sale in a shop slot, at the slot's price. +void Entity_Pickup::MakeShopItem(int shopId) +{ + if (price != 0) return; + + Room& room = *g_game->room; + ShopOffer offer = {.shopItemId = shopId, .subType = subtype, .variant = variant}; + shopItemId = shopId; + price = room_shop_item_price(room, offer, nullptr); + price = room_shop_discount(room, -1, price, nullptr); + update_price_sprite(price); +} + +// The Coupon wisps a player's room holds, each worth a coin at the shop. +static int coupon_wisps_count() +{ + int count = 0; + for (Entity* wisp : g_game->room->entityList.wispEL) count += wisp->subtype == COLLECTIBLE_COUPON; + return count; +} + +// 006e83a0 Whether a player can pay the price (Entity_Pickup::CanPickupShopItem): coins with the Coupon wisps for +// coins, never a spike offer by touch, anything for a player without health, the heart price's containers and soul +// hearts, and spikes when they hurt. Co-op ghosts never buy. +bool Entity_Pickup::CanPickupShopItem(Entity_Player& player) +{ + if (player.isCoopGhost) return false; + if (price > 0 && price > player.numCoins + coupon_wisps_count()) return false; + if (price == PRICE_SPIKES_OFFER) return false; + if (player.GetHealthType() == HEALTH_NO_HEALTH || player.HasInstantDeathCurse()) return true; + + if (price >= PRICE_ONE_HEART_AND_ONE_SOUL_HEART && price < 0) + { + HeartCost cost = HEART_COSTS[-price]; + if (cost.soul > 0 && cost.red == 0) return player.soulHearts > 0; + if (cost.soul > 0) return player.GetEffectiveMaxHearts() >= 2; + if (cost.red > 0) return player.GetEffectiveMaxHearts() > 0; + } + if (price != PRICE_SPIKES) return true; + return player.TakeDamage(SPIKES_PRICE_DAMAGE, DAMAGE_PURCHASE, EntityRef(), SPIKES_PRICE_COUNTDOWN); +} + +// 007d8630 Counts coins a player spent: Keeper's Sack keeps them for its stats, and the floor's room records the +// spending, unlocking at 40 coins. +static void coins_spent_count(Entity_Player& player, int coins) +{ + if (player.HasCollectible(COLLECTIBLE_KEEPERS_SACK)) + { + player.keepersSackBonus += coins; + player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_KEEPERS_SACK, -1); + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_KEEPERS_SACK, true, 1); + } + RoomDescriptor* desc = g_game->room->descriptor; + if (!desc) return; + desc->totalMoneySpent = (int16_t)(desc->totalMoneySpent + coins); + if ((uint16_t)desc->totalMoneySpent > SHOP_SPENDING_UNLOCK) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_SHOP_SPENDING); +} + +// The health a devil deal takes: the price's containers and soul hearts, Your Soul's trinket (sometimes kept when +// golden), nothing for a player without health, who takes every other deal away instead. +static bool deal_health_pay(Entity_Player& player, int price) +{ + bool isFree = player.GetHealthType() == HEALTH_NO_HEALTH || player.HasInstantDeathCurse(); + if (price == PRICE_SOUL) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_YOUR_SOUL); + float keepOdds = multiplier == 2 ? YOUR_SOUL_KEEP_TWO + : multiplier == 3 ? YOUR_SOUL_KEEP_THREE + : YOUR_SOUL_KEEP_ONE; + if (player.GetTrinketRNG(TRINKET_YOUR_SOUL).RandomFloat() <= keepOdds) + player.TryRemoveTrinket(TRINKET_YOUR_SOUL); + return isFree; + } + if (isFree || price == PRICE_SPIKES) return isFree; + + if (price == PRICE_THREE_SOULHEARTS) + { + int soulPaid = std::min((player.soulHearts + 1) / 2, 3); + player.AddMaxHearts(-std::max(3 - soulPaid, 0) * 2, false); + player.AddSoulHearts(-soulPaid * 2, false); + return false; + } + HeartCost cost = HEART_COSTS[-price]; + if (cost.red > 0) player.AddMaxHearts(-cost.red * 2, false); + if (cost.soul > 0) player.AddSoulHearts(-cost.soul * 2, false); + return false; +} + +// 006e84d0 Pays for a bought ware (Entity_Pickup::TriggerShopPurchase): coins less the Coupon wisps, which burn, or +// the deal's health, which counts as devil damage. A player without health takes the other deals away. A ware bought +// with Restock or in Greed mode restocks its shop slot. +void Entity_Pickup::TriggerShopPurchase(Entity_Player& player, int spentMoney) +{ + if (spentMoney == 0) spentMoney = price; + if (spentMoney != 0) + { + priceANM2.Reset(); + if (spentMoney > 0) + { + int wisps = 0; + for (Entity* wisp : g_game->room->entityList.wispEL) + { + if (wisp->type != ENTITY_FAMILIAR || wisp->variant != Entity_Familiar::WISP || + wisp->subtype != COLLECTIBLE_COUPON) + continue; + if (wisps++ < spentMoney) wisp->Kill(EntityRef()); + } + spentMoney = std::max(spentMoney - wisps, 0); + player.AddCoins(-spentMoney); + coins_spent_count(player, spentMoney); + // The online stats tally of coins spent (Player_stats_add 00425ac0) is not written yet. + } + else + { + bool isOthersTaken = deal_health_pay(player, spentMoney); + player.set_last_damage(DAMAGE_DEVIL_DEAL, EntityRef()); + if (isOthersTaken) other_deals_take(); + if (player.CanPickupItem() && !player.IsHoldingItem()) player.try_trigger_astral_projection(); + } + } + + Room& room = *g_game->room; + bool isRestocked = + g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_RESTOCK, LAZARUS_SHARE_CHECK) || g_game->IsGreedMode(); + if (variant != PICKUP_COLLECTIBLE && spentMoney != 0 && isRestocked && room.roomType == ROOM_SHOP) + room_restock_trigger(room, room.GetGridIndex(pos), shopItemId); +} + +// A player without health taking a devil deal: the room's other deals vanish in a poof, and on the Dark Room's start +// the red chests too. +void Entity_Pickup::other_deals_take() +{ + Game& game = *g_game; + bool isDarkRoomStart = + !game.IsGreedMode() && game.stage == STAGE_DARK_ROOM && game.startingRoomIdx == game.currentRoomIdx; + for (Entity* entity : game.room->entityList.updateEL) + { + if (entity->type != ENTITY_PICKUP || entity == this) continue; + Entity_Pickup& other = *static_cast(entity); + bool isDeal = other.variant == PICKUP_COLLECTIBLE && other.subtype != 0 && other.price < 0; + if (!isDeal && !(isDarkRoomStart && other.variant == PICKUP_REDCHEST)) continue; + + Vector poof = vector_make(other.pos.x, other.pos.y + DEVIL_DEAL_POOF_DROP); + game.Spawn({.position = poof, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + other.timeout = DEVIL_DEAL_TIMEOUT; + } +} + +// A bought ware's end, the priced part of 006e8ae0's tail: the player lifts it and pays, a pickup goes, and the run +// counts the purchase. +void Entity_Pickup::purchase_finish(Entity_Player& player, int paidPrice) +{ + if (variant == PICKUP_TRINKET) sprite.Play("PlayerPickupSparkle"); + if (variant != PICKUP_COLLECTIBLE) player.AnimatePickup(&sprite, false, "Pickup"); + TriggerShopPurchase(player, paidPrice); + if (variant != PICKUP_COLLECTIBLE) + { + Remove(); + UpdateLootPreview(); + } + if (variant == PICKUP_HEART || variant == PICKUP_BOMB || variant == PICKUP_COIN) + g_game->gameStateFlags |= 1ull << GAME_STATE_HEART_BOMB_COIN_PICKED; + g_manager->persistentGameData.IncreaseEventCounter(EVENT_SHOP_PURCHASES, 1); +} + +// 005b19b0, 006ee440 A random velocity for a dropped pickup (Isaac::GetRandomPickupVelocity), from an RNG or the +// global one: a speed of 5 in a random direction (slower in challenge rooms, or lobbed downward for type 1), tried +// ten times for a clear path seven steps long. +Vector Entity_Pickup::GetRandomPickupVelocity(const Vector& position, RNG* rng, uint32_t ePickupVelType) +{ + Vector velocity{}; + for (int attempt = 0; attempt < PICKUP_VELOCITY_TRIES; attempt++) + { + float unit = 0; + if (!rng) unit = (float)Random() * RANDOM_UNIT_SCALE; + else + { + uint32_t value = rng->Next(); + value ^= value >> 3; + value ^= value << 1; + value ^= value >> 14; + unit = (float)value * PICKUP_VELOCITY_SCALE; + } + float angle = unit * PICKUP_VELOCITY_ROUND + unit * PICKUP_VELOCITY_ROUND; + velocity = vector_make(std::cos(angle) * PICKUP_VELOCITY_SPEED, std::sin(angle) * PICKUP_VELOCITY_SPEED); + if (ePickupVelType != 0) velocity.y = velocity.y * PICKUP_VELOCITY_LOB + PICKUP_VELOCITY_LOB_BASE; + else if (g_game->room->roomType == ROOM_CHALLENGE) velocity = vector_scale(velocity, PICKUP_VELOCITY_CHALLENGE); + + Vector end = vector_add(vector_scale(velocity, PICKUP_VELOCITY_REACH), position); + if (room_check_line(position, end, LINE_MODE_CELL, 0)) break; + } + return velocity; +} diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 333adea..33992fc 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -1,5 +1,6 @@ #include "entity_player.h" #include "data.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_npc.h" #include "game.h" @@ -39,7 +40,6 @@ constexpr float EDEN_FIRE_DELAY_SPREAD = 1.5f; constexpr float EDEN_RANGE_SPREAD = 120; constexpr float EDEN_SHOT_SPEED_SPREAD = 0.5f; constexpr int DEATHMATCH_HEART_SCALE = 8; -constexpr uint32_t GRAPHICS_PREMULTIPLIED_ALPHA = 4; // The shift triples Init seeds the player's generators with: one stepping the init seed, one for each list of // generators, and the one every item generator keeps. @@ -63,15 +63,11 @@ constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_START_RUNE_CHANCE = 10; constexpr int COLOR_PRIORITY_TOP = 255; constexpr int DAILY_CHRISTMAS = 19; -constexpr int EFFECT_BLOOD_SPLAT = 7; constexpr int EMPTY_HEART_RED_HEARTS = 3; constexpr int EVENT_BONUS_ITEMS = 114; -constexpr int FAMILIAR_ABYSS_LOCUST = 231; -constexpr int FAMILIAR_LIL_PORTAL = 232; constexpr int GIANTBOOK_EMPTY_HEART = 41; constexpr int GIANTBOOK_ETERNAL = 6; constexpr int GIANTBOOK_ETERNAL_BLACK = 46; -constexpr uint32_t LEVEL_STATE_SOL = 1 << 18; constexpr int LOCUST_SUBTYPE_START = 25; constexpr int PEE_ALPHA = 180; constexpr int PEE_OFFSET = 244; @@ -469,7 +465,7 @@ void Entity_Player::sprites_load() } int sourceFactor = - g_graphicsManager_flags & GRAPHICS_PREMULTIPLIED_ALPHA ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA; + KAGE::Graphics::manager.isPremultipliedAlpha ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA; for (auto [crown, path] : {std::pair{&crownOfLightSprite, "gfx/CrownOfLight.anm2"}, std::pair{&darkPrincesCrownSprite, "gfx/DarkPrincesCrown.anm2"}}) { @@ -846,7 +842,7 @@ void Entity_Player::companions_init() .spawner = this, .subType = LOCUST_SUBTYPE_START, .type = ENTITY_FAMILIAR, - .variant = FAMILIAR_ABYSS_LOCUST, + .variant = Entity_Familiar::ABYSS_LOCUST, .seed = Random()}) ->Update(); break; @@ -975,7 +971,7 @@ void Entity_Player::level_items_apply(bool isForced) if (!isCoopGhost) for (Entity* entity : game.room->entityList.mainEL) if (Entity_Familiar* familiar = dynamic_cast(entity); - familiar && familiar->IsType(ENTITY_FAMILIAR, FAMILIAR_LIL_PORTAL, 1) && familiar->player == this) + familiar && familiar->IsType(ENTITY_FAMILIAR, Entity_Familiar::LIL_PORTAL, 1) && familiar->player == this) familiar->subtype = 0; floor_maps_apply(); @@ -1028,7 +1024,7 @@ void Entity_Player::floor_maps_apply() { if (game.lastBossRoomListIdx >= 0) game.roomList[game.lastBossRoomListIdx].displayFlags |= ROOM_DISPLAY_ICON; game.minimap.Refresh(); - game.levelStateFlags |= LEVEL_STATE_SOL; + game.levelStateFlags |= 1u << LEVEL_STATE_SOL; } if (HasCollectible(COLLECTIBLE_LUNA)) game.reveal_secret_room(); if (HasTrinket(TRINKET_MISSING_POSTER)) diff --git a/src/entity_player.h b/src/entity_player.h index 17e27fb..077ee5f 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -31,7 +31,6 @@ constexpr int TRINKET_SLOT_COUNT = 2; constexpr int WEAPON_SLOT_COUNT = 5; constexpr uint32_t QUEUED_GOLDEN = 0x2; constexpr uint32_t TRINKET_GOLDEN_FLAG = 0x8000; -constexpr uint32_t TRINKET_ID_MASK = 0x7fff; constexpr uint8_t WILD_CARD_NONE = 0xff; // The characters, by their ids in players.xml (Lua's PlayerType). @@ -181,85 +180,196 @@ enum PlayerItemId : int { COLLECTIBLE_SAD_ONION = 1, COLLECTIBLE_SPOON_BENDER = 3, + COLLECTIBLE_NUMBER_ONE = 6, COLLECTIBLE_SKATOLE = 9, + COLLECTIBLE_1UP = 11, + COLLECTIBLE_VIRUS = 13, COLLECTIBLE_COMPASS = 21, + COLLECTIBLE_BREAKFAST = 25, + COLLECTIBLE_BIBLE = 33, + COLLECTIBLE_BOOK_OF_BELIAL = 34, + COLLECTIBLE_NECRONOMICON = 35, + COLLECTIBLE_POOP = 36, COLLECTIBLE_TELEPORT = 44, + COLLECTIBLE_YUM_HEART = 45, COLLECTIBLE_LUCKY_FOOT = 46, + COLLECTIBLE_SHOOP_DA_WHOOP = 49, + COLLECTIBLE_DR_FETUS = 52, COLLECTIBLE_TREASURE_MAP = 54, COLLECTIBLE_BOOK_OF_SHADOWS = 58, COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE = 59, + COLLECTIBLE_BATTERY = 63, + COLLECTIBLE_STEAM_SALE = 64, + COLLECTIBLE_HOURGLASS = 66, + COLLECTIBLE_TECHNOLOGY = 68, + COLLECTIBLE_CHOCOLATE_MILK = 69, + COLLECTIBLE_CUBE_OF_MEAT = 73, + COLLECTIBLE_PHD = 75, + COLLECTIBLE_BOOK_OF_REVELATIONS = 78, + COLLECTIBLE_DEAD_CAT = 81, + COLLECTIBLE_THE_NAIL = 83, + COLLECTIBLE_SPELUNKER_HAT = 91, COLLECTIBLE_RELIC = 98, COLLECTIBLE_D6 = 105, COLLECTIBLE_WAFER = 108, COLLECTIBLE_MONEY_EQUALS_POWER = 109, COLLECTIBLE_GUARDIAN_ANGEL = 112, COLLECTIBLE_DEMON_BABY = 113, + COLLECTIBLE_MOMS_KNIFE = 114, COLLECTIBLE_DEAD_BIRD = 117, COLLECTIBLE_BRIMSTONE = 118, COLLECTIBLE_WHORE_OF_BABYLON = 122, + COLLECTIBLE_MONSTER_MANUAL = 123, COLLECTIBLE_RAZOR_BLADE = 126, + COLLECTIBLE_PONY = 130, COLLECTIBLE_MOMS_PURSE = 139, + COLLECTIBLE_BOBS_CURSE = 140, COLLECTIBLE_NOTCHED_AXE = 147, + COLLECTIBLE_IPECAC = 149, COLLECTIBLE_MUTANT_SPIDER = 153, + COLLECTIBLE_PEEPER = 155, COLLECTIBLE_BLOODY_LUST = 157, + COLLECTIBLE_EPIC_FETUS = 168, COLLECTIBLE_HOLY_WATER = 178, + COLLECTIBLE_WHITE_PONY = 181, COLLECTIBLE_SACRED_HEART = 182, COLLECTIBLE_3_DOLLAR_BILL = 191, + COLLECTIBLE_MIDAS_TOUCH = 202, + COLLECTIBLE_BALL_OF_BANDAGES = 207, + COLLECTIBLE_GUPPYS_COLLAR = 212, COLLECTIBLE_ANEMIC = 214, + COLLECTIBLE_ANTI_GRAVITY = 222, + COLLECTIBLE_PYROMANIAC = 223, COLLECTIBLE_CRICKETS_BODY = 224, + COLLECTIBLE_MONSTROS_LUNG = 229, COLLECTIBLE_BALL_OF_TAR = 231, + COLLECTIBLE_STOP_WATCH = 232, COLLECTIBLE_KEY_PIECE_1 = 238, COLLECTIBLE_KEY_PIECE_2 = 239, + COLLECTIBLE_INFAMY = 242, COLLECTIBLE_BLUE_MAP = 246, + COLLECTIBLE_BFFS = 247, + COLLECTIBLE_STARTER_DECK = 251, + COLLECTIBLE_LITTLE_BAGGY = 252, + COLLECTIBLE_BLOOD_CLOT = 254, + COLLECTIBLE_FIRE_MIND_COSTUME = 256, + COLLECTIBLE_HOT_BOMBS = 256, COLLECTIBLE_FIRE_MIND = 257, COLLECTIBLE_MISSING_NO = 258, + COLLECTIBLE_BLACK_CANDLE = 260, + COLLECTIBLE_MISSING_PAGE_2 = 262, COLLECTIBLE_LEECH = 270, COLLECTIBLE_LIL_BRIMSTONE = 275, + COLLECTIBLE_ISAACS_HEART = 276, COLLECTIBLE_DARK_BUM = 278, + COLLECTIBLE_THE_JAR = 290, + COLLECTIBLE_FLUSH = 291, + COLLECTIBLE_SATANIC_BIBLE = 292, COLLECTIBLE_BUTTER_BEAN = 294, COLLECTIBLE_TAURUS = 299, COLLECTIBLE_SCORPIO = 305, COLLECTIBLE_HOLY_MANTLE = 313, + COLLECTIBLE_STRANGE_ATTRACTOR = 315, COLLECTIBLE_CURSED_EYE = 316, COLLECTIBLE_UNDEFINED = 324, + COLLECTIBLE_BREATH_OF_LIFE = 326, COLLECTIBLE_POLAROID = 327, COLLECTIBLE_NEGATIVE = 328, + COLLECTIBLE_LUDOVICO = 329, COLLECTIBLE_SOY_MILK = 330, COLLECTIBLE_MIND = 333, + COLLECTIBLE_BOOMERANG = 338, COLLECTIBLE_WOODEN_NICKEL = 349, + COLLECTIBLE_TOXIC_SHOCK = 350, + COLLECTIBLE_GLASS_CANNON = 352, COLLECTIBLE_INCUBUS = 360, COLLECTIBLE_SWORN_PROTECTOR = 363, + COLLECTIBLE_EPIPHORA = 368, + COLLECTIBLE_DEAD_EYE = 373, + COLLECTIBLE_HOST_HAT = 375, + COLLECTIBLE_RESTOCK = 376, + COLLECTIBLE_BURSTING_SACK = 377, + COLLECTIBLE_PAY_TO_PLAY = 380, COLLECTIBLE_SERAPHIM = 390, COLLECTIBLE_ZODIAC = 392, + COLLECTIBLE_SERPENTS_KISS = 393, + COLLECTIBLE_MARKED = 394, + COLLECTIBLE_TECH_X = 395, + COLLECTIBLE_LUSTY_BLOOD = 411, COLLECTIBLE_CAMBION_CONCEPTION = 412, COLLECTIBLE_IMMACULATE_CONCEPTION = 413, + COLLECTIBLE_MORE_OPTIONS = 414, COLLECTIBLE_CROWN_OF_LIGHT = 415, COLLECTIBLE_SUCCUBUS = 417, + COLLECTIBLE_BLACK_POWDER = 420, COLLECTIBLE_GLOWING_HOUR_GLASS = 422, + COLLECTIBLE_NIGHT_LIGHT = 425, + COLLECTIBLE_HEAD_OF_THE_KEEPER = 429, COLLECTIBLE_MOMS_BOX = 439, COLLECTIBLE_KIDNEY_STONE = 440, COLLECTIBLE_DARK_PRINCES_CROWN = 442, + COLLECTIBLE_APPLE = 443, + COLLECTIBLE_LEAD_PENCIL = 444, COLLECTIBLE_BELLY_BUTTON = 458, + COLLECTIBLE_GLAUCOMA = 460, + COLLECTIBLE_BROKEN_GLASS_CANNON = 474, + COLLECTIBLE_SMELTER = 479, + COLLECTIBLE_DATAMINER = 481, COLLECTIBLE_WAIT_WHAT = 484, COLLECTIBLE_METRONOME = 488, COLLECTIBLE_DEEP_POCKETS = 416, + COLLECTIBLE_DUALITY = 498, COLLECTIBLE_GREEDS_GULLET = 501, + COLLECTIBLE_LITTLE_HORN = 503, + COLLECTIBLE_BROKEN_MODEM = 514, + COLLECTIBLE_COUPON = 521, + COLLECTIBLE_MOVING_BOX = 523, + COLLECTIBLE_DEATHS_LIST = 530, + COLLECTIBLE_HAEMOLACRIA = 531, COLLECTIBLE_SCHOOLBAG = 534, + COLLECTIBLE_BROKEN_SHOVEL = 550, + COLLECTIBLE_BROKEN_SHOVEL_1 = 550, + COLLECTIBLE_GOLDEN_RAZOR = 555, + COLLECTIBLE_ALMOND_MILK = 561, COLLECTIBLE_DREAM_CATCHER = 566, COLLECTIBLE_PLAYDOUGH_COOKIE = 570, + COLLECTIBLE_EYE_OF_THE_OCCULT = 572, COLLECTIBLE_RED_KEY = 580, + COLLECTIBLE_WAVY_CAP = 582, COLLECTIBLE_BOOK_OF_VIRTUES = 584, COLLECTIBLE_ALABASTER_BOX = 585, COLLECTIBLE_SOL = 588, COLLECTIBLE_LUNA = 589, COLLECTIBLE_URANUS = 596, + COLLECTIBLE_MOMS_BRACELET = 604, + COLLECTIBLE_ETERNAL_D6 = 609, + COLLECTIBLE_LARYNX = 611, COLLECTIBLE_BIRTHRIGHT = 619, + COLLECTIBLE_KNIFE_PIECE_1 = 626, + COLLECTIBLE_KNIFE_PIECE_2 = 627, + COLLECTIBLE_DOGMA = 633, COLLECTIBLE_ERASER = 638, + COLLECTIBLE_URN_OF_SOULS = 640, + COLLECTIBLE_MAGIC_SKIN = 642, + COLLECTIBLE_4_5_VOLT = 647, + COLLECTIBLE_VADE_RETRO = 653, + COLLECTIBLE_FALSE_PHD = 654, + COLLECTIBLE_SPIN_TO_WIN = 655, + COLLECTIBLE_DAMOCLES_PASSIVE = 656, + COLLECTIBLE_PASSIVE_DAMOCLES = 656, COLLECTIBLE_VASCULITIS = 657, + COLLECTIBLE_BINGE_EATER = 664, COLLECTIBLE_STRAW_MAN = 667, + COLLECTIBLE_DADS_NOTE = 668, + COLLECTIBLE_SAUSAGE = 669, COLLECTIBLE_REDEMPTION = 673, COLLECTIBLE_EMPTY_HEART = 676, + COLLECTIBLE_ASTRAL_PROJECTION = 677, + COLLECTIBLE_C_SECTION = 678, COLLECTIBLE_LIL_ABADDON = 679, + COLLECTIBLE_INNER_CHILD = 688, + COLLECTIBLE_GLITCHED_CROWN = 689, + COLLECTIBLE_SANGUINE_BOND = 692, COLLECTIBLE_HEARTBREAK = 694, COLLECTIBLE_BLOODY_GUST = 695, COLLECTIBLE_SALVATION = 696, @@ -276,32 +386,78 @@ enum PlayerItemId : int COLLECTIBLE_JUPITER = 594, COLLECTIBLE_MEGA_MUSH = 625, COLLECTIBLE_MONTEZUMAS_REVENGE = 680, + COLLECTIBLE_ESAU_JR = 703, + COLLECTIBLE_BERSERK = 704, + COLLECTIBLE_STAPLER = 708, + COLLECTIBLE_SUPLEX = 709, + COLLECTIBLE_BAG_OF_CRAFTING = 710, + COLLECTIBLE_FLIP = 711, + COLLECTIBLE_RECALL = 714, + COLLECTIBLE_EVERYTHING_JAR = 720, + COLLECTIBLE_TMTRAINER = 721, COLLECTIBLE_DECAP_ATTACK = 729, + COLLECTIBLE_STYE = 731, + TRINKET_POOL_SHIFT = 2, + TRINKET_ROSARY_BEAD = 7, + TRINKET_CALLUS = 14, TRINKET_PAPER_CLIP = 19, + TRINKET_MONKEY_PAW = 20, TRINKET_MYSTERIOUS_PAPER = 21, + TRINKET_DAEMONS_TAIL = 22, TRINKET_MISSING_POSTER = 23, TRINKET_BUTT_PENNY = 24, TRINKET_CHILDS_HEART = 34, + TRINKET_MATCH_STICK = 41, TRINKET_CURSED_SKULL = 43, TRINKET_MISSING_PAGE = 48, TRINKET_MAGGYS_FAITH = 55, TRINKET_CAINS_EYE = 59, + TRINKET_EVES_BIRD_FOOT = 60, + TRINKET_LEFT_HAND = 61, + TRINKET_SHINY_ROCK = 62, + TRINKET_SAFETY_SCISSORS = 63, TRINKET_RAINBOW_WORM = 64, + TRINKET_WATCH_BATTERY = 72, TRINKET_ERROR = 75, TRINKET_FADED_POLAROID = 69, + TRINKET_RIB_OF_GREED = 84, TRINKET_LIL_LARVA = 86, + TRINKET_NO = 88, + TRINKET_CHILD_LEASH = 89, + TRINKET_MECONIUM = 91, TRINKET_USED_DIAPER = 93, TRINKET_STORE_KEY = 83, + TRINKET_FISH_TAIL = 94, + TRINKET_OUROBOROS_WORM = 96, TRINKET_TONSIL = 97, + TRINKET_VIBRANT_BULB = 100, + TRINKET_DIM_BULB = 101, TRINKET_DUCT_TAPE = 109, + TRINKET_BLOODY_CROWN = 111, TRINKET_STEM_CELL = 119, TRINKET_WOODEN_CROSS = 121, TRINKET_BUTTER = 122, + TRINKET_BABY_BENDER = 127, + TRINKET_BROKEN_PADLOCK = 136, TRINKET_BETHS_FAITH = 142, + TRINKET_PERFECTION = 145, + TRINKET_FRIENDSHIP_NECKLACE = 148, + TRINKET_BLUE_KEY = 150, + TRINKET_FLAT_FILE = 151, + TRINKET_HOLY_CROWN = 155, TRINKET_MOTHERS_KISS = 156, + TRINKET_GILDED_KEY = 159, TRINKET_LUCKY_SACK = 160, + TRINKET_WICKED_CROWN = 161, + TRINKET_AZAZELS_STUMP = 162, + TRINKET_MODELING_CLAY = 166, TRINKET_HOLLOW_HEART = 168, + TRINKET_YOUR_SOUL = 173, + TRINKET_STRANGE_KEY = 175, + TRINKET_RC_REMOTE = 179, TRINKET_FOUND_SOUL = 180, + TRINKET_BROKEN_GLASSES = 187, + TRINKET_ID_MASK = 0x7fff, NULLITEM_BLINDFOLD = 14, NULLITEM_BLANKFACE = 15, @@ -309,11 +465,15 @@ enum PlayerItemId : int NULLITEM_SPIN_TO_WIN = 50, NULLITEM_INTRUDER = 55, NULLITEM_REVERSE_CHARIOT = 63, + NULLITEM_REVERSE_HANGED_MAN = 65, NULLITEM_REVERSE_SUN = 66, + NULLITEM_WAVY_CAP_1 = 71, NULLITEM_LUNA = 74, + NULLITEM_ESAU_JR = 100, NULLITEM_SPIRIT_SHACKLES_DISABLED = 102, NULLITEM_FORGOTTEN_BOMB = 106, NULLITEM_JACOBS_CURSE = 109, + NULLITEM_BLOODY_BABYLON = 110, NULLITEM_LOST_CURSE = 112, NULLITEM_SOUL_FORGOTTEN = 120, NULLITEM_SOUL_JACOB = 121, @@ -338,6 +498,7 @@ enum PlayerAchievement : int ACHIEVEMENT_LAZARUS_HOLDS_ANEMIA = 331, ACHIEVEMENT_MAGDALENE_HOLDS_A_PILL = 332, ACHIEVEMENT_SAMSON_HOLDS_CHILDS_HEART = 334, + ACHIEVEMENT_TEARS_UP_ITEMS = 378, ACHIEVEMENT_GOLDEN_RAZOR = 583 }; @@ -346,6 +507,7 @@ enum PlayerChallenge : int { CHALLENGE_HAVE_A_HEART = 25, CHALLENGE_GUARDIAN = 30, + CHALLENGE_PONG = 30, CHALLENGE_BACKASSWARDS = 31, CHALLENGE_BLOODY_MARY = 37, CHALLENGE_BAPTISM_BY_FIRE = 38, @@ -355,6 +517,10 @@ enum PlayerChallenge : int CHALLENGE_RED_REDEMPTION = 44 }; +// How far a held item's sprite rises over the head, and the Missing Pages form's index. +constexpr float HELD_SPRITE_RISE = -4; +constexpr int PLAYER_FORM_MISSING_PAGES = 15; + // One active item slot: the item, its charges and the data it keeps between uses. struct ActiveItemDesc { @@ -916,7 +1082,6 @@ public: 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); @@ -965,6 +1130,7 @@ private: void walk_velocity_update(Vector walkInput); bool walking_items_has(); void walk_animation_update(); + void sprite_scale_update(); void shoot_input_read(ShootInput& input); void head_turn(Vector toward); void charge_store_changed(int effectiveCharge, int oldCharge); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index 5c97ccb..b76c1fe 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -4,6 +4,7 @@ #include "entity_pickup.h" #include "entity_tear.h" #include "game.h" +#include "grid_entity_door.h" #include "hud.h" #include "kage_input.h" #include "key_configs.h" @@ -14,6 +15,7 @@ #include "menu_manager.h" #include "npc_ai.h" #include "room.h" +#include "room_special.h" #include #include #include @@ -22,69 +24,34 @@ // The items and trinkets the active item code names (Lua's CollectibleType and TrinketType). enum ActiveItemId : int { - COLLECTIBLE_BIBLE = 33, - COLLECTIBLE_BOOK_OF_BELIAL = 34, - COLLECTIBLE_NECRONOMICON = 35, - COLLECTIBLE_POOP = 36, + COLLECTIBLE_MR_BOOM = 37, COLLECTIBLE_TAMMYS_HEAD = 38, COLLECTIBLE_MOMS_BRA = 39, COLLECTIBLE_KAMIKAZE = 40, COLLECTIBLE_MOMS_PAD = 41, - COLLECTIBLE_YUM_HEART = 45, COLLECTIBLE_DOCTORS_REMOTE = 47, COLLECTIBLE_LEMON_MISHAP = 56, - COLLECTIBLE_BATTERY = 63, COLLECTIBLE_ANARCHIST_COOKBOOK = 65, - COLLECTIBLE_HOURGLASS = 66, - COLLECTIBLE_BOOK_OF_REVELATIONS = 78, COLLECTIBLE_9_VOLT = 116, - COLLECTIBLE_MONSTER_MANUAL = 123, COLLECTIBLE_DEAD_SEA_SCROLLS = 124, - COLLECTIBLE_PONY = 130, COLLECTIBLE_GUPPYS_PAW = 133, COLLECTIBLE_SPIDER_BUTT = 171, - COLLECTIBLE_WHITE_PONY = 181, - COLLECTIBLE_MIDAS_TOUCH = 202, COLLECTIBLE_SHARP_PLUG = 205, COLLECTIBLE_D100 = 283, COLLECTIBLE_D4 = 284, - COLLECTIBLE_FLUSH = 291, - COLLECTIBLE_SATANIC_BIBLE = 292, COLLECTIBLE_MAGIC_FINGERS = 295, - COLLECTIBLE_BREATH_OF_LIFE = 326, - COLLECTIBLE_BOOMERANG = 338, - COLLECTIBLE_GLASS_CANNON = 352, COLLECTIBLE_CAR_BATTERY = 356, COLLECTIBLE_D12 = 386, COLLECTIBLE_D8 = 406, COLLECTIBLE_MINE_CRAFTER = 427, - COLLECTIBLE_BROKEN_GLASS_CANNON = 474, COLLECTIBLE_POTATO_PEELER = 487, - COLLECTIBLE_MOVING_BOX = 523, COLLECTIBLE_MR_ME = 527, COLLECTIBLE_HALLOWED_GROUND = 543, - COLLECTIBLE_GOLDEN_RAZOR = 555, - COLLECTIBLE_WAVY_CAP = 582, - COLLECTIBLE_ETERNAL_D6 = 609, - COLLECTIBLE_LARYNX = 611, COLLECTIBLE_SHARP_KEY = 623, COLLECTIBLE_STITCHES = 635, - COLLECTIBLE_MAGIC_SKIN = 642, - COLLECTIBLE_4_5_VOLT = 647, - COLLECTIBLE_SPIN_TO_WIN = 655, - COLLECTIBLE_ESAU_JR = 703, - COLLECTIBLE_BERSERK = 704, - COLLECTIBLE_SUPLEX = 709, - COLLECTIBLE_BAG_OF_CRAFTING = 710, - COLLECTIBLE_FLIP = 711, - COLLECTIBLE_RECALL = 714, - COLLECTIBLE_EVERYTHING_JAR = 720, COLLECTIBLE_ANIMA_SOLA = 722, TRINKET_BROKEN_REMOTE = 4, - TRINKET_MECONIUM = 91, - TRINKET_VIBRANT_BULB = 100, - TRINKET_DIM_BULB = 101, TRINKET_M = 138, TRINKET_PANIC_BUTTON = 149, TRINKET_EXPANSION_PACK = 181 @@ -97,6 +64,7 @@ enum ActiveSound : int ACTIVE_SOUND_DEATH_CARD = 33, ACTIVE_SOUND_DEVIL_CARD = 34, ACTIVE_SOUND_FART = 37, + ACTIVE_SOUND_MR_BOOM = 40, ACTIVE_SOUND_GASCAN_POUR = 51, ACTIVE_SOUND_VAMP_GULP = 157, ACTIVE_SOUND_BATTERY_CHARGE = 170, @@ -116,8 +84,19 @@ enum ActiveEntity : int ACTIVE_ENTITY_MOM = 45, ACTIVE_ENTITY_MOMS_HEART = 78, ACTIVE_ENTITY_SATAN = 84, + ACTIVE_EFFECT_POOF = 15, ACTIVE_EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, - ACTIVE_EFFECT_BATTERY = 49 + ACTIVE_EFFECT_BATTERY = 49, + ACTIVE_BOMB_BIG = 1 +}; + +// The kinds of battery (Lua's BatterySubType). +enum BatterySubType : int +{ + BATTERY_NORMAL = 1, + BATTERY_MICRO = 2, + BATTERY_MEGA = 3, + BATTERY_GOLDEN = 4 }; // The kinds of poop The Poop drops (Lua's GridPoopVariant). @@ -129,11 +108,13 @@ enum PoopVariant : int POOP_WHITE = 6 }; -constexpr uint32_t BULB_CACHE_FLAGS = - CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_SHOTSPEED | CACHE_RANGE | CACHE_SPEED | CACHE_LUCK; constexpr int ACHIEVEMENT_HALO = 27; constexpr int CHALLENGE_APRILS_FOOL = 32; +constexpr int ACTIVE_PICKUP_HOLD_FRAMES = 30; +constexpr int BATTERY_CHARGE = 6; +constexpr int BATTERY_MICRO_CHARGE = 2; constexpr int CHARGE_FLASH_MAX = 12; +constexpr int EVENT_BATTERIES_COLLECTED = 195; constexpr int DAMAGE_COUNTDOWN_FRAMES = 30; constexpr int GLOWING_HOUR_GLASS_LIT_USES = 3; constexpr int GOLDEN_RAZOR_PRICE = 5; @@ -142,6 +123,7 @@ constexpr int INPUT_HOOK_TRIGGERED = 1; constexpr int INPUT_RAW_ACTION = 33; constexpr int MECONIUM_CHANCES[] = {33, 66, 100}; constexpr int MIDAS_POOP_CHANCE = 34; +constexpr int MR_BOOM_SOUND_DELAY = 4; constexpr int NINE_VOLT_RECHARGE_FRAMES = 450; constexpr int NECROMANCER_FORM_ITEMS = 3; constexpr int OVERLAY_DELAY = 3; @@ -152,13 +134,12 @@ constexpr int REVELATIONS_STATE_FLAG = 7; constexpr int SUPLEX_AIMING = 2; constexpr int TAMMY_TEAR_COUNT = 10; constexpr int TIMED_RECHARGE_STEP = 1; +constexpr int UNUSED_COLLECTIBLES[] = {43, 61, 235}; constexpr int YUM_HEART_OTHER_HEARTS = 1; constexpr int YUM_HEART_OWN_HEARTS = 2; constexpr uint8_t WILD_CARD_ACTIVE = 2; constexpr uint64_t DAMAGE_RED_HEARTS = 1ull << 5; -constexpr uint64_t DAMAGE_INVINCIBLE = 1ull << 13; constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; -constexpr uint64_t DAMAGE_IGNORE_ARMOR = 1ull << 30; constexpr uint64_t KAMIKAZE_DAMAGE_FLAGS = DAMAGE_EXPLOSION | DAMAGE_NO_PENALTIES | DAMAGE_IGNORE_ARMOR; constexpr uint64_t RAZOR_BLADE_DAMAGE_FLAGS = DAMAGE_RED_HEARTS | DAMAGE_INVINCIBLE; constexpr uint64_t SPIDER_BUTT_DAMAGE_FLAGS = DAMAGE_IGNORE_ARMOR; @@ -168,6 +149,9 @@ constexpr float DEATHMATCH_RAZOR_DAMAGE = 10; constexpr float FULL_CIRCLE = 360; constexpr float KAMIKAZE_DAMAGE = 185; constexpr float MIDAS_LUCK_SCALE = 10; +constexpr float MR_BOOM_DAMAGE_BONUS = 85; +constexpr float MR_BOOM_SCALE = 1.5f; +constexpr float PEDESTAL_DOOR_NEAR = 70; constexpr float RAZOR_BLADE_DAMAGE = 1; constexpr float RAZOR_BLADE_FIRST_SCALE = 2; constexpr float SPIDER_BUTT_DAMAGE = 10; @@ -885,17 +869,30 @@ static void kamikaze_use(ItemUse& use) .isLineCheck = false}); } -// Teleport!: off to a random room of the floor, as Game::MoveToRandomRoom does it, which game.h does not declare yet. +// Mr. Boom: a big bomb at the player's feet carrying its bomb effects, bigger and stronger than a placed one. +static void mr_boom_use(ItemUse& use) +{ + Entity_Player& player = use.player; + EntitySpawn spawn = {.position = player.pos, .spawner = &player, .type = ENTITY_BOMB, .variant = ACTIVE_BOMB_BIG, + .seed = Random()}; + + if (Entity_Bomb* bomb = dynamic_cast(g_game->Spawn(spawn))) + { + bomb->tearFlags = player.GetBombFlags(false); + bomb->scale = MR_BOOM_SCALE; + bomb->isLoadCostumes = true; + bomb->explosionDamage += MR_BOOM_DAMAGE_BONUS; + } + g_manager->sfxManager.Play(ACTIVE_SOUND_MR_BOOM, {.frameDelay = MR_BOOM_SOUND_DELAY}); +} + +// Teleport!: off to a random room of the floor. static void teleport_use(ItemUse& use) { Entity_Player& player = use.player; - Game& game = *g_game; if (player.variant != PLAYER_VARIANT_PLAYER) return; - uint32_t seed = player.GetCollectibleRNG(COLLECTIBLE_TELEPORT).Next(); - game.leaveDoor = -1; - game.StartRoomTransition( - {.player = &player, .animation = TRANSITION_TELEPORT, .roomIndex = game.GetRandomRoomIndex(false, seed)}); + game_random_room_move(*g_game, false, player.GetCollectibleRNG(COLLECTIBLE_TELEPORT).Next(), &player); } // Yum Heart: a red heart for the player, half a heart for every other player. @@ -932,7 +929,36 @@ static void book_of_revelations_use(ItemUse& use) g_game->SetStateFlag(REVELATIONS_STATE_FLAG, true); } -// The D6 and the Eternal D6: every pedestal item of the room rerolled, which Entity_Pickup does not declare yet. +// A pedestal the D6 rerolls: another item from the pools, or none a quarter of the time for the Eternal D6, then a poof. +// The D6's wisps for Book of Virtues are not written yet. +static void pedestal_reroll(ItemUse& use, Entity_Pickup& pickup) +{ + constexpr int ETERNAL_D6_RNG_SHIFT = 44; + constexpr float ETERNAL_D6_EMPTY_CHANCE = 0.25f; + + bool isEmptied = false; + if (use.id == COLLECTIBLE_ETERNAL_D6) + { + RNG rng = rng_make(pickup.dropRNG._seed, ETERNAL_D6_RNG_SHIFT); + isEmptied = rng.RandomFloat() <= ETERNAL_D6_EMPTY_CHANCE; + } + if (isEmptied) + { + pickup.empty_pedestal(); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the Eternal D6 in a deathmatch)"); + } + else + { + pickup.Morph(pickup.type, pickup.variant, 0, true, false, false); + pickup.isTouched = false; + if (use.player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed && use.id == COLLECTIBLE_D6) + reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the D6's wisps)"); + } + g_game->Spawn({.position = pickup.pos, .type = ENTITY_EFFECT, .variant = ACTIVE_EFFECT_POOF, .seed = Random()}); +} + +// The D6 and the Eternal D6: every pedestal item of the room rerolled. static void d6_use(ItemUse& use) { Entity_Player& player = use.player; @@ -949,7 +975,7 @@ static void d6_use(ItemUse& use) Entity_Pickup* pickup = static_cast(entity); if (pickup->CanReroll() && (pickup->optionsPickupIndex == 0 || pickup->timeout < 0)) - reconstruction_missing("Entity_Pickup::Morph 006e30a0 (the D6's reroll)"); + pedestal_reroll(use, *pickup); } if (use.id == COLLECTIBLE_ETERNAL_D6 && player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the Eternal D6's wisps)"); @@ -1007,6 +1033,8 @@ static void item_effect_run(ItemUse& use) return book_of_belial_use(use); case COLLECTIBLE_POOP: return poop_use(use); + case COLLECTIBLE_MR_BOOM: + return mr_boom_use(use); case COLLECTIBLE_TAMMYS_HEAD: return tammys_head_use(use); case COLLECTIBLE_MOMS_BRA: @@ -1290,3 +1318,131 @@ void Entity_Player::ControlActiveItem(int slot) if (AreControlsEnabled() && isTriggered) active_trigger(*this, slot); if (slot == ACTIVE_SLOT_PRIMARY) bulbs_update(*this, chargeBefore, slot); } + +// The actives whose temporary effect the plain frame, stats and tears are written for: the first floor's actives that +// leave one. Book of Belial and Razor Blade change the damage and tears, which are not written for effects yet. +bool is_temporary_effect_plain(const TemporaryEffect& effect) +{ + constexpr int PLAIN_EFFECT_ITEMS[] = {COLLECTIBLE_BIBLE, + COLLECTIBLE_POOP, + COLLECTIBLE_MR_BOOM, + COLLECTIBLE_TAMMYS_HEAD, + COLLECTIBLE_MOMS_BRA, + COLLECTIBLE_KAMIKAZE, + COLLECTIBLE_TELEPORT, + COLLECTIBLE_YUM_HEART, + COLLECTIBLE_LEMON_MISHAP, + COLLECTIBLE_BOOK_OF_REVELATIONS, + COLLECTIBLE_D6, + COLLECTIBLE_SPIDER_BUTT, + COLLECTIBLE_ETERNAL_D6}; + + return effect.item->IsCollectible() && + std::ranges::find(PLAIN_EFFECT_ITEMS, effect.item->id) != std::end(PLAIN_EFFECT_ITEMS); +} + +// 007da7a0 Whether an active slot's item stays when another active is taken from a pedestal: an empty or unknown +// item, the unused ids, and the books Book of Virtues and Judas's Birthright put in the slot. +bool is_active_slot_kept(Entity_Player& player, int slot) +{ + if (slot >= ACTIVE_SLOT_COUNT) return true; + + int item = player.activeItems[slot].item; + bool isUnused = std::ranges::find(UNUSED_COLLECTIBLES, item) != std::end(UNUSED_COLLECTIBLES); + bool isBook = item == COLLECTIBLE_BOOK_OF_VIRTUES || item == COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE; + return item == 0 || item >= (int)g_manager->itemConfig.collectibles.size() || isUnused || + !g_manager->itemConfig.GetCollectible(item) || isBook; +} + +// The active part of 0075f0e0: the item takes its slot (the Schoolbag first moves the first slot's item to an empty +// second), dropping the book Book of Virtues or Judas's Birthright put there, and any other item there is no longer +// owned. It starts with its given charge, its initial charge for a negative one, or full. Its stats count only with a +// passive cache, and the bulb trinkets reread them. The item pool AddCollectible does not take is not kept. +void active_collectible_add(Entity_Player& player, ItemConfig_Item& item, const ActiveGain& gain) +{ + int charge = gain.charge; + if (charge < 0) charge = item.initCharge; + if (charge < 0) charge = player.GetCollectibleMaxCharge(gain.item, gain.varData); + + ActiveItemDesc& active = player.activeItems[gain.slot]; + if (active.item == COLLECTIBLE_BOOK_OF_VIRTUES || active.item == COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) active.item = 0; + bool isSchoolbagMove = gain.slot == ACTIVE_SLOT_PRIMARY && player.HasCollectible(COLLECTIBLE_SCHOOLBAG) && + player.activeItems[ACTIVE_SLOT_SECONDARY].item == 0; + if (isSchoolbagMove) std::swap(player.activeItems[ACTIVE_SLOT_PRIMARY], player.activeItems[ACTIVE_SLOT_SECONDARY]); + if (active.item < 0) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (replacing a procedural active)"); + if (active.item > 0) + player.collectibleCounts[active.item] = std::max(player.collectibleCounts[active.item] - 1, 0); + + active.item = gain.item; + active.batteryCharge = 0; + active.varData = gain.varData; + player.SetActiveCharge(charge, gain.slot); + active.subCharge = 0; + active.partialCharge = 0; + if (player.itemState == 0) + { + player.ResetItemState(); + player.isActiveUsed = false; + player.itemHoldCooldown = ACTIVE_PICKUP_HOLD_FRAMES; + } + + if (item.isPassiveCache) player.cacheFlags |= item.cacheFlags; + if (!player.HasTrinket(TRINKET_DIM_BULB) && !player.HasTrinket(TRINKET_VIBRANT_BULB)) return; + player.cacheFlags |= BULB_CACHE_FLAGS; + player.EvaluateItems(); +} + +// The active part of 006e8ae0: the item held up is added first, then the first slot's active (the Schoolbag needs +// both slots filled) goes onto the pedestal with its charge and data, its pickup turned over in place. A pedestal by a +// door moves off it. Whether the items were exchanged. +bool active_pedestal_swap(Entity_Pickup& pickup, Entity_Player& player) +{ + player.FlushQueueItem(); + ActiveItemDesc held = player.activeItems[ACTIVE_SLOT_PRIMARY]; + bool isFirstKept = !ItemConfig::IsValidCollectible(held.item) || is_active_slot_kept(player, ACTIVE_SLOT_PRIMARY); + bool isSecondKept = player.HasCollectible(COLLECTIBLE_SCHOOLBAG) && + (!ItemConfig::IsValidCollectible(player.activeItems[ACTIVE_SLOT_SECONDARY].item) || + is_active_slot_kept(player, ACTIVE_SLOT_SECONDARY)); + if (isFirstKept || isSecondKept) return false; + + pickup.subtype = held.item; + player.RemoveCollectible(held.item, false, ACTIVE_SLOT_PRIMARY, false); + pickup.Morph(pickup.type, pickup.variant, pickup.subtype, false, true, true); + pickup.charge = held.batteryCharge + held.charge; + pickup.varData = held.varData; + pickup.UpdateSprite(true); + + auto isNear = [&](GridEntity_Door* door) + { + float near = PEDESTAL_DOOR_NEAR * PEDESTAL_DOOR_NEAR; + return door && vector_length_squared(vector_sub(door->Position(), player.pos)) < near; + }; + if (std::ranges::any_of(g_game->room->doors, isNear)) pickup.gridRepositionState = 1; + return true; +} + +// The battery part of 006e8ae0: a battery charges the first active slot that takes it (a normal or timed one), six +// charges for a lil' or golden battery and two for a micro one, while a mega battery overcharges every slot twice +// over. Whether it was taken. The golden battery's own effect is not written yet. +bool battery_collect(Entity_Pickup& battery, Entity_Player& player) +{ + bool isMega = battery.subtype == BATTERY_MEGA; + bool isTaken = false; + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(player.activeItems[slot].item); + int maxCharge = player.GetActiveMaxCharge(slot); + ChargeType chargeType = active_charge_type(player, slot); + if (!item || (chargeType != CHARGE_NORMAL && chargeType != CHARGE_TIMED)) continue; + + int charge = isMega ? maxCharge * 2 : battery.subtype == BATTERY_MICRO ? BATTERY_MICRO_CHARGE : BATTERY_CHARGE; + if (player.AddActiveCharge(charge, slot, true, isMega, false) == 0) continue; + isTaken = true; + if (!isMega) break; + } + if (!isTaken) return false; + + g_manager->persistentGameData.IncreaseEventCounter(EVENT_BATTERIES_COLLECTED, 1); + if (battery.subtype == BATTERY_GOLDEN) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0 (a golden battery)"); + return true; +} diff --git a/src/entity_player_bombs.cpp b/src/entity_player_bombs.cpp index b34e6ba..f69ca21 100644 --- a/src/entity_player_bombs.cpp +++ b/src/entity_player_bombs.cpp @@ -14,16 +14,12 @@ // The items a player's bombs ask about (Lua's CollectibleType and TrinketType). constexpr int COLLECTIBLE_BOBBY_BOMB = 125; -constexpr int COLLECTIBLE_BOBS_CURSE = 140; constexpr int COLLECTIBLE_BUTT_BOMBS = 209; constexpr int COLLECTIBLE_SAD_BOMBS = 220; -constexpr int COLLECTIBLE_HOT_BOMBS = 256; -constexpr int COLLECTIBLE_STRANGE_ATTRACTOR = 315; constexpr int COLLECTIBLE_BOMBER_BOY = 353; constexpr int COLLECTIBLE_SCATTER_BOMBS = 366; constexpr int COLLECTIBLE_STICKY_BOMBS = 367; constexpr int COLLECTIBLE_MR_MEGA = 106; -constexpr int COLLECTIBLE_BLACK_POWDER = 420; constexpr int COLLECTIBLE_GLITTER_BOMBS = 432; constexpr int COLLECTIBLE_FAST_BOMBS = 517; constexpr int COLLECTIBLE_NANCY_BOMBS = 563; @@ -49,7 +45,6 @@ constexpr std::array SHORT_FUSE_DAMAGE = {15.000001f, 30.000002f, 50}; constexpr int BOMBS_MAX = 99; constexpr int CONSUMABLE_BOMBS = 1 << 2; constexpr int CONSUMABLE_GIGA_BOMBS = 1 << 6; -constexpr int SOUND_FETUS_LAND = 40; constexpr int SOUND_GLITTER_FUSE = 867; constexpr int PLACE_SOUND_DELAY = 4; diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp new file mode 100644 index 0000000..dc877e7 --- /dev/null +++ b/src/entity_player_collectibles.cpp @@ -0,0 +1,243 @@ +#include "entity_player.h" +#include "active_items.h" +#include "entity_config.h" +#include "entity_pickup.h" +#include "game.h" +#include "hud.h" +#include "log.h" +#include "manager.h" +#include + +// The collectibles and null items losing an item names (Lua's CollectibleType and NullItemID). +enum RemovalItem : int +{ + REMOVAL_MAGIC_MUSHROOM = 12, + REMOVAL_NECRONOMICON = 35, + REMOVAL_DEAD_CAT = 81, + REMOVAL_MISSING_PAGE_2 = 262, + REMOVAL_LEO = 302, + REMOVAL_MARS = 593, + REMOVAL_DOUBLED_COSTUME_A = 665, + REMOVAL_HEARTBREAK = 694, + REMOVAL_DOUBLED_COSTUME_B = 730, + REMOVAL_KEY_PIECE_1 = 238, + REMOVAL_KEY_PIECE_2 = 239, + REMOVAL_KNIFE_PIECE_1 = 626, + REMOVAL_KNIFE_PIECE_2 = 627, + REMOVAL_VOID = 477, + REMOVAL_BINGE_EATER = 664, + + NULLITEM_BRIMSTONE_TWICE = 45, + NULLITEM_MARS_DASH = 58, + NULLITEM_DOUBLED_A = 125, + NULLITEM_DOUBLED_B = 126 +}; + +// The collectibles whose loss does more than the counts: pockets and trinkets dropped for want of room, Mom's Box, +// The Jar, Purity, Greed's Gullet, Rock Bottom and Red Key. +constexpr int REMOVAL_EFFECT_ITEMS[] = {139, 251, 252, 290, 407, 416, 439, 454, 458, 501, 562, 580}; + +// The collectibles whose effect ends with more than its costume: Hourglass, My Little Unicorn, Gamekid, Dead Bird, +// How to Jump, Unicorn Stump, Taurus, Purity, Camo Undies, Wavy Cap, Mega Mush, Berserk, Dark Arts and the rest. +constexpr int EFFECT_END_ITEMS[] = {66, 77, 93, 117, 282, 298, 299, 409, 497, 582, 610, 625, 704, 705}; + +constexpr int DEAD_CAT_LIVES_PER_COPY = 9; +constexpr int HEARTBREAK_BROKEN_HEARTS = 3; +constexpr int PLAYER_FORM_LEO = 13; + +// 00721b70 Takes an item out of the history: the first entry of the same kind and id, Tainted Isaac's inventory +// following. A locked history keeps its items. Whether one was removed. +bool history_item_remove(History& history, const HistoryItem& item) +{ + if (history.isLocked) return false; + + std::vector& items = history.historyItems; + auto found = std::ranges::find_if(items, [&](HistoryItem& other) + { return other.isTrinket == item.isTrinket && other.id == item.id; }); + bool isRemoved = found != items.end(); + if (isRemoved) history.remove_index_refs((int)(items.erase(found) - items.begin())); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + return isRemoved; +} + +// 007220a0 Tainted Isaac's inventory forgets a history index: its slot empties, later indices move down and the filled +// slots close up in order. +void History::remove_index_refs(int index) +{ + std::array& inventory = player->inventory; + + for (int& entry : inventory) + { + if (entry == index) entry = -1; + else if (index < entry) entry--; + } + std::ranges::stable_partition(inventory, [](int entry) { return entry >= 0; }); +} + +// 007a4760 Swaps the first two active slots when the second holds an item, putting away any item state, and has the +// HUD reload them. The bulb trinkets reread the stats. +void Entity_Player::SwapActiveItems() +{ + + if (activeItems[ACTIVE_SLOT_SECONDARY].item == 0) return; + + ResetItemState(); + itemStateCooldown = 0; + std::swap(activeItems[ACTIVE_SLOT_PRIMARY], activeItems[ACTIVE_SLOT_SECONDARY]); + itemHoldCooldown = 0; + if (HasTrinket(TRINKET_DIM_BULB) || HasTrinket(TRINKET_VIBRANT_BULB)) + { + cacheFlags |= BULB_CACHE_FLAGS; + EvaluateItems(); + } + g_game->hud.InvalidateActiveItem(this, -1); +} + +// 0078ff90 What losing a collectible undoes: Leo's and Magic Mushroom's count towards their form, Dead Cat's lives, and +// Heartbreak's broken hearts. With the last copy gone, the Missing Pages count drops, and an effect that clears on +// removal ends. Netplay's stats are offline. +void Entity_Player::TriggerCollectibleRemoved(int collectibleId) +{ + if (collectibleId == REMOVAL_MAGIC_MUSHROOM || collectibleId == REMOVAL_LEO) + IncrementPlayerFormCounter(PLAYER_FORM_LEO, -1); + else if (collectibleId == REMOVAL_DEAD_CAT) + deadCatLives = (short)std::min(deadCatLives, GetCollectibleNum(REMOVAL_DEAD_CAT) * DEAD_CAT_LIVES_PER_COPY); + else if (collectibleId == REMOVAL_HEARTBREAK) AddBrokenHearts(-HEARTBREAK_BROKEN_HEARTS); + + if (GetCollectibleNum(collectibleId) <= 0) + { + if (collectibleId == REMOVAL_NECRONOMICON || collectibleId == REMOVAL_MISSING_PAGE_2) + IncrementPlayerFormCounter(PLAYER_FORM_MISSING_PAGES, -1); + if (std::ranges::find(REMOVAL_EFFECT_ITEMS, collectibleId) != std::end(REMOVAL_EFFECT_ITEMS)) + reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90 (an item that made room)"); + } + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (temporaryEffects.HasCollectibleEffect(collectibleId) && item && item->isClearEffectsOnRemove) + temporaryEffects.RemoveCollectibleEffect(collectibleId, 1); +} + +// The costume a lost item wears in place of its own for a second copy, while fewer than two copies are left. +static void doubled_costume_remove(Entity_Player& player, int collectibleId) +{ + struct DoubledCostume + { + int item = 0; + int nullItem = 0; + }; + constexpr DoubledCostume DOUBLED_COSTUMES[] = {{COLLECTIBLE_BRIMSTONE, NULLITEM_BRIMSTONE_TWICE}, + {REMOVAL_DOUBLED_COSTUME_A, NULLITEM_DOUBLED_A}, + {REMOVAL_DOUBLED_COSTUME_B, NULLITEM_DOUBLED_B}}; + + for (const DoubledCostume& doubled : DOUBLED_COSTUMES) + if (doubled.item == collectibleId && player.GetCollectibleNum(collectibleId) < 2) + player.RemoveCostume(g_manager->itemConfig.GetNullItem(doubled.nullItem)); +} + +// 00793970 An item's temporary effect ran out or was taken: a collectible's costume comes off unless the item keeps +// it, the doubled ones with it. The items whose end does more, and trinket and null item effects, are not written yet. +void Entity_Player::trigger_collectible_effect_removed(ItemConfig_Item* item, int) +{ + if (!item->IsCollectible()) + reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970 (a trinket or null effect)"); + doubled_costume_remove(*this, item->id); + if (std::ranges::find(EFFECT_END_ITEMS, item->id) != std::end(EFFECT_END_ITEMS)) + reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970 (an item's own end)"); + TryRemoveCollectibleCostume(item->id, true); +} + +// 0078f840 Takes a collectible from the player: a voided active leaves the Void, a helper's item goes from its +// backup, an active only from a slot (the first slot empties into the second). The count, the costumes, the +// transformations and the history follow, and the stats are evaluated again. +void Entity_Player::RemoveCollectible(int type, bool isIgnoreModifiers, int activeSlot, bool isRemoveFromForm) +{ + ItemConfig& items = g_manager->itemConfig; + ItemConfig_Item* item = items.GetCollectible(type); + if (type == 0 || !item) return; + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) InvalidateCoPlayerItems(); + + bool isActive = item->type == ITEM_ACTIVE; + if (!isIgnoreModifiers) + { + auto voided = std::ranges::find(voidedCollectibles, type); + bool isVoidUse = activeSlot < 0 || GetActiveItem(activeSlot) == REMOVAL_VOID; + if (isActive && isVoidUse && voided != voidedCollectibles.end()) + { + log_printf(LOG_INFO, "Removing voided collectible %d (%s) from player %d (%s)\n", type, + item->GetLocalizedName().c_str(), playerIndex, name.c_str()); + voidedCollectibles.erase(voided); + cacheFlags |= item->cacheFlags; + return EvaluateItems(); + } + if (isValid && backupPlayer && backupPlayer->HasCollectible(type, ITEM_CHECK_OWNED) && !isActive) + { + backupPlayer->RemoveCollectible(type, false, 0, true); + bool isPieceItem = type == REMOVAL_KEY_PIECE_1 || type == REMOVAL_KEY_PIECE_2 || + type == REMOVAL_KNIFE_PIECE_1 || type == REMOVAL_KNIFE_PIECE_2; + if (!isPieceItem) return; + cacheFlags |= item->cacheFlags; + return EvaluateItems(); + } + } + if (isActive && (activeSlot < 0 || activeSlot >= ACTIVE_SLOT_COUNT)) return; + + log_printf(LOG_INFO, "Removing collectible %d (%s) from player %d (%s)\n", type, item->GetLocalizedName().c_str(), + playerIndex, name.c_str()); + if (type < 0) reconstruction_missing("Entity_Player::RemoveCollectible 0078f840 (a procedural item)"); + if (collectibleCounts[type] >= 1) collectibleCounts[type]--; + else if (!proceduralItems.empty()) + reconstruction_missing("Entity_Player::RemoveCollectible 0078f840 (the procedural item copying it)"); + + bool isSlotGiven = activeSlot >= 0 && activeSlot < ACTIVE_SLOT_COUNT && activeItems[activeSlot].item == type; + int first = isSlotGiven ? activeSlot : 0; + int end = isSlotGiven ? activeSlot + 1 : ACTIVE_SLOT_COUNT; + for (int slot = first; slot < end; slot++) + { + if (activeItems[slot].item != type) continue; + activeItems[slot].batteryCharge = 0; + activeItems[slot].item = 0; + if (slot == ACTIVE_SLOT_PRIMARY) SwapActiveItems(); + } + + TriggerCollectibleRemoved(type); + doubled_costume_remove(*this, type); + if (collectibleCounts[type] < 1) + { + if (item->isAddCostumeOnPickup && !HasCollectible(type)) RemoveCostume(item); + if (type == REMOVAL_MARS) RemoveCostume(items.GetNullItem(NULLITEM_MARS_DASH)); + } + + if (isRemoveFromForm) + { + int formCount = std::min((int)items.playerForms.size(), PLAYER_FORM_SLOTS); + for (int form = 0; form < formCount; form++) + if (items.playerForms[form] && items.playerForms[form]->tags != 0 && + item->HasTags(items.playerForms[form]->tags)) + IncrementPlayerFormCounter(form, -1); + } + + history_item_remove(history, {.time = g_game->frameCount, .isTrinket = false, .id = type}); + cacheFlags |= item->cacheFlags; + if (HasCollectible(REMOVAL_BINGE_EATER) && item->HasTags(TAG_FOOD)) + cacheFlags |= items.GetCollectible(REMOVAL_BINGE_EATER)->cacheFlags; + EvaluateItems(); + UpdateBookOfVirtues(false); +} + +// 007ab380 Holds a collectible up over the head: the pedestal's sprite showing the item plays its animation (left +// alone when it already shows it), lifted a little, while the player plays its own. +void Entity_Player::AnimateCollectible(int collectibleId, std::string_view animName, std::string_view spriteAnimName) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (!item) return; + + heldSprite.Reset(); + EntityConfig_Entity* pedestal = g_manager->entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_COLLECTIBLE, 0); + heldSprite.Load(pedestal->anm2Path, GRAPHICS_DEFER); + if (collectibleId < 0) reconstruction_missing("Entity_Player::AnimateCollectible 007ab380 (a procedural item)"); + heldSprite.ReplaceSpritesheet(1, item->gfxFilename); + heldSprite.LoadGraphics(); + heldSprite.Play(spriteAnimName); + heldSprite.offset = vector_make(0, HELD_SPRITE_RISE); + PlayExtraAnimation(animName); +} diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index e79ec3c..8c1c169 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -11,39 +11,19 @@ #include constexpr int COLLECTIBLE_BINKY = 438; -constexpr int COLLECTIBLE_BOBS_CURSE = 140; -constexpr int COLLECTIBLE_BOOMERANG = 338; constexpr int COLLECTIBLE_CONE_HEAD = 457; -constexpr int COLLECTIBLE_DOGMA = 633; constexpr int COLLECTIBLE_DULL_RAZOR = 486; constexpr int COLLECTIBLE_EVIL_CHARM = 632; -constexpr int COLLECTIBLE_GLASS_CANNON = 352; -constexpr int COLLECTIBLE_HOST_HAT = 375; -constexpr int COLLECTIBLE_HOT_BOMBS = 256; constexpr int COLLECTIBLE_HYPERCOAGULATION = 724; -constexpr int COLLECTIBLE_INNER_CHILD = 688; -constexpr int COLLECTIBLE_IPECAC = 149; -constexpr int COLLECTIBLE_ISAACS_HEART = 276; constexpr int COLLECTIBLE_JELLY_BELLY = 690; -constexpr int COLLECTIBLE_LARYNX = 611; constexpr int COLLECTIBLE_MARBLES = 538; constexpr int COLLECTIBLE_METAL_PLATE = 449; -constexpr int COLLECTIBLE_MOMS_BRACELET = 604; constexpr int COLLECTIBLE_PLUTO = 598; -constexpr int COLLECTIBLE_PYROMANIAC = 223; constexpr int COLLECTIBLE_SCAPULAR = 142; -constexpr int COLLECTIBLE_SHOOP_DA_WHOOP = 49; constexpr int COLLECTIBLE_SPIRIT_SHACKLES = 674; -constexpr int COLLECTIBLE_ASTRAL_PROJECTION = 677; -constexpr int COLLECTIBLE_BERSERK = 704; -constexpr int COLLECTIBLE_BLACK_CANDLE = 260; -constexpr int COLLECTIBLE_THE_NAIL = 83; constexpr int TRINKET_BLIND_RAGE = 81; -constexpr int TRINKET_CALLUS = 14; constexpr int TRINKET_CROW_HEART = 107; constexpr int TRINKET_FINGER_BONE = 128; -constexpr int TRINKET_MONKEY_PAW = 20; -constexpr int TRINKET_PERFECTION = 145; constexpr int TRINKET_SWALLOWED_M80 = 178; constexpr int TRINKET_WALNUT = 108; constexpr int NULLITEM_BOOMERANG = 30; @@ -62,18 +42,13 @@ constexpr int HIT_TRINKETS[] = {40, 48, 29, 1, 8, 67, 158, 97, 105, 33, 104, 122 constexpr int CROWN_OF_LIGHT = 415; constexpr int HYPERCOAGULATION_IGNORED = 0x10040000; -constexpr int ENTITY_MOM = 45; -constexpr int ENTITY_MOMS_HEART = 78; -constexpr int ENTITY_BISHOP = 805; constexpr int ENTITY_SEGMENTED_WORM = 903; constexpr int ENTITY_DAMAGE_RELAY = 966; constexpr int SEGMENTED_WORM_VARIANT = 10; constexpr int WHITE_FIRE_VARIANT = 4; constexpr int EFFECT_SELF_DAMAGE = 19; constexpr int EFFECT_POISON_CLOUD = 123; -constexpr int FAMILIAR_WISP = 206; constexpr int ITEM_STATE_HOLD_STILL = 47; -constexpr int ENEMY_TYPE_FIRST = 10; constexpr int ENEMY_TYPE_LAST = 999; constexpr int BABY_GHOST = 59; constexpr int BABY_HALO = 24; @@ -90,8 +65,6 @@ constexpr int ULTRA_GREED = 406; constexpr int ULTRA_GREED_DOOR = 294; constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; -constexpr int SOUND_FIREDEATH_HISS = 43; -constexpr int SOUND_ISAAC_HURT_GRUNT = 55; constexpr int SOUND_NAIL_HURT_1 = 104; constexpr int SOUND_NAIL_HURT_2 = 106; constexpr int SOUND_MOM_VOX = 84; @@ -102,7 +75,6 @@ constexpr int SOUND_FRAME_DELAY = 2; constexpr uint64_t DAMAGE_RED_HEARTS = 1ull << 5; constexpr uint64_t DAMAGE_INVINCIBLE_IGNORED = 1ull << 13; -constexpr uint64_t DAMAGE_SPAWN_FLY = 1ull << 14; constexpr uint64_t DAMAGE_FAKE = 1ull << 21; constexpr uint64_t DAMAGE_NO_MODIFIERS = 1ull << 25; constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; @@ -112,7 +84,6 @@ constexpr uint64_t DAMAGE_NO_HURT_EFFECTS = 0x100d0400; constexpr uint64_t DAMAGE_ISAACS_HEART_PIERCE = 0x2820; constexpr uint64_t DAMAGE_UNPENALIZED = DAMAGE_NO_PENALTIES | DAMAGE_RED_HEARTS; -constexpr int LEVEL_STATE_DAMAGED = 5; constexpr int LAST_DAMAGE_STAGE_MAX = 13; constexpr int HURT_FRAMES_PER_HEART = 60; constexpr int HURT_HEARTS_MAX = 2; @@ -152,7 +123,6 @@ constexpr int EVIL_CHARM_GRID_VARIANT = 10000; // The temporary effects that make the player invincible to any hit: Gamekid, My Little Unicorn, Unicorn Stump and // Teleport. constexpr int INVINCIBLE_EFFECTS[] = {93, 77, 298, 44}; -constexpr int COLLECTIBLE_BREATH_OF_LIFE = 326; constexpr int COLLECTIBLE_DARK_ARTS = 705; constexpr int COLLECTIBLE_GNAWED_LEAF = 210; constexpr int NULLITEM_INVINCIBLE_SHIELD = 59; @@ -204,7 +174,7 @@ static bool is_wisp_shield_present(Entity_Player& player) { return std::ranges::any_of(g_game->room->entityList.updateEL, [&](Entity* entity) { - return !entity->isDead && entity->IsFamiliar() && entity->variant == FAMILIAR_WISP && + return !entity->isDead && entity->IsFamiliar() && entity->variant == Entity_Familiar::WISP && entity->subtype == COLLECTIBLE_DULL_RAZOR && static_cast(entity)->player == &player; }); @@ -456,7 +426,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Magdalene's damage taken)"); totalDamageTaken += amount; } - if (source.type >= ENEMY_TYPE_FIRST && source.type <= ENEMY_TYPE_LAST) + if (source.type >= ENTITY_FIRST_ENEMY && source.type <= ENEMY_TYPE_LAST) bestiary_count_add(g_manager->persistentGameData.bestiary.hits, source.type, source.variant); if (game.debugFlags & DEBUG_DAMAGE_VALUES) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (spawn_debug_damage_text)"); @@ -486,7 +456,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR { Entity* entity = game.room->entityList.updateEL[i]; if (entity->IsFamiliar() && static_cast(entity)->player == this) - reconstruction_missing("Entity_Familiar::trigger_player_damage 0062b750"); + static_cast(entity)->trigger_player_damage({source, damage, damageFlags}); else if (!entity->IsFamiliar() && entity->IsEnemy()) static_cast(entity)->on_player_damaged(); } @@ -582,9 +552,9 @@ void Entity_Player::death_count(const EntityRef& source, uint64_t damageFlags) { PersistentGameData_Bestiary& bestiary = g_manager->persistentGameData.bestiary; - if (source.type >= ENEMY_TYPE_FIRST && source.type <= ENEMY_TYPE_LAST) + if (source.type >= ENTITY_FIRST_ENEMY && source.type <= ENEMY_TYPE_LAST) bestiary_count_add(bestiary.deaths, source.type, source.variant); - else if (source.spawnerType >= ENEMY_TYPE_FIRST && source.spawnerType <= ENEMY_TYPE_LAST) + else if (source.spawnerType >= ENTITY_FIRST_ENEMY && source.spawnerType <= ENEMY_TYPE_LAST) bestiary_count_add(bestiary.deaths, source.spawnerType, (int)source.spawnerVariant); if ((damageFlags & DAMAGE_EXPLOSION) && source.type == ENTITY_TEAR && source.entity) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the achievement for dying to Ipecac)"); diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index 8bf1711..fe0ee63 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -13,63 +13,31 @@ #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; @@ -345,7 +313,7 @@ void Entity_Player::room_exit(bool isKeepHolyMantle) 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 && + return isOwned && entity->variant == Entity_Familiar::BLOOD_BABY && entity->subtype != CLOT_SUBTYPE_UNCOUNTED && !entity->isDead; }; EntityList_EL& persistent = game.room->entityList.persistentEL; @@ -478,7 +446,7 @@ 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); + for (int sound : {SOUND_SPLATTER, SOUND_TEAR_IMPACTS}) 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); @@ -486,7 +454,8 @@ void Entity_Player::preload_item_sounds() 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); + sfx.Preload(SOUND_BEEP); + sfx.Preload(SOUND_ITEMRECHARGE); if (HasCollectible(COLLECTIBLE_BATTERY) || HasTrinket(TRINKET_AAA_BATTERY)) sfx.Preload(SOUND_BATTERYCHARGE); } if (HasCollectible(COLLECTIBLE_POOP)) sfx.Preload(SOUND_FART); @@ -527,7 +496,7 @@ void Entity_Player::spawn_locusts() for (int i = 0; i < count; i++) { EntitySpawn spawn = {.position = pos, .spawner = this, .subType = subType, .type = ENTITY_FAMILIAR, - .variant = FAMILIAR_BLUE_FLY, .seed = Random()}; + .variant = Entity_Familiar::BLUE_FLY, .seed = Random()}; Entity* locust = g_game->Spawn(spawn); locust->ClearEntityFlags(FLAG_APPEAR); } diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index a3f034d..48ce093 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "active_items.h" #include "entity_familiar.h" #include "entity_tear.h" #include "game.h" @@ -69,9 +70,6 @@ constexpr std::array EVALUATION_UNHANDLED_ITEMS = {671, 686, 240, 304, constexpr std::array WEAPON_ITEMS = {329, 395, 579, 678, 52, 68, 114, 118, 168, 229}; // The constants of the other sections: the collectibles, trinkets, null items and characters they ask about. -constexpr int COLLECTIBLE_BINGE_EATER = 664; -constexpr int COLLECTIBLE_PASSIVE_DAMOCLES = 656; -constexpr int PLAYER_FORM_SPIDER_BABY = 12; constexpr int PILL_TEARS_UP = 16; constexpr int PILL_LARGER = 32; constexpr int PILL_SMALLER = 33; @@ -81,29 +79,11 @@ constexpr int BABY_SKIN_SPOON = 4; constexpr int BABY_SKIN_BONE = 57; constexpr int BABY_SKIN_GHOST_A = 58; constexpr int BABY_SKIN_GHOST_B = 59; -constexpr int TRINKET_AZAZELS_STUMP = 162; -constexpr int NULLITEM_BLOODY_BABYLON = 110; constexpr int NULLITEM_SPIRIT_SHACKLES_SOUL = 101; constexpr int NULLITEM_REVERSE_DEVIL = 67; -constexpr int NULLITEM_ESAU_JR = 100; constexpr int NULLITEM_HUGE_GROWTH = 41; constexpr int COLLECTIBLE_SPIRIT_SWORD = 579; -constexpr int COLLECTIBLE_C_SECTION = 678; -constexpr int COLLECTIBLE_EPIC_FETUS = 168; -constexpr int COLLECTIBLE_MOMS_KNIFE = 114; -constexpr int COLLECTIBLE_HAEMOLACRIA = 531; -constexpr int COLLECTIBLE_MONSTROS_LUNG = 229; -constexpr int COLLECTIBLE_DR_FETUS = 52; -constexpr int COLLECTIBLE_TECH_X = 395; -constexpr int COLLECTIBLE_TECHNOLOGY = 68; -constexpr int COLLECTIBLE_LUDOVICO = 329; -constexpr int COLLECTIBLE_BERSERK = 704; -constexpr int COLLECTIBLE_SPIRIT_SHACKLES = 677; -constexpr int COLLECTIBLE_ANTI_GRAVITY = 222; constexpr int COLLECTIBLE_2SPOOKY = 554; -constexpr int COLLECTIBLE_VIRUS = 13; -constexpr int COLLECTIBLE_TOXIC_SHOCK = 350; -constexpr int COLLECTIBLE_LUSTY_BLOOD = 411; constexpr int SPRITE_SCALE_UNLOCK = 3; constexpr int ACHIEVEMENT_HUGE = 361; constexpr float SIZE_STEP = 0.322f; @@ -119,8 +99,6 @@ constexpr float BERSERK_CHARGE_FULL = 100000; constexpr float HOLOGRAM_ALPHA = 0.2f; constexpr float COLOR_OFFSET_UNIT = 0.003921569f; constexpr float HELD_THROW_SCALE = 0.1f; -constexpr int COLLECTIBLE_MOMS_BRACELET = 604; -constexpr int COLLECTIBLE_SUPLEX = 709; // Whether the player owns any of the listed collectibles. static bool is_owning_any(Entity_Player& player, std::span collectibles) @@ -128,30 +106,22 @@ static bool is_owning_any(Entity_Player& player, std::span collectibl 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). +// Whether the character and run are ones the evaluation is reconstructed for (see EVALUATION_UNHANDLED_ITEMS), with +// only the temporary effects of the actives written for them. 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() && + !game.deathmatchManager.is_active() && + std::ranges::all_of(temporaryEffects.effects, is_temporary_effect_plain) && trinkets == std::array{} && !isSmelted && proceduralItems.empty() && itemWispsList.empty(); } @@ -635,7 +605,7 @@ static bool is_spirit(Entity_Player& p) (p.babySkin == BABY_SKIN_GHOST_B || p.babySkin == BABY_SKIN_GHOST_A); return p.playerType == PLAYER_THELOST || p.playerType == PLAYER_THELOST_B || p.playerType == PLAYER_JACOB2_B || p.playerType == PLAYER_THESOUL || isGhostBaby || p.isCoopGhost || - effects.GetCollectibleEffectNum(COLLECTIBLE_SPIRIT_SHACKLES) == 1 || + effects.GetCollectibleEffectNum(COLLECTIBLE_ASTRAL_PROJECTION) == 1 || effects.HasNullEffect(NULLITEM_REVERSE_SUN) || effects.HasNullEffect(NULLITEM_SPIRIT_SHACKLES_SOUL) || effects.HasNullEffect(NULLITEM_LOST_CURSE); } @@ -813,7 +783,7 @@ static bool is_flying(Entity_Player& p) p.playerType == PLAYER_THESOUL; return isFlyingType || p.HasPlayerForm(3) || effects.HasCollectibleEffect(33) || effects.HasCollectibleEffect(20) || effects.HasCollectibleEffect(409) || effects.HasTrinketEffect(118) || p.HasPlayerForm(14) || - effects.GetCollectibleEffectNum(COLLECTIBLE_SPIRIT_SHACKLES) == 1 || + effects.GetCollectibleEffectNum(COLLECTIBLE_ASTRAL_PROJECTION) == 1 || effects.HasNullEffect(NULLITEM_REVERSE_SUN) || effects.HasNullEffect(NULLITEM_REVERSE_DEVIL) || effects.HasNullEffect(NULLITEM_ESAU_JR) || effects.HasNullEffect(NULLITEM_SPIRIT_SHACKLES_SOUL) || effects.HasNullEffect(NULLITEM_LOST_CURSE) || effects.HasTrinketEffect(TRINKET_AZAZELS_STUMP) || @@ -921,18 +891,6 @@ static void color_evaluate(Entity_Player& p) if (isSynced) p.ResetColor(); } -// The familiars section of 00763570, not written yet: it stops the game when an owned item, effect or trinket asks -// for familiars, and otherwise only hands the section to the mods. -static void familiars_check(Entity_Player& p) -{ - bool isAsked = is_cache_owned(p, CACHE_FAMILIARS) || !p.temporaryEffects.effects.empty() || - std::ranges::any_of(p.trinkets, [](uint32_t trinket) { return trinket != 0; }) || - p.numLeprosy > 0 || p.tonsilCount > 0 || p.potatoPeelerCounter > 0 || - p.potatoPeelerBandageCounter > 0 || p.HasPlayerForm(PLAYER_FORM_SPIDER_BABY); - if (isAsked) reconstruction_missing("Entity_Player::EvaluateItems 00763570 (familiars)"); - static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_FAMILIARS); -} - // The weapon the player's items and character give, before the pairs that cancel out. static WeaponType weapon_type_get(Entity_Player& p) { @@ -1019,7 +977,7 @@ void Entity_Player::EvaluateItems() if (cacheFlags & CACHE_TEARFLAG) tear_flags_evaluate(*this); if (cacheFlags & CACHE_TEARCOLOR) tear_color_evaluate(*this); if (cacheFlags & CACHE_FLYING) flying_evaluate(*this); - if ((cacheFlags & CACHE_FAMILIARS) && variant == PLAYER_VARIANT_PLAYER && isValid) familiars_check(*this); + if ((cacheFlags & CACHE_FAMILIARS) && variant == PLAYER_VARIANT_PLAYER && isValid) familiars_evaluate(*this); if (cacheFlags & CACHE_LUCK) luck_evaluate(*this, bonus); if ((cacheFlags & CACHE_SIZE) && variant == PLAYER_VARIANT_PLAYER) size_evaluate(*this); if (cacheFlags & CACHE_COLOR) color_evaluate(*this); @@ -1041,14 +999,8 @@ void Entity_Player::EvaluateItems() cacheFlags = 0; } -// The collectibles the frame (00782af0) and the tear parameters (007bf6c0) look at themselves, which their plain -// paths do not cover yet. +// The collectibles the frame (00782af0) looks at itself, which its plain path does 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() @@ -1056,9 +1008,3 @@ bool Entity_Player::is_frame_plain() return is_character_plain() && !is_owning_any(*this, FRAME_ITEMS) && !is_owning_any(*this, WEAPON_ITEMS) && !is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS); } - -// Whether the player's tears take their plain parameters: a plain character holding none of the tear items. -bool Entity_Player::is_tear_hit_plain() -{ - return is_frame_plain() && !is_owning_any(*this, TEAR_HIT_ITEMS); -} diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 793b1ae..f46e6a5 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -44,10 +44,8 @@ constexpr int SHOOT_HISTORY_SIZE = 3; constexpr int SPECIAL_DAILY_BUTTER_BEAN = 41; constexpr int SUPLEX_LANDING = 2; -constexpr int COLLECTIBLE_EPIPHORA = 368; constexpr int COLLECTIBLE_HOW_TO_JUMP = 282; constexpr int COLLECTIBLE_POINTY_RIB = 544; -constexpr int COLLECTIBLE_URN_OF_SOULS = 640; constexpr int TRINKET_TEARDROP_CHARM = 139; // The effects that stop the player shooting while on: Gamekid, My Little Unicorn and Unicorn Stump. constexpr int NO_SHOOT_EFFECTS[] = {93, 77, 298}; @@ -637,9 +635,30 @@ void Entity_Player::update_shooting() while (shootDirectionHistory.size() > SHOOT_HISTORY_SIZE) shootDirectionHistory.pop_front(); } +// The temporary effects' part of 00782af0: Mars' dash, a pony's charge and Recall ignore knockback, the stats are +// evaluated when the effects changed, and the timed ones count down. The items' frame (update_effects) is not reached +// by a plain player. +static void temporary_effects_update(Entity_Player& player) +{ + + TemporaryEffects& effects = player.temporaryEffects; + bool isDashing = effects.HasCollectibleEffect(COLLECTIBLE_MARS) || player.ponyCharge >= 1 || + effects.HasCollectibleEffect(COLLECTIBLE_RECALL); + if (isDashing) player.AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + else player.ClearEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + if (effects.isEvaluateCachePending) + { + player.cacheFlags |= effects.cacheFlags; + player.EvaluateItems(); + } + effects.isEvaluateCachePending = false; + if (!player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) effects.Update(); +} + // 00782af0 The player's frame. Only the frame of a plain character is reconstructed: the base entity moves it, it walks -// by its input, shoots, and its body animates. Items, effects, held and queued items, extra animations and the bomb, -// item, pocket and drop actions stop the game until reached. +// by its input, uses its bomb, active and pocket buttons, shoots, its temporary effects count down and its body +// animates. Items, effects the plain frame does not know, the held entity and the drop button stop the game until +// reached. void Entity_Player::Update() { if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; @@ -658,9 +677,8 @@ void Entity_Player::Update() if (isDead) return death_update(); if (!is_frame_plain() || heldEntity) reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and item animations)"); - for (ButtonAction action : {ACTION_PILL_CARD, ACTION_DROP}) - if (isControlsEnabled && action_value(action, controllerIndex) > 0) - reconstruction_missing("Entity_Player::Update 00782af0 (items, pockets and drop)"); + if (isControlsEnabled && action_value(ACTION_DROP, controllerIndex) > 0) + reconstruction_missing("Entity_Player::Update 00782af0 (items, pockets and drop)"); Entity::Update(); if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) @@ -672,10 +690,13 @@ void Entity_Player::Update() if (playerCostumeMap[layer].index >= 0) reconstruction_missing("Entity_Player::Update 00782af0 (body costumes following the walk)"); } + sprite_scale_update(); update_body_animations(); update_bomb_input(); ControlActiveItem(ACTIVE_SLOT_PRIMARY); + pocket_use_input(); update_shooting(); + temporary_effects_update(*this); walk_animation_update(); if (damageCooldown > 0) damageCooldown--; if (controlsCooldown > 0) controlsCooldown--; diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index 495a7b5..54a350a 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -1,6 +1,7 @@ #include "entity_player.h" #include "game.h" #include "manager.h" +#include constexpr int CONSUMABLE_MAX = 99; constexpr int DEEP_POCKETS_COIN_MAX = 999; @@ -742,8 +743,6 @@ void Entity_Player::charge_store_changed(int effectiveCharge, int oldCharge) { constexpr int SOUND_BATTERY_CHARGE = 171; constexpr int SOUND_ITEM_RECHARGE = 218; - constexpr uint32_t TRINKET_DIM_BULB = 100; - constexpr uint32_t TRINKET_VIBRANT_BULB = 101; constexpr int POCKET_SLOT = 3; constexpr int RED_KEY_SLOT = 2; diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 15d9bc4..a082215 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "active_items.h" #include "entity_familiar.h" #include "entity_pickup.h" #include "stage_transition.h" @@ -550,15 +551,10 @@ void Entity_Player::TriggerNewRoom_TemporaryEffects() } // 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_BLOOD_CLOT = 254; constexpr int COLLECTIBLE_RUBBER_CEMENT = 221; constexpr int COLLECTIBLE_COUNT_UNLOCK = 50; constexpr int ACHIEVEMENT_MANY_COLLECTIBLES = 330; -constexpr int ACHIEVEMENT_TEARS_UP_ITEMS = 378; -constexpr int TEARS_UP_UNLOCK_COUNT = 10; constexpr int EVENT_BLOOD_CLOT = 200; constexpr int EVENT_RUBBER_CEMENT = 201; constexpr int PILL_TEARS_UP = 16; @@ -583,7 +579,6 @@ constexpr TagUnlock STARS_UNLOCK = {TAG_STARS, 2, 406}; // The pickups, sounds and stand-ins the collectibles' own pickup effects (in 0075f0e0) use. constexpr int COIN_LUCKY_PENNY = 5; -constexpr int TRINKET_MATCH_STICK = 41; constexpr int SOUND_KISS_LIPS = 219; constexpr int SOUND_PEEPER_POP = 237; constexpr int DEAD_CAT_LIVES = 9; @@ -613,7 +608,6 @@ constexpr std::array CHAOS_PICKUPS = {PICKUP_TRINKET, PICKUP_P // The hearts Mr. Dolly rolls between. constexpr std::array DOLLY_HEARTS = {HEART_RED, HEART_SOUL, HEART_BLACK}; - // 007aa800 Whether the player may take a collectible now: not while the hold cooldown runs, and a helper player never // takes an active. bool Entity_Player::CanAddCollectible(int collectibleId) @@ -655,7 +649,6 @@ bool Entity_Player::IsItemQueueEmpty() // 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; @@ -772,9 +765,6 @@ void Entity_Player::UpdateBookOfVirtues(bool isAddedBookOfVirtues) // 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); @@ -1271,8 +1261,9 @@ static void collectible_late_effect_apply(Entity_Player& p, const CollectibleGai // 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 -// own pickup effect runs, its cache flags are evaluated, transformations count it, and its costume goes on. Book of -// Virtues takes its slot. Actives, procedural items and the pickup effects not written yet stop the game. +// own pickup effect runs, its cache flags are evaluated, transformations count it, and its costume goes on. An active +// takes its slot, and Book of Virtues an empty first one. Procedural items and the pickup effects not written yet stop +// the game. void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData) { Game& game = *g_game; @@ -1310,8 +1301,8 @@ void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int a if (isFirstTime) collectible_pickups_add(*item); } - if (item->type == ITEM_ACTIVE) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (an active item)"); - cacheFlags |= item->cacheFlags; + if (item->type == ITEM_ACTIVE) active_collectible_add(*this, *item, {type, charge, slot, varData}); + else cacheFlags |= item->cacheFlags; if (HasCollectible(COLLECTIBLE_BINGE_EATER) && item->HasTags(TAG_FOOD)) cacheFlags |= g_manager->itemConfig.GetCollectible(COLLECTIBLE_BINGE_EATER)->cacheFlags; CollectibleGain gain{type, charge, activeSlot, isFirstTime}; diff --git a/src/entity_player_kills.cpp b/src/entity_player_kills.cpp index 80bbc41..eee7694 100644 --- a/src/entity_player_kills.cpp +++ b/src/entity_player_kills.cpp @@ -11,17 +11,12 @@ #include constexpr int COLLECTIBLE_CHARM_OF_THE_VAMPIRE = 62; -constexpr int COLLECTIBLE_LUSTY_BLOOD = 411; constexpr int COLLECTIBLE_JUMPER_CABLES = 520; -constexpr int COLLECTIBLE_DEATHS_LIST = 530; constexpr int COLLECTIBLE_BERSERK_KILLS = 704; constexpr int TRINKET_SAMSONS_LOCK = 58; -constexpr int TRINKET_EVES_BIRD_FOOT = 60; constexpr int TRINKET_BAT_WING_KILLS = 118; constexpr int TRINKET_SIGIL_OF_BAPHOMET = 189; constexpr int NULLITEM_BAT_WING = 40; -constexpr int EFFECT_HEART = 49; -constexpr int SOUND_VAMP_GULP = 157; constexpr int SOUND_VAMP_DOUBLE = 614; constexpr int SOUND_BOOK_SHADOWS_SIGIL = 1028; @@ -142,7 +137,7 @@ static void berserk_update(Entity_Player& player, Entity& npc) for (Entity* shot : entity_query_radius(player.pos, BERSERK_SHOT_RADIUS, QUERY_PROJECTILES)) { - bool isStoppable = !(static_cast(shot)->projectileFlags & PROJECTILE_CANT_BE_STOPPED); + bool isStoppable = !(static_cast(shot)->projectileFlags & PROJECTILE_CANT_HIT_PLAYER); if (shot->type == ENTITY_PROJECTILE && !shot->isDead && isStoppable) shot->isDead = true; } } diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 42ed81f..921cd2b 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -5,18 +5,10 @@ bool Entity_Player::TryThrow(const EntityRef&, const Vector&, float) { reconstruction_missing("Entity_Player::TryThrow 007d2930"); } -void Entity_Player::RemoveCollectible(int, bool, int, bool) -{ - reconstruction_missing("Entity_Player::RemoveCollectible 0078f840"); -} Entity_Familiar* Entity_Player::AddWisp(int, Vector, bool, bool) { reconstruction_missing("Entity_Player::AddWisp 005c93b0"); } -void Entity_Player::trigger_collectible_effect_removed(ItemConfig_Item*, int) -{ - reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970"); -} void Entity_Player::SetMinDamageCooldown(int) { reconstruction_missing("Entity_Player::SetMinDamageCooldown 004361d0"); @@ -53,8 +45,6 @@ void Entity_Player::QueueExtraAnimation(std::string_view) { reconstruction_missing("Entity_Player::QueueExtraAnimation 007539c0"); } -RNG& Entity_Player::GetPillRNG(int) { reconstruction_missing("Entity_Player::GetPillRNG 00753a00"); } -RNG& Entity_Player::GetCardRNG(int) { reconstruction_missing("Entity_Player::GetCardRNG 00753a60"); } uint32_t Entity_Player::IsSubPlayer() { reconstruction_missing("Entity_Player::IsSubPlayer 00753ac0"); } void Entity_Player::release_weapons_and_effects(bool) { @@ -74,10 +64,6 @@ void Entity_Player::restore_curse_mist_backup(int*) { reconstruction_missing("Entity_Player::restore_curse_mist_backup 00759950"); } -Entity* Entity_Player::AddBlueFlies(int, Vector, Entity*) -{ - reconstruction_missing("Entity_Player::AddBlueFlies 007599d0"); -} void Entity_Player::RemoveBlueFly() { reconstruction_missing("Entity_Player::RemoveBlueFly 00759b80"); } void Entity_Player::AddLeprosy() { reconstruction_missing("Entity_Player::AddLeprosy 00759b90"); } Entity* Entity_Player::AddBoneOrbital(Vector) { reconstruction_missing("Entity_Player::AddBoneOrbital 00759bc0"); } @@ -116,10 +102,6 @@ void Entity_Player::RemoveCollectibleByHistoryIndex(int, bool) { reconstruction_missing("Entity_Player::RemoveCollectibleByHistoryIndex 0078fec0"); } -void Entity_Player::TriggerCollectibleRemoved(int) -{ - reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90"); -} void Entity_Player::update_effects() { reconstruction_missing("Entity_Player::update_effects 00794e50"); } void Entity_Player::update_ladder() { reconstruction_missing("Entity_Player::update_ladder 0079f3c0"); } Entity_Bomb* Entity_Player::FireBomb(Vector, Vector, Entity*) @@ -129,43 +111,26 @@ Entity_Bomb* Entity_Player::FireBomb(Vector, Vector, Entity*) 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"); } -void Entity_Player::AddPocketItem(int, uint32_t) { reconstruction_missing("Entity_Player::AddPocketItem 007a3af0"); } void Entity_Player::AddCard(int) { reconstruction_missing("Entity_Player::AddCard 007a3c10"); } void Entity_Player::AddPill(int) { reconstruction_missing("Entity_Player::AddPill 007a3c30"); } int Entity_Player::GetCard(int) { reconstruction_missing("Entity_Player::GetCard 007a3c50"); } int Entity_Player::GetPill(int) { reconstruction_missing("Entity_Player::GetPill 007a3c80"); } void Entity_Player::SetCard(int, int) { reconstruction_missing("Entity_Player::SetCard 007a3cb0"); } void Entity_Player::SetPill(int, int) { reconstruction_missing("Entity_Player::SetPill 007a3cf0"); } -void Entity_Player::pocket_use_input() { reconstruction_missing("Entity_Player::pocket_use_input 007a3d30"); } void Entity_Player::pockets_rotate() { reconstruction_missing("Entity_Player::pockets_rotate 007a42b0"); } -void Entity_Player::SwapActiveItems() { reconstruction_missing("Entity_Player::SwapActiveItems 007a4760"); } void Entity_Player::RemovePocketItem(int) { reconstruction_missing("Entity_Player::RemovePocketItem 007a4850"); } void Entity_Player::DropPocketItem(int, Vector) { reconstruction_missing("Entity_Player::DropPocketItem 007a48f0"); } int Entity_Player::GetTrinket(uint32_t) { reconstruction_missing("Entity_Player::GetTrinket 007a6430"); } -void Entity_Player::AnimateCollectible(int, std::string_view, std::string_view) -{ - reconstruction_missing("Entity_Player::AnimateCollectible 007ab380"); -} void Entity_Player::AnimateTrinket(int, std::string_view, std::string_view) { reconstruction_missing("Entity_Player::AnimateTrinket 007ab550"); } -void Entity_Player::AnimateCard(int, std::string_view) -{ - reconstruction_missing("Entity_Player::AnimateCard 007ab6b0"); -} -void Entity_Player::AnimatePill(int, std::string_view) -{ - reconstruction_missing("Entity_Player::AnimatePill 007abb00"); -} void Entity_Player::AnimateTrapdoor() { reconstruction_missing("Entity_Player::AnimateTrapdoor 007abc00"); } void Entity_Player::AnimateLightTravel() { reconstruction_missing("Entity_Player::AnimateLightTravel 007abc10"); } void Entity_Player::AnimatePitfallIn(bool) { reconstruction_missing("Entity_Player::AnimatePitfallIn 007abc20"); } void Entity_Player::AnimatePitfallOut() { reconstruction_missing("Entity_Player::AnimatePitfallOut 007abc90"); } void Entity_Player::AnimateAppear() { reconstruction_missing("Entity_Player::AnimateAppear 007abcb0"); } void Entity_Player::AnimateTeleport(bool) { reconstruction_missing("Entity_Player::AnimateTeleport 007abcc0"); } -void Entity_Player::AnimateHappy() { reconstruction_missing("Entity_Player::AnimateHappy 007abd30"); } -void Entity_Player::AnimateSad() { reconstruction_missing("Entity_Player::AnimateSad 007abd90"); } void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } void Entity_Player::TryRemoveTrinketCostume(int) { @@ -192,7 +157,6 @@ void Entity_Player::TriggerTrinketRemoved(uint32_t) reconstruction_missing("Entity_Player::TriggerTrinketRemoved 007adb30"); } void Entity_Player::DonateLuck(int) { reconstruction_missing("Entity_Player::DonateLuck 007b2200"); } -void Entity_Player::UseCard(int, uint32_t) { reconstruction_missing("Entity_Player::UseCard 007b2230"); } void Entity_Player::update_footprints() { reconstruction_missing("Entity_Player::update_footprints 007b8cb0"); } void Entity_Player::SetFootprintColor(KColor, bool) { @@ -237,7 +201,6 @@ void Entity_Player::RemoveSkinCostume() { reconstruction_missing("Entity_Player: void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Player::SetShootingCooldown 007c37f0"); } void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } bool Entity_Player::CanUsePill(int) { reconstruction_missing("Entity_Player::CanUsePill 007c40e0"); } -void Entity_Player::UsePill(int, int, uint32_t) { reconstruction_missing("Entity_Player::UsePill 007c4180"); } void Entity_Player::AddDeadEyeCharge() { reconstruction_missing("Entity_Player::AddDeadEyeCharge 007c78b0"); } void Entity_Player::ClearDeadEyeCharge() { reconstruction_missing("Entity_Player::ClearDeadEyeCharge 007c78e0"); } void Entity_Player::update_purity_glow() { reconstruction_missing("Entity_Player::update_purity_glow 007c7c60"); } @@ -382,10 +345,6 @@ void Entity_Player::remove_wooden_cross_mantles() { reconstruction_missing("Entity_Player::remove_wooden_cross_mantles 007db160"); } -void Entity_Player::TriggerEchoChamber(uint32_t, int) -{ - reconstruction_missing("Entity_Player::TriggerEchoChamber 007db740"); -} void Entity_Player::add_random_drug_item_effect() { reconstruction_missing("Entity_Player::add_random_drug_item_effect 007dbba0"); @@ -418,4 +377,3 @@ void Entity_Player::PlayCollectibleAnim(int, bool, std::string_view, int) } 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_pockets.cpp b/src/entity_player_pockets.cpp new file mode 100644 index 0000000..8450ff1 --- /dev/null +++ b/src/entity_player_pockets.cpp @@ -0,0 +1,697 @@ +#include "entity_player.h" +#include "active_items.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "game.h" +#include "hud.h" +#include "key_configs.h" +#include "log.h" +#include "lua_callbacks.h" +#include "lua_engine.h" +#include "menu_manager.h" +#include "manager.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include + +// The cards the first floor's rooms, chests and rocks drop most (Lua's Card). +enum CardId : int +{ + CARD_ID_FOOL = 1, + CARD_ID_EMPEROR = 5, + CARD_ID_HIEROPHANT = 6, + CARD_ID_LOVERS = 7, + CARD_ID_JUSTICE = 9, + CARD_ID_HERMIT = 10, + CARD_ID_CLUBS_2 = 23, + CARD_ID_DIAMONDS_2 = 24, + CARD_ID_SPADES_2 = 25, + CARD_ID_HEARTS_2 = 26, + CARD_ID_VANILLA_LAST = 97 +}; + +// The pill effects the first floor's pills most often have (Lua's PillEffect). +enum PillEffectId : int +{ + PILL_ID_BALLS_OF_STEEL = 2, + PILL_ID_BOMBS_ARE_KEYS = 3, + PILL_ID_HEALTH_DOWN = 6, + PILL_ID_HEALTH_UP = 7, + PILL_ID_RANGE_DOWN = 11, + PILL_ID_RANGE_UP = 12, + PILL_ID_SPEED_DOWN = 13, + PILL_ID_SPEED_UP = 14, + PILL_ID_TEARS_DOWN = 15, + PILL_ID_TEARS_UP = 16, + PILL_ID_LUCK_DOWN = 17, + PILL_ID_LUCK_UP = 18, + PILL_ID_GULP = 43, + PILL_ID_EXPERIMENTAL = 49, + PILL_ID_COUNT = 50 +}; + +// What a card's or pill's use goes on with after its effect: the item held up, nothing more, or nothing at all. +enum PocketUseEnd +{ + POCKET_END_ANIMATE, + POCKET_END_SKIP_ANIMATION, + POCKET_END_RETURN +}; + +// The sounds the pockets play (Lua's SoundEffect). +enum PocketSound : int +{ + POCKET_SOUND_POWERUP_SPEWER = 132, + POCKET_SOUND_THUMBS_DOWN = 267, + POCKET_SOUND_THUMBSUP = 268, + POCKET_SOUND_THUMBSUP_AMPLIFIED = 602, + POCKET_SOUND_THUMBS_DOWN_AMPLIFIED = 603, + POCKET_SOUND_POWERUP_SPEWER_AMPLIFIED = 604 +}; + +constexpr uint32_t STAT_PILL_COLOR_FLAGS = CACHE_COLOR; +constexpr int ACHIEVEMENT_GULP = 386; +constexpr int ANNOUNCER_FRAMES_RANDOM = 900; +constexpr int ANNOUNCER_FRAMES = 2; +constexpr int CHALLENGE_RANDOM_POCKETS = 32; +constexpr int COLLECTIBLE_TAROT_CLOTH = 451; +constexpr int COLLECTIBLE_ECHO_CHAMBER = 700; +constexpr int DELAYED_SFX_FRAMES = 2; +constexpr int GULP_UNLOCK_USES = 4; +constexpr int PILL_COLOR_GOLD = 14; +constexpr int PLAYING_CARD_EMPTY = 2; +constexpr int CARD_HEART_COUNT = 2; +constexpr int BOMBS_ARE_KEYS_CHANGED = 0x1e; +constexpr int STAGE_HOME = 13; +constexpr int STAT_COLOR_FRAMES = 15; +constexpr int STAT_COLOR_PRIORITY = 255; +constexpr int TAROT_ROOM_TYPE_BOSS = 5; +constexpr int TAROT_ROOM_TYPE_SHOP = 2; +constexpr int DAEMONS_TAIL_HEART_ODDS = 5; +constexpr int USE_ITEM_ACTION_TRIGGER = 8; +constexpr uint8_t WILD_CARD_PILL = 0; +constexpr uint8_t WILD_CARD_CARD = 1; +constexpr float CARD_HELD_RISE = -12; +constexpr float POCKET_DROP_STEP = 40; +constexpr float STAT_COLOR_TINT = 0.3f; + +// An up pill's color left over the player (a colorize) and the offsets of the flash it starts with. +struct StatPillColor +{ + std::array colorize{}; + std::array flashOffset{}; +}; + +constexpr StatPillColor HEALTH_UP_COLOR = {{1, 0.5f, 0, 0.33f}, {0.5f, 0.25f, 0.25f}}; +constexpr StatPillColor RANGE_UP_COLOR = {{0.5f, 1, 1, 0.33f}, {0.25f, 0.5f, 0.5f}}; +constexpr StatPillColor SPEED_UP_COLOR = {{1, 1, 0, 0.33f}, {0.5f, 0.5f, 0.25f}}; +constexpr StatPillColor TEARS_UP_COLOR = {{0.5f, 0.5f, 1, 0.33f}, {0.4f, 0.4f, 0.5f}}; +constexpr StatPillColor LUCK_UP_COLOR = {{0, 1, 0, 0.33f}, {0.25f, 0.5f, 0.25f}}; + +// A card's or pill's use as its effect runs: the player, its generator, and the sound an up pill plays. +struct PocketUse +{ + Entity_Player& player; + RNG& rng; + int sound = POCKET_SOUND_POWERUP_SPEWER; + bool isCarBattery = false; + bool isHorse = false; + bool isPlayAnimation = true; +}; + +// Plays a sound the seeds may swap for a fart, at full volume. +static void sound_fart_play(int sound) +{ + int id = sound; + + seed_fart_sound_override(&id); + g_manager->sfxManager.Play(id, {}); +} + +// Plays the player's pending delayed sound at once and queues another, played now when it has no delay, as +// Entity_Player::PlayDelayedSFX does for the announcer. +static void announcer_queue(Entity_Player& player, int sound, int soundDelay, int frameDelay) +{ + if (player.delayedSfxId != 0 && player.delayedSfxDelay > 0) sound_fart_play(player.delayedSfxId); + if (soundDelay == 0) + { + sound_fart_play(sound); + sound = 0; + frameDelay = DELAYED_SFX_FRAMES; + } + player.delayedSfxId = sound; + player.delayedSfxVolume = 1; + player.delayedSfxDelay = soundDelay; + player.delayedSfxFrameDelay = frameDelay; +} + +// The frames the announcer waits by the options: long when it speaks only at random. +static int announcer_frames() +{ + return g_manager->optionsConfig.announcerVoiceMode == ANNOUNCER_VOICE_MODE_RANDOM ? ANNOUNCER_FRAMES_RANDOM + : ANNOUNCER_FRAMES; +} + +// Whether the announcer may speak: half the time in random mode, always in always mode, unless the use hides it. +static bool is_announcer_rolled(uint32_t flags) +{ + AnnouncerVoiceMode mode = g_manager->optionsConfig.announcerVoiceMode; + bool isRolled = (Random() & 1) == 0; + return ((isRolled && mode == ANNOUNCER_VOICE_MODE_RANDOM) || mode == ANNOUNCER_VOICE_MODE_ALWAYS) && + !(flags & USE_NOANNOUNCER); +} + +// Whether the run is on one of the first six floors, where the Ascent silences the announcer. +static bool is_ascent_stage() +{ + return g_game->stage >= 1 && g_game->stage <= 6; +} + +// Spawns a pickup on a free spot near the player, seeded from the use's generator. +static void pocket_pickup_spawn(PocketUse& use, int variant, int subType) +{ + Entity_Player& player = use.player; + uint32_t seed = use.rng.Next(); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = POCKET_DROP_STEP}); + + g_game->Spawn({.position = position, .spawner = &player, .subType = subType, .type = ENTITY_PICKUP, + .variant = variant, .seed = seed}); +} + +// 00753a60 The player's generator for a card, the last one for an id out of range. +RNG& Entity_Player::GetCardRNG(int cardId) +{ + if (cardId < 0 || cardId >= (int)cardRNGs.size()) log_printf(LOG_ASSERT, "Card ID out of bounds!\n"); + return cardRNGs[std::min((size_t)std::max(cardId, 0), cardRNGs.size() - 1)]; +} + +// 00753a00 The player's generator for a pill effect, the last one for an id out of range. +RNG& Entity_Player::GetPillRNG(int pillEffect) +{ + if (pillEffect < 0 || pillEffect >= (int)pillRNGs.size()) log_printf(LOG_ASSERT, "Pill ID out of bounds!\n"); + return pillRNGs[std::min((size_t)std::max(pillEffect, 0), pillRNGs.size() - 1)]; +} + +// 007a3af0 Puts a card, pill or pocket active in the first pocket slot (after a pocket active there), the others +// moving down. Full pockets drop their cards and pills first, and a helper player drops what it gets. +void Entity_Player::AddPocketItem(int id, uint32_t pocketItemType) +{ + int maxPockets = (int)GetMaxPocketItems() + (pocketItemType == POCKET_ACTIVE ? 1 : 0); + if (pocketItems[0].id != 0 && pocketItems[maxPockets - 1].id != 0) + for (int slot = 0; slot < maxPockets; slot++) + if (pocketItems[slot].id != 0 && pocketItems[slot].type != POCKET_ACTIVE) DropPocketItem(slot, pos); + + int insert = pocketItems[0].type == POCKET_ACTIVE && pocketItems[0].id > 0 ? 1 : 0; + if (pocketItems[maxPockets - 1].id == 0) + for (int slot = maxPockets - 1; slot > insert; slot--) pocketItems[slot] = pocketItems[slot - 1]; + pocketItems[insert] = {id, (PocketItemType)pocketItemType}; + g_game->room->UpdateRedKey(); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); + if (parent && pocketItemType != POCKET_ACTIVE) DropPocketItem(insert, pos); +} + +// 007db740 Echo Chamber repeats the last three cards and pills used. Not written yet. +void Entity_Player::TriggerEchoChamber(uint32_t, int) +{ + if (HasCollectible(COLLECTIBLE_ECHO_CHAMBER)) + reconstruction_missing("Entity_Player::TriggerEchoChamber 007db740 (Echo Chamber)"); +} + +// 007abd30 Plays the thumbs up with its sound. +void Entity_Player::AnimateHappy() +{ + sound_fart_play(POCKET_SOUND_THUMBSUP); + PlayExtraAnimation("Happy"); +} + +// 007abd90 Plays the thumbs down with its sound. +void Entity_Player::AnimateSad() +{ + sound_fart_play(POCKET_SOUND_THUMBS_DOWN); + PlayExtraAnimation("Sad"); +} + +// Sets a held sprite's overlay to one frame of an animation. +static void overlay_frame_set(ANM2& sprite, std::string_view animation, float frame) +{ + if (sprite.SetOverlayAnimation(animation) && sprite.overlayAnimState.animData) + sprite.overlayAnimState.SetFrameFloat(frame); +} + +// 007ab6b0 Holds a card up: its front from the cards sheet, or the card pickup's own sprite when the sheet has no +// front for it, while the player plays the given animation. A mod's card front is not written yet. +void Entity_Player::AnimateCard(int cardId, std::string_view animName) +{ + ItemConfig_Card* card = g_manager->itemConfig.GetCard(cardId); + if (cardId > CARD_ID_VANILLA_LAST && card && card->moddedCardFront) + reconstruction_missing("Entity_Player::AnimateCard 007ab6b0 (a mod's card front)"); + + heldSprite.Reset(); + heldSprite.Load("gfx/ui/ui_cardspills.anm2", GRAPHICS_LOAD); + heldSprite.Play("Sparkle"); + overlay_frame_set(heldSprite, "CardFronts", (float)cardId); + bool isFrontShown = false; + for (int layer = 0; layer < (int)heldSprite.layerStates.size(); layer++) + { + const AnimationFrame* frame = heldSprite.overlayAnimState.GetLayerFrame(layer); + isFrontShown |= frame && frame->isVisible; + } + + EntityConfig_Entity* pickup = + card ? g_manager->entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_TAROTCARD, card->pickupSubtype) : nullptr; + if (!isFrontShown && pickup) + { + heldSprite.Load(pickup->anm2Path, GRAPHICS_LOAD); + heldSprite.Play("Sparkle"); + overlay_frame_set(heldSprite, "HUD", 0); + } + heldSprite.offset = vector_make(0, CARD_HELD_RISE); + PlayExtraAnimation(animName); +} + +// 007abb00 Holds a pill up in its color's pickup sprite while the player plays the given animation. +void Entity_Player::AnimatePill(int pillColor, std::string_view animName) +{ + heldSprite.Reset(); + if (EntityConfig_Entity* pill = g_manager->entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_PILL, pillColor)) + { + heldSprite.Load(pill->anm2Path, GRAPHICS_LOAD); + heldSprite.Play("Sparkle"); + overlay_frame_set(heldSprite, "HUD", 0); + } + heldSprite.offset = vector_make(0, CARD_HELD_RISE); + PlayExtraAnimation(animName); +} + +// The pocket part of 006e8ae0: a free hand takes a card (its name and description shown, but for Jacob and Esau) or a +// pill, holding it up. Whether it was taken. The challenge that turns cards into items and the seeds that hide or +// scramble the text are not written yet. +bool pocket_item_collect(Entity_Pickup& pocket, Entity_Player& player) +{ + constexpr int CHALLENGE_CARDS_AS_ITEMS = 43; + + if (player.IsHoldingItem()) return false; + if (g_game->challenge == CHALLENGE_CARDS_AS_ITEMS) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0 (a card as an item)"); + if (pocket.variant == PICKUP_PILL) + { + player.AddPocketItem(pocket.subtype, POCKET_PILL); + player.AnimatePill(pocket.subtype, "UseItem"); + return true; + } + + player.AddPocketItem(pocket.subtype, POCKET_CARD); + player.AnimateCard(pocket.subtype, "UseItem"); + ItemConfig_Card* card = g_manager->itemConfig.GetCard(pocket.subtype); + if (player.playerType == PLAYER_JACOB || player.playerType == PLAYER_ESAU || !card) return true; + + Seeds& seeds = g_game->seedEffects; + if (seeds.HasSeedEffect(SEED_MYSTERY_TAROT_CARDS) || seeds.HasSeedEffect(SEED_DYSLEXIA)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0 (a card's hidden or scrambled text)"); + g_game->hud.show_pill_name(&player, card->GetName().c_str(), card->description_get().c_str()); + return true; +} + +// The Fool: back to the floor's first room. +static PocketUseEnd fool_use(PocketUse& use) +{ + if (use.isCarBattery) return POCKET_END_RETURN; + + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .dimension = 0, + .roomIndex = g_game->startingRoomIdx}); + return POCKET_END_SKIP_ANIMATION; +} + +// The Emperor and the Hermit: off to the floor's boss room or shop, when it has one. +static PocketUseEnd room_card_use(PocketUse& use, int roomType) +{ + if (use.isCarBattery) return POCKET_END_RETURN; + + int roomIndex = g_game->QueryRoomTypeIndex(roomType, false, use.rng, false); + if (roomIndex < 0) return POCKET_END_ANIMATE; + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .roomIndex = roomIndex}); + if (roomType == TAROT_ROOM_TYPE_SHOP) return POCKET_END_SKIP_ANIMATION; + use.isPlayAnimation = false; + return POCKET_END_ANIMATE; +} + +// The Hierophant and the Lovers: two soul or red hearts. +static PocketUseEnd hearts_card_use(PocketUse& use, int heartSubType) +{ + if (use.isCarBattery) return POCKET_END_RETURN; + + for (int i = 0; i < CARD_HEART_COUNT; i++) pocket_pickup_spawn(use, PICKUP_HEART, heartSubType); + return POCKET_END_ANIMATE; +} + +// Justice: a heart (Daemon's Tail lets one in five through), a bomb, a key and a coin. +static PocketUseEnd justice_use(PocketUse& use) +{ + Entity_Player& player = use.player; + if (use.isCarBattery) return POCKET_END_RETURN; + + bool isTailed = player.HasTrinket(TRINKET_DAEMONS_TAIL); + if (!isTailed || player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_HEART_ODDS) == 0) + pocket_pickup_spawn(use, PICKUP_HEART, 0); + pocket_pickup_spawn(use, PICKUP_BOMB, 0); + pocket_pickup_spawn(use, PICKUP_KEY, 0); + pocket_pickup_spawn(use, PICKUP_COIN, 0); + return POCKET_END_ANIMATE; +} + +// The 2 of Clubs, Diamonds, Spades and Hearts: double the bombs, coins, keys or red hearts, or two when there are +// none. Tainted Bethany's hearts are her blood charges. +static PocketUseEnd playing_card_use(PocketUse& use, int card) +{ + Entity_Player& player = use.player; + auto doubled = [](int count) { return count == 0 ? PLAYING_CARD_EMPTY : count; }; + if (use.isCarBattery) return POCKET_END_RETURN; + + if (card == CARD_ID_CLUBS_2) player.AddBombs(doubled(player.numBombs)); + else if (card == CARD_ID_DIAMONDS_2) player.AddCoins(doubled(player.numCoins)); + else if (card == CARD_ID_SPADES_2) player.AddKeys(doubled(player.numKeys)); + else if (player.playerType == PLAYER_BETHANY_B) player.AddBloodCharge(doubled(player.effectiveBloodCharge)); + else if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::UseCard 007b2230 (the 2 of Hearts in a deathmatch)"); + else player.AddHearts(doubled(player.redHearts), false, false); + return POCKET_END_ANIMATE; +} + +// Runs a card's own effect. The cards not written yet stop the game. +static PocketUseEnd card_effect_run(PocketUse& use, int card) +{ + switch (card) + { + case CARD_ID_FOOL: + return fool_use(use); + case CARD_ID_EMPEROR: + return room_card_use(use, TAROT_ROOM_TYPE_BOSS); + case CARD_ID_HIEROPHANT: + return hearts_card_use(use, HEART_SOUL); + case CARD_ID_LOVERS: + return hearts_card_use(use, HEART_RED); + case CARD_ID_JUSTICE: + return justice_use(use); + case CARD_ID_HERMIT: + return room_card_use(use, TAROT_ROOM_TYPE_SHOP); + case CARD_ID_CLUBS_2: + case CARD_ID_DIAMONDS_2: + case CARD_ID_SPADES_2: + case CARD_ID_HEARTS_2: + return playing_card_use(use, card); + } + reconstruction_missing(("Entity_Player::UseCard 007b2230 (card " + std::to_string(card) + ")").c_str()); +} + +// 007b2230 Uses a card: its effect, the card held up unless hidden, the announcer naming it now and then, and the mods' +// MC_USE_CARD. The random cards challenge and Tarot Cloth's doubled tarot cards are not written yet. +void Entity_Player::UseCard(int cardType, uint32_t useFlag) +{ + ItemConfig_Card* card = cardType >= 0 ? g_manager->itemConfig.GetCard(cardType) : nullptr; + if (!card) return; + + int frames = announcer_frames(); + if (g_game->challenge == CHALLENGE_RANDOM_POCKETS) + reconstruction_missing("Entity_Player::UseCard 007b2230 (the random cards challenge)"); + if (HasCollectible(COLLECTIBLE_TAROT_CLOTH) && (card->cardType == CARD_TAROT || card->cardType == CARD_TAROT_REVERSE)) + reconstruction_missing("Entity_Player::UseCard 007b2230 (Tarot Cloth)"); + + PocketUse use = {.player = *this, .rng = GetCardRNG(cardType)}; + use.isCarBattery = useFlag & USE_CARBATTERY; + use.isPlayAnimation = !(useFlag & USE_NOANIM); + bool isAnnounced = is_announcer_rolled(useFlag) && (!is_ascent_stage() || !g_game->GetStateFlag(GAME_STATE_BACKWARDS_PATH)) && + g_game->stage != STAGE_HOME; + + PocketUseEnd end = card_effect_run(use, cardType); + if (end == POCKET_END_RETURN) return; + if (end == POCKET_END_ANIMATE && use.isPlayAnimation) AnimateCard(cardType, "UseItem"); + if (isAnnounced && card->announcerVoice != 0) announcer_queue(*this, card->announcerVoice, card->announcerDelay, frames); + lua_callback_check(MC_USE_CARD, "Entity_Player::UseCard 007b2230: the mods' MC_USE_CARD 00863cc0"); +} + +// 00763290 Unlocks the tears ups achievement once ten Tears Up pills and tears up items are taken. +void tears_up_unlock_check(Entity_Player& player) +{ + int tearsUps = PILL_ID_TEARS_UP < (int)player.pillEffectUses.size() ? player.pillEffectUses[PILL_ID_TEARS_UP] : 0; + for (ItemConfig_Item* item : g_manager->itemConfig.GetTaggedItems(TAG_TEARS_UP)) + if (item->IsCollectible()) tearsUps += player.collectibleCounts[item->id]; + if (tearsUps >= TEARS_UP_UNLOCK_COUNT) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_TEARS_UP_ITEMS); +} + +// A stat pill: its stats asked for, the thumbs down for a down pill, the thumbs up with a flash of the stat's color for +// an up pill, the color staying over the player. +static void stat_pill_use(PocketUse& use, uint32_t cacheFlags, const StatPillColor* color) +{ + Entity_Player& player = use.player; + + player.cacheFlags |= cacheFlags; + if (!color) return player.AnimateSad(); + player.cacheFlags |= STAT_PILL_COLOR_FLAGS; + player.AnimateHappy(); + sound_fart_play(use.sound); + player.colorOverride = COLOR_DEFAULT; + std::ranges::copy(color->colorize, player.colorOverride._colorize); + ColorMod flash = {{STAT_COLOR_TINT, STAT_COLOR_TINT, STAT_COLOR_TINT, 1}, {}, {}}; + std::ranges::copy(color->flashOffset, flash._offset); + player.SetColor(flash, STAT_COLOR_FRAMES, STAT_COLOR_PRIORITY, true, true); +} + +// Balls of Steel: two soul hearts, four for a horse pill. +static void balls_of_steel_use(PocketUse& use) +{ + use.player.AddSoulHearts(use.isHorse ? 8 : 4, false); + use.player.AnimateHappy(); + sound_fart_play(use.sound); +} + +// Bombs Are Key: bombs and keys swap, golden ones too, and a horse pill adds half of each again. +static void bombs_are_keys_use(PocketUse& use) +{ + Entity_Player& player = use.player; + if (player.playerType == PLAYER_BLUEBABY_B) + reconstruction_missing("Entity_Player::UsePill 007c4180 (Bombs Are Key with poop)"); + + std::swap(player.numKeys, player.numBombs); + std::swap(player.hasGoldenKey, player.hasGoldenBomb); + if (use.isHorse) + { + player.AddBombs((player.numBombs + 1) / 2); + player.AddKeys((player.numKeys + 1) / 2); + } + player.ConsumableCountChanged(BOMBS_ARE_KEYS_CHANGED); + player.AnimateHappy(); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// Health Down: a heart container less, two for a horse pill, and the death it may cause prevented when it can. +static void health_down_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.AddMaxHearts(use.isHorse ? -4 : -2, false); + player.TryPreventDeath(); + player.sprite.overlayAnimState.SetAnimationData(nullptr); + player.AnimateSad(); +} + +// Health Up: an empty heart container, two for a horse pill, with the stat pills' red flash. +static void health_up_use(PocketUse& use) +{ + use.player.AddMaxHearts(use.isHorse ? 4 : 2, false); + stat_pill_use(use, 0, &HEALTH_UP_COLOR); +} + +// Runs a pill's own effect. The effects not written yet stop the game. +static void pill_effect_run(PocketUse& use, int pillEffect) +{ + switch (pillEffect) + { + case PILL_ID_BALLS_OF_STEEL: + return balls_of_steel_use(use); + case PILL_ID_BOMBS_ARE_KEYS: + return bombs_are_keys_use(use); + case PILL_ID_HEALTH_DOWN: + return health_down_use(use); + case PILL_ID_HEALTH_UP: + return health_up_use(use); + case PILL_ID_RANGE_DOWN: + return stat_pill_use(use, CACHE_RANGE, nullptr); + case PILL_ID_RANGE_UP: + return stat_pill_use(use, CACHE_RANGE, &RANGE_UP_COLOR); + case PILL_ID_SPEED_DOWN: + return stat_pill_use(use, CACHE_SPEED, nullptr); + case PILL_ID_SPEED_UP: + return stat_pill_use(use, CACHE_SPEED, &SPEED_UP_COLOR); + case PILL_ID_TEARS_DOWN: + return stat_pill_use(use, CACHE_FIREDELAY, nullptr); + case PILL_ID_TEARS_UP: + return stat_pill_use(use, CACHE_FIREDELAY, &TEARS_UP_COLOR); + case PILL_ID_LUCK_DOWN: + return stat_pill_use(use, CACHE_LUCK, nullptr); + case PILL_ID_LUCK_UP: + return stat_pill_use(use, CACHE_LUCK, &LUCK_UP_COLOR); + } + reconstruction_missing(("Entity_Player::UsePill 007c4180 (pill effect " + std::to_string(pillEffect) + ")").c_str()); +} + +// The pill's name and description as the HUD shows them, its #keys looked up in the "PocketItems" string table. +static std::string pocket_text(std::string_view text) +{ + bool isMissing = false; + if (text.empty() || text[0] != '#') return std::string(text); + + StringTable& table = g_manager->stringTable; + std::string_view localized = table.get_string("PocketItems", table.language, text.substr(1), &isMissing); + return std::string(isMissing ? text : localized); +} + +// 007c4180 Uses a pill effect: the screen blooms, the pill color is identified, its name shows and its use counts, +// its effect runs, the announcer names it now and then and the mods see it. A horse pill doubles the count and swaps +// the thumbs' sounds for louder ones. The golden pill, the random pills challenge, the seeds that hide or scramble +// pill names, False PHD and the versus mode's remote players are not written yet. The original keeps the last pill +// color for the save, which the curated player has no field for. +void Entity_Player::UsePill(int pillEffect, int pillColor, uint32_t useFlags) +{ + Game& game = *g_game; + game.bloomDuration = 30; + game.bloomTimer = 30; + game.bloomStrength = 1; + if (game.deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::UsePill 007c4180 (a versus mode's remote player)"); + + bool isHorse = pillColor & PILL_HORSE_FLAG; + int color = (int)(pillColor & PILL_COLOR_MASK); + if (color == PILL_COLOR_GOLD) reconstruction_missing("Entity_Player::UsePill 007c4180 (the golden pill)"); + game.itemPool.identifiedPillEffects[std::min(color, PILL_COLOR_GOLD)] = true; + + ItemConfig_Pill* pill = pillEffect >= 0 ? g_manager->itemConfig.GetPillEffect(pillEffect) : nullptr; + if (game.challenge == CHALLENGE_RANDOM_POCKETS) + reconstruction_missing("Entity_Player::UsePill 007c4180 (the random pills challenge)"); + if (game.seedEffects.HasSeedEffect(SEED_PILLS_NEVER_IDENTIFY) || game.seedEffects.HasSeedEffect(SEED_DYSLEXIA)) + reconstruction_missing("Entity_Player::UsePill 007c4180 (a pill's hidden or scrambled name)"); + std::string name = pill ? pocket_text(pill->name) : std::string(); + std::string description = pill ? pocket_text(pill->desc) : std::string(); + if (!(useFlags & USE_NOHUD) && pillEffect != PILL_ID_EXPERIMENTAL) + game.hud.show_pill_name(this, name.c_str(), description.c_str()); + if (pillEffect >= 0 && pillEffect < (int)pillEffectUses.size()) pillEffectUses[pillEffect] += isHorse ? 2 : 1; + tears_up_unlock_check(*this); + if (pillEffectUses.size() > PILL_ID_GULP && pillEffectUses[PILL_ID_GULP] > GULP_UNLOCK_USES) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_GULP); + + int frames = announcer_frames(); + PocketUse use = {.player = *this, .rng = GetPillRNG(pillEffect)}; + use.isHorse = isHorse; + use.sound = isHorse ? POCKET_SOUND_POWERUP_SPEWER_AMPLIFIED : POCKET_SOUND_POWERUP_SPEWER; + bool isAnnounced = is_announcer_rolled(useFlags) && + ((!is_ascent_stage() && game.stage != STAGE_HOME) || !game.GetStateFlag(GAME_STATE_BACKWARDS_PATH)); + pill_effect_run(use, pillEffect); + + if (isAnnounced && pill && pill->announcerVoice != 0) + announcer_queue(*this, isHorse ? pill->announcerVoiceSuper : pill->announcerVoice, pill->announcerDelay, frames); + lua_engine_get().UsePill(pillEffect, this, useFlags); + if (isHorse && sprite.IsPlaying("Happy")) + { + g_manager->sfxManager.Stop(POCKET_SOUND_THUMBSUP); + g_manager->sfxManager.Play(POCKET_SOUND_THUMBSUP_AMPLIFIED, {}); + } + else if (isHorse && sprite.IsPlaying("Sad")) + { + g_manager->sfxManager.Stop(POCKET_SOUND_THUMBS_DOWN); + g_manager->sfxManager.Play(POCKET_SOUND_THUMBS_DOWN_AMPLIFIED, {}); + } + if (HasCollectible(COLLECTIBLE_FALSE_PHD)) reconstruction_missing("Entity_Player::UsePill 007c4180 (False PHD)"); +} + +// The first pocket item is used up: the others move up and the last slot empties. +static void pockets_shift(Entity_Player& player) +{ + std::array& pockets = player.pocketItems; + + for (int slot = 0; slot + 1 < POCKET_SLOT_COUNT; slot++) pockets[slot] = pockets[slot + 1]; + pockets.back().id = 0; +} + +// 007a3d30 Reads the pocket button: a pocket active is used through its slot, else (when the controls allow and no +// item is being used) the first card or pill is used and leaves the pockets (a golden pill only now and then), saving +// the rewind state first. The player's familiars may fart for a pill. Jacob and Esau's shared button and Endless +// Nameless' copies are not written yet. +void Entity_Player::pocket_use_input() +{ + constexpr int EVENT_PILLS_USED = 6; + constexpr int EVENT_CARDS_USED = 196; + constexpr int COLLECTION_PILL = 43; + constexpr int COLLECTION_CARD = 61; + constexpr int CARD_ID_RED_KEY_CRACKED = 78; + constexpr int CARD_ID_WILD = 80; + constexpr int CARD_ID_EXCEPTION = 48; + constexpr int TRINKET_ENDLESS_NAMELESS = 79; + constexpr int GOLDEN_PILL_KEEP_CHANCE = 5; + constexpr int PERCENT = 100; + + Game& game = *g_game; + if (game.stageTransition.state != STAGE_TRANSITION_NONE || game.roomTransition.is_active() || IsHologram()) return; + if (playerType == PLAYER_JACOB || playerType == PLAYER_ESAU) + reconstruction_missing("Entity_Player::pocket_use_input 007a3d30 (Jacob and Esau's shared button)"); + + bool isTriggered = input_is_action_triggered(ACTION_PILL_CARD, controllerIndex, this); + if (HasEntityFlags(FLAG_FEAR) || isCoopGhost) isTriggered = false; + if (pocketItems[0].type == POCKET_ACTIVE && pocketItems[0].id > 0) + return ControlActiveItem(pocketItems[0].id - 1); + if (!isControlsEnabled || controlsCooldown > 0 || !isTriggered || bodySprite.IsPlaying("UseItem")) return; + + game.save_rewind_state(-1); + game.isPocketItemRewindSaved = true; + log_printf(LOG_INFO, "Action PillCard Triggered\n"); + PocketItem used = pocketItems[0]; + if (used.id == 0) return; + + lastActionTriggers |= USE_ITEM_ACTION_TRIGGER; + PersistentGameData& save = g_manager->persistentGameData; + if (used.type == POCKET_CARD) + { + if (used.id == CARD_ID_RED_KEY_CRACKED && !is_active_usable(*this, COLLECTIBLE_RED_KEY, -1)) return; + save.AddToCollection(COLLECTION_CARD); + save.IncreaseEventCounter(EVENT_CARDS_USED, 1); + pockets_shift(*this); + TriggerEchoChamber(POCKET_CARD, used.id); + UseCard(used.id, USE_OWNED); + if (used.id != CARD_ID_WILD && used.id != CARD_ID_EXCEPTION) + { + wildCardItemType = WILD_CARD_CARD; + wildCardItem = used.id; + wildCardVarData = 0; + } + } + else if (used.type == POCKET_PILL) + { + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity->IsFamiliar() && static_cast(entity)->player == this) + static_cast(entity)->farting_baby_fart(); + save.IncreaseEventCounter(EVENT_PILLS_USED, 1); + save.AddToCollection(COLLECTION_PILL); + int effect = game.itemPool.GetPillEffect((uint32_t)used.id, this); + bool isGoldenKept = (used.id & PILL_COLOR_MASK) == PILL_COLOR_GOLD && + GetCollectibleRNG(COLLECTIBLE_PHD).RandomInt(PERCENT) >= GOLDEN_PILL_KEEP_CHANCE; + if (!isGoldenKept) pockets_shift(*this); + TriggerEchoChamber(POCKET_PILL, used.id); + UsePill(effect, used.id, 0); + wildCardItemType = WILD_CARD_PILL; + wildCardItem = effect; + wildCardVarData = used.id; + if (cacheFlags != 0) + { + InvalidateCoPlayerItems(); + EvaluateItems(); + } + } + else ControlActiveItem(used.id - 1); + + if (HasTrinket(TRINKET_ENDLESS_NAMELESS) && used.type != POCKET_ACTIVE) + reconstruction_missing("Entity_Player::pocket_use_input 007a3d30 (Endless Nameless' copy)"); + game.hud.refresh_request(HUD_REFRESH_PLAYER); +} diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index 63ec66e..e8e524c 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -8,19 +8,16 @@ constexpr int TRINKET_TICK = 53; constexpr int TRINKET_DOOR_STOP = 124; -constexpr int TRINKET_MODELING_CLAY = 166; constexpr int TRINKET_LIL_CLOT = 176; constexpr int TRINKET_BETHS_ESSENCE = 182; constexpr int TRINKET_THE_TWINS = 183; constexpr int COLLECTIBLE_BROKEN_WATCH = 337; -constexpr int COLLECTIBLE_TOXIC_SHOCK = 350; constexpr int COLLECTIBLE_DOG_TOOTH = 445; constexpr int COLLECTIBLE_BELIAL_PARTNER = 474; constexpr int COLLECTIBLE_BELIAL_EFFECT = 214; constexpr int COLLECTIBLE_POKE_GO = 505; constexpr int COLLECTIBLE_MERCURIUS = 590; constexpr int COLLECTIBLE_SATURNUS = 595; -constexpr int COLLECTIBLE_DOGMA = 633; constexpr int NULL_ITEM_BELIAL = 123; constexpr int NULL_ITEM_FORGOTTEN_CHALLENGE = 106; constexpr int BELIAL_NULL_COUNT = 4; @@ -32,7 +29,6 @@ constexpr int CHALLENGE_FORGOTTEN_COSTUME = 42; constexpr int BABY_SKIN_WITH_FOLLOWER = 58; constexpr int STAGE_ID_HOME = 35; constexpr int STAGE_MOMS_FLOOR = 6; -constexpr int ENTITY_ROTGUT = 911; constexpr int BETHS_ESSENCE_WISPS = 5; constexpr int BETHS_ESSENCE_CHANCE_DOUBLE = 50; constexpr int BETHS_ESSENCE_CHANCE_TRIPLE = 100; @@ -48,7 +44,6 @@ constexpr int GREED_WAVE_MAX = 12; constexpr int DOOR_STOP_UNLOCK_COPIES = 3; constexpr int DOOR_STOP_BOSS_RUSH_COPIES = 2; constexpr float DOOR_STOP_REACH_SQUARED = 10000; -constexpr uint32_t LEVEL_STATE_DUNGEON_ROCK_BROKEN = 1u << 13; constexpr float DOOR_ENTER_OFFSET = 40; constexpr uint32_t DOOR_SIDES = 4; constexpr int ROCK_STATE_BROKEN = 2; @@ -174,7 +169,7 @@ static void dog_tooth_apply(Entity_Player& player) int rockIdx = room.dungeonRockIdx; GridEntity* rock = rockIdx >= 0 && rockIdx < ROOM_GRID_CELLS ? room.gridEntities[rockIdx] : nullptr; bool isRock = rock && std::ranges::find(DOG_TOOTH_ROCKS, rock->type) != std::end(DOG_TOOTH_ROCKS); - if (!(game.levelStateFlags & LEVEL_STATE_DUNGEON_ROCK_BROKEN) && isRock && rock->state != ROCK_STATE_BROKEN) + if (!(game.levelStateFlags & 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN) && isRock && rock->state != ROCK_STATE_BROKEN) delayed_sound_queue(player, SOUND_DOG_TOOTH_ROCK, DOG_TOOTH_ROCK_DELAY); } diff --git a/src/entity_player_tears.cpp b/src/entity_player_tears.cpp new file mode 100644 index 0000000..a2187b9 --- /dev/null +++ b/src/entity_player_tears.cpp @@ -0,0 +1,916 @@ +#include "entity_familiar.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include +#include +#include + +// The tear's size from its damage: a root, the item scale (above one it grows by its log) and a little of the damage. +constexpr float TEAR_SCALE_ROOT = 0.23f; +constexpr float TEAR_SCALE_SIZE = 0.55f; +constexpr float TEAR_SCALE_DAMAGE = 0.01f; +constexpr float EXPLOSIVE_TEAR_SCALE = 0.5f; +constexpr float QUADSPLIT_TEAR_SCALE = 1.2f; +constexpr float HOLOGRAM_TEAR_ALPHA = 0.2f; +constexpr int TINT_ALPHA = 3; + +// What a familiar's tears deal: Blood Babies a third, Twisted Babies half, the rest three quarters but Lilith's. +constexpr float BLOOD_BABY_DAMAGE = 0.35f; +constexpr float TWISTED_BABY_DAMAGE = 0.5f; +constexpr float FAMILIAR_DAMAGE = 0.75f; +constexpr float BFFS_DAMAGE = 2; +constexpr float EVE_B_TEAR_SCALE = 0.8f; +constexpr float JACOB_TEAR_SCALE = 0.9f; +constexpr ColorMod LIL_DELIRIUM_COLOR = {{1, 1, 1, 1}, {2.4f, 2.4f, 2.4f, 1}, {0, 0, 0}}; + +// The chances the items roll: a percent out of a hundred, or one in a denominator that luck lowers. +constexpr int PERCENT = 100; +constexpr int TRINKET_PERCENT_ONE = 10; +constexpr int TRINKET_PERCENT_TWO = 20; +constexpr int TRINKET_PERCENT_MORE = 33; +constexpr float PINKY_EYE_LUCK = 5; +constexpr float PUSH_PIN_LUCK = 5; +constexpr int SERPENTS_KISS_PERCENT = 15; +constexpr int FRUIT_CAKE_FLAGS = 84; +constexpr int GLAUCOMA_CHANCE = 20; +constexpr int FEAR_PERCENT = 15; +constexpr int FEAR_LUCK_BASE = 100; +constexpr int BEGOTTEN_FEAR_CHANCE = 30; +constexpr int URANUS_FREEZE_CHANCE = 10; +constexpr int SINUS_INFECTION_CHANCE = 5; +constexpr int GODS_FLESH_CHANCE = 5; +constexpr int QUARTER_MASK = 3; + +// The worms Almond Milk rolls, by how many it gives: four under 5%, three under 10%, two under 30%, one under 80%. +constexpr std::array ALMOND_WORM_ODDS = {0.05f, 0.1f, 0.3f, 0.8f}; +constexpr std::array ALMOND_WORMS = {TEAR_FLAT, TEAR_SQUARE, TEAR_SPIRAL, TEAR_WIGGLE, + TEAR_ORBIT, TEAR_PULSE, TEAR_BOOMERANG, TEAR_HOMING, + TEAR_BOUNCE, TEAR_ORBIT_ADVANCED, TEAR_TURN_HORIZONTAL, + TEAR_BIG_SPIRAL}; +constexpr std::array ALMOND_LASER_WORMS = {TEAR_SQUARE, TEAR_WIGGLE, TEAR_ORBIT, + TEAR_HOMING, TEAR_BOOMERANG, TEAR_SPIRAL}; +// The flags Fruit Cake never adds unless the tear had them: the bombs' and the Tractor Beam's. +constexpr std::array FRUIT_CAKE_EXCLUDED = {TEAR_BLACK_HP_DROP, TEAR_GLITTER_BOMB, TEAR_BUTT_BOMB, + TEAR_SAD_BOMB, TEAR_TRACTOR_BEAM, TEAR_SCATTER_BOMB}; + +// The damage and size the eye and Stye items, Terra, the teeth and Haemolacria give. +constexpr float PEEPER_DAMAGE = 1.35f; +constexpr float CHEMICAL_PEEL_DAMAGE = 2; +constexpr float BLOOD_CLOT_DAMAGE = 1; +constexpr float BLOOD_CLOT_SCALE = 1.25f; +constexpr float BLOOD_CLOT_HEIGHT = 10; +constexpr float STYE_DAMAGE = 1.2857143f; +constexpr float STYE_SCALE = 1.25f; +constexpr float STYE_SPEED = 0.8f; +constexpr float ALMOND_MILK_SCALE = 0.7f; +constexpr float SOY_MILK_SCALE = 0.5f; +constexpr float DEAD_ONION_SCALE = 1.5f; +constexpr float PROPTOSIS_SCALE = 3; +constexpr float PISCES_SCALE = 1.25f; +constexpr float PUPULA_SCALE = 3; +constexpr float TROPICAMIDE_SCALE_ADD = 0.2f; +constexpr float TROPICAMIDE_SCALE = 1.25f; +constexpr float TERRA_SCALE_EXPONENT = 0.2f; +constexpr float EUTHANASIA_DAMAGE = 3; +constexpr float BLACK_TOOTH_DAMAGE = 2; +constexpr float TOOTH_DAMAGE = 3.2f; +constexpr float APPLE_DAMAGE = 4; +constexpr float PARASITOID_HEIGHT = 2; +constexpr float BEGOTTEN_SCALE = 2; +constexpr float KNOCKOUT_SCALE = 1.5f; +constexpr float HAEMOLACRIA_SCALE = 1.71f; +constexpr float SHRINK_DAMAGE = 3; +constexpr float PLAYDOUGH_DAMAGE = 2; +constexpr float PLAYDOUGH_COLORIZE_ALPHA = 1.5f; +constexpr float GOLDEN_RAZOR_STEP = 3; +constexpr float GOLDEN_RAZOR_MAX = 0.9f; +constexpr float GOLDEN_RAZOR_RED = 0.1f; +constexpr float GOLDEN_RAZOR_GREEN = 0.05f; +constexpr std::array GOLDEN_RAZOR_COLORIZE = {2, 1, 0, 1}; + +// The mass and knockback of Almond Milk, Soy Milk, the knockback items and Blister. +constexpr float ALMOND_MILK_MASS = 0.3f; +constexpr float SOY_MILK_MASS = 0.2f; +constexpr float KNOCKBACK_MASS = 3; +constexpr float BLISTER_KNOCKBACK = 3; +constexpr float NAILS_KNOCKBACK = 2; + +// What a Blood Baby's color gives its tears. +constexpr float BLACK_BABY_DAMAGE = 1.25f; +constexpr float BLACK_BABY_SCALE = 1.1f; +constexpr float ETERNAL_BABY_DAMAGE = 1.5f; +constexpr float ETERNAL_BABY_SCALE = 1.3f; +constexpr ColorMod GOLD_BABY_COLOR = {{1, 1, 1, 1}, {2, 1, 0, 1}, {0, 0, 0}}; + +constexpr int SOUND_OCULAR_RIFT = 1087; + +// The items, trinkets and null effects the tear parameters look at, beside the player's own. +constexpr int COLLECTIBLE_BLOOD_OF_THE_MARTYR = 7; +constexpr int COLLECTIBLE_CUPIDS_ARROW = 48; +constexpr int COLLECTIBLE_PACT = 80; +constexpr int COLLECTIBLE_SPIDER_BITE = 89; +constexpr int COLLECTIBLE_SMALL_ROCK = 90; +constexpr int COLLECTIBLE_COMMON_COLD = 103; +constexpr int COLLECTIBLE_MOMS_CONTACTS = 110; +constexpr int COLLECTIBLE_STIGMATA = 138; +constexpr int COLLECTIBLE_TOUGH_LOVE = 150; +constexpr int COLLECTIBLE_CHEMICAL_PEEL = 154; +constexpr int COLLECTIBLE_TOOTH_PICKS = 183; +constexpr int COLLECTIBLE_MOMS_EYESHADOW = 200; +constexpr int COLLECTIBLE_IRON_BAR = 201; +constexpr int COLLECTIBLE_LOST_CONTACT = 213; +constexpr int COLLECTIBLE_MOMS_PERFUME = 228; +constexpr int COLLECTIBLE_ABADDON = 230; +constexpr int COLLECTIBLE_DEATHS_TOUCH = 237; +constexpr int COLLECTIBLE_DARK_MATTER = 259; +constexpr int COLLECTIBLE_PROPTOSIS = 261; +constexpr int COLLECTIBLE_SAGITTARIUS = 306; +constexpr int COLLECTIBLE_PISCES = 309; +constexpr int COLLECTIBLE_DEAD_ONION = 336; +constexpr int COLLECTIBLE_8_INCH_NAILS = 359; +constexpr int COLLECTIBLE_HOLY_LIGHT = 374; +constexpr int COLLECTIBLE_PUPULA_DUPLEX = 379; +constexpr int COLLECTIBLE_GODS_FLESH = 398; +constexpr int COLLECTIBLE_MAW_OF_THE_VOID = 399; +constexpr int COLLECTIBLE_EXPLOSIVO = 401; +constexpr int COLLECTIBLE_FRUIT_CAKE = 418; +constexpr int COLLECTIBLE_VARICOSE_VEINS = 452; +constexpr int COLLECTIBLE_COMPOUND_FRACTURE = 453; +constexpr int COLLECTIBLE_SINUS_INFECTION = 459; +constexpr int COLLECTIBLE_PARASITOID = 461; +constexpr int COLLECTIBLE_EYE_OF_BELIAL = 462; +constexpr int COLLECTIBLE_SULFURIC_ACID = 463; +constexpr int COLLECTIBLE_EUTHANASIA = 496; +constexpr int COLLECTIBLE_POP = 529; +constexpr int COLLECTIBLE_LACHRYPHAGY = 532; +constexpr int COLLECTIBLE_MUCORMYCOSIS = 553; +constexpr int COLLECTIBLE_TERRA = 592; +constexpr int COLLECTIBLE_SCOOPER = 605; +constexpr int COLLECTIBLE_OCULAR_RIFT = 606; +constexpr int COLLECTIBLE_LODESTONE = 617; +constexpr int COLLECTIBLE_ROTTEN_TOMATO = 618; +constexpr int COLLECTIBLE_KNOCKOUT_DROPS = 637; +constexpr int COLLECTIBLE_TROPICAMIDE = 659; +constexpr int TRINKET_PINKY_EYE = 30; +constexpr int TRINKET_PUSH_PIN = 31; +constexpr int TRINKET_RED_PATCH = 40; +constexpr int TRINKET_BLISTER = 77; +constexpr int TRINKET_BLACK_TOOTH = 95; +constexpr int TRINKET_NOSE_GOBLIN = 98; +constexpr int TRINKET_SUPER_BALL = 99; +constexpr int TRINKET_JAW_BREAKER = 129; +constexpr int TRINKET_CHEWED_PEN = 130; +constexpr int TRINKET_BRAIN_WORM = 144; +constexpr int NULLITEM_BLOOD_OATH = 54; +constexpr int NULLITEM_IT_HURTS = 57; +constexpr int NULLITEM_JUDAS_BIRTHRIGHT = 123; +constexpr int NULLITEM_JUDAS_BIRTHRIGHT_TIMED = 124; +constexpr int NULLITEM_JUDAS_BIRTHRIGHT_PERMANENT = 130; +constexpr int BABY_SHADOW = 13; +constexpr int BABY_BEGOTTEN = 21; +constexpr int BABY_SUPER_GREED = 54; +constexpr int FAMILIAR_FINGER = 110; +constexpr int FAMILIAR_TWISTED_BABY = 235; +constexpr int RED_STEW_BLOOD_FRAMES = 90; + +// The Blood Baby colors whose tears are bloody, and what the others give. +enum BloodBabyColor : int +{ + BLOOD_BABY_RED = 0, + BLOOD_BABY_BLACK = 2, + BLOOD_BABY_ETERNAL = 3, + BLOOD_BABY_GOLD = 4, + BLOOD_BABY_BONE = 5, + BLOOD_BABY_ROTTEN = 6, + BLOOD_BABY_BROKEN = 7 +}; + +// A tint and offset the items lay over the tear's color, keeping its colorize. +struct TearTint +{ + std::array tint{}; + std::array offset{}; +}; + +constexpr TearTint POISON_TINT = {{0.5f, 0.97f, 0.5f, 1}, {}}; +constexpr TearTint PUSH_PIN_TINT = {{1.5f, 2, 2, 0.5f}, {}}; +constexpr TearTint CONTACTS_TINT = {{1.25f, 0.05f, 0.15f, 1}, {}}; +constexpr TearTint SPIDER_BITE_TINT = {{2, 2, 2, 1}, {50 / 255.0f, 50 / 255.0f, 50 / 255.0f}}; +constexpr TearTint TAR_TINT = {{0.15f, 0.15f, 0.15f, 1}, {}}; +constexpr TearTint COMMON_COLD_TINT = {{0.4f, 0.97f, 0.5f, 1}, {}}; +constexpr TearTint EYESHADOW_TINT = {{1, 0, 1, 1}, {50 / 255.0f, 0, 0}}; +constexpr TearTint IRON_BAR_TINT = {{0.5f, 0.5f, 0.5f, 1}, {}}; +constexpr TearTint ABADDON_TINT = {{100 / 255.0f, 100 / 255.0f, 100 / 255.0f, 1}, {}}; +constexpr TearTint PERFUME_TINT = {{1, 1, 116 / 255.0f, 1}, {43 / 255.0f, 37 / 255.0f, 0}}; +constexpr TearTint BEGOTTEN_TINT = {{0, 0, 0, 1}, {}}; +constexpr TearTint BLOOD_CLOT_TINT = {{1, 0, 0, 1}, {}}; +constexpr TearTint STYE_TINT = {{1.5f, 2, 2, 1}, {}}; +constexpr TearTint EXPLOSIVO_TINT = {{0.2f, 0.09f, 0.065f, 1}, {}}; +constexpr TearTint SUPER_BALL_TINT = {{1, 1, 0.8f, 1}, {0.1f, 0.1f, 0.1f}}; +constexpr TearTint SCORPIO_TINT = {{50 / 255.0f, 1, 50 / 255.0f, 1}, {}}; +constexpr TearTint ROTTEN_TOMATO_TINT = {{0.7f, 0.14f, 0.1f, 1}, {0.3f, 0, 0}}; +constexpr std::array ACID_TINT = {1, 1, 0.1f, 1}; +constexpr ColorMod HORN_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod GODS_FLESH_COLOR = {{0.6f, 0.7f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr std::array LODESTONE_COLORIZE = {0.5f, 0.5f, 0.5f, 1}; + +// The colorize of each of Playdough Cookie's nine effects, and how its roll and strength draw from luck. +constexpr std::array, 9> PLAYDOUGH_COLORIZES = {{{1, 0.4f, 1.2f}, + {0.4f, 0.8f, 0.5f}, + {0.9f, 0.2f, 0.2f}, + {0.8f, 0.9f, 0.1f}, + {1, 0.4f, 0.7f}, + {1, 0.4f, 0.2f}, + {0.4f, 0.7f, 1}, + {0.3f, 0.4f, 1}, + {0.7f, 0.6f, 0.4f}}}; +constexpr float PLAYDOUGH_BASE = 11; +constexpr float PLAYDOUGH_LUCK = 0.2f; +constexpr int PLAYDOUGH_MIN = 6; +constexpr float PLAYDOUGH_STRENGTH_BASE = 6; +constexpr float PLAYDOUGH_STRENGTH_LUCK = 0.5f; + +// The bloody variant of each tear look that has one. +struct BloodVariant +{ + int variant; + int bloody; +}; + +constexpr std::array BLOOD_VARIANTS = {{{TEAR_BLUE, TEAR_BLOOD}, + {TEAR_CUPID_BLUE, TEAR_CUPID_BLOOD}, + {TEAR_NAIL, TEAR_NAIL_BLOOD}, + {TEAR_PUPULA, TEAR_PUPULA_BLOOD}, + {TEAR_GODS_FLESH, TEAR_GODS_FLESH_BLOOD}, + {TEAR_GLAUCOMA, TEAR_GLAUCOMA_BLOOD}, + {TEAR_EYE, TEAR_EYE_BLOOD}}}; + +// What GetTearHitParams works out on its way: the weapon and familiar firing, the damage before the items, the size +// multiplier explosive tears halve, the eye the tear leaves from, and whether it turns bloody. +struct TearHitState +{ + Entity_Familiar* familiar = nullptr; + WeaponType weaponType = WEAPON_TEARS; + float baseDamage = 0; + float scaleMultiplier = 1; + bool isBloody = false; + bool isLeftEye = false; + bool isRightEye = false; +}; + +// Whether a one in denominator chance hits, drawing nothing when it is certain. +static bool chance_roll(int denominator) +{ + return denominator == 0 || Random() % (uint32_t)denominator == 0; +} + +// Whether a luck chance of one in base less luck times its scale, at least minimum, hits. +static bool luck_roll(const Entity_Player& player, int base, float luckScale, int minimum) +{ + return chance_roll(std::max(base - (int)(player.luck * luckScale), minimum)); +} + +// The base of a trinket's chance by its multiplier: one copy (or none), two, three, or more. +static int trinket_base(Entity_Player& player, int trinket, std::array bases) +{ + int multiplier = player.GetTrinketMultiplier(trinket); + return multiplier == 2 ? bases[1] : multiplier == 3 ? bases[2] : multiplier > 3 ? bases[3] : bases[0]; +} + +// Whether a trinket's percent chance hits on its own generator. +static bool trinket_percent_roll(Entity_Player& player, int trinket, float luckScale) +{ + int chance = trinket_base(player, trinket, + {TRINKET_PERCENT_ONE, TRINKET_PERCENT_TWO, TRINKET_PERCENT_MORE, TRINKET_PERCENT_MORE}); + chance += (int)(player.luck * luckScale); + return player.trinketRNGs[trinket].Next() % PERCENT < (uint32_t)chance; +} + +// Whether the player has a collectible or its temporary effect. +static bool is_having(Entity_Player& player, int collectible) +{ + return player.HasCollectible(collectible) || player.temporaryEffects.HasCollectibleEffect(collectible); +} + +// Lays a tint and offset over the tear's color. +static void tint_apply(ColorMod& color, const TearTint& tint) +{ + std::copy(tint.tint.begin(), tint.tint.end(), color._tint); + std::copy(tint.offset.begin(), tint.offset.end(), color._offset); +} + +// Familiars' tears deal less (Blood Babies outside versus a third, Twisted Babies half, the rest three quarters but +// Lilith's), twice with BFFS!, and Baby-Bender's or Lil Delirium's look. +static void familiar_params_apply(Entity_Player& player, TearParams& params, TearHitState& state) +{ + Entity_Familiar& familiar = *state.familiar; + if (familiar.variant == Entity_Familiar::BLOOD_BABY) + { + if (!g_game->deathmatchManager.is_active()) params.tearDamage *= BLOOD_BABY_DAMAGE; + } + else + { + if (familiar.variant == FAMILIAR_TWISTED_BABY) params.tearDamage *= TWISTED_BABY_DAMAGE; + if (player.playerType != PLAYER_LILITH && player.playerType != PLAYER_LILITH_B) + params.tearDamage *= FAMILIAR_DAMAGE; + } + if (player.HasCollectible(COLLECTIBLE_BFFS)) params.tearDamage *= BFFS_DAMAGE; + + if (player.HasTrinket(TRINKET_BABY_BENDER) && !params.tearFlags[TEAR_HOMING]) + reconstruction_missing("Entity_Player::GetTearHitParams 007bf6c0 (Baby-Bender's familiar tears)"); + else if (familiar.isLilDelirium) + { + std::copy(std::begin(LIL_DELIRIUM_COLOR._colorize), std::end(LIL_DELIRIUM_COLOR._colorize), + params.tearColor._colorize); + params.tearVariant = TEAR_BLOOD; + } +} + +// The status chances of the first items: Pinky Eye's and Serpent's Kiss's poison, Push Pin, Mom's Contacts, Holy +// Light, Spider Bite, Chewed Pen and Ball of Tar, Common Cold, Mom's Eyeshadow, Iron Bar and Fruit Cake. +static void status_chances_apply(Entity_Player& player, TearParams& params, const TearHitState& state) +{ + TearFlags& flags = params.tearFlags; + ColorMod& color = params.tearColor; + auto poison = [&]() + { + flags.set(TEAR_POISON); + if (state.weaponType != WEAPON_BOMBS) std::copy(POISON_TINT.tint.begin(), POISON_TINT.tint.end(), color._tint); + std::fill(std::begin(color._offset), std::end(color._offset), 0.0f); + }; + + if (player.HasTrinket(TRINKET_PINKY_EYE) && trinket_percent_roll(player, TRINKET_PINKY_EYE, PINKY_EYE_LUCK)) + poison(); + if (player.HasCollectible(COLLECTIBLE_SERPENTS_KISS) && Random() % PERCENT < SERPENTS_KISS_PERCENT) poison(); + if (player.HasTrinket(TRINKET_PUSH_PIN) && trinket_percent_roll(player, TRINKET_PUSH_PIN, PUSH_PIN_LUCK)) + { + flags.set(TEAR_PIERCING); + flags.set(TEAR_SPECTRAL); + tint_apply(color, PUSH_PIN_TINT); + params.tearVariant = TEAR_CUPID_BLUE; + } + if (player.HasCollectible(COLLECTIBLE_MOMS_CONTACTS) && luck_roll(player, 5, 0.15f, 2)) + { + flags.set(TEAR_FREEZE); + tint_apply(color, CONTACTS_TINT); + } + if (is_having(player, COLLECTIBLE_HOLY_LIGHT) && luck_roll(player, 10, 0.9f, 2)) flags.set(TEAR_LIGHT_FROM_HEAVEN); + if (player.HasCollectible(COLLECTIBLE_SPIDER_BITE) && luck_roll(player, 4, 0.2f, 1)) + { + tint_apply(color, SPIDER_BITE_TINT); + flags.set(TEAR_SLOW); + } + + int penBase = trinket_base(player, TRINKET_CHEWED_PEN, {10, 5, 3, 10}); + bool isTar = player.HasTrinket(TRINKET_CHEWED_PEN) && chance_roll(std::max(penBase - (int)(player.luck * 0.5f), 1)); + if (player.HasCollectible(COLLECTIBLE_BALL_OF_TAR) && luck_roll(player, 10, 0.5f, 1)) isTar = true; + if (isTar) + { + flags.set(TEAR_GISH); + flags.set(TEAR_SLOW); + tint_apply(color, TAR_TINT); + } + if (player.HasCollectible(COLLECTIBLE_COMMON_COLD) && luck_roll(player, 4, 0.25f, 1)) + { + flags.set(TEAR_POISON); + tint_apply(color, COMMON_COLD_TINT); + } + if (player.HasCollectible(COLLECTIBLE_MOMS_EYESHADOW) && luck_roll(player, 10, 0.334f, 1)) + { + tint_apply(color, EYESHADOW_TINT); + flags.set(TEAR_CHARM); + } + if (is_having(player, COLLECTIBLE_IRON_BAR) && luck_roll(player, 10, 0.334f, 1)) + { + tint_apply(color, IRON_BAR_TINT); + flags.set(TEAR_CONFUSION); + } + if (is_having(player, COLLECTIBLE_FRUIT_CAKE)) + { + int bit = (int)(Random() % FRUIT_CAKE_FLAGS); + if (std::ranges::find(FRUIT_CAKE_EXCLUDED, bit) == FRUIT_CAKE_EXCLUDED.end()) flags.set(bit); + } +} + +// Whether the tear turns bloody: the blood items (unless Soy or Almond Milk), the eye and character ones, the bloody +// Blood Babies and the nulls that bleed. +static bool is_bloody(Entity_Player& player, const TearHitState& state) +{ + TemporaryEffects& effects = player.temporaryEffects; + auto has = [&](int id) { return player.HasCollectible(id); }; + bool isMilk = has(COLLECTIBLE_SOY_MILK) || has(COLLECTIBLE_ALMOND_MILK); + bool isBloodItem = has(COLLECTIBLE_ABADDON) || has(COLLECTIBLE_MONSTROS_LUNG) || + has(COLLECTIBLE_BLOOD_OF_THE_MARTYR) || has(COLLECTIBLE_STIGMATA) || has(COLLECTIBLE_PACT) || + has(COLLECTIBLE_TOOTH_PICKS) || + (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_SHADOW) || + effects.HasCollectibleEffect(COLLECTIBLE_BOOK_OF_BELIAL) || has(COLLECTIBLE_SMALL_ROCK) || + effects.HasCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON) || + effects.HasCollectibleEffect(COLLECTIBLE_RAZOR_BLADE) || + effects.HasTrinketEffect(TRINKET_RED_PATCH) || + effects.HasCollectibleEffect(COLLECTIBLE_VARICOSE_VEINS) || has(COLLECTIBLE_MAW_OF_THE_VOID) || + effects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL); + if (!isMilk && isBloodItem) return true; + + int type = player.playerType; + if (has(COLLECTIBLE_KIDNEY_STONE) || has(COLLECTIBLE_APPLE) || has(COLLECTIBLE_EYE_OF_BELIAL) || + (has(COLLECTIBLE_LEAD_PENCIL) && state.isLeftEye) || (has(COLLECTIBLE_PEEPER) && state.isLeftEye) || + type == PLAYER_LAZARUS2 || type == PLAYER_BLACKJUDAS || player.redStewBonusDuration > RED_STEW_BLOOD_FRAMES) + return true; + + Entity_Familiar* familiar = state.familiar; + bool isBloodyBaby = familiar && familiar->variant == Entity_Familiar::BLOOD_BABY && + (familiar->subtype == BLOOD_BABY_RED || familiar->subtype == BLOOD_BABY_ROTTEN || + familiar->subtype == BLOOD_BABY_BROKEN); + return (effects.HasCollectibleEffect(COLLECTIBLE_SCOOPER) && state.isRightEye) || type == PLAYER_ESAU || + type == PLAYER_JUDAS_B || type == PLAYER_LAZARUS2_B || type == PLAYER_BETHANY_B || isBloodyBaby || + std::ranges::any_of(std::array{NULLITEM_BLOOD_OATH, NULLITEM_INTRUDER, NULLITEM_JUDAS_BIRTHRIGHT, + NULLITEM_JUDAS_BIRTHRIGHT_TIMED, NULLITEM_JUDAS_BIRTHRIGHT_STAGE, + NULLITEM_JUDAS_BIRTHRIGHT_PERMANENT, NULLITEM_ESAU_JR}, + [&](int id) { return effects.HasNullEffect(id); }) || + (effects.HasCollectibleEffect(COLLECTIBLE_DECAP_ATTACK) && has(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)); +} + +// Picks the eye: the left one when asked for, or at random for familiars and one eyed shooters. +static void eye_choose(Entity_Player& player, TearParams& params, TearHitState& state, int displacement) +{ + bool isOneEyed = state.familiar || player.playerType == PLAYER_CAIN || + player.HasCollectible(COLLECTIBLE_LEAD_PENCIL) || !player.weaponTypes[WEAPON_TEARS] || + player.HasCollectible(COLLECTIBLE_CURSED_EYE) || player.HasCollectible(COLLECTIBLE_STAPLER) || + player.playerType == PLAYER_CAIN_B; + state.isLeftEye = displacement < 0 || (isOneEyed && (Random() & 1) == 0); + state.isRightEye = displacement >= 1 && !state.isLeftEye; + params.tearDisplacement = state.isLeftEye ? -1 : state.isRightEye ? 1 : 0; +} + +// The items working by the eye: Lachryphagy, Glaucoma, Mom's Perfume and Abaddon, the Begotten baby, The Peeper, The +// Scooper, Chemical Peel, Sulfuric Acid, Blood Clot and Stye. +static void eye_items_apply(Entity_Player& player, TearParams& params, TearHitState& state) +{ + TearFlags& flags = params.tearFlags; + ColorMod& color = params.tearColor; + auto has = [&](int id) { return player.HasCollectible(id); }; + + if (has(COLLECTIBLE_LACHRYPHAGY) && (state.weaponType == WEAPON_TEARS || state.weaponType == WEAPON_MONSTROS_LUNGS)) + params.tearVariant = TEAR_HUNGRY; + if (has(COLLECTIBLE_GLAUCOMA) && Random() % GLAUCOMA_CHANCE == 0) + { + flags.set(TEAR_PERMANENT_CONFUSION); + params.tearVariant = TEAR_GLAUCOMA; + } + if (has(COLLECTIBLE_MOMS_PERFUME) || has(COLLECTIBLE_ABADDON)) + { + int denominator = std::max(FEAR_LUCK_BASE - (int)player.luck, 1); + if (Random() % (uint32_t)denominator < FEAR_PERCENT) + { + if (has(COLLECTIBLE_ABADDON)) tint_apply(color, ABADDON_TINT); + else if (has(COLLECTIBLE_MOMS_PERFUME)) tint_apply(color, PERFUME_TINT); + flags.set(TEAR_FEAR); + } + } + if (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_BEGOTTEN) + { + if (Random() % BEGOTTEN_FEAR_CHANCE == 0) flags.set(TEAR_FEAR); + params.tearScale *= BEGOTTEN_SCALE; + tint_apply(color, BEGOTTEN_TINT); + } + + if (has(COLLECTIBLE_PEEPER) && state.isLeftEye) + { + state.isBloody = true; + params.tearDamage *= PEEPER_DAMAGE; + } + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_SCOOPER) && state.isRightEye) + { + state.isBloody = true; + params.tearDamage *= PEEPER_DAMAGE; + } + if (has(COLLECTIBLE_CHEMICAL_PEEL) && state.isLeftEye) + { + state.isBloody = true; + params.tearDamage += CHEMICAL_PEEL_DAMAGE; + } + if (has(COLLECTIBLE_SULFURIC_ACID) && (Random() & QUARTER_MASK) == 0) + { + flags.set(TEAR_ACID); + std::copy(ACID_TINT.begin(), ACID_TINT.end(), color._tint); + } + if (has(COLLECTIBLE_BLOOD_CLOT) && state.isLeftEye) + { + tint_apply(color, BLOOD_CLOT_TINT); + params.tearDamage += BLOOD_CLOT_DAMAGE; + params.tearScale *= BLOOD_CLOT_SCALE; + params.tearHeight -= BLOOD_CLOT_HEIGHT; + } + if (has(COLLECTIBLE_STYE) && state.isRightEye) + { + tint_apply(color, STYE_TINT); + params.tearDamage *= STYE_DAMAGE; + params.tearScale *= STYE_SCALE; + params.speedMultiplier *= STYE_SPEED; + } +} + +// The items changing the tear's look and size: Proptosis to Head of the Keeper, in the order the game checks them. +static void look_items_apply(Entity_Player& player, TearParams& params, const TearHitState& state) +{ + TearFlags& flags = params.tearFlags; + auto has = [&](int id) { return player.HasCollectible(id); }; + int zodiac = player.GetZodiacEffect(); + + if (is_having(player, COLLECTIBLE_PROPTOSIS)) params.tearScale *= PROPTOSIS_SCALE; + if (has(COLLECTIBLE_PISCES) || zodiac == COLLECTIBLE_PISCES) params.tearScale *= PISCES_SCALE; + if (has(COLLECTIBLE_CUPIDS_ARROW) || has(COLLECTIBLE_SAGITTARIUS) || zodiac == COLLECTIBLE_SAGITTARIUS) + params.tearVariant = TEAR_CUPID_BLUE; + if (has(COLLECTIBLE_8_INCH_NAILS)) params.tearVariant = TEAR_NAIL; + if (has(COLLECTIBLE_PUPULA_DUPLEX)) + { + params.tearVariant = TEAR_PUPULA; + params.tearScale *= PUPULA_SCALE; + } + if (has(COLLECTIBLE_TROPICAMIDE)) params.tearScale = (params.tearScale + TROPICAMIDE_SCALE_ADD) * TROPICAMIDE_SCALE; + if (is_having(player, COLLECTIBLE_URANUS)) + { + params.tearVariant = TEAR_ICE; + if (Random() % URANUS_FREEZE_CHANCE == 0) flags.set(TEAR_FREEZE); + } + if (has(COLLECTIBLE_TERRA)) + { + float roll = random_unit() * 2 - 1; + params.tearVariant = TEAR_ROCK; + params.tearScale *= std::pow(2.0f, roll * TERRA_SCALE_EXPONENT); + params.tearDamage *= std::pow(2.0f, roll); + } + if (player.temporaryEffects.HasNullEffect(NULLITEM_REVERSE_HANGED_MAN)) flags.set(TEAR_COIN_DROP_DEATH); + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) params.tearVariant = TEAR_DIAMOND; + if (is_having(player, COLLECTIBLE_STRANGE_ATTRACTOR)) params.tearVariant = TEAR_METALLIC; + if (is_having(player, COLLECTIBLE_EUTHANASIA) && luck_roll(player, 30, 2, 4)) + { + params.tearVariant = TEAR_NEEDLE; + flags.set(TEAR_NEEDLE_FLAG); + params.tearDamage *= EUTHANASIA_DAMAGE; + } + if (has(COLLECTIBLE_SINUS_INFECTION) && Random() % SINUS_INFECTION_CHANCE == 0) + { + params.tearVariant = TEAR_BOOGER; + flags.set(TEAR_BOOGER_FLAG); + } + if (player.HasTrinket(TRINKET_NOSE_GOBLIN)) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_NOSE_GOBLIN); + float boogerChance = multiplier == 2 ? 0.2f : multiplier == 3 ? 0.3f : 0.1f; + float homingChance = multiplier == 2 ? 0.75f : multiplier == 3 ? 1 : 0.5f; + if (random_unit() <= boogerChance) + { + params.tearVariant = TEAR_BOOGER; + flags.set(TEAR_BOOGER_FLAG); + if (random_unit() <= homingChance) flags.set(TEAR_HOMING); + } + } + if (has(COLLECTIBLE_MUCORMYCOSIS) && (Random() & QUARTER_MASK) == 0) + { + params.tearVariant = TEAR_SPORE; + flags.set(TEAR_SPORE_FLAG); + } + if (has(COLLECTIBLE_EXPLOSIVO) && (Random() & QUARTER_MASK) == 0) + { + flags.set(TEAR_STICKY); + int look = params.tearVariant; + if (look == TEAR_BLUE || look == TEAR_BLOOD || look == TEAR_CUPID_BLUE || look == TEAR_CUPID_BLOOD) + params.tearVariant = TEAR_EXPLOSIVO; + else tint_apply(params.tearColor, EXPLOSIVO_TINT); + } + if (is_having(player, COLLECTIBLE_LOST_CONTACT)) params.tearVariant = TEAR_LOST_CONTACT; + if (has(COLLECTIBLE_COMPOUND_FRACTURE)) params.tearVariant = TEAR_BONE; + if (is_having(player, COLLECTIBLE_GODS_FLESH) && Random() % GODS_FLESH_CHANCE == 0) + { + params.tearVariant = TEAR_GODS_FLESH; + flags.set(TEAR_GODS_FLESH_FLAG); + if (state.weaponType != WEAPON_TEARS) params.tearColor = GODS_FLESH_COLOR; + } + if (has(COLLECTIBLE_POP)) params.tearVariant = state.isBloody ? TEAR_EYE_BLOOD : TEAR_EYE; + if (is_having(player, COLLECTIBLE_DARK_MATTER) && luck_roll(player, 3, 0.1f, 1)) flags.set(TEAR_FEAR); + if (is_having(player, COLLECTIBLE_HEAD_OF_THE_KEEPER) || + (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_SUPER_GREED)) + { + params.tearVariant = TEAR_COIN; + flags.set(TEAR_GREED_COIN); + } + if (is_having(player, COLLECTIBLE_DEATHS_TOUCH)) params.tearVariant = TEAR_SCHYTHE; +} + +// The trinkets and items with damage floors: Super Ball, Scorpio, Black Tooth, Jaw Breaker and Tough Love, Apple, +// Parasitoid, Ouroboros Worm, Little Horn and Golden Razor's gold. +static void damage_items_apply(Entity_Player& player, TearParams& params, const TearHitState& state) +{ + TearFlags& flags = params.tearFlags; + float luck = player.luck; + auto floor = [&](float multiplier) + { + params.tearDamage = std::max(params.tearDamage, state.baseDamage * multiplier); + }; + + if (player.HasTrinket(TRINKET_SUPER_BALL) && + chance_roll(std::max(trinket_base(player, TRINKET_SUPER_BALL, {10, 5, 3, 10}) - (int)(luck * 0.5f), 0))) + { + flags.set(TEAR_BOUNCE); + tint_apply(params.tearColor, SUPER_BALL_TINT); + } + if (player.HasCollectible(COLLECTIBLE_SCORPIO) || player.GetZodiacEffect() == COLLECTIBLE_SCORPIO) + tint_apply(params.tearColor, SCORPIO_TINT); + if (player.HasTrinket(TRINKET_BLACK_TOOTH) && + chance_roll(std::max(trinket_base(player, TRINKET_BLACK_TOOTH, {33, 16, 11, 33}) - (int)luck, 0))) + { + floor(BLACK_TOOTH_DAMAGE); + params.tearVariant = TEAR_BLACK_TOOTH; + flags.set(TEAR_POISON); + } + + bool isTooth = player.HasTrinket(TRINKET_JAW_BREAKER) && + chance_roll(std::max(trinket_base(player, TRINKET_JAW_BREAKER, {10, 5, 3, 10}) - (int)luck, 0)); + if (is_having(player, COLLECTIBLE_TOUGH_LOVE) && chance_roll(std::max(10 - (int)luck, 0))) isTooth = true; + if (isTooth) + { + floor(TOOTH_DAMAGE); + params.tearVariant = TEAR_TOOTH; + } + if (player.HasCollectible(COLLECTIBLE_APPLE) && chance_roll(std::max(15 - (int)luck, 0))) + { + floor(APPLE_DAMAGE); + params.tearVariant = TEAR_RAZOR; + } + if (player.HasCollectible(COLLECTIBLE_PARASITOID) && chance_roll(std::max(7 - (int)luck, 2))) + { + params.tearVariant = TEAR_EGG; + flags.set(TEAR_EGG_FLAG); + params.tearHeight *= PARASITOID_HEIGHT; + } + if (player.HasTrinket(TRINKET_OUROBOROS_WORM) && chance_roll(std::max(10 - (int)luck, 1))) flags.set(TEAR_HOMING); + if (player.HasCollectible(COLLECTIBLE_LITTLE_HORN) && chance_roll(std::max(20 - (int)luck, 5))) + { + flags.set(TEAR_HORN); + params.tearColor = HORN_COLOR; + } + + TemporaryEffect* razor = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_GOLDEN_RAZOR); + if (!razor || razor->count <= 0) return; + + float gold = std::clamp((float)razor->count / GOLDEN_RAZOR_STEP, 0.0f, GOLDEN_RAZOR_MAX); + for (int i = 0; i < 4; i++) + params.tearColor._colorize[i] += (GOLDEN_RAZOR_COLORIZE[i] - params.tearColor._colorize[i]) * gold; + params.tearColor._offset[0] += gold * GOLDEN_RAZOR_RED; + params.tearColor._offset[1] += gold * GOLDEN_RAZOR_GREEN; +} + +// What the weapon adds: the bombs' flags, the explosive and quad split sizes, Haemolacria's balloon and burst, the +// Forgotten's bone and the fetus. +static void weapon_params_apply(Entity_Player& player, TearParams& params, TearHitState& state) +{ + TearFlags& flags = params.tearFlags; + WeaponType weapon = state.weaponType; + bool isHaemolacria = player.HasCollectible(COLLECTIBLE_HAEMOLACRIA); + if (weapon == WEAPON_BOMBS || weapon == WEAPON_ROCKETS) flags |= player.GetBombFlags(true); + + if (weapon != WEAPON_TEARS && weapon != WEAPON_FETUS) + { + if (isHaemolacria) flags.set(TEAR_BURSTSPLIT); + return; + } + bool isLudovico = flags[TEAR_LUDOVICO]; + if (flags[TEAR_EXPLOSIVE] && !isLudovico) state.scaleMultiplier = EXPLOSIVE_TEAR_SCALE; + if (flags[TEAR_QUADSPLIT] && !isLudovico) params.tearScale *= QUADSPLIT_TEAR_SCALE; + if (isHaemolacria) + { + bool isLaser = player.HasCollectible(COLLECTIBLE_BRIMSTONE) || player.HasCollectible(COLLECTIBLE_TECHNOLOGY) || + player.HasCollectible(COLLECTIBLE_TECH_X); + params.tearVariant = isLaser ? TEAR_BALLOON_BRIMSTONE + : player.HasCollectible(COLLECTIBLE_DR_FETUS) ? TEAR_BALLOON_BOMB + : TEAR_BALLOON; + params.tearScale *= HAEMOLACRIA_SCALE; + flags.set(TEAR_BURSTSPLIT); + } + else if ((player.playerType == PLAYER_THEFORGOTTEN || player.playerType == PLAYER_THEFORGOTTEN_B) && + params.tearVariant != TEAR_SCHYTHE) + params.tearVariant = TEAR_BONE; + if (weapon == WEAPON_FETUS) params.tearVariant = TEAR_FETUS; +} + +// Playdough Cookie's roll: one effect of nine with its colorize. A strong roll (never for lasers) drops the status +// effects and turns fire into bait. +static void playdough_apply(Entity_Player& player, TearParams& params, const TearHitState& state) +{ + TearFlags& flags = params.tearFlags; + int effectRange = std::max((int)(PLAYDOUGH_BASE - player.luck * PLAYDOUGH_LUCK), PLAYDOUGH_MIN); + uint32_t effect = Random() % (uint32_t)effectRange; + uint32_t strengthRange = (uint32_t)(int)(PLAYDOUGH_STRENGTH_BASE - player.luck * PLAYDOUGH_STRENGTH_LUCK); + int strength = strengthRange == 0 ? 0 : (int)(Random() % strengthRange); + WeaponType weapon = state.weaponType; + if (weapon == WEAPON_LASER || weapon == WEAPON_BRIMSTONE || weapon == WEAPON_TECH_X) strength = 0; + + switch (effect) + { + case 0: flags.set((Random() & 1) == 0 ? TEAR_TURN_HORIZONTAL : TEAR_HOMING); break; + case 1: flags.set(TEAR_POISON); break; + case 2: + if ((Random() & 1) != 0) params.tearDamage *= PLAYDOUGH_DAMAGE; + else if (strength < 2) flags.set(TEAR_FREEZE); + break; + case 3: + if (strength < 3) flags.set(TEAR_FEAR); + break; + case 4: + if (strength < 3) flags.set(TEAR_CHARM); + break; + case 5: + if ((Random() & 1) != 0 && strength <= 2) flags.set(TEAR_BAIT); + else if (strength < 4) flags.set(TEAR_BURN); + break; + case 6: flags.set((Random() & 1) == 0 || strength > 2 ? TEAR_ICE_FLAG : TEAR_SLOW); break; + case 7: + if (strength < 2) flags.set(TEAR_SHRINK); + break; + } + const auto& colorize = PLAYDOUGH_COLORIZES[std::min(effect, PLAYDOUGH_COLORIZES.size() - 1)]; + std::copy(colorize.begin(), colorize.end(), params.tearColor._colorize); + params.tearColor._colorize[3] = PLAYDOUGH_COLORIZE_ALPHA; +} + +// The late items: Lodestone, Rotten Tomato, Knockout Drops, Ocular Rift, Jacob's size, the shrinking flag's damage, +// Almond Milk's worms, Playdough Cookie and Berserk's gore. +static void late_items_apply(Entity_Player& player, TearParams& params, const TearHitState& state, Entity* source) +{ + TearFlags& flags = params.tearFlags; + auto has = [&](int id) { return player.HasCollectible(id); }; + + if (has(COLLECTIBLE_LODESTONE) && chance_roll(std::max((int)(6 - player.luck), 1))) + { + std::copy(LODESTONE_COLORIZE.begin(), LODESTONE_COLORIZE.end(), params.tearColor._colorize); + flags.set(TEAR_MAGNETIZE); + } + if (has(COLLECTIBLE_ROTTEN_TOMATO) && chance_roll(std::max((int)(6 - player.luck), 1))) + { + tint_apply(params.tearColor, ROTTEN_TOMATO_TINT); + flags.set(TEAR_BAIT); + } + if (has(COLLECTIBLE_KNOCKOUT_DROPS) && chance_roll(std::max((int)(10 - player.luck), 1))) + { + flags.set(TEAR_PUNCH); + params.tearVariant = TEAR_FIST; + params.tearScale *= KNOCKOUT_SCALE; + } + if (has(COLLECTIBLE_OCULAR_RIFT) && chance_roll(std::max(20 - (int)player.luck, 5))) + { + if (!state.familiar || source->variant != FAMILIAR_FINGER) npc_sound_play(SOUND_OCULAR_RIFT, 1, 2, 1); + flags.set(TEAR_RIFT); + params.tearColor = HORN_COLOR; + } + if (player.playerType == PLAYER_JACOB) params.tearScale *= JACOB_TEAR_SCALE; + if (flags[TEAR_SHRINK]) params.tearDamage *= SHRINK_DAMAGE; + + if (has(COLLECTIBLE_ALMOND_MILK)) + { + float roll = random_unit(); + int worms = (int)std::ranges::count_if(ALMOND_WORM_ODDS, [&](float odds) { return roll < odds; }); + WeaponType weapon = state.weaponType; + bool isLaser = weapon == WEAPON_LASER || weapon == WEAPON_BRIMSTONE || weapon == WEAPON_TECH_X; + if (isLaser) worms = std::min(worms, 1); + for (int i = 0; i < worms; i++) + flags.set(isLaser ? ALMOND_LASER_WORMS[Random() % ALMOND_LASER_WORMS.size()] + : ALMOND_WORMS[Random() % ALMOND_WORMS.size()]); + } + if (has(COLLECTIBLE_PLAYDOUGH_COOKIE)) playdough_apply(player, params, state); + if (state.weaponType == WEAPON_BONE && player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BERSERK)) + flags.set(TEAR_EXTRA_GORE); +} + +// What a Blood Baby's color gives its tears: black dark matter and fear, eternal homing, gold Midas, bone shards and +// rotten Mulligan flies. +static void blood_baby_apply(Entity_Player& player, TearParams& params, Entity_Familiar& familiar) +{ + TearFlags& flags = params.tearFlags; + switch (familiar.subtype) + { + case BLOOD_BABY_BLACK: + params.tearVariant = TEAR_DARK_MATTER; + params.tearDamage *= BLACK_BABY_DAMAGE; + params.tearScale *= BLACK_BABY_SCALE; + flags.set(TEAR_DARK_MATTER_FLAG); + if (luck_roll(player, 5, 0.1f, 1)) flags.set(TEAR_FEAR); + break; + case BLOOD_BABY_ETERNAL: + params.tearDamage *= ETERNAL_BABY_DAMAGE; + params.tearScale *= ETERNAL_BABY_SCALE; + flags.set(TEAR_HOMING); + break; + case BLOOD_BABY_GOLD: + if (luck_roll(player, 9, 0.25f, 3)) flags.set(TEAR_MIDAS); + color_multiply(params.tearColor, GOLD_BABY_COLOR); + break; + case BLOOD_BABY_BONE: + flags.set(TEAR_BONE_FLAG); + params.tearVariant = TEAR_BONE; + break; + case BLOOD_BABY_ROTTEN: flags.set(TEAR_MULLIGAN); break; + } +} + +// The weight and push of the milks, the knockback items and Blister, and Brain Worm's piercing. +static void mass_knockback_apply(Entity_Player& player, TearParams& params) +{ + auto has = [&](int id) { return player.HasCollectible(id); }; + bool isNails = has(COLLECTIBLE_8_INCH_NAILS) || has(COLLECTIBLE_TERRA); + if (has(COLLECTIBLE_ALMOND_MILK)) params.massMultiplier *= ALMOND_MILK_MASS; + else if (has(COLLECTIBLE_SOY_MILK)) params.massMultiplier *= SOY_MILK_MASS; + bool isPisces = has(COLLECTIBLE_PISCES) || player.GetZodiacEffect() == COLLECTIBLE_PISCES; + if (isPisces || isNails || player.HasTrinket(TRINKET_BLISTER)) params.massMultiplier *= KNOCKBACK_MASS; + + if (player.HasTrinket(TRINKET_BLISTER)) + params.knockbackMultiplier = (float)player.GetTrinketMultiplier(TRINKET_BLISTER) * BLISTER_KNOCKBACK; + else if (isNails) params.knockbackMultiplier = NAILS_KNOCKBACK; + + int brainWorm = player.GetTrinketMultiplier(TRINKET_BRAIN_WORM); + RNG& rng = player.trinketRNGs[TRINKET_BRAIN_WORM]; + bool isPiercing = brainWorm == 2 ? (rng.Next() & QUARTER_MASK) == 0 : brainWorm > 2 && (rng.Next() & 1) == 0; + if (!isPiercing) return; + params.tearFlags.set(TEAR_PIERCING); + params.tearVariant = TEAR_CUPID_BLUE; +} + +// 007bf6c0 What a tear from the player (or its familiar) is fired with: its stats, flags, color and look from the +// items, the eye it leaves from, and a size from its damage. Every item's roll draws in the order the game draws it. +TearParams Entity_Player::GetTearHitParams(WeaponType weaponType, float damageScale, int displacement, Entity* source) +{ + TearHitState state; + state.weaponType = weaponType; + state.familiar = source && source->type == ENTITY_FAMILIAR ? static_cast(source) : nullptr; + + TearParams params; + params.tearDamage = damageScale * damage; + params.tearHeight = tearHeight; + params.tearFlags = tearFlags; + params.tearColor = tearColor; + if (state.familiar) familiar_params_apply(*this, params, state); + if (playerType == PLAYER_EVE_B) params.tearScale *= EVE_B_TEAR_SCALE; + state.baseDamage = params.tearDamage; + + status_chances_apply(*this, params, state); + if (temporaryEffects.HasNullEffect(NULLITEM_IT_HURTS)) + { + params.tearVariant = TEAR_BLOOD; + params.tearFlags.set(TEAR_BLOOD_CREEP); + } + if (HasCollectible(COLLECTIBLE_ALMOND_MILK)) params.tearScale *= ALMOND_MILK_SCALE; + else if (HasCollectible(COLLECTIBLE_SOY_MILK)) params.tearScale *= SOY_MILK_SCALE; + if (HasCollectible(COLLECTIBLE_DEAD_ONION)) params.tearScale *= DEAD_ONION_SCALE; + + bool isBloodVariant = params.tearVariant == TEAR_BLOOD; + eye_choose(*this, params, state, displacement); + state.isBloody = (isBloodVariant || is_bloody(*this, state)) && !HasCollectible(COLLECTIBLE_CHOCOLATE_MILK); + eye_items_apply(*this, params, state); + look_items_apply(*this, params, state); + damage_items_apply(*this, params, state); + weapon_params_apply(*this, params, state); + late_items_apply(*this, params, state, source); + if (state.familiar && state.familiar->variant == Entity_Familiar::BLOOD_BABY) + blood_baby_apply(*this, params, *state.familiar); + mass_knockback_apply(*this, params); + + float size = params.tearScale > 1 ? std::log(params.tearScale) + 1 : params.tearScale; + float baseDamage = state.baseDamage; + params.tearScale = + (std::sqrt(baseDamage) * TEAR_SCALE_ROOT + size * TEAR_SCALE_SIZE + baseDamage * TEAR_SCALE_DAMAGE) * + state.scaleMultiplier; + if (state.isBloody) + for (const BloodVariant& blood : BLOOD_VARIANTS) + if (params.tearVariant == blood.variant) + { + params.tearVariant = blood.bloody; + break; + } + if (IsHologram()) params.tearColor._tint[TINT_ALPHA] = HOLOGRAM_TEAR_ALPHA; + if (get_seeded_variant() != -1) + reconstruction_missing("Entity_Player::GetTearHitParams 007bf6c0 (the G-Fuel seed's nails)"); + + NetplayManager& netplay = g_manager->netplayManager; + if (netplay.is_online() && !netplay.IsIdxLocalPlayer(controllerIndex) && !g_game->deathmatchManager.is_active()) + params.tearColor._tint[TINT_ALPHA] *= (float)g_manager->optionsConfig.onlinePlayerOpacity * 0.09f + 0.1f; + return params; +} + +// The part of 00782af0 that sizes the player: the crowns and the blood gush follow the sprite's last scale, and a +// plain player's sprite takes its scale (Magic Mushroom's), times the lifting pose's while the body animates. +void Entity_Player::sprite_scale_update() +{ + crownOfLightSprite.scale = sprite.scale; + darkPrincesCrownSprite.scale = sprite.scale; + bloodGushSprite.scale = sprite.scale; + if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost) return; + + sprite.scale = playerSpriteScale; + if (!bodySprite.isLoaded || !bodySprite.IsPlaying()) return; + if (const NullFrame* walk = bodySprite.GetNullFrame("ItemWalk")) + sprite.scale = vector_make(sprite.scale.x * walk->scale.x, sprite.scale.y * walk->scale.y); +} diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index 86cc748..7fc70a4 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -16,21 +16,14 @@ constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float DEGREES_PER_RADIAN = 57.295776f; constexpr float DUNGEON_TEAR_HEIGHT_MAX = -5.1f; constexpr float DUNGEON_TEAR_OFFSET_Y = -18; -constexpr float EXPLOSIVE_TEAR_SCALE = 0.5f; constexpr float INHERIT_SCALE = 0.6f; constexpr float LANE_HALF_ARC = 90; constexpr float LANE_SPREAD_X = 1.15f; constexpr float LANE_SPREAD_Y = 0.8f; -constexpr float QUADSPLIT_TEAR_SCALE = 1.2f; constexpr float RANDOM_UNIT = 2.3283064e-10f; constexpr float SPREAD_CLAMP = 90; constexpr float TEAR_FALL_SPREAD = 0.2f; -constexpr float TEAR_SCALE_DAMAGE = 0.01f; constexpr float TEAR_SCALE_MIN = 0.01f; -constexpr float TEAR_SCALE_ROOT = 0.23f; -constexpr float TEAR_SCALE_SIZE = 0.55f; -constexpr float HOLOGRAM_TEAR_ALPHA = 0.2f; -constexpr int TINT_ALPHA = 3; constexpr float WIZ_EYE_ANGLE = 45; // How much each extra tear widens a volley's tears and lasers, by what adds it, and how the other weapons follow. constexpr float SPREAD_ITEM_LASER = 2.333f; @@ -61,7 +54,6 @@ constexpr int DARK_ARTS_STEPS = 16; constexpr float DARK_ARTS_STEP = 0.0625f; constexpr int MAX_TEARS = 16; constexpr int MAX_EYES = 8; -constexpr int RED_STEW_BLOOD_FRAMES = 90; constexpr int BABY_TECHNOLOGY = 16; constexpr int BABY_TWENTY_TWENTY = 65; constexpr int PLAYERFORM_CONJOINED = 7; @@ -70,34 +62,18 @@ constexpr int TRANSFORMATION_COUNT = 3; constexpr int TEAR_COLOR_PRIORITY = 255; constexpr int COLLECTIBLE_20_20 = 245; -constexpr int COLLECTIBLE_ALMOND_MILK = 561; -constexpr int COLLECTIBLE_ANTI_GRAVITY = 222; constexpr int COLLECTIBLE_BRIMSTONE_WEAPON = 118; -constexpr int COLLECTIBLE_C_SECTION = 678; -constexpr int COLLECTIBLE_CHOCOLATE_MILK = 69; constexpr int COLLECTIBLE_CURSED_EYE_WEAPON = 316; constexpr int COLLECTIBLE_DEAD_TOOTH = 446; -constexpr int COLLECTIBLE_DR_FETUS = 52; -constexpr int COLLECTIBLE_EPIC_FETUS = 168; constexpr int COLLECTIBLE_EVIL_EYE = 410; constexpr int COLLECTIBLE_EYE_SORE = 558; constexpr int COLLECTIBLE_INNER_EYE = 2; constexpr int COLLECTIBLE_LARGE_ZIT = 502; -constexpr int COLLECTIBLE_LEAD_PENCIL = 444; constexpr int COLLECTIBLE_LOKIS_HORNS = 87; -constexpr int COLLECTIBLE_LUDOVICO = 329; -constexpr int COLLECTIBLE_MARKED = 394; constexpr int COLLECTIBLE_MOMS_EYE = 55; -constexpr int COLLECTIBLE_MOMS_KNIFE = 114; -constexpr int COLLECTIBLE_MONSTROS_LUNG = 229; constexpr int COLLECTIBLE_NEPTUNUS = 597; -constexpr int COLLECTIBLE_STAPLER = 708; -constexpr int COLLECTIBLE_STYE = 731; -constexpr int COLLECTIBLE_TECH_X = 395; -constexpr int COLLECTIBLE_TECHNOLOGY = 68; constexpr int COLLECTIBLE_THE_WIZ = 358; constexpr int COLLECTIBLE_TRACTOR_BEAM = 397; -constexpr int NULLITEM_REVERSE_HANGED_MAN = 65; constexpr int NULLITEM_DARK_ARTS = 111; // The items GetWeaponModifiers turns into modifier bits, in the order it asks. @@ -377,47 +353,6 @@ PosVel Entity_Player::GetMultiShotPositionVelocity(int loopIndex, WeaponType wea return shot; } -// 007bf6c0 What a tear from the player is fired with: its stats, flags and color, the eye it leaves from, and a scale -// from its damage. Only a plain player's tears are written yet: items, effects, familiars and other characters stop the -// game until reached. -TearParams Entity_Player::GetTearHitParams(WeaponType weaponType, float damageScale, int displacement, Entity* source) -{ - 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; - params.tearDamage = damageScale * damage; - params.tearHeight = tearHeight; - params.tearFlags = tearFlags; - params.tearColor = tearColor; - float baseDamage = params.tearDamage; - float scaleMultiplier = 1; - - bool isOneEyed = playerType == PLAYER_CAIN || HasCollectible(COLLECTIBLE_LEAD_PENCIL) || - !weaponTypes[WEAPON_TEARS] || HasCollectible(COLLECTIBLE_CURSED_EYE_WEAPON) || - HasCollectible(COLLECTIBLE_STAPLER) || playerType == PLAYER_CAIN_B; - bool isLeftEye = displacement < 0 || (isOneEyed && (Random() & 1) == 0); - params.tearDisplacement = isLeftEye ? -1 : (displacement >= 1 ? 1 : 0); - - if (weaponType == WEAPON_TEARS || weaponType == WEAPON_FETUS) - { - bool isLudovico = params.tearFlags.test(TEAR_LUDOVICO); - if (params.tearFlags.test(TEAR_EXPLOSIVE) && !isLudovico) scaleMultiplier = EXPLOSIVE_TEAR_SCALE; - if (params.tearFlags.test(TEAR_QUADSPLIT) && !isLudovico) params.tearScale *= QUADSPLIT_TEAR_SCALE; - if ((playerType == PLAYER_THEFORGOTTEN || playerType == PLAYER_THEFORGOTTEN_B) && - params.tearVariant != TEAR_SCHYTHE) - params.tearVariant = TEAR_BONE; - if (weaponType == WEAPON_FETUS) params.tearVariant = TEAR_FETUS; - } - - float size = params.tearScale > 1 ? std::log(params.tearScale) + 1 : params.tearScale; - params.tearScale = - (std::sqrt(baseDamage) * TEAR_SCALE_ROOT + size * TEAR_SCALE_SIZE + baseDamage * TEAR_SCALE_DAMAGE) * - scaleMultiplier; - if (IsHologram()) params.tearColor._tint[TINT_ALPHA] = HOLOGRAM_TEAR_ALPHA; - return params; -} - // 00790af0 Fires a tear with the player's hit params from a shot (from the player's tear offset when it shoots it // itself): its height, fall, scale, color, range, Dead Eye's (or Dark Arts') glow and an index, updated once and moved // back a frame. diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index ed41d39..3f3b8ec 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -1,12 +1,1607 @@ #include "entity_projectile.h" -#include "log.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "lua_callbacks.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include +#include +#include +#include -constexpr int PROJECTILE_MEAT = 11; +// The shot a fresh projectile is: its height, slight random fall, homing, curving and change defaults. +constexpr float HEIGHT_START = -23; +constexpr float FALL_SPREAD = 0.2f; +constexpr float HALF = 0.5f; +constexpr float CURVING_DEFAULT = 0.015f; +constexpr float ACCELERATION_DEFAULT = 1.01f; +constexpr int CHANGE_TIMEOUT_DEFAULT = 30; +constexpr float WEAKNESS_SPEED = 0.8f; -// 00652f60 Only a Globin's meat shot holds the doors shut, unless nothing can stop it. +// The heights a shot flies between: it lands above the floor one, and hits low only above the high one. +constexpr float FLOOR_HEIGHT = -5; +constexpr float HIGH_HEIGHT = -50; +constexpr float GRAVITY_PULL = 0.1f; +constexpr float FALL_DRAG = 0.9f; +constexpr float CRAWLSPACE_OFFSET_Y = -15; +constexpr float CRAWLSPACE_MIN_ACCEL = 0.001f; +constexpr float CRAWLSPACE_MARGIN_TOP = -600; +constexpr float CRAWLSPACE_MARGIN = -200; +constexpr float FIRE_CRAWLSPACE_LAYER_Y = 8; + +// The flags that let a shot pass the grid, and the bit flag set that changes one at once. +constexpr uint64_t GRID_PASS_FLAGS = + PROJECTILE_GHOST | PROJECTILE_ORBIT_CW | PROJECTILE_ORBIT_CCW | PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_CONTINUUM; +constexpr uint64_t FRIENDLY_FLAGS = PROJECTILE_HIT_ENEMIES | PROJECTILE_CANT_HIT_PLAYER; +constexpr uint64_t CHANGE_BOTH_FLAGS = + PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | PROJECTILE_CHANGE_VELOCITY_AFTER_TIMEOUT; +constexpr uint64_t BURST3_CHILD_CLEARED = PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT | PROJECTILE_SINE_VELOCITY; + +// The flags whose effects belong to the late bosses and items, and are not reconstructed. +constexpr uint64_t UNRECONSTRUCTED_FLAGS = PROJECTILE_CONTINUUM | PROJECTILE_STASIS | PROJECTILE_FIRE_WAVE | + PROJECTILE_FIRE_WAVE_X | PROJECTILE_FIRE_SPAWN | PROJECTILE_BLUE_FIRE_SPAWN | + PROJECTILE_LASER_SHOT | PROJECTILE_BROCCOLI | PROJECTILE_SIDE_WAVE; + +// Time: the share a slowed shot keeps, the near stop of a held or paused one, and the Hourglass's fade. +constexpr float SLOW_SCALE = 0.5f; +constexpr float HELD_SCALE = 0.02f; +constexpr float HOURGLASS_FADE_FRAMES = 30; +constexpr ColorMod SLOWED_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}}; +constexpr int SLOWED_COLOR_FRAMES = 2; + +// The Broken Modem's freeze: its chance by luck, and how long a frozen shot waits before vanishing. +constexpr int MODEM_CHANCE_BASE = 67; +constexpr int MODEM_CHANCE_MIN = 50; +constexpr int MODEM_THAW_SPREAD = 7; +constexpr int MODEM_THAW_MIN = 12; +constexpr int MODEM_SEED_FRAMES = 30; +constexpr int MODEM_SEED_STEP = 100; +constexpr RNG MODEM_RNG = {0, 5, 21, 12}; +constexpr float MODEM_CLAMP_MAX = 16; +constexpr float MODEM_SCREEN_SCALE = 0.65f; +constexpr float MODEM_ORIGIN_X = 60; +constexpr float MODEM_ORIGIN_Y = 140; +constexpr float MODEM_SCREEN_WIDTH = 338; +constexpr float MODEM_SCREEN_HEIGHT = 182; + +// The animations: the size steps of the tear-like ones and the keys the others are cached by. +constexpr float SIZE_STEP_SCALE = 3; +constexpr int SIZE_STEP_MAX = 13; +constexpr float CORN_BIG_STEP = 6; +constexpr float FCUK_BIG_SCALE = 1.5f; +constexpr float COIN_LAYER_SCALE = 2.75f; +constexpr float FIRE_GROW_FRAMES = 15; +constexpr float FIRE_SIZE_MIN = 0.1f; +constexpr int ANIM_KEY_BONE = 100; +constexpr int ANIM_KEY_FIRE = 200; +constexpr int ANIM_KEY_CORN = 300; +constexpr int ANIM_KEY_COIN = 400; +constexpr int ANIM_KEY_MEAT = 600; +constexpr int ANIM_KEY_FCUK = 700; +constexpr float DOGMA_DEPTH_OFFSET = 300; +constexpr uint64_t DOGMA_ELECTRIC_FLAGS = PROJECTILE_SHIELDED | PROJECTILE_BLUE_FIRE_SPAWN; + +// Homing: the reach of SMART and its pull, and SMART_PERFECT's reach and pull. +constexpr float SMART_RANGE = 500; +constexpr float SMART_REACH = 100; +constexpr float SMART_LEAD = 0.5f; +constexpr float SMART_PULL = 1.4f; +constexpr float SMART_DRAG = 0.92f; +constexpr int SMART_RETARGET_FRAMES = 3; +constexpr float PERFECT_RANGE = 5000; +constexpr float PERFECT_PULL = 0.1f; +constexpr float PERFECT_SPEED_MIN = 0.001f; +constexpr ColorMod SMART_COLOR = {{1, 1, 1, 1}, {0.8f, 0.15f, 1, 1}, {0.26f, 0.05f, 0.4f}}; +constexpr ColorMod GHOST_COLOR = {{0.2f, 0.2f, 0.2f, 0.5f}, {0, 0, 0, 0}, {175 / 255.0f, 175 / 255.0f, 175 / 255.0f}}; + +// Flight: the orbits' pull, the wiggles' period and size, the zigzags' turns and the speed caps. +constexpr float ORBIT_PULL = 0.5f; +constexpr float WAVE_FRAMES = 30; +constexpr float WIGGLE_SIZE = 3; +constexpr float MEGA_WIGGLE_GROWTH = 0.04f; +constexpr float MEGA_WIGGLE_GROWN = 4; +constexpr float MEGA_WIGGLE_BASE = 3; +constexpr float ROTGUT_WIGGLE_MIN = 2; +constexpr float ROTGUT_WIGGLE_MAX = 5; +constexpr float ROTGUT_WIGGLE_PERIOD = 100; +constexpr float ROTGUT_WIGGLE_PUSH = 0.0075f; +constexpr int ROTGUT_RNG_SHIFT = 8; +constexpr float SAWTOOTH_FRAMES = 30; +constexpr float TRIANGLE_FRAMES = 15; +constexpr float ZIGZAG_START_TURN = 45; +constexpr float SAWTOOTH_TURN = 135; +constexpr float TRIANGLE_TURN = 90; +constexpr float TURN_ROOM_MARGIN = 120; +constexpr float TURN_ALIGN_MAX = 0.05f; +constexpr float TURN_ALIGN_MIN = -0.4f; +constexpr float TURN_SPEED = 2; +constexpr float TARGET_ARRIVED = 10; +constexpr float TARGET_HOVER_FRAMES = 150; +constexpr float TARGET_HOVER_HEIGHT = -15; +constexpr float ACCELERATE_EX_FRAMES = 20; +constexpr float HUSH_SPEED_MAX = 9; +constexpr float SHADY_SPEED_MAX = 10; + +// The splits: BURST3's wait and chance, the speed below which a child speeds up, and the children's fall. +constexpr float BURST3_WAIT = 20; +constexpr int BURST3_CHANCE = 30; +constexpr float SPLIT_SLOW_SPEED_SQUARED = 25; +constexpr float SPLIT_SPEED_BOOST = 1.6f; +constexpr float SPLIT_HEIGHT_SHARE = 0.6f; +constexpr float SPLIT_SCALE_LOSS = 0.667f; +constexpr float SPLIT_FALL_ACCEL = 0.1f; +constexpr float SPLIT_FALL_SPEED = -3; +constexpr float BURST_HEIGHT = -11.875f; +constexpr float BURST_FALL_SPREAD = 0.2f; +constexpr float BURST_FALL_SPEED = 0.06f; +constexpr float BURST_SCALE_SHARE = 0.6f; +constexpr int BURST_COUNT = 4; +constexpr float BURST8_LIFE = 45; +constexpr float BURST8_BLOODFLY_LIFE = 10; +constexpr int BURST8_COUNT = 8; +constexpr int BURST8_BLOODFLY_COUNT = 6; +constexpr float BURST8_SPEED = 10; +constexpr float BURST8_CHILD_SCALE = 0.66f; +constexpr float BACK_SPLIT_TURN = 24; +constexpr float BACK_SPLIT_SPEED = 10; +constexpr float BACK_SPLIT_ACCEL = -0.04f; +constexpr int BURSTSPLIT_COUNT = 16; +constexpr float BURSTSPLIT_SPEED_MIN = -10; +constexpr float BURSTSPLIT_SPEED_MAX = -22; +constexpr float BURSTSPLIT_ANGLE = 70; +constexpr float BURSTSPLIT_ACCEL = 0.75f; +constexpr float BURSTSPLIT_SCALE_MIN = 0.9f; +constexpr ColorMod BURSTSPLIT_SPLASH_COLOR = {{1, 1, 1, 1}, {0.2f, 1.2f, 0, 1}, {0, 0, 0}}; +constexpr ColorMod BURSTSPLIT_COLOR = {{1, 1, 1, 1}, {2.7f, 3, 2, 1}, {0, 0, 0}}; + +// The splash a dead shot leaves: poof sizes and sounds, the creep its flags leave and the explosion. +constexpr float POOF_SCALE_SHARE = 0.8f; +constexpr float TEAR_POOF_SMALL = 0.4f; +constexpr float TEAR_POOF_LARGE = 0.8f; +constexpr float POOF_SOUND_MARGIN = -80; +constexpr float RIGHT_ANGLE = 90; +constexpr float CORN_PARTICLE_SPEED = 2; +constexpr int CORN_PARTICLES = 4; +constexpr int BONE_PARTICLES = 8; +constexpr float COIN_PARTICLE_SPEED = 3; +constexpr float COIN_PARTICLE_SPEED_MIN = 2; +constexpr int COIN_PARTICLES = 4; +constexpr float COIN_SOUND_PITCH = 2; +constexpr float COIN_SOUND_PITCH_SPREAD = 0.5f; +constexpr float COIN_SOUND_VOLUME = 0.2f; +constexpr float FIRE_POOF_ALPHA = 0.3f; +constexpr float POOF_RAISE = -10; +constexpr ColorMod PUKE_POOF_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {124 / 255.0f, 94 / 255.0f, 75 / 255.0f}}; +constexpr ColorMod FCUK_POOF_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float EXPLOSION_DAMAGE = 50; +constexpr float EXPLOSION_RADIUS = 60; +constexpr float ACID_SCALE = 3; +constexpr float ACID_GHOST_SCALE = 1.5f; +constexpr int ACID_GHOST_TIMEOUT = 10; +constexpr float ACID_SPLAT_SCALE = 0.8f; +constexpr float GOO_SCALE = 3; +constexpr float GOO_SMALL_SCALE = 2; +constexpr int GOO_TIMEOUT = 150; +constexpr int RED_CREEP_TIMEOUT = 90; +constexpr int RED_CREEP_FRAMES = 2; +constexpr float BROWN_CREEP_TICKS = 20; +constexpr int BROWN_CREEP_TIMEOUT = 180; + +// The Soul pushes shots from its holder, a few at a time. +constexpr int SOUL_CHANCE = 3; +constexpr float SOUL_REACH = 80; +constexpr float SOUL_PUSH = 0.1f; +constexpr float SOUL_PUSH_MIN = 0.05f; +constexpr float SOUL_DISTANCE_START = 1e9f; +constexpr float ANTI_GRAVITY_RATE = 0.2f; +constexpr float ANTI_GRAVITY_BOB = 2; +constexpr float FADEOUT_RATE = 0.1f; +constexpr float BOUNCE_FLOOR_SPEED = 2; +constexpr float BOUNCE_FLOOR_REBOUND = -2; +constexpr float REFLECT_REBOUND = 0.85f; +constexpr int CIRCLE_RNG_SHIFT = 44; +constexpr int CIRCLE_CHANCE = 100; +constexpr int CIRCLE_PROC_MAX = 32; + +// Hits: a small player lets shots pass over, hats block falling ones, Infamy blocks some, the frozen flash. +constexpr float PLAYER_HIT_SCALE_MIN = 0.5f; +constexpr float HAT_CRAWLSPACE_SIDE = 0.8f; +constexpr int HIT_COUNTDOWN = 30; +constexpr float ENEMY_HIT_BONUS = 5; +constexpr float GRID_HIT_DAMAGE = 35; +constexpr int FREEZE_DURATION = 90; +constexpr int GREED_COINS_MAX = 3; +constexpr float GREED_COIN_SPEED = 5; +constexpr float GREED_COIN_SPEED_MIN = 2; +constexpr float SINGE_PUSH = 0.2f; +constexpr int MOTHER_SELF_HIT_FRAMES = 5; +constexpr int INFAMY_COLOR_FRAMES = 15; +constexpr ColorMod FROZEN_COLOR = {{0.6f, 0.6f, 0.6f, 1}, {0, 0, 0, 0}, {0.4f, 0.4f, 0.4f}}; +constexpr int FROZEN_FRAMES = 30; + +// Spawn flags: a champion's shot hits harder and bigger, a weak shooter's smaller. +constexpr float CHAMPION_DAMAGE_MAX = 2; +constexpr float CHAMPION_SHOT_SCALE = 1.2173913f; +constexpr float WEAK_SHOT_SCALE = 0.8f; +constexpr int COLOR_PRIORITY = 255; +constexpr int COLOR_PRIORITY_NONE = -1; + +constexpr int ENTITY_MR_FRED = 270; +constexpr int ENTITY_MEGA_SATAN_2 = 275; +constexpr int ENTITY_RED_GHOST = 285; +constexpr int ENTITY_TARBOY = 307; +constexpr int ENTITY_NECRO = 828; +constexpr int ENTITY_SHADY = 888; +constexpr int MOTHER_BALL = 10; +constexpr int BEAST_FIRE_BALL = 20; +constexpr int ROTGUT_HEART = 2; + +constexpr int EFFECT_BONE_PARTICLE = 35; +constexpr int EFFECT_CORN_POOF = 43; +constexpr int EFFECT_CORN_PARTICLE = 58; +constexpr int EFFECT_COIN_POOF = 97; +constexpr int EFFECT_COIN_PARTICLE = 98; +constexpr int EFFECT_HUSH_POOF = 102; +constexpr int EFFECT_GODHEAD_AURA = 123; +constexpr int EFFECT_DOGMA_POOF = 200; +constexpr int GODHEAD_AURA_SUBTYPE = 4; +constexpr int BLOOD_EXPLOSION_SPLASH = 3; +constexpr int ACID_SPLAT_SUBTYPE = 0; +constexpr int FIRE_POOF_SUBTYPE = 1; +constexpr int BONE_PARTICLE_SUBTYPE = 1; + +constexpr int SOUND_BLOOD_SPLASH = 30; +constexpr int SOUND_COIN_IMPACT = 138; +constexpr int SOUND_INFAMY_BLOCK = 863; +constexpr int SOUND_PIN_GOO = 934; +constexpr int SOUND_BEAST_FIRE = 700; + +constexpr int COLLECTIBLE_SOUL = 335; +constexpr int COLLECTIBLE_BETRAYAL = 391; +constexpr int COLLECTIBLE_CIRCLE_OF_PROTECTION = 423; +constexpr uint32_t CHALLENGE_BROKEN_WATCH = 22; + +// The familiars shots hurt (the two Infamy guards as the player does), and the subtype of the one that is spared. +constexpr std::array HURT_FAMILIARS = {62, 67, 100, 206, 211, 237}; +constexpr std::array INFAMY_FAMILIARS = {62, 67}; +constexpr int SPARED_FAMILIAR = 206; +constexpr int SPARED_FAMILIAR_SUBTYPE = 702; + +// The variants whose splash is a poof sized by the shot. +constexpr std::array POOF_VARIANTS = {PROJECTILE_NORMAL, PROJECTILE_PUKE, PROJECTILE_TEAR, PROJECTILE_CORN, + PROJECTILE_HUSH, PROJECTILE_FCUK, PROJECTILE_WING, PROJECTILE_PEEP}; + +template +static bool is_listed(const std::array& list, int value) +{ + return std::find(list.begin(), list.end(), value) != list.end(); +} + +static bool is_crawlspace() +{ + return g_game->room->roomType == ROOM_DUNGEON; +} + +// Vector::Rotated: v turned by an angle in degrees. +static Vector vector_rotated(Vector v, float degrees) +{ + Vector turn = vector_from_angle(degrees); + return vector_make(v.x * turn.x - v.y * turn.y, v.x * turn.y + v.y * turn.x); +} + +static float lerp(float from, float to, float t) +{ + return from + (to - from) * t; +} + +// Math::timescale_factor: how much of a per-tick factor is left over a step of timeScale ticks. +static float timescale_factor(float factor, float timeScale) +{ + return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale); +} + +// The phase of a wave of WAVE_FRAMES frames at a time, in radians. +static float wave_phase(float time) +{ + return time * PI_F * 2 / WAVE_FRAMES; +} + +// The wiggles' sideways direction, a unit vector across the velocity (or the velocity's own when it has none). +static Vector wiggle_side(Vector velocity) +{ + return vector_normalized(vector_make(velocity.y, -velocity.x)); +} + +// Plays a sound through the fart seeds, at a pitch and volume, unless the sound is muted by the frame delay. +static void sound_play(int sound, float pitch, float volume) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = volume, .pitch = pitch}); +} + +// Makes a sprite layer add its light to what is under it (BlendMode::SetMode's additive mode). +static void layer_additive_set(ANM2& sprite, int layerId) +{ + LayerState* layer = sprite.GetLayer(layerId); + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; + + layer->blendMode[BLEND_EQUATION] = BLEND_EQUATION_ADD; + layer->blendMode[BLEND_RGB_SOURCE] = isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA; + layer->blendMode[BLEND_RGB_DEST] = BLEND_FACTOR_ONE; + layer->blendMode[BLEND_ALPHA_SOURCE] = BLEND_FACTOR_ONE; + layer->blendMode[BLEND_ALPHA_DEST] = BLEND_FACTOR_ONE; +} + +// Spawns an effect at a position. Game::Spawn returning nothing crashes the original. Callers skip what it sets. +static Entity_Effect* effect_spawn(int variant, const Vector& position, Entity* spawner, int subType = 0) +{ + uint32_t seed = Random(); + Entity* effect = g_game->Spawn({.position = position, .spawner = spawner, .subType = subType, + .type = ENTITY_EFFECT, .variant = variant, .seed = seed}); + return static_cast(effect); +} + +// Spawns a shot from a shot, taking on its spawner type and variant as the splits do. +static Entity_Projectile* child_spawn(Entity_Projectile& source, const EntitySpawn& spawn) +{ + Entity* spawned = g_game->Spawn(spawn); + if (!spawned) return nullptr; + + auto* child = static_cast(spawned); + child->spawnerType = source.spawnerType; + child->spawnerVariant = source.spawnerVariant; + return child; +} + +// Whether the shot is the players' (it hits enemies and not players). +static bool is_friendly_shot(uint64_t flags) +{ + return (flags & FRIENDLY_FLAGS) == FRIENDLY_FLAGS; +} + +static bool is_any_player_holding(int collectible) +{ + return g_game->playerManager.AnyoneHasCollectible(collectible); +} + +// 00652b90 Starts a shot 23 high with a slight random fall, no flags, its config's sprite and the default homing, +// curving and change. Fire glows, and a weak shooter's shots are weak and slow. +void Entity_Projectile::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) +{ + Entity::Init(entityType, entityVariant, entitySubType, seed); + entityGridCollisionClass = GRIDCOLL_BULLET; + if (config) sprite.Load(config->anm2Path, GRAPHICS_LOAD); + + height = HEIGHT_START; + fallingSpeed = (random_unit() - HALF) * FALL_SPREAD; + fallingAccel = 0; + scale = 1; + projectileFlags = 0; + homingStrength = 1; + curvingStrength = CURVING_DEFAULT; + acceleration = ACCELERATION_DEFAULT; + orbitDistance = 0; + animKey = -1; + collisionDamage = 1; + isRenderedAtGround = false; + changeFlags = 0; + changeVelocity = 0; + changeTimeout = CHANGE_TIMEOUT_DEFAULT; + maxHitPoints = 0; + modemPosition = {}; + motionHook = nullptr; + + if (variant == PROJECTILE_FIRE) + { + layer_additive_set(sprite, 0); + if (is_crawlspace()) sprite.GetLayer(0)->pos = vector_make(0, FIRE_CRAWLSPACE_LAYER_Y); + } + if (spawnerEntity && spawnerEntity->HasEntityFlags(FLAG_WEAKNESS)) + { + AddEntityFlags(FLAG_WEAKNESS); + velocity = vector_scale(velocity, WEAKNESS_SPEED); + } + orbitParentVelocity = {}; +} + +// 00652df0 Its time scale: the room's, halved for a hostile shot by the Stop Watch, the Broken Watch's slow rooms +// and the Hourglass fading out, and for a friendly one by the room's slowdown. Slowed shots go at half speed, held +// or paused ones nearly stop. +float Entity_Projectile::time_scale_get() +{ + Room& room = *g_game->room; + float timeScale = room.GetTimeScale(this); + + if (is_friendly_shot(projectileFlags)) + { + if (room.HasSlowDown()) timeScale *= SLOW_SCALE; + } + else if (!parent || !parent->IsFriendly()) + { + TemporaryEffects& effects = room.temporaryEffects; + bool isBrokenWatchSlow = + g_game->challenge != CHALLENGE_BROKEN_WATCH && room.brokenWatchState == BROKEN_WATCH_SLOW; + if (effects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH) || isBrokenWatchSlow) timeScale *= SLOW_SCALE; + else if (TemporaryEffect* hourglass = effects.GetCollectibleEffect(COLLECTIBLE_HOURGLASS)) + timeScale *= 1 - std::min(std::max((float)hourglass->cooldown / HOURGLASS_FADE_FRAMES, 0.0f), 1.0f) * + SLOW_SCALE; + } + if (projectileFlags & PROJECTILE_SLOWED) timeScale *= SLOW_SCALE; + if (pauseTimer > 0 || holdCountdown > 0) timeScale *= HELD_SCALE; + return timeScale; +} + +// 00653070 Flies the shot for a frame: its animation, the base update, its flags' steering and wiggles, its fall, +// and its splash once it has died. A shot the Broken Modem froze waits, then vanishes. +void Entity_Projectile::Update() +{ + speedMultiplier = time_scale_get(); + if (pauseTimer > 0) pauseTimer--; + if (projectileFlags & GRID_PASS_FLAGS) isCollidesWithGrid = false; + if (projectileFlags & UNRECONSTRUCTED_FLAGS) + { + char name[96]; + std::snprintf(name, sizeof(name), "Entity_Projectile::Update 00653070: the projectile flags %llx", + (unsigned long long)(projectileFlags & UNRECONSTRUCTED_FLAGS)); + reconstruction_missing(name); + } + if (modem_freeze_update()) return; + + animation_update(); + if (is_crawlspace() && FrameCount() == 1) + { + if (fallingAccel > 0 && std::fabs(velocity.x) > velocity.y) velocity.y = fallingSpeed * HALF + velocity.y; + if (!g_game->room->IsBeastDungeon() && (projectileFlags & PROJECTILE_EXPLODE)) + projectileFlags &= ~(PROJECTILE_GHOST | PROJECTILE_NO_WALL_COLLIDE); + } + Entity::Update(); + if (FrameCount() == 1) first_frame_update(); + + if (projectileFlags & PROJECTILE_BURST8) + { + bool isBloodfly = subtype == 0 && spawnerType == ENTITY_SUCKER && spawnerVariant == SUCKER_BLOODFLY; + if (updateTime > (isBloodfly ? BURST8_BLOODFLY_LIFE : BURST8_LIFE)) isDead = true; + } + trails_update(); + if (isDead) return death_update(); + + if (motionHook) motionHook(*this, PROJECTILE_STEP_UPDATE); + homing_update(); + steering_update(); + if (wiggles_update()) return; + speed_update(); + fall_update(); + late_update(); +} + +// The Broken Modem's freeze: a frozen shot vanishes after a while, and waits in place until then. Whether it did. +bool Entity_Projectile::modem_freeze_update() +{ + if (!HasEntityFlags(FLAG_FREEZE)) return false; + + if (freezeCountdown <= 0 && IsFrame((int)(Random() % MODEM_THAW_SPREAD) + MODEM_THAW_MIN, 0)) + { + ClearEntityFlags(FLAG_FREEZE); + modemPosition = {}; + Remove(); + return true; + } + if (isDead) return false; + + velocity = {}; + Entity::Update(); + return true; +} + +// The animation of its variant, played once per change of size or variant: the tear-like ones by size, the bones, +// fire, corn and coins at a random frame, and its shadow by its scale. +void Entity_Projectile::animation_update() +{ + char name[32]; + int sizeStep = std::min((int)(scale * SIZE_STEP_SCALE + SIZE_STEP_SCALE), SIZE_STEP_MAX); + auto frame_randomize = [this]() + { + int length = sprite.animState.GetAnimationLength(); + if (length > 0) sprite.SetFrame((float)(dropRNG._seed % (uint32_t)length)); + }; + + switch (variant) + { + case PROJECTILE_NORMAL: + case PROJECTILE_PUKE: + case PROJECTILE_TEAR: + case PROJECTILE_HUSH: + if (animKey == sizeStep) break; + if (spawnerType == ENTITY_DOGMA) + { + bool isElectric = projectileFlags & DOGMA_ELECTRIC_FLAGS; + std::snprintf(name, sizeof(name), isElectric ? "DogmaElectricTear%d" : "DogmaTear%d", sizeStep); + renderDepthOffset = DOGMA_DEPTH_OFFSET; + sprite.bitflags |= ANIM_RENDER_STATIC; + } + else std::snprintf(name, sizeof(name), "RegularTear%d", sizeStep); + sprite.Play(name); + animKey = sizeStep; + break; + case PROJECTILE_BONE: + if (animKey == ANIM_KEY_BONE) break; + sprite.Play("Move"); + if (sprite.animState.animData) frame_randomize(); + animKey = ANIM_KEY_BONE; + break; + case PROJECTILE_FIRE: + if (animKey != ANIM_KEY_FIRE) + { + sprite.Play("Flickering"); + frame_randomize(); + layer_additive_set(sprite, 0); + animKey = ANIM_KEY_FIRE; + isUnknown176 = false; + } + sprite.GetLayer(0)->size = + vector_scale(vector_make(1, 1), std::clamp(updateTime / FIRE_GROW_FRAMES, FIRE_SIZE_MIN, 1.0f)); + break; + case PROJECTILE_CORN: + { + if (animKey == ANIM_KEY_CORN) break; + bool isBig = scale * SIZE_STEP_SCALE + SIZE_STEP_SCALE > CORN_BIG_STEP; + std::snprintf(name, sizeof(name), isBig ? "Big%02d" : "Small%02d", random_below(4) + 1); + sprite.Play(name); + animKey = ANIM_KEY_CORN; + break; + } + case PROJECTILE_COIN: + if (animKey != ANIM_KEY_COIN) + { + sprite.Play("MoveHori"); + frame_randomize(); + animKey = ANIM_KEY_COIN; + } + sprite.rotation = vector_angle(velocity); + sprite.GetLayer(0)->size = vector_scale(vector_make(1, 1), scale / COIN_LAYER_SCALE); + break; + case PROJECTILE_FCUK: + if (animKey == ANIM_KEY_FCUK) break; + sprite.Play(scale < FCUK_BIG_SCALE ? "Small" : "Big"); + animKey = ANIM_KEY_FCUK; + break; + case PROJECTILE_ROCK: + case PROJECTILE_WING: + case PROJECTILE_LAVA: + case PROJECTILE_HEAD: + case PROJECTILE_PEEP: + reconstruction_missing("Entity_Projectile::Update 00653070: this projectile variant's animation"); + } + + // A shot without a config crashes the original here. This leaves its shadow. + if (config) shadowSize = scale * config->shadowSize; + if (variant == PROJECTILE_GRID) shadowSize += shadowSize; + else if (variant == PROJECTILE_MEAT && animKey != ANIM_KEY_MEAT) + { + sprite.Play("Move"); + frame_randomize(); + animKey = ANIM_KEY_MEAT; + } +} + +// Its first frame after the base update: a Godhead shot takes its aura. +void Entity_Projectile::first_frame_update() +{ + if ((projectileFlags & PROJECTILE_EXPLODE) && spawnerType == ENTITY_HERETIC) + reconstruction_missing("Entity_Projectile::Update 00653070: the Heretic's glowing shot"); + if (!(projectileFlags & PROJECTILE_GODHEAD)) return; + + uint32_t seed = Random(); + Entity* aura = g_game->Spawn({.position = pos, .velocity = velocity, .spawner = spawnerEntity, + .subType = GODHEAD_AURA_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_GODHEAD_AURA, .seed = seed}); + if (!aura) return; + aura->sprite.scale = vector_make(scale, scale); + aura->parent = this; + aura->Update(); +} + +// The trails the late bosses' shots leave, which are not reconstructed. +void Entity_Projectile::trails_update() +{ + bool isNecroBone = spawnerType == ENTITY_NECRO && variant == PROJECTILE_BONE; + bool isBeastFire = (projectileFlags & PROJECTILE_EXPLODE) && spawnerType == ENTITY_BEAST && + spawnerVariant == BEAST_FIRE_BALL; + bool isMotherShot = spawnerType == ENTITY_MOTHER && spawnerVariant == 0 && subtype == 1; + if (isNecroBone || isBeastFire || isMotherShot) + reconstruction_missing("Entity_Projectile::Update 00653070: a late boss's shot trail"); +} + +// Its splash: a poof by its variant or an explosion, the creep and splits its flags leave, then it is removed. +// A frozen shot just vanishes. +void Entity_Projectile::death_update() +{ + if (HasEntityFlags(FLAG_FREEZE)) return Remove(); + + death_poof_spawn(); + death_flags_apply(); + death_bursts_spawn(); + Remove(); + if (variant == PROJECTILE_FIRE && spawnerType == ENTITY_BEAST) npc_sound_play(SOUND_BEAST_FIRE, 1, 2, 1); +} + +// The poof of a dead shot by its variant, or the explosion of an exploding one, tinted its color. +void Entity_Projectile::death_poof_spawn() +{ + Entity_Effect* poof = nullptr; + + if (projectileFlags & PROJECTILE_EXPLODE) + { + poof = effect_spawn(EFFECT_BOMB_EXPLOSION, pos, nullptr); + explosion_damage({.position = pos, + .source = parent ? parent.get() : this, + .damageFlags = DAMAGE_EXPLOSION, + .damage = EXPLOSION_DAMAGE, + .radius = EXPLOSION_RADIUS}); + projectileFlags &= ~PROJECTILE_EXPLODE; + if (spawnerType == ENTITY_HERETIC || (spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL)) + reconstruction_missing("Entity_Projectile::Update 00653070: a late boss's exploding shot"); + } + else if (is_listed(POOF_VARIANTS, variant)) + { + int effect = EFFECT_BULLET_POOF; + int sound = height > FLOOR_HEIGHT ? SOUND_SPLATTER : SOUND_TEAR_IMPACTS; + float poofScale = scale * POOF_SCALE_SHARE; + float volume = 1; + + if (variant == PROJECTILE_TEAR) + { + if (scale < TEAR_POOF_SMALL) effect = EFFECT_TEAR_POOF_VERYSMALL; + else if (scale < TEAR_POOF_LARGE) effect = EFFECT_TEAR_POOF_SMALL; + else effect = height <= FLOOR_HEIGHT ? EFFECT_TEAR_POOF_A : EFFECT_TEAR_POOF_B; + if (scale < TEAR_POOF_LARGE) poofScale = 1; + if (scale < TEAR_POOF_SMALL) volume = POOF_VOLUME_TINY; + else if (scale < TEAR_POOF_LARGE) volume = POOF_VOLUME_SMALL; + } + else if (variant == PROJECTILE_CORN) + { + game_particles_spawn({.color = sprite.color, + .position = pos, + .height = height, + .speed = random_unit() * CORN_PARTICLE_SPEED + 1, + .count = CORN_PARTICLES, + .variant = EFFECT_CORN_PARTICLE}); + effect = EFFECT_CORN_POOF; + } + else if (variant == PROJECTILE_HUSH) effect = EFFECT_HUSH_POOF; + else if (sprite.bitflags & ANIM_RENDER_STATIC) effect = EFFECT_DOGMA_POOF; + + poof = effect_spawn(effect, pos, nullptr); + if (poof) + { + poof->posOffset = posOffset; + poof->sprite.scale = vector_make(poofScale, poofScale); + poof->sprite.rotation = (float)random_below(4) * RIGHT_ANGLE; + } + if (g_game->room->IsPositionInRoom(pos, POOF_SOUND_MARGIN)) sound_play(sound, 1, volume); + } + else if (variant == PROJECTILE_BONE) + { + game_particles_spawn({.color = sprite.color, + .position = pos, + .height = height, + .speed = random_unit() * CORN_PARTICLE_SPEED + 1, + .count = BONE_PARTICLES, + .subType = BONE_PARTICLE_SUBTYPE, + .variant = EFFECT_BONE_PARTICLE}); + } + else if (variant == PROJECTILE_FIRE) + { + Entity_Effect* smoke = effect_spawn(EFFECT_POOF01, vector_add(pos, vector_make(0, POOF_RAISE)), nullptr, + FIRE_POOF_SUBTYPE); + ColorMod color = sprite.color; + color._tint[3] *= FIRE_POOF_ALPHA; + if (smoke) smoke->SetColor(color, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + } + else if (variant == PROJECTILE_COIN) + { + Entity_Effect* coinPoof = effect_spawn(EFFECT_COIN_POOF, vector_add(pos, vector_make(0, POOF_RAISE)), nullptr); + if (coinPoof) coinPoof->SetColor(COLOR_DEFAULT, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + float speed = random_unit() * COIN_PARTICLE_SPEED + COIN_PARTICLE_SPEED_MIN; + game_particles_spawn({.color = sprite.color, + .position = pos, + .height = height, + .speed = speed, + .count = random_below(2) + COIN_PARTICLES, + .variant = EFFECT_COIN_PARTICLE}); + sound_play(SOUND_COIN_IMPACT, random_unit() * COIN_SOUND_PITCH_SPREAD + COIN_SOUND_PITCH, COIN_SOUND_VOLUME); + } + else if (variant == PROJECTILE_GRID || variant == PROJECTILE_ROCK || variant == PROJECTILE_MEAT) + reconstruction_missing("Entity_Projectile::Update 00653070: this projectile variant's splash"); + + if (!(projectileFlags & PROJECTILE_EXPLODE) && (projectileFlags & PROJECTILE_CREEP_BROWN)) + { + Entity_Effect* creep = effect_spawn(EFFECT_CREEP_BROWN, pos, this); + if (creep) + { + creep->Update(); + creep->SetTimeout(BROWN_CREEP_TIMEOUT); + } + } + if (!poof) return; + + poof->SetColor(sprite.color, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + if (variant == PROJECTILE_PUKE) poof->SetColor(PUKE_POOF_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + else if (variant == PROJECTILE_FCUK) + poof->SetColor(FCUK_POOF_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); +} + +// The creep a dead shot's flags leave: acid with a splat, and goo, smaller from Pin's, Tar Boy's and the Leapers'. +void Entity_Projectile::death_flags_apply() +{ + if (projectileFlags & (PROJECTILE_ACID_GREEN | PROJECTILE_ACID_RED)) + { + int creepVariant = (projectileFlags & PROJECTILE_ACID_GREEN) ? EFFECT_CREEP_GREEN : EFFECT_CREEP_RED; + Entity_Effect* creep = effect_spawn(creepVariant, pos, this); + if (creep) + { + creep->spawnerType = spawnerType; + bool isGhost = projectileFlags & PROJECTILE_GHOST; + float creepScale = isGhost ? ACID_GHOST_SCALE : ACID_SCALE; + creep->sprite.scale = vector_make(creepScale, creepScale); + if (isGhost) creep->SetTimeout(ACID_GHOST_TIMEOUT); + creep->Update(); + } + Entity_Effect* splat = effect_spawn(EFFECT_BLOOD_SPLAT, pos, nullptr, ACID_SPLAT_SUBTYPE); + if (splat) + { + float splatScale = random_unit() + ACID_SPLAT_SCALE; + splat->sprite.scale = vector_make(splatScale, splatScale); + splat->SetColor(sprite.color, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + splat->Update(); + } + } + if (!(projectileFlags & PROJECTILE_GOO)) return; + + bool isPin = spawnerType == ENTITY_PIN; + bool isSmall = isPin || spawnerType == ENTITY_TARBOY || spawnerType == ENTITY_LEAPER; + Entity_Effect* goo = effect_spawn(isPin ? EFFECT_CREEP_WHITE : EFFECT_CREEP_BLACK, pos, this); + if (goo) + { + if (!isPin && isSmall) goo->SetTimeout(GOO_TIMEOUT); + float gooScale = isSmall ? GOO_SMALL_SCALE : GOO_SCALE; + goo->sprite.scale = vector_make(gooScale, gooScale); + goo->Update(); + } + if (isPin) npc_sound_play(SOUND_PIN_GOO, 1, 2, 1); +} + +// The shots a dead shot splits into: four for BURST (a cross from Pin's), eight or six for BURST8, two back for +// BACK_SPLIT and a fan of sixteen for BURSTSPLIT. +void Entity_Projectile::death_bursts_spawn() +{ + if (projectileFlags & PROJECTILE_BURST) + { + if (spawnerType == ENTITY_ROTGUT && spawnerVariant == ROTGUT_HEART) + reconstruction_missing("Entity_Projectile::Update 00653070: Rotgut's bursting shot"); + + bool isPin = spawnerType == ENTITY_PIN; + float speed = vector_length(velocity); + Vector shot = isPin ? vector_make(speed, 0) : vector_scale(random_direction(), speed); + if (isPin && random_below(2) == 0) shot = vector_rotated(shot, ZIGZAG_START_TURN); + if (isPin && vector_length_squared(shot) < SPLIT_SLOW_SPEED_SQUARED) + shot = vector_scale(shot, SPLIT_SPEED_BOOST); + + for (int i = 0; i < BURST_COUNT; i++) + { + Vector childVelocity = shot; + if (!isPin) + { + childVelocity = i < 2 ? shot : vector_make(shot.y, -shot.x); + if (i & 1) childVelocity = vector_scale(childVelocity, -1); + } + Entity_Projectile* child = child_spawn(*this, {.position = vector_sub(pos, velocity), + .velocity = childVelocity, + .spawner = isPin ? nullptr : parent.get(), + .type = type, + .variant = variant, + .seed = Random()}); + if (isPin) shot = vector_make(shot.y, -shot.x); + if (!child) continue; + + if (isPin) + { + child->height = std::min(height * SPLIT_HEIGHT_SHARE, HEIGHT_START); + child->scale = std::max(scale - SPLIT_SCALE_LOSS, 1.0f); + child->fallingAccel = SPLIT_FALL_ACCEL; + child->fallingSpeed = SPLIT_FALL_SPEED; + } + else + { + child->height = BURST_HEIGHT; + child->fallingAccel = fallingAccel; + child->fallingSpeed = random_unit() * BURST_FALL_SPREAD - BURST_FALL_SPEED; + child->SetCollisionDamage(1); + child->scale = scale * BURST_SCALE_SHARE; + } + child->projectileFlags = projectileFlags & ~PROJECTILE_BURST; + child->SetColor(sprite.color, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + child->parent = parent.get(); + child->Update(); + } + } + + if (projectileFlags & PROJECTILE_BURST8) + { + pos = vector_sub(pos, vector_scale(gridCollisionVelocity, 2)); + sound_play(SOUND_BLOOD_SPLASH, 1, 1); + effect_spawn(EFFECT_BLOOD_EXPLOSION, pos, nullptr, BLOOD_EXPLOSION_SPLASH); + bool isBloodfly = spawnerType == ENTITY_SUCKER && spawnerVariant == SUCKER_BLOODFLY; + int count = isBloodfly ? BURST8_BLOODFLY_COUNT : BURST8_COUNT; + for (int i = 0; i < count; i++) + { + Vector shot = vector_scale(vector_from_angle((float)i * 360 / (float)count), BURST8_SPEED); + Entity_Projectile* child = child_spawn(*this, {.position = vector_add(pos, shot), + .velocity = shot, + .spawner = spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = Random()}); + if (!child) continue; + + uint64_t flags = projectileFlags & ~PROJECTILE_BURST8; + if (subtype > 0) + { + child->scale = scale * BURST8_CHILD_SCALE; + child->subtype = subtype - 1; + flags = projectileFlags; + } + child->projectileFlags = flags; + } + } + + if (projectileFlags & PROJECTILE_BACK_SPLIT) + { + Vector back = vector_scale(vector_normalized(velocity), -1); + for (int side = -1; side < 2; side += 2) + { + Vector shot = vector_scale(vector_rotated(back, (float)side * BACK_SPLIT_TURN), BACK_SPLIT_SPEED); + Entity_Projectile* child = child_spawn(*this, {.position = vector_add(pos, shot), + .velocity = shot, + .spawner = spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = Random()}); + if (!child) continue; + child->fallingAccel = BACK_SPLIT_ACCEL; + child->projectileFlags = projectileFlags & ~PROJECTILE_BACK_SPLIT; + } + } + + if (!(projectileFlags & PROJECTILE_BURSTSPLIT)) return; + if (spawnerType == ENTITY_ROTGUT && spawnerVariant == ROTGUT_HEART) + reconstruction_missing("Entity_Projectile::Update 00653070: Rotgut's split shot"); + + sound_play(SOUND_BLOOD_SPLASH, 1, 1); + Entity_Effect* splash = effect_spawn(EFFECT_BLOOD_EXPLOSION, pos, nullptr, BLOOD_EXPLOSION_SPLASH); + if (splash) splash->SetColor(BURSTSPLIT_SPLASH_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + for (int i = 0; i < BURSTSPLIT_COUNT; i++) + { + float speed = lerp(BURSTSPLIT_SPEED_MIN, BURSTSPLIT_SPEED_MAX, random_unit()); + float angle = lerp(-BURSTSPLIT_ANGLE, BURSTSPLIT_ANGLE, random_unit()); + Vector shot = vector_rotated(vector_make(0, speed), angle); + Entity_Projectile* child = child_spawn(*this, {.position = pos, + .velocity = shot, + .spawner = spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = Random()}); + if (!child) continue; + + child->SetColor(BURSTSPLIT_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + child->projectileFlags = projectileFlags & ~(PROJECTILE_BURSTSPLIT | PROJECTILE_EXPLODE); + child->fallingAccel = BURSTSPLIT_ACCEL; + child->scale = random_unit() * BURST_SCALE_SHARE + BURSTSPLIT_SCALE_MIN; + } +} + +// Homing: SMART_PERFECT turns straight at its target, SMART pulls toward a near one (purple while it does). A +// friendly shot goes after enemies. +void Entity_Projectile::homing_update() +{ + auto target_find = [this](float range) + { + bool isFriendly = (spawnerEntity && spawnerEntity->HasEntityFlags(FLAG_CHARM)) || + (projectileFlags & PROJECTILE_CANT_HIT_PLAYER); + if (isFriendly) + reconstruction_missing("Entity_Projectile::Update 00653070: a friendly shot's nearest enemy " + "(Game::GetNearestEnemy 00707370)"); + target = game_nearest_target_player(pos, spawnerEntity, false, true, range); + }; + + if (projectileFlags & PROJECTILE_SMART_PERFECT) + { + if (!target) target_find(PERFECT_RANGE); + if (!target) return; + Vector pull = vector_scale(vector_sub(target->pos, pos), PERFECT_PULL); + velocity = vector_resized(vector_add(velocity, pull), std::max(vector_length(velocity), PERFECT_SPEED_MIN)); + return; + } + if (!(projectileFlags & PROJECTILE_SMART)) return; + + if (IsFrame(SMART_RETARGET_FRAMES, 0)) target = nullptr; + if (!target) target_find(SMART_RANGE); + if (target) + { + Vector lead = vector_sub(vector_add(target->pos, vector_scale(target->velocity, SMART_LEAD)), pos); + if (vector_length(lead) < SMART_REACH) + { + Vector pull = vector_scale(vector_normalized(vector_sub(target->pos, pos)), SMART_PULL); + velocity = vector_add(velocity, vector_scale(pull, homingStrength * speedMultiplier)); + velocity = vector_scale(velocity, + timescale_factor(lerp(1, SMART_DRAG, homingStrength), speedMultiplier)); + } + } + if (color._tint[0] == 1) SetColor(SMART_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); +} + +// The steering flags: the ghost's look, the creep trails, the orbits, the curves, the turn toward a player at +// their height and the pull along a tractor beam. +void Entity_Projectile::steering_update() +{ + if ((projectileFlags & PROJECTILE_GHOST) && spawnerType != ENTITY_RED_GHOST) + SetColor(GHOST_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + if ((projectileFlags & PROJECTILE_RED_CREEP) && IsFrame(RED_CREEP_FRAMES, 0)) + { + Entity_Effect* creep = effect_spawn(EFFECT_CREEP_RED, pos, this); + if (creep && spawnerType != ENTITY_MR_FRED) creep->SetTimeout(RED_CREEP_TIMEOUT); + } + if ((projectileFlags & PROJECTILE_CREEP_BROWN) && GetIntervalTicks(BROWN_CREEP_TICKS, 0)) + { + Entity_Effect* creep = effect_spawn(EFFECT_CREEP_BROWN, pos, this); + if (creep) + { + creep->Update(); + creep->SetTimeout(BROWN_CREEP_TIMEOUT); + } + } + orbit_update(); + + if (projectileFlags & (PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT)) + { + float speed = vector_length(velocity); + Vector side = vector_make(-velocity.y, velocity.x); + if (projectileFlags & PROJECTILE_CURVE_LEFT) side = vector_scale(side, -1); + velocity = vector_add(velocity, vector_scale(side, speed * curvingStrength * speedMultiplier)); + velocity = vector_resized(velocity, speed); + } + + if (projectileFlags & PROJECTILE_TURN_HORIZONTAL) + { + Room& room = *g_game->room; + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector toPlayer = vector_sub(player->pos, pos); + float alignment = vector_dot(vector_make(0, 1), vector_normalized(toPlayer)); + bool isInRoom = + room.topLeftPos.x - TURN_ROOM_MARGIN < pos.x && pos.x < room.bottomRightPos.x + TURN_ROOM_MARGIN; + if (alignment >= TURN_ALIGN_MAX || alignment <= TURN_ALIGN_MIN || !isInRoom) continue; + + Vector turn = vector_make(vector_length(velocity) * TURN_SPEED, 0); + velocity = vector_dot(toPlayer, turn) <= 0 ? vector_scale(turn, -1) : turn; + projectileFlags &= ~PROJECTILE_TURN_HORIZONTAL; + break; + } + } + + if (!(projectileFlags & PROJECTILE_TRACTOR_BEAM)) return; + bool isBeamGone = !spawnerEntity || vector_is_zero(spawnerEntity->targetPosition); + float beamLength = isBeamGone ? 0 : vector_length(spawnerEntity->targetPosition); + Vector origin = isBeamGone ? Vector{} : spawnerEntity->pos; + Vector direction = isBeamGone ? Vector{} : vector_scale(spawnerEntity->targetPosition, 1 / beamLength); + Vector offset = vector_sub(pos, origin); + float along = vector_dot(offset, direction) < 0 ? -vector_length(offset) : vector_length(offset); + if (isBeamGone || along < 0 || beamLength < along) + { + isDead = true; + projectileFlags &= ~PROJECTILE_TRACTOR_BEAM; + return; + } + float speed = vector_length(velocity); + pos = vector_add(origin, vector_scale(direction, along)); + velocity = vector_scale(direction, speed); +} + +// The orbits: it circles its target position (or its parent with ORBIT_PARENT, moving along with it), pulled to its +// orbit distance. +void Entity_Projectile::orbit_update() +{ + if (!(projectileFlags & (PROJECTILE_ORBIT_CW | PROJECTILE_ORBIT_CCW))) return; + + bool isParentOrbit = (projectileFlags & PROJECTILE_ORBIT_PARENT) && parent; + if (isParentOrbit) velocity = vector_sub(velocity, orbitParentVelocity); + + Vector center = isParentOrbit ? parent->pos : targetPosition; + Vector offset = vector_sub(pos, center); + Vector tangent = vector_make(-offset.y, offset.x); + if (projectileFlags & PROJECTILE_ORBIT_CCW) tangent = vector_scale(tangent, -1); + float pull = orbitDistance <= 0 + ? ORBIT_PULL + : std::clamp(1 - vector_length(offset) / orbitDistance, -1.0f, 1.0f) * ORBIT_PULL; + Vector heading = vector_normalized(vector_add(vector_scale(offset, pull), tangent)); + velocity = vector_scale(heading, vector_length(velocity)); + if (!isParentOrbit) return; + + velocity = vector_add(velocity, parent->velocity); + orbitParentVelocity = parent->velocity; + targetPosition = parent->pos; +} + +// The wiggles and zigzags, and the pull back to its parent, which removes it once it arrives. Whether it did. +bool Entity_Projectile::wiggles_update() +{ + if (projectileFlags & PROJECTILE_WIGGLE_ROTGUT) + { + RNG rng; + rng.SetSeed(initSeed, ROTGUT_RNG_SHIFT); + float strength = lerp(ROTGUT_WIGGLE_MIN, ROTGUT_WIGGLE_MAX, rng.RandomFloat()); + float phase = updateTime / ROTGUT_WIGGLE_PERIOD + rng.RandomFloat(); + float length = vector_length(targetPosition); + Vector direction = vector_scale(targetPosition, 1 / length); + float along = vector_dot(velocity, direction); + Vector forward = vector_scale(direction, along); + Vector wiggle = vector_scale(vector_rotated(direction, RIGHT_ANGLE), strength * std::sin(phase * 2 * PI_F)); + if (along < length) forward = vector_add(forward, vector_scale(direction, length * ROTGUT_WIGGLE_PUSH)); + velocity = vector_add(forward, wiggle); + } + if (projectileFlags & PROJECTILE_SINE_VELOCITY) + pos = vector_add(pos, vector_scale(velocity, std::sin(wave_phase(updateTime)))); + + float wiggleTime = (float)wiggleFrameOffset + updateTime; + if (projectileFlags & PROJECTILE_WIGGLE) + { + float speed = spawnerType == ENTITY_MOTHER ? 2 : 1; + float wave = std::cos(wave_phase(wiggleTime * speed)) * WIGGLE_SIZE; + pos = vector_add(pos, vector_scale(wiggle_side(velocity), wave)); + } + if (projectileFlags & PROJECTILE_MEGA_WIGGLE) + { + float size = std::min(wiggleTime * MEGA_WIGGLE_GROWTH, MEGA_WIGGLE_GROWN) + MEGA_WIGGLE_BASE; + pos = vector_add(pos, vector_scale(wiggle_side(velocity), std::cos(wave_phase(wiggleTime)) * size)); + } + + auto zigzag = [this](float frames, float turn) + { + int peak = (int)(std::sqrt(2.0f) * frames / (std::sqrt(2.0f) + 1)); + if (FrameCount() == 1) velocity = vector_rotated(velocity, ZIGZAG_START_TURN); + else if (update_ticks_get() >= 1) + { + int step = (int)updateTime % (int)frames; + if (step == peak) velocity = vector_rotated(velocity, -turn); + else if (step == 0) velocity = vector_rotated(velocity, turn); + } + }; + if (projectileFlags & PROJECTILE_SAWTOOTH_WIGGLE) zigzag(SAWTOOTH_FRAMES, SAWTOOTH_TURN); + if (projectileFlags & PROJECTILE_TRIANGLE) zigzag(TRIANGLE_FRAMES, TRIANGLE_TURN); + + if (!(projectileFlags & PROJECTILE_MOVE_TO_PARENT) || !parent) return false; + Vector toParent = vector_sub(parent->pos, pos); + velocity = vector_resized(toParent, vector_length(velocity)); + if (vector_length_squared(toParent) >= vector_length_squared(velocity)) return false; + Remove(); + return true; +} + +// The speed flags: the pull to a position, acceleration (capped for Hush's and Shady's shots), deceleration and the +// acceleration that grows in, and BURST3's split into three. +void Entity_Projectile::speed_update() +{ + if (projectileFlags & PROJECTILE_ACCELERATE_TO_POSITION) + { + Vector toTarget = vector_sub(targetPosition, pos); + float distance = vector_length(toTarget); + if (distance >= TARGET_ARRIVED) + { + AddVelocity(vector_scale(toTarget, homingStrength / distance), false); + if (updateTime < TARGET_HOVER_FRAMES) + { + fallingSpeed = 0; + height = TARGET_HOVER_HEIGHT; + } + } + else isDead = true; + } + if (projectileFlags & PROJECTILE_ACCELERATE) + { + velocity = vector_scale(velocity, timescale_factor(acceleration, speedMultiplier)); + float speed = vector_length(velocity); + float speedMax = spawnerType == ENTITY_HUSH ? HUSH_SPEED_MAX : SHADY_SPEED_MAX; + bool isCapped = spawnerType == ENTITY_HUSH || spawnerType == ENTITY_SHADY; + if (isCapped && speed > speedMax) velocity = vector_scale(velocity, speedMax / speed); + } + if (projectileFlags & PROJECTILE_DECELERATE) + velocity = vector_scale(velocity, timescale_factor(1 / acceleration, speedMultiplier)); + if (projectileFlags & PROJECTILE_ACCELERATE_EX) + { + float grown = lerp(1, acceleration, std::min(updateTime / ACCELERATE_EX_FRAMES, 1.0f)); + velocity = vector_scale(velocity, timescale_factor(grown, speedMultiplier)); + } + + if (!(projectileFlags & PROJECTILE_BURST3) || updateTime <= BURST3_WAIT) return; + bool isSplitting = (update_ticks_get() > 0 && random_below(BURST3_CHANCE) == 0) || spawnerType == ENTITY_PIN; + if (!isSplitting) return; + + std::array shots = {vector_make(-velocity.y, velocity.x), vector_make(velocity.y, -velocity.x), + velocity}; + constexpr std::array CURVES = {PROJECTILE_CURVE_LEFT, PROJECTILE_CURVE_RIGHT, + PROJECTILE_SINE_VELOCITY}; + for (int i = 0; i < 3; i++) + { + Vector shot = shots[i]; + if (vector_length_squared(shot) < SPLIT_SLOW_SPEED_SQUARED) shot = vector_scale(shot, SPLIT_SPEED_BOOST); + Entity_Projectile* child = child_spawn(*this, {.position = vector_sub(pos, velocity), + .velocity = shot, + .type = type, + .variant = variant, + .seed = Random()}); + if (!child) continue; + + child->height = std::min(height * SPLIT_HEIGHT_SHARE, HEIGHT_START); + child->scale = std::max(scale - SPLIT_SCALE_LOSS, 1.0f); + if (scale > 1) + { + child->fallingAccel = fallingAccel; + random_unit(); + } + else + { + projectileFlags &= ~PROJECTILE_BURST3; + child->fallingAccel = SPLIT_FALL_ACCEL; + child->fallingSpeed = SPLIT_FALL_SPEED; + } + child->projectileFlags = (projectileFlags & ~BURST3_CHILD_CLEARED) | CURVES[i]; + child->SetColor(sprite.color, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + child->parent = parent.get(); + child->Update(); + } + Kill(EntityRef()); +} + +// Its fall by its speed and gravity. In a crawlspace it drops under gravity and is removed once it heads out of the +// room. +void Entity_Projectile::fall_update() +{ + if (is_any_player_holding(COLLECTIBLE_CIRCLE_OF_PROTECTION)) + { + RNG rng; + rng.SetSeed(initSeed, CIRCLE_RNG_SHIFT); + if ((int)rng.RandomInt(CIRCLE_CHANCE) <= CIRCLE_PROC_MAX) + reconstruction_missing("Entity_Projectile::Update 00653070: the Circle of Protection's reflection"); + } + + fallingSpeed = speedMultiplier * fallingAccel + speedMultiplier * GRAVITY_PULL + + timescale_factor(FALL_DRAG, speedMultiplier) * fallingSpeed; + height = fallingSpeed * speedMultiplier + height; + if (!is_crawlspace()) return; + + if (fallingAccel >= CRAWLSPACE_MIN_ACCEL) velocity.y = fallingAccel * speedMultiplier + velocity.y; + else if (height > CRAWLSPACE_SINK_HEIGHT) velocity.y = speedMultiplier * CRAWLSPACE_SINK_SPEED + velocity.y; + + Room& room = *g_game->room; + Vector clamped = room.GetClampedPositionImpl(pos, CRAWLSPACE_MARGIN_TOP, CRAWLSPACE_MARGIN, CRAWLSPACE_MARGIN, + CRAWLSPACE_MARGIN); + if ((clamped.x != pos.x || clamped.y != pos.y) && vector_dot(vector_sub(clamped, pos), velocity) < 0) Remove(); + if (room.IsBeastDungeon()) reconstruction_missing("Entity_Projectile::Update 00653070: the Beast's lava"); +} + +// The rest of its frame: the slowdown's tint, the timed changes, the bounces, its height's collision, The Soul's +// push, its landing, the Broken Modem's freeze, the fade out and the hover. +void Entity_Projectile::late_update() +{ + Room& room = *g_game->room; + bool isSlowedLook = projectileFlags & PROJECTILE_SLOWED; + if (!isSlowedLook && is_friendly_shot(projectileFlags)) isSlowedLook = room.HasSlowDown(); + else if (!isSlowedLook && (!parent || !parent->IsFriendly())) + isSlowedLook = room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS) || + room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH) || + room.GetBrokenWatchState() == BROKEN_WATCH_SLOW; + if (isSlowedLook) + { + ColorMod slowed = SLOWED_COLOR; + color_multiply(slowed, color); + SetColor(slowed, SLOWED_COLOR_FRAMES, COLOR_PRIORITY, false, true); + } + + auto is_change_due = [this]() + { return changeTimeout < 1 || GetIntervalTicks((float)changeTimeout, 0) != 0; }; + if ((projectileFlags & PROJECTILE_CHANGE_VELOCITY_AFTER_TIMEOUT) && is_change_due() && FrameCount() > 0) + { + velocity = vector_resized(velocity, changeVelocity); + if ((changeFlags & CHANGE_BOTH_FLAGS) != CHANGE_BOTH_FLAGS) + projectileFlags &= ~PROJECTILE_CHANGE_VELOCITY_AFTER_TIMEOUT; + } + ground_update(); + if ((projectileFlags & PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT) && FrameCount() > 0 && is_change_due()) + std::swap(projectileFlags, changeFlags); + update_height_collision(); + + if (update_ticks_get() > 0 && random_below(SOUL_CHANCE) == 0 && is_any_player_holding(COLLECTIBLE_SOUL)) + { + Entity_Player* nearest = nullptr; + float best = SOUL_DISTANCE_START; + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = vector_length_squared(vector_sub(player->pos, pos)); + if (player->HasCollectible(COLLECTIBLE_SOUL) && distance < best) + { + nearest = player; + best = distance; + } + } + if (nearest && best < SOUL_REACH * SOUL_REACH) + { + float push = random_unit() * (SOUL_REACH - std::sqrt(best)) * SOUL_PUSH + SOUL_PUSH_MIN; + velocity = vector_add(velocity, vector_resized(vector_sub(pos, nearest->pos), push)); + } + } + + if (height > FLOOR_HEIGHT || (isCollidesWithGrid && height >= HIGH_HEIGHT)) isDead = true; + if (is_any_player_holding(COLLECTIBLE_BROKEN_MODEM)) + { + int luck = (int)g_game->playerManager.get_total_luck(); + if (random_below(std::max(MODEM_CHANCE_BASE - luck, MODEM_CHANCE_MIN)) == 0 && !isDead) + { + modemPosition = pos; + AddEntityFlags(FLAG_FREEZE); + velocity = {}; + } + } + + if (projectileFlags & PROJECTILE_FADEOUT) + { + entityCollisionClass = ENTCOLL_NONE; + sprite.color._tint[3] -= speedMultiplier * FADEOUT_RATE; + if (sprite.color._tint[3] <= 0) Remove(); + } + if (!(projectileFlags & PROJECTILE_ANTI_GRAVITY)) return; + height = lerp(height, HIGH_HEIGHT, ANTI_GRAVITY_RATE); + fallingSpeed = 0; + posOffset.y = std::sin(updateTime * ANTI_GRAVITY_RATE) * ANTI_GRAVITY_BOB + height; + if (!parent) isDead = true; +} + +// The bounces: off the floor (or what stands on it) with BOUNCE_FLOOR, and off the walls its collision points +// touch with BOUNCE, the walls alone when it flies high. +void Entity_Projectile::ground_update() +{ + if (projectileFlags & PROJECTILE_BOUNCE_FLOOR) + { + uint32_t collision = room_grid_collision_at(pos); + bool isBlocked = collision == COLLISION_OBJECT || collision == COLLISION_SOLID; + float floor = isBlocked ? HIGH_HEIGHT : FLOOR_HEIGHT; + if ((isBlocked || collision == COLLISION_NONE) && height > floor && fallingSpeed > BOUNCE_FLOOR_SPEED) + { + height = floor; + fallingSpeed *= BOUNCE_FLOOR_REBOUND; + } + } + if (!(projectileFlags & PROJECTILE_BOUNCE)) return; + + Vector normal{}; + uint32_t threshold = height < HIGH_HEIGHT ? COLLISION_WALL : COLLISION_OBJECT; + for (const Vector& point : collisionPoints) + if (room_grid_collision_at(vector_add(pos, point)) >= threshold) normal = vector_add(normal, point); + if (vector_is_zero(normal)) return; + + normal = vector_normalized(normal); + float into = -vector_dot(normal, velocity); + if (into >= 0) return; + velocity = vector_add(velocity, vector_scale(normal, into * 2)); + pos = vector_add(pos, velocity); +} + +// 0065c510 Moves it half a step for the frame between updates, with its wiggles and tractor beam, resolves the grid +// and places its sprite at the height it will fall to. +void Entity_Projectile::Interpolate() +{ + if (HasEntityFlags(FLAG_NO_INTERPOLATE)) + { + ClearEntityFlags(FLAG_NO_INTERPOLATE); + return; + } + + preInterpolatePos = pos; + pos = vector_add(pos, vector_scale(velocity, friction * speedMultiplier * HALF)); + if (motionHook) motionHook(*this, PROJECTILE_STEP_INTERPOLATE); + + float wiggleTime = (float)wiggleFrameOffset + updateTime; + if (projectileFlags & PROJECTILE_SINE_VELOCITY) + pos = vector_add(pos, vector_scale(velocity, std::sin(wave_phase(updateTime)) * HALF)); + if (projectileFlags & PROJECTILE_WIGGLE) + { + float speed = spawnerType == ENTITY_MOTHER ? 2 : 1; + float wave = std::cos(wave_phase(wiggleTime * speed)) * WIGGLE_SIZE * HALF; + pos = vector_add(pos, vector_scale(wiggle_side(velocity), wave)); + } + if (projectileFlags & PROJECTILE_MEGA_WIGGLE) + { + float size = std::min(wiggleTime * MEGA_WIGGLE_GROWTH, MEGA_WIGGLE_GROWN) + MEGA_WIGGLE_BASE; + pos = vector_add(pos, vector_scale(wiggle_side(velocity), std::cos(wave_phase(wiggleTime)) * size * HALF)); + } + if ((projectileFlags & PROJECTILE_TRACTOR_BEAM) && spawnerEntity && !vector_is_zero(spawnerEntity->targetPosition)) + { + float beamLength = vector_length(spawnerEntity->targetPosition); + Vector direction = vector_scale(spawnerEntity->targetPosition, 1 / beamLength); + Vector offset = vector_sub(pos, spawnerEntity->pos); + float along = vector_dot(offset, direction) < 0 ? -vector_length(offset) : vector_length(offset); + if (along >= 0 && along <= beamLength) + { + float speed = vector_length(velocity); + pos = vector_add(spawnerEntity->pos, vector_scale(direction, along)); + velocity = vector_scale(direction, speed); + } + } + + isInterpolating = true; + CollideWithGrid(GRID_COLLISION_SIMULATE); + if (is_crawlspace()) + { + posOffset.y = CRAWLSPACE_OFFSET_Y; + return; + } + + float next = (projectileFlags & PROJECTILE_STASIS) ? (HEIGHT_START - height) * ANTI_GRAVITY_RATE + : fallingSpeed * speedMultiplier * HALF; + next += height; + if (fallingAccel < 0) + { + float aboveFloor = std::max(next + HOVER_FLOOR_DISTANCE, 0.0f); + next = next * HALF + HOVER_OFFSET_LIFT + aboveFloor * aboveFloor; + } + if (projectileFlags & PROJECTILE_ANTI_GRAVITY) + next = std::sin((speedMultiplier * HALF + updateTime) * ANTI_GRAVITY_RATE) * ANTI_GRAVITY_BOB + height; + posOffset.y = next; +} + +// 0065cb60 Draws the shot, at the floor when it is rendered at the ground. A shot the Broken Modem froze draws +// where it froze, scaled down and glitching. +void Entity_Projectile::Render(const Vector& offset) +{ + if (isRenderedAtGround) posOffset.y -= height; + + bool isModemFrozen = HasEntityFlags(FLAG_FREEZE) && !vector_is_zero(modemPosition); + if (!isModemFrozen) Entity::Render(offset); + else + { + float pixelScale = g_displayPixelRatio * g_screenPointScale; + auto screen_get = [pixelScale](float world, float origin, float screenSize) + { + float screen = ((world - origin) * MODEM_SCREEN_SCALE + screenSize * HALF) * pixelScale + HALF; + return std::floor(screen) / pixelScale; + }; + Vector frozen = vector_add(modemPosition, posOffset); + renderPosition.x = screen_get(frozen.x, MODEM_ORIGIN_X, g_screenWidth - MODEM_SCREEN_WIDTH) + offset.x; + renderPosition.y = screen_get(frozen.y, MODEM_ORIGIN_Y, g_screenHeight - MODEM_SCREEN_HEIGHT) + offset.y; + + RNG rng = MODEM_RNG; + rng._seed = (uint32_t)(g_game->frameCount / MODEM_SEED_FRAMES) * MODEM_SEED_STEP + 1; + SpriteDraw draw = {renderPosition, {}, {}}; + draw.topLeftClamp.y = rng.RandomFloat() * MODEM_CLAMP_MAX; + draw.topLeftClamp.x = rng.RandomFloat() * MODEM_CLAMP_MAX; + draw.bottomRightClamp.y = rng.RandomFloat() * MODEM_CLAMP_MAX; + draw.bottomRightClamp.x = rng.RandomFloat() * MODEM_CLAMP_MAX; + sprite.Render(draw); + } + if (isRenderedAtGround) posOffset.y += height; +} + +// 0065b500 Places its sprite at its height (lifted on a curve near the floor when it rises) and lets it hit +// entities and the grid while low. A crawlspace keeps it at a fixed height and lets it hit everything. +void Entity_Projectile::update_height_collision() +{ + bool isGridPassing = projectileFlags & (GRID_PASS_FLAGS | PROJECTILE_BOUNCE); + if (is_crawlspace()) + { + posOffset.y = CRAWLSPACE_OFFSET_Y; + if (height > CRAWLSPACE_HEIGHT_MAX) height = CRAWLSPACE_HEIGHT_MAX; + entityCollisionClass = ENTCOLL_ALL; + bool isGridHit = !isGridPassing || (projectileFlags & PROJECTILE_EXPLODE); + entityGridCollisionClass = isGridHit ? GRIDCOLL_BULLET : GRIDCOLL_NONE; + if (g_game->room->IsBeastDungeon()) entityGridCollisionClass = GRIDCOLL_NONE; + } + else + { + float offsetY = height; + if (fallingAccel < 0) + { + float aboveFloor = std::max(height + HOVER_FLOOR_DISTANCE, 0.0f); + offsetY = height * HALF + HOVER_OFFSET_LIFT + aboveFloor * aboveFloor; + } + posOffset.y = offsetY; + if (height >= HIGH_HEIGHT) + { + entityCollisionClass = ENTCOLL_ALL; + entityGridCollisionClass = isGridPassing ? GRIDCOLL_NONE : GRIDCOLL_BULLET; + } + else if (!(projectileFlags & PROJECTILE_ANY_HEIGHT_ENTITY_HIT)) entityCollisionClass = ENTCOLL_NONE; + } + if (HasEntityFlags(FLAG_FREEZE)) entityCollisionClass = ENTCOLL_NONE; +} + +// 0065b670 Hits what it touches: a player above its reach (unless a hat or Infamy blocks it), an enemy when it is +// friendly, and the familiars that take hits. Singe's ball, frozen enemies and poop break it. Whether the collision +// is ignored. The Beast's lava ball never stops a collision. +bool Entity_Projectile::HandleCollision(Entity* collider, bool isLow) +{ + LuaResult luaResult = lua_engine_get().PreProjectileCollision(this, collider, isLow); + if (luaResult == LUA_RESULT_TRUE) return true; + if (luaResult == LUA_RESULT_FALSE) return false; + + bool isLava = variant == PROJECTILE_LAVA; + if (isLow) + { + if (collider->type == ENTITY_SINGE && collider->variant == SINGE_BALL) + { + isDead = true; + if (collider->friction == 0) return isLava; + Vector push = vector_scale(velocity, SINGE_PUSH * collider->speedMultiplier / collider->friction); + collider->velocity = vector_add(collider->velocity, push); + return isLava; + } + if (collider->IsEnemy() && collider->HasEntityFlags(FLAG_ICE_FROZEN)) + { + collider->TakeDamage(1, 0, EntityRef(), HIT_COUNTDOWN); + isDead = true; + return false; + } + if (collider->type == ENTITY_POOP) + { + collider->TakeDamage(1, DAMAGE_COUNTDOWN, EntityRef(this), HIT_COUNTDOWN); + isDead = true; + return false; + } + } + if (spawnerType == ENTITY_DARK_ESAU) + { + if (collider->type == ENTITY_FAMILIAR) return true; + if (collider->type == ENTITY_PLAYER && spawnerEntity && spawnerEntity->spawnerEntity.get() != collider) + return true; + } + + if (!isLow && collider->type == ENTITY_PLAYER) return player_hit(*static_cast(collider)); + if (isLow && (collider->IsVulnerableEnemy(nullptr) || collider->type == ENTITY_DARK_ESAU)) + { + bool isOwnHit = parent && parent->GetHitListIndex() == collider->GetHitListIndex(); + if (!isOwnHit) return enemy_hit(collider); + + bool isMotherBall = parent->type == ENTITY_MOTHER && parent->variant == MOTHER_BALL; + if (isMotherBall && g_game->frameCount - spawnFrame > MOTHER_SELF_HIT_FRAMES) return enemy_hit(collider); + return isLava; + } + if (isLow) return isLava; + return familiar_hit(collider); +} + +// A player hit: friendly shots spare players their shooter is friendly with, a shrunk player lets high shots pass, +// a hat blocks falling ones and Infamy some, then it hurts. Greed's shots take coins, frozen ones stop the player. +bool Entity_Projectile::player_hit(Entity_Player& player) +{ + if (projectileFlags & PROJECTILE_CANT_HIT_PLAYER) + { + Entity* shooter = spawnerEntity; + if (!shooter || !shooter->HasEntityFlags(FLAG_FRIENDLY | FLAG_CHARM)) return true; + if (shooter->IsDamageSourceFriendly(EntityRef(&player))) return true; + } + if (g_game->deathmatchManager.is_active() && IsDescendantOf(&player)) return true; + if (player.isCoopGhost) return true; + float playerSize = std::clamp(player.sprite.scale.y, PLAYER_HIT_SCALE_MIN, 1.0f); + if (posOffset.y < playerSize * HIGH_HEIGHT) return true; + + isDead = true; + bool isDamaged = false; + bool isHatBlocked = false; + if (player.HasCollectible(COLLECTIBLE_SPELUNKER_HAT) || player.HasCollectible(COLLECTIBLE_HOST_HAT)) + { + if (is_crawlspace()) isHatBlocked = vector_normalized(vector_sub(pos, player.pos)).x < HAT_CRAWLSPACE_SIDE; + else isHatBlocked = fallingAccel > 0 && height - fallingSpeed * speedMultiplier < HIGH_HEIGHT; + } + if (!(projectileFlags & PROJECTILE_EXPLODE) && !isHatBlocked) + { + int chance = g_game->deathmatchManager.is_active() ? 4 : 2; + if (!player.HasCollectible(COLLECTIBLE_INFAMY) || random_below(chance) != 0) + { + uint64_t damageFlags = (projectileFlags & PROJECTILE_FIRE_FLAG) ? DAMAGE_FIRE : 0; + isDamaged = player.TakeDamage(collisionDamage, damageFlags, EntityRef(this), HIT_COUNTDOWN); + } + else + { + sound_play(SOUND_INFAMY_BLOCK, 1, 1); + player.SetColor(INFAMY_COLOR, INFAMY_COLOR_FRAMES, COLOR_PRIORITY, true, true); + } + } + + if ((projectileFlags & PROJECTILE_GREED) && isDamaged && player.numCoins > 0) + { + player.AddCoins(-1); + int dropped = std::min((int)(Random() % GREED_COINS_MAX) + 1, player.numCoins); + for (int i = 0; i < dropped; i++) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + float speed = random_unit() * GREED_COIN_SPEED + GREED_COIN_SPEED_MIN; + g_game->Spawn({.position = pos, + .velocity = vector_scale(direction, speed), + .subType = COIN_PENNY, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = seed}); + } + player.AddCoins(-dropped); + } + if (projectileFlags & PROJECTILE_FREEZE) + { + player.controlsCooldown = FROZEN_FRAMES; + player.SetColor(FROZEN_COLOR, FROZEN_FRAMES, COLOR_PRIORITY_NONE, true, true); + } + return isDead ? variant == PROJECTILE_LAVA : true; +} + +// An enemy hit: only a friendly shot (or any shot at a friendly or baited enemy) hurts it, harder than a player, +// and a frozen shot freezes it. Mother's and Mega Satan's shots pass their own kind. +bool Entity_Projectile::enemy_hit(Entity* collider) +{ + bool isLava = variant == PROJECTILE_LAVA; + if ((projectileFlags & PROJECTILE_CANT_HIT_PLAYER) && + (collider->HasEntityFlags(FLAG_FRIENDLY) || collider->type == ENTITY_DARK_ESAU)) + return true; + bool isTargetable = collider->HasEntityFlags(FLAG_BAITED | FLAG_FRIENDLY) || collider->type == ENTITY_DARK_ESAU; + if (!(projectileFlags & PROJECTILE_HIT_ENEMIES) && !isTargetable) return true; + + if (parent && parent->type == ENTITY_MOTHER) + { + if (parent->variant == MOTHER_BALL && collider->type == ENTITY_MOTHER && collider->variant == MOTHER_BALL) + { + isDead = true; + return isLava; + } + } + else if (parent && (parent->type == ENTITY_MEGA_SATAN || parent->type == ENTITY_MEGA_SATAN_2)) + { + if (collider->type == ENTITY_MEGA_SATAN || collider->type == ENTITY_MEGA_SATAN_2) return isLava; + } + + isDead = true; + if (projectileFlags & PROJECTILE_EXPLODE) return isLava; + float hitDamage = variant == PROJECTILE_GRID ? GRID_HIT_DAMAGE : collisionDamage + ENEMY_HIT_BONUS; + collider->TakeDamage(hitDamage, 0, EntityRef(this), HIT_COUNTDOWN); + if (projectileFlags & PROJECTILE_FREEZE) collider->AddFreeze(EntityRef(this), FREEZE_DURATION, false); + return isLava; +} + +// A familiar hit: the familiars that take shots are hurt unless the shot is friendly. Infamy guards a player-like +// familiar as it does the player. +bool Entity_Projectile::familiar_hit(Entity* collider) +{ + bool isLava = variant == PROJECTILE_LAVA; + if (collider->type != ENTITY_FAMILIAR || !is_listed(HURT_FAMILIARS, collider->variant)) return isLava; + if (collider->variant == SPARED_FAMILIAR && collider->subtype == SPARED_FAMILIAR_SUBTYPE) return isLava; + if (projectileFlags & PROJECTILE_CANT_HIT_PLAYER) return true; + + isDead = true; + int chance = g_game->deathmatchManager.is_active() ? 4 : 2; + Entity_Player* player = static_cast(collider)->player; + bool isInfamyBlocked = is_listed(INFAMY_FAMILIARS, collider->variant) && player && + player->HasCollectible(COLLECTIBLE_INFAMY) && random_below(chance) == 0; + if ((projectileFlags & PROJECTILE_EXPLODE) || isInfamyBlocked) return isLava; + + collider->TakeDamage(collisionDamage, 0, EntityRef(this), HIT_COUNTDOWN); + return false; +} + +// 00652f60 Only a Globin's meat shot holds the doors shut, unless it cannot hit players. bool Entity_Projectile::CanShutDoors() { - return variant == PROJECTILE_MEAT && !(projectileFlags & PROJECTILE_CANT_BE_STOPPED); + return variant == PROJECTILE_MEAT && !(projectileFlags & PROJECTILE_CANT_HIT_PLAYER); } // 00456420 Raises it. @@ -45,52 +1640,64 @@ void Entity_Projectile::AddScale(float amount) scale = amount + scale; } -// The rest of Entity_Projectile is not reconstructed yet. - -// 00652b90 -void Entity_Projectile::Init(int, int, int, uint32_t) +// 00652fa0 Turns it on the enemies at a new velocity: it stops homing, orbiting, curving and changing its flags, +// hits only enemies, leaves its parent and lives on, bouncing back up if it was falling. +void Entity_Projectile::Reflect(const Vector& newVelocity) { - reconstruction_missing("Entity_Projectile::Init 00652b90"); + constexpr uint64_t CLEARED = PROJECTILE_SMART | PROJECTILE_ORBIT_CW | PROJECTILE_ORBIT_CCW | + PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT | PROJECTILE_TURN_HORIZONTAL | + PROJECTILE_MOVE_TO_PARENT | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + projectileFlags = (projectileFlags & ~CLEARED) | FRIENDLY_FLAGS; + changeFlags = (changeFlags & ~CLEARED) | FRIENDLY_FLAGS; + velocity = newVelocity; + parent = nullptr; + isDead = false; + if (fallingAccel > 0 && fallingSpeed > 0) fallingSpeed = -fallingSpeed * REFLECT_REBOUND; } -// 00653070 -void Entity_Projectile::Update() +// 00652f80 Kills it without the effects of its flags. +void Entity_Projectile::die_without_flags() { - reconstruction_missing("Entity_Projectile::Update 00653070"); + projectileFlags = 0; + isDead = true; } -// 0065c510 -void Entity_Projectile::Interpolate() +// 006cb010 Hands a fired shot what its shooter carries: the hits a charmed, friendly or baited shooter's shots deal +// (and, with Betrayal held, any enemy's), the parent friendly shots keep, and a champion's color, damage and size. +void Entity_Projectile::apply_spawn_flags(const ProjectileShooter& shooter) { - reconstruction_missing("Entity_Projectile::Interpolate 0065c510"); -} + if (shooter.flags & FLAG_SLOW) projectileFlags |= PROJECTILE_SLOWED; + if (shooter.flags & FLAG_CHARM) projectileFlags |= PROJECTILE_HIT_ENEMIES; + if (shooter.flags & FLAG_FRIENDLY) projectileFlags |= PROJECTILE_CANT_HIT_PLAYER; -// 0065cb60 -void Entity_Projectile::Render(const Vector&) -{ - reconstruction_missing("Entity_Projectile::Render 0065cb60"); -} + if (Entity* entity = shooter.entity) + { + bool isEnemyShooter = (g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || + Entity::is_enemy_type(entity->type); + if (isEnemyShooter && + g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_BETRAYAL, LAZARUS_SHARE_CHECK)) + projectileFlags |= PROJECTILE_HIT_ENEMIES; + if ((projectileFlags & PROJECTILE_HIT_ENEMIES) || (shooter.flags & FLAG_BAITED)) parent = entity; + } -// 0065b670 -bool Entity_Projectile::HandleCollision(Entity*, bool) -{ - reconstruction_missing("Entity_Projectile::HandleCollision 0065b670"); -} - -// 00652fa0 -void Entity_Projectile::Reflect(Entity*, const Vector&) -{ - reconstruction_missing("Entity_Projectile::Reflect 00652fa0"); -} - -// 0065b500 -void Entity_Projectile::update_height_collision() -{ - reconstruction_missing("Entity_Projectile::update_height_collision 0065b500"); -} - -// 0067a080 -void Entity_Projectile::Deflect(Entity*, const Vector&) -{ - reconstruction_missing("Entity_Projectile::Deflect 0067a080"); + float sizeScale = 1; + if (shooter.championColor >= 0) + { + if (variant == PROJECTILE_BONE) + { + ColorMod tinted = color; + color_multiply(tinted, champion_sprite_color_get(shooter.championColor)); + SetColor(tinted, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + } + if (shooter.championColor != CHAMPION_TINY) + { + SetCollisionDamage(std::min(collisionDamage + collisionDamage, CHAMPION_DAMAGE_MAX)); + sizeScale = CHAMPION_SHOT_SCALE; + if (shooter.championColor == CHAMPION_ORANGE) projectileFlags |= PROJECTILE_GREED; + else if (shooter.championColor == CHAMPION_TRANSPARENT) projectileFlags |= PROJECTILE_GHOST; + } + } + sizeScale *= shooter.scale; + if (shooter.flags & FLAG_WEAKNESS) sizeScale *= WEAK_SHOT_SCALE; + if (sizeScale != 1) scale = sizeScale * scale; } diff --git a/src/entity_projectile.h b/src/entity_projectile.h index bf8177b..1fd88a2 100644 --- a/src/entity_projectile.h +++ b/src/entity_projectile.h @@ -2,23 +2,127 @@ #include "entity.h" -// Lua's ProjectileFlags that the entity list reads. -enum ProjectileFlag : uint64_t +// Lua's ProjectileVariant: the look of a shot, which also picks its splash. +enum ProjectileVariant : int { - PROJECTILE_HIT_ENEMIES = 1ull << 7, - PROJECTILE_CANT_BE_STOPPED = 1ull << 31, - PROJECTILE_SHIELDED = 1ull << 44 + PROJECTILE_NORMAL, + PROJECTILE_BONE, + PROJECTILE_FIRE, + PROJECTILE_PUKE, + PROJECTILE_TEAR, + PROJECTILE_CORN, + PROJECTILE_HUSH, + PROJECTILE_COIN, + PROJECTILE_GRID, + PROJECTILE_ROCK, + PROJECTILE_RING, + PROJECTILE_MEAT, + PROJECTILE_FCUK, + PROJECTILE_WING, + PROJECTILE_LAVA, + PROJECTILE_HEAD, + PROJECTILE_PEEP }; -// Construction and destruction (00652b50, 00652b00) are the defaults. +// Lua's ProjectileFlags: how a shot flies and what it does when it lands. +// FIRE is PROJECTILE_FIRE_FLAG, the variant taking the plain name. +enum ProjectileFlag : uint64_t +{ + PROJECTILE_SMART = 1ull << 0, + PROJECTILE_EXPLODE = 1ull << 1, + PROJECTILE_ACID_GREEN = 1ull << 2, + PROJECTILE_GOO = 1ull << 3, + PROJECTILE_GHOST = 1ull << 4, + PROJECTILE_WIGGLE = 1ull << 5, + PROJECTILE_BOOMERANG = 1ull << 6, + PROJECTILE_HIT_ENEMIES = 1ull << 7, + PROJECTILE_ACID_RED = 1ull << 8, + PROJECTILE_GREED = 1ull << 9, + PROJECTILE_RED_CREEP = 1ull << 10, + PROJECTILE_ORBIT_CW = 1ull << 11, + PROJECTILE_ORBIT_CCW = 1ull << 12, + PROJECTILE_NO_WALL_COLLIDE = 1ull << 13, + PROJECTILE_CREEP_BROWN = 1ull << 14, + PROJECTILE_FIRE_FLAG = 1ull << 15, + PROJECTILE_BURST = 1ull << 16, + PROJECTILE_ANY_HEIGHT_ENTITY_HIT = 1ull << 17, + PROJECTILE_CURVE_LEFT = 1ull << 18, + PROJECTILE_CURVE_RIGHT = 1ull << 19, + PROJECTILE_TURN_HORIZONTAL = 1ull << 20, + PROJECTILE_SINE_VELOCITY = 1ull << 21, + PROJECTILE_MEGA_WIGGLE = 1ull << 22, + PROJECTILE_SAWTOOTH_WIGGLE = 1ull << 23, + PROJECTILE_SLOWED = 1ull << 24, + PROJECTILE_TRIANGLE = 1ull << 25, + PROJECTILE_MOVE_TO_PARENT = 1ull << 26, + PROJECTILE_ACCELERATE = 1ull << 27, + PROJECTILE_DECELERATE = 1ull << 28, + PROJECTILE_BURST3 = 1ull << 29, + PROJECTILE_CONTINUUM = 1ull << 30, + PROJECTILE_CANT_HIT_PLAYER = 1ull << 31, + PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT = 1ull << 32, + PROJECTILE_CHANGE_VELOCITY_AFTER_TIMEOUT = 1ull << 33, + PROJECTILE_STASIS = 1ull << 34, + PROJECTILE_FIRE_WAVE = 1ull << 35, + PROJECTILE_FIRE_WAVE_X = 1ull << 36, + PROJECTILE_ACCELERATE_EX = 1ull << 37, + PROJECTILE_BURST8 = 1ull << 38, + PROJECTILE_FIRE_SPAWN = 1ull << 39, + PROJECTILE_ANTI_GRAVITY = 1ull << 40, + PROJECTILE_TRACTOR_BEAM = 1ull << 41, + PROJECTILE_BOUNCE = 1ull << 42, + PROJECTILE_BOUNCE_FLOOR = 1ull << 43, + PROJECTILE_SHIELDED = 1ull << 44, + PROJECTILE_BLUE_FIRE_SPAWN = 1ull << 45, + PROJECTILE_LASER_SHOT = 1ull << 46, + PROJECTILE_GODHEAD = 1ull << 47, + PROJECTILE_SMART_PERFECT = 1ull << 48, + PROJECTILE_BURSTSPLIT = 1ull << 49, + PROJECTILE_WIGGLE_ROTGUT = 1ull << 50, + PROJECTILE_FREEZE = 1ull << 51, + PROJECTILE_ACCELERATE_TO_POSITION = 1ull << 52, + PROJECTILE_BROCCOLI = 1ull << 53, + PROJECTILE_BACK_SPLIT = 1ull << 54, + PROJECTILE_SIDE_WAVE = 1ull << 55, + PROJECTILE_ORBIT_PARENT = 1ull << 56, + PROJECTILE_FADEOUT = 1ull << 57 +}; + +// When a shot's motion hook runs: on its update, or on the interpolation between two. +enum ProjectileStep : int +{ + PROJECTILE_STEP_UPDATE, + PROJECTILE_STEP_INTERPOLATE +}; + +struct Entity_Projectile; + +// A function some shooters give their shots (ProjectileParams 0xa0), run on every update and interpolation. +using ProjectileHook = void (*)(Entity_Projectile& projectile, ProjectileStep step); + +// What a shot takes from what fired it: the shooter (none for a timer or effect), its entity flags, its scale and its +// champion color (-1 for none). +struct ProjectileShooter +{ + Entity* entity = nullptr; + uint64_t flags = 0; + float scale = 1; + int championColor = -1; +}; + +// Construction and destruction (00652b00, 00652b50) are the defaults. // Field accessors (00417830, 00444c90, 00447740, 004b70a0, 004d3060, 004d3070, 0085e300, 0085e310, 0085e360) are the // public fields. // An enemy shot (Lua's EntityProjectile): its height and fall, damage, homing and curving, and the projectile flags // that change how it flies and what it does when it lands. +// The flags and variants of the late bosses (Mother, Dogma, the Beast, Rotgut) and a few rare items stop the game. struct Entity_Projectile : Entity { + ProjectileHook motionHook = nullptr; uint64_t changeFlags = 0; uint64_t projectileFlags = 0; + Vector modemPosition{}; + Vector orbitParentVelocity{}; float acceleration = 0; float changeVelocity = 0; float curvingStrength = 0; @@ -45,9 +149,32 @@ struct Entity_Projectile : Entity void AddFallingSpeed(float amount); void AddFallingAccel(float amount); void AddProjectileFlags(uint64_t added); - void Reflect(Entity* unused, const Vector& newVelocity); - void update_height_collision(); - void Deflect(Entity* newSpawner, const Vector& velocity); void AddChangeFlags(uint64_t added); void AddScale(float amount); + void Reflect(const Vector& newVelocity); + void die_without_flags(); + void apply_spawn_flags(const ProjectileShooter& shooter); + void update_height_collision(); + +private: + float time_scale_get(); + bool modem_freeze_update(); + void animation_update(); + void first_frame_update(); + void trails_update(); + void death_update(); + void death_poof_spawn(); + void death_flags_apply(); + void death_bursts_spawn(); + void homing_update(); + void orbit_update(); + void steering_update(); + bool wiggles_update(); + void speed_update(); + void fall_update(); + void ground_update(); + void late_update(); + bool player_hit(Entity_Player& player); + bool enemy_hit(Entity* collider); + bool familiar_hit(Entity* collider); }; diff --git a/src/entity_slot.cpp b/src/entity_slot.cpp index d5d2d4e..d0d5aa4 100644 --- a/src/entity_slot.cpp +++ b/src/entity_slot.cpp @@ -1,5 +1,6 @@ #include "entity_slot.h" #include "entity_config.h" +#include "entity_pickup.h" #include "game.h" #include "log.h" #include "manager.h" @@ -53,6 +54,8 @@ constexpr float BLOOD_MACHINE_OFFSET_X = -5; constexpr float MACHINE_WIDTH = 1.5f; constexpr float SHELL_GAME_WIDTH = 3; constexpr float MACHINE_DEPTH = 0.75f; +constexpr int HELL_GAME_PRIZE_LAYER = 7; +constexpr int CRANE_GAME_PRIZE_LAYER = 2; // Whether the run counts toward achievements (Game::AchievementUnlocksDisallowed 00705080, which Game does not declare // yet): not on a custom seed, a seed or mod that blocks them, or a rerun. @@ -216,8 +219,20 @@ void Entity_Slot::spawn_break_drops() reconstruction_missing("Entity_Slot::spawn_break_drops 00663aa0"); } -// 00665500 -void Entity_Slot::SetPrizeType(int) +// 00665500 Sets the collectible a slot pays out, shown on the Hell Game's prize layer or the Crane Game's glass (a +// question mark under Curse of the Blind). +void Entity_Slot::SetPrizeType(int collectibleId) { - reconstruction_missing("Entity_Slot::SetPrizeType 00665500"); + prizeCollectible = collectibleId; + bool isBlind = g_game->GetCurses() & CURSE_OF_BLIND; + if (variant == SLOT_HELL_GAME) + { + Entity_Pickup::load_collectible_gfx(prizeAnm2, HELL_GAME_PRIZE_LAYER, prizeCollectible, dropRNG._seed, isBlind); + prizeAnm2.LoadGraphics(); + } + else if (variant == SLOT_CRANE_GAME) + { + Entity_Pickup::load_collectible_gfx(sprite, CRANE_GAME_PRIZE_LAYER, prizeCollectible, dropRNG._seed, isBlind); + sprite.LoadGraphics(); + } } diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index cb8136b..41b05eb 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -7,7 +7,9 @@ #include "log.h" #include "lua_engine.h" #include "manager.h" +#include "npc_ai.h" #include "room.h" +#include "room_grid.h" #include "sfx_manager.h" #include #include @@ -24,10 +26,7 @@ constexpr float TEAR_SCALE_MIN = 0.01f; constexpr float TEAR_FLOOR_HEIGHT = -5; constexpr float TEAR_GRID_HIT_HEIGHT = -60; constexpr float CRAWLSPACE_OFFSET_Y = -18; -constexpr float CRAWLSPACE_HEIGHT_MAX = -5.1f; constexpr float CRAWLSPACE_RANGE_SHARE = 0.6f; -constexpr float CRAWLSPACE_SINK_HEIGHT = -10; -constexpr float CRAWLSPACE_SINK_SPEED = 0.5f; constexpr float CRAWLSPACE_ROOM_MARGIN = -256; constexpr float CRAWLSPACE_FIRE_RAISE = 4; constexpr float CRAWLSPACE_LEVEL_SLOPE = 0.05f; @@ -37,14 +36,10 @@ constexpr float GRAVITY_FALL_DRAG = 0.9f; constexpr float HOVER_HEIGHT_BOB = 0.5f; constexpr int HOVER_BOB_FRAMES = 15; constexpr float ROOM_SLOWDOWN_SCALE = 0.75f; -constexpr float DEGREES_PER_RADIAN = 57.295776f; -constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; -constexpr float RANDOM_DIRECTION_HALF_TURN = 3.14f; +constexpr float RIGHT_ANGLE = 90; // The height offset a tear flying without gravity draws at: a fixed lift, and a curve near the floor. constexpr float HOVER_OFFSET_SCALE = 0.4f; -constexpr float HOVER_OFFSET_LIFT = -15; -constexpr float HOVER_FLOOR_DISTANCE = 8.5f; constexpr float FIXED_HEIGHT_OFFSET = -8; constexpr float GFUEL_NAIL_OFFSET = -12; @@ -59,17 +54,15 @@ constexpr float TEAR_EFFECT_SCALE = 0.45f; // The tear effect sprite's flag for drawing behind the tear. constexpr unsigned int TEAR_EFFECT_BEHIND = 1 << 13; constexpr float GFUEL_SIZE_DIVISOR = 3; +constexpr float GFUEL_NAIL_WIDTH = 3; // The splash a dying tear leaves: the poof sizes by its scale, the sounds, and the stains blood tears leave. constexpr float POOF_SCALE_SMALL = 0.4f; constexpr float POOF_SCALE_LARGE = 0.8f; -constexpr float POOF_VOLUME_SMALL = 0.85f; -constexpr float POOF_VOLUME_TINY = 0.7f; constexpr float SWORD_BEAM_VOLUME = 0.3f; constexpr float SWORD_BEAM_PITCH = 2; constexpr float SWORD_BEAM_PITCH_SPREAD = 0.5f; constexpr int SWORD_BEAM_POOF_SUBTYPE = 22; -constexpr float RIGHT_ANGLE = 90; constexpr int STAIN_COUNT_MAX = 5; constexpr float STAIN_SPREAD = 24; constexpr float STAIN_SCALE = 0.3f; @@ -91,41 +84,145 @@ constexpr int GRID_PATH_TEAR_WALL = 3000; constexpr float LAUNCH_DRAG_TIME = 5; constexpr float LAUNCH_DRAG_FRICTION = 0.55f; -constexpr int EFFECT_BLOOD_SPLAT = 7; -constexpr int EFFECT_BULLET_POOF = 11; -constexpr int EFFECT_TEAR_POOF_A = 12; -constexpr int EFFECT_TEAR_POOF_B = 13; -constexpr int EFFECT_TEAR_POOF_SMALL = 79; -constexpr int EFFECT_TEAR_POOF_VERYSMALL = 80; +// How the flags move a tear: Anti-Gravity's wait, homing's search and pull, Hook Worm's turns, Lump of Coal's growth, +// Proptosis' shrinking, My Reflection's pull, Pulse Worm's beat and Flat Worm's stretch. +constexpr int WAIT_FRAMES = 90; +constexpr int HOMING_SEARCH_FRAMES = 4; +constexpr float HOMING_LOOK_AHEAD = 5; +constexpr float HOMING_RADIUS = 128; +constexpr float HOMING_SCORE_NONE = 1e9f; +constexpr float HOMING_PULL = 2; +constexpr int SQUARE_START_FRAME = 3; +constexpr int SQUARE_LOOP_START = 5; +constexpr int SQUARE_LOOP_FRAMES = 22; +constexpr int SQUARE_TURN_LEFT_SLOW = 0; +constexpr int SQUARE_TURN_LEFT = 7; +constexpr int SQUARE_TURN_RIGHT_SLOW = 10; +constexpr int SQUARE_TURN_RIGHT = 19; +constexpr float GROW_DAMAGE = 0.014f; +constexpr float GROW_SCALE = 0.01f; +constexpr float SHRINK_START = 4; +constexpr float SHRINK_FAST = 0.08f; +constexpr float SHRINK_SLOW = 0.03f; +constexpr float SHRINK_FAST_SHARE = 3; +constexpr float SHRINK_DAMAGE_MIN = 0.1f; +constexpr int SPECTRAL_GRID_CHANCE = 8; +constexpr float BOOMERANG_ANCHOR_LIFT = 2; +constexpr float BOOMERANG_RANGE_START = 60; +constexpr float BOOMERANG_REACH_MIN = 20; +constexpr float BOOMERANG_SPEED = 10; +constexpr float PULSE_STRENGTH = 0.3f; +constexpr float PULSE_RATE = 0.7f; +constexpr float PULSE_BASE = 0.6f; +constexpr float PULSE_OFFSET = 0.7f; +constexpr float SQUARE_SPEED_SHARE = 0.5f; +constexpr float BOOMERANG_REACH_SHARE = 0.5f; +constexpr float FLAT_STRETCH = 0.5f; +constexpr float PUPULA_SPIN = 45; +constexpr float TURN_AWAY = -0.1f; +constexpr int BOUNCE_SOUND = 905; + +// The wiggles: Wiggle Worm's sideways sway, Ring Worm's spiral and Ouroboros Worm's wide one. +constexpr float WIGGLE_RATE = 0.7f; +constexpr float WIGGLE_SPEED_SHARE = 0.5f; +constexpr float WIGGLE_MAX = 5; +constexpr float SPIRAL_RATE = 0.7f; +constexpr float SPIRAL_SIDE = 10; +constexpr float SPIRAL_FORWARD = 20; +constexpr float BIG_SPIRAL_RATE = 0.2f; +constexpr float BIG_SPIRAL_RADIUS = 15; +constexpr float QUARTER_TURN = 1.5707964f; +constexpr float HALF_FRAME = 0.5f; + +// The pieces a dying tear breaks into: Parasite's two halves, Compound Fracture's shards and Cricket's Body's four. +constexpr float SPLIT_DAMAGE_MIN = 1; +constexpr float SPLIT_HEIGHT_SHARE = 1.5f; +constexpr float SPLIT_DAMAGE = 0.5f; +constexpr float SPLIT_RISING_DAMAGE = 0.25f; +constexpr float SPLIT_RISING_ACCEL = 2; +constexpr float SPLIT_SCALE = 0.5f; +constexpr float BONE_DAMAGE = 0.5f; +constexpr int BONE_SHARDS = 2; +constexpr const char* BROKEN_BONE_SHEET = "gfx/tears_brokenbone.png"; +constexpr int QUADSPLIT_PIECES = 4; +constexpr float QUADSPLIT_SLOW_SQUARED = 0.1f; +constexpr float QUADSPLIT_SLOW_SPEED = 10; +constexpr float QUADSPLIT_DAMAGE = 0.5f; +constexpr float QUADSPLIT_SCALE = 0.6f; +constexpr float QUADSPLIT_HEIGHT_SHARE = 0.5f; +constexpr float QUADSPLIT_FALL_SHARE = 0.3f; +constexpr float PLAYER_TEAR_HEIGHT = -23.75f; +// The creep Mysterious Liquid's and It Hurts' tears leave where they die. +constexpr float CREEP_MARGIN = 15; +constexpr float CREEP_SCALE = 0.4f; + +// What a hit's flags do: the slowing and its tint (Ball of Tar's dark), and the durations of the status effects. +constexpr int SLOW_DURATION = 60; +constexpr float SLOW_AMOUNT = 0.9f; +constexpr ColorMod SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}}; +constexpr ColorMod GISH_COLOR = {{0.2f, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int POISON_DURATION = 40; +constexpr int POISON_DURATION_VERSUS = 60; +constexpr int FREEZE_DURATION = -50; +constexpr int FREEZE_DURATION_VERSUS = -45; +constexpr int CHARM_DURATION = 150; +constexpr int CONFUSION_DURATION = 150; +constexpr int CONFUSION_SPREAD = 30; +constexpr int PERMANENT_CONFUSION = -99999999; +constexpr int PERMANENT_CONFUSION_BOSS = -300; +constexpr int PERMANENT_CONFUSION_VERSUS = -240; +constexpr int FEAR_DURATION = -150; +constexpr int BURN_DURATION = 40; +constexpr int BURN_DURATION_LONG = 80; +constexpr int MIDAS_DURATION = 90; +constexpr int MAGNETIZE_DURATION = 150; +constexpr int BAIT_DURATION = 180; +constexpr int ICE_DURATION = 10; +constexpr int SHRINK_DURATION = -150; +constexpr int GREED_COIN_CHANCE = 20; +constexpr int HP_DROP_CHANCE = 3; +constexpr float HIT_DIRECTION_MIN_SPEED = 0.02f; + +constexpr int EFFECT_FIRE_JET = 147; constexpr int SOUND_TEAR_FIRE = 153; constexpr int SOUND_FETUS_FIRE = 237; constexpr float FETUS_FIRE_PITCH = 1.2f; -constexpr int SOUND_TEAR_IMPACTS = 150; -constexpr int SOUND_SPLATTER = 258; +constexpr int SOUND_LITTLE_HORN = 868; constexpr int SOUND_SWORD_BEAM_IMPACT = 49; constexpr int SOUND_TECH_SWORD_BEAM_IMPACT = 134; +constexpr int SOUND_DELAY = 2; + +// How Tiny Planet's and My Reflection's tears are thrown when fired. +constexpr float ORBIT_FALL_SCALE = 3; +constexpr float HYDROBOUNCE_LIFT = 15; +constexpr float HYDROBOUNCE_ACCEL = 3; +constexpr float BOOMERANG_FALL_SCALE = 0.5f; +constexpr float BOOMERANG_ACCEL_OFFSET = 0.08f; +constexpr float BOOMERANG_ACCEL_SCALE = 0.25f; -constexpr int COLLECTIBLE_NUMBER_ONE = 6; constexpr int COLLECTIBLE_EVES_MASCARA = 310; -constexpr int COLLECTIBLE_DEAD_EYE = 373; constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; +constexpr int TRINKET_PULSE_WORM = 9; +constexpr int TRINKET_WIGGLE_WORM = 10; +constexpr int TRINKET_RING_WORM = 11; +constexpr int TRINKET_FLAT_WORM = 12; +constexpr int TRINKET_HOOK_WORM = 26; // Onan's Streak punishes a tear that misses with a hit to its player. constexpr float STREAK_DAMAGE = 1; -constexpr uint64_t DAMAGE_INVINCIBLE = 1ull << 13; constexpr int STREAK_DAMAGE_COUNTDOWN = 30; -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"; // The variants whose splash and flight are reconstructed: plain tears and the ones that only change the sprite. -constexpr std::array TEAR_PLAIN_VARIANTS = { - TEAR_BLUE, TEAR_BLOOD, TEAR_LOST_CONTACT, TEAR_CUPID_BLUE, TEAR_CUPID_BLOOD, - TEAR_PUPULA, TEAR_PUPULA_BLOOD, TEAR_GODS_FLESH, TEAR_GODS_FLESH_BLOOD, TEAR_MULTIDIMENSIONAL, - TEAR_GLAUCOMA, TEAR_GLAUCOMA_BLOOD, TEAR_NEEDLE, TEAR_BELIAL, TEAR_HUNGRY, - TEAR_FIST, TEAR_ICE, TEAR_SWORD_BEAM, TEAR_TECH_SWORD_BEAM}; +constexpr std::array TEAR_PLAIN_VARIANTS = { + TEAR_BLUE, TEAR_BLOOD, TEAR_METALLIC, TEAR_FIRE_MIND, TEAR_DARK_MATTER, + TEAR_MYSTERIOUS, TEAR_LOST_CONTACT, TEAR_CUPID_BLUE, TEAR_CUPID_BLOOD, TEAR_PUPULA, + TEAR_PUPULA_BLOOD, TEAR_GODS_FLESH, TEAR_GODS_FLESH_BLOOD, TEAR_MULTIDIMENSIONAL, TEAR_GLAUCOMA, + TEAR_GLAUCOMA_BLOOD, TEAR_NEEDLE, TEAR_BELIAL, TEAR_HUNGRY, TEAR_FIST, + TEAR_ICE, TEAR_SWORD_BEAM, TEAR_TECH_SWORD_BEAM}; // The variants whose splash is a bullet poof rather than a tear poof. constexpr std::array TEAR_BULLET_POOF_VARIANTS = {TEAR_BLOOD, TEAR_CUPID_BLOOD, TEAR_PUPULA_BLOOD, TEAR_GODS_FLESH_BLOOD, TEAR_GLAUCOMA_BLOOD, TEAR_BELIAL, @@ -147,7 +244,7 @@ constexpr std::array STONE_ANIMATION_VARIANTS = {TEAR_STONE, TEAR_BOOGER // its sprite. Rift's tears show Little Horn's effect tinted. constexpr const char* TEAR_HALO_ANM2 = "gfx/TearHalo.anm2"; constexpr ColorMod RIFT_EFFECT_COLOR = {{1, 0.7f, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -// A render flag the creep, fire and dark matter effects and their first layer carry, read by nothing written yet. +// A render flag the creep, fire and dark matter effects and their first layer carry. The flight turns such layers. constexpr unsigned int TEAR_EFFECT_LAYERED = 1 << 12; // A tear effect: the flag that shows it and its sprite. @@ -167,6 +264,54 @@ constexpr std::array TEAR_EFFECTS = {{ {TEAR_DARK_MATTER_FLAG, "gfx/DarkMatterTearEffect.anm2"}, }}; +// A flag whose behaviour is not reconstructed yet, and where the game stops when a tear carries it. +struct UnhandledFlag +{ + int flag = 0; + const char* name = nullptr; +}; + +constexpr std::array UPDATE_UNHANDLED_FLAGS = {{ + {TEAR_LUDOVICO, "Entity_Tear::Update 006670f0: a Ludovico tear"}, + {TEAR_DETONATE, "Entity_Tear::Update 006670f0: a detonating tear"}, + {TEAR_LASER, "Entity_Tear::Update 006670f0: Technology Zero's lasers"}, + {TEAR_LASERSHOT, "Entity_Tear::Update 006670f0: a laser shot tear"}, + {TEAR_HYDROBOUNCE, "Entity_Tear::Update 006670f0: a bouncing water tear"}, + {TEAR_EXPLOSIVE, "Entity_Tear::Update 006670f0: an explosive tear"}, + {TEAR_BURSTSPLIT, "Entity_Tear::Update 006670f0: Haemolacria's burst"}, + {TEAR_ORBIT, "Entity_Tear::Update 006670f0: an orbiting tear"}, + {TEAR_ORBIT_ADVANCED, "Entity_Tear::Update 006670f0: an orbiting tear"}, + {TEAR_FETUS_FLAG, "Entity_Tear::Update 006670f0: a fetus tear"}, + {TEAR_OCCULT, "Entity_Tear::Update 006670f0: Eye of the Occult's steering"}, + {TEAR_ATTRACTOR, "Entity_Tear::Update 006670f0: Strange Attractor's pull"}, + {TEAR_STICKY, "Entity_Tear::Update 006670f0: a sticking tear"}, + {TEAR_SPORE_FLAG, "Entity_Tear::Update 006670f0: a sticking tear"}, + {TEAR_BOOGER_FLAG, "Entity_Tear::Update 006670f0: a sticking tear"}, + {TEAR_GLOW, "Entity_Tear::Update 006670f0: Godhead's aura"}, + {TEAR_DECELERATE, "Entity_Tear::Update 006670f0: a slowing tear"}, + {TEAR_ACCELERATE, "Entity_Tear::Update 006670f0: a speeding tear"}, + {TEAR_ABSORB, "Entity_Tear::Update 006670f0: Lachryphagy's absorbing"}, + {TEAR_CHAIN, "Entity_Tear::Update 006670f0: a chained tear"}, + {TEAR_TRACTOR_BEAM, "Entity_Tear::Update 006670f0: Tractor Beam's guide"}, + {TEAR_POP, "Entity_Tear::Update 006670f0: Pop!'s bouncing"}, + {TEAR_REROLL_ROCK_WISP, "Entity_Tear::Update 006670f0: a rock rerolling tear"}, + {TEAR_CONTINUUM, "Entity_Tear::Update 006670f0: Continuum's wrapping"}, + {TEAR_BOUNCE_WALLSONLY, "Entity_Tear::Update 006670f0: a wall bouncing tear"}, + {TEAR_INTERVAL_FLAGS, "Entity_Tear::Update 006670f0: flags swapped on an interval"}, + {TEAR_INTERVAL_SPEED, "Entity_Tear::Update 006670f0: a speed reset on an interval"}, + {TEAR_PARENT_STEER, "Entity_Tear::Update 006670f0: a tear steering to its parent"}, +}}; + +constexpr std::array HIT_UNHANDLED_FLAGS = {{ + {TEAR_COIN_DROP_DEATH, "Entity_Tear::ApplyTearFlagEffects 0067af60: a drop on death"}, + {TEAR_CARD_DROP_DEATH, "Entity_Tear::ApplyTearFlagEffects 0067af60: a drop on death"}, + {TEAR_RUNE_DROP_DEATH, "Entity_Tear::ApplyTearFlagEffects 0067af60: a drop on death"}, + {TEAR_ECOLI, "Entity_Tear::ApplyTearFlagEffects 0067af60: E. Coli's poop"}, + {TEAR_ENEMY_TO_WISP, "Entity_Tear::ApplyTearFlagEffects 0067af60: an enemy turned to a wisp"}, + {TEAR_REROLL_ENEMY, "Entity_Tear::ApplyTearFlagEffects 0067af60: an enemy rerolled"}, + {TEAR_MOM_STOMP_WISP, "Entity_Tear::ApplyTearFlagEffects 0067af60: Mom's stomp"}, +}}; + // The splash a dying tear leaves: its poof and its sound. struct TearSplash { @@ -183,39 +328,12 @@ static bool is_listed(const std::array& list, int value) return std::find(list.begin(), list.end(), value) != list.end(); } -static Vector vector_add(Vector a, Vector b) +// Stops the game at the first flag in the list a tear carries. +template +static void unhandled_check(const TearFlags& flags, const std::array& list) { - return vector_make(a.x + b.x, a.y + b.y); -} - -static Vector vector_sub(Vector a, Vector b) -{ - return vector_make(a.x - b.x, a.y - b.y); -} - -static float vector_length(Vector v) -{ - return std::sqrt(v.x * v.x + v.y * v.y); -} - -// A random fraction of one, as random_float makes it. -static float random_unit() -{ - return (float)Random() * RANDOM_UNIT_SCALE; -} - -// A random number below max, or 0 for none. -static int random_below(int max) -{ - return max == 0 ? 0 : (int)(Random() % (uint32_t)max); -} - -// A random unit direction, as MusicManager::RandomVector draws it. -static Vector random_direction() -{ - float angle = random_unit() * RANDOM_DIRECTION_HALF_TURN; - angle += angle; - return vector_make(std::cos(angle), std::sin(angle)); + for (const UnhandledFlag& unhandled : list) + if (flags[unhandled.flag]) reconstruction_missing(unhandled.name); } // How much of a per-tick factor is left over a step of timeScale ticks (Math::timescale_factor). @@ -237,11 +355,17 @@ static bool is_remote_player(Entity_Player* player) return player && netplay.is_online() && !netplay.IsIdxLocalPlayer(player->controllerIndex); } +// Whether a tear is one of the nails the G-Fuel seed turns into bullets. +static bool is_gfuel_nail(int variant) +{ + return (variant == TEAR_NAIL || variant == TEAR_NAIL_BLOOD) && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL); +} + // Makes a sprite layer add its light to what is under it. static void layer_additive_set(ANM2& sprite, int layerId) { LayerState* layer = sprite.GetLayer(layerId); - bool isPremultiplied = g_graphicsManager_flags & GRAPHICS_PREMULTIPLIED_ALPHA; + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; layer->blendMode[BLEND_EQUATION] = BLEND_EQUATION_ADD; layer->blendMode[BLEND_RGB_SOURCE] = isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA; @@ -250,13 +374,6 @@ static void layer_additive_set(ANM2& sprite, int layerId) layer->blendMode[BLEND_ALPHA_DEST] = BLEND_FACTOR_ONE; } -// Plays a sound at a volume and pitch, through the fart seeds. -static void sound_play(int sound, float volume, float pitch) -{ - seed_fart_sound_override(&sound); - g_manager->sfxManager.Play(sound, {.volume = volume, .pitch = pitch}); -} - // In Onan's Streak, a tear that misses hurts its player. static void streak_end(Entity_Player& player) { @@ -264,6 +381,31 @@ static void streak_end(Entity_Player& player) player.TakeDamage(STREAK_DAMAGE, DAMAGE_INVINCIBLE, EntityRef(), STREAK_DAMAGE_COUNTDOWN); } +// A vector turned a quarter turn, as Vector::Rotated turns it by 90 degrees. +static Vector vector_quarter_turn(Vector v) +{ + float angle = RIGHT_ANGLE * DEGREES_TO_RADIANS; + return vector_make(v.x * std::cos(angle) - v.y * std::sin(angle), v.x * std::sin(angle) + v.y * std::cos(angle)); +} + +// 007c2d50 How strong a worm trinket makes its flag's motion: its multiplier, at least one, and one for the other +// flags or without a player. +float worm_multiplier_get(Entity_Player* player, int flag) +{ + int trinket = 0; + switch (flag) + { + case TEAR_WIGGLE: trinket = TRINKET_WIGGLE_WORM; break; + case TEAR_PULSE: trinket = TRINKET_PULSE_WORM; break; + case TEAR_SPIRAL: trinket = TRINKET_RING_WORM; break; + case TEAR_FLAT: trinket = TRINKET_FLAT_WORM; break; + case TEAR_SQUARE: trinket = TRINKET_HOOK_WORM; break; + case TEAR_BIG_SPIRAL: trinket = TRINKET_OUROBOROS_WORM; break; + default: return 1; + } + return player ? (float)std::max(player->GetTrinketMultiplier(trinket), 1) : 1; +} + // 006660a0 Starts a tear 23 high with a slight random fall, base damage and scale, no flags, links or targets, and // the sprite of its config. The brimstone balloon's glow and the G-Fuel nails' sprites add light. void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) @@ -322,8 +464,7 @@ void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uin tearRange = TEAR_RANGE_DEFAULT; tearIdx = -1; - bool isGFuelNail = (variant == TEAR_NAIL || variant == TEAR_NAIL_BLOOD) && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL); - if (isGFuelNail) + if (is_gfuel_nail(variant)) { sprite.Load(variant == TEAR_NAIL ? GFUEL_NAIL_ANM2 : GFUEL_NAIL_BLOOD_ANM2, GRAPHICS_LOAD); layer_additive_set(sprite, variant == TEAR_NAIL ? 0 : 1); @@ -332,7 +473,7 @@ void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uin } // 006670f0 Flies the tear for a frame, or splashes and removes it once it has died. While held it bobs at its -// parent, and while waiting it hovers until its player stops firing. +// parent, while waiting it hovers until its player stops firing, and its flags steer, grow, shrink and split it. void Entity_Tear::Update() { if (isFireSoundPending) @@ -340,7 +481,6 @@ void Entity_Tear::Update() play_fire_sound(); isFireSoundPending = false; } - if (tearFlags.any()) reconstruction_missing("Entity_Tear::Update 006670f0: the tear flags' effects"); if (!is_listed(TEAR_PLAIN_VARIANTS, variant)) reconstruction_missing("Entity_Tear::Update 006670f0: this tear variant's flight and splash"); @@ -354,7 +494,10 @@ void Entity_Tear::Update() isDead = true; deathFlags = TEAR_DEATH_FORCED; } + if (is_gfuel_nail(variant)) tearFlags.reset(TEAR_LASERSHOT); + unhandled_check(tearFlags, UPDATE_UNHANDLED_FLAGS); wait_update(); + death_creep_spawn(); if (laserShotLaser) { isVisible = true; @@ -388,10 +531,18 @@ bool Entity_Tear::hold_update() return true; } -// Counts down a waiting tear, which ends at once when its player stops firing and then flies on with the velocity -// it waited with. It bobs while it waits. +// Starts Anti-Gravity's wait, keeping the velocity for later, or counts a waiting tear down. It ends at once when its +// player stops firing and then flies on with the velocity it waited with. It bobs while it waits. void Entity_Tear::wait_update() { + if (tearFlags[TEAR_WAIT]) + { + waitFrames = WAIT_FRAMES; + tearFlags.reset(TEAR_WAIT); + continueVelocity = velocity; + velocity = {}; + return; + } if (waitFrames <= 0) return; Entity* owner = parent; @@ -408,6 +559,24 @@ void Entity_Tear::wait_update() SetHeight(height + ((waitFrames / HOVER_BOB_FRAMES & 1) == 0 ? HOVER_HEIGHT_BOB : -HOVER_HEIGHT_BOB)); } +// Leaves the creep a dying tear's flags call for: Mysterious Liquid's green and It Hurts' red, sized by the tear. +// An explosive tear or Bob's head leaves none. +void Entity_Tear::death_creep_spawn() +{ + if (!isDead || tearFlags[TEAR_EXPLOSIVE] || variant == TEAR_BOBS_HEAD) return; + + for (int flag : {TEAR_MYSTERIOUS_LIQUID_CREEP, TEAR_BLOOD_CREEP}) + { + if (!tearFlags[flag]) continue; + Vector position = g_game->room->GetClampedPosition(pos, CREEP_MARGIN); + int creepVariant = flag == TEAR_BLOOD_CREEP ? EFFECT_PLAYER_CREEP_RED : EFFECT_PLAYER_CREEP_GREEN; + Entity* creep = g_game->Spawn({.position = position, .spawner = spawnerEntity, .type = ENTITY_EFFECT, + .variant = creepVariant, .seed = Random()}); + creep->sprite.scale = vector_make(CREEP_SCALE * fScale, CREEP_SCALE * fScale); + creep->Update(); + } +} + // The splash of a dying tear by its variant: a bullet poof for the blood-like ones, a tear poof sized by its scale // (the larger one above the floor) for the rest, and the sword beams' own. static TearSplash splash_get(Entity_Tear& tear) @@ -448,12 +617,13 @@ static TearSplash splash_get(Entity_Tear& tear) return splash; } -// Splashes the dead tear: its sound, its poof in its color at its height, the stains some leave, then removes it. -// Game::Spawn returning nothing crashes the original. This skips the poof. +// Splashes the dead tear: its sound, Cricket's Body's four pieces, its poof in its color at its height, the stains +// some leave, then removes it. Game::Spawn returning nothing crashes the original. This skips the poof. void Entity_Tear::death_update() { TearSplash splash = splash_get(*this); - if (splash.sound) sound_play(splash.sound, splash.volume, splash.pitch); + if (splash.sound) npc_sound_play(splash.sound, splash.volume, SOUND_DELAY, splash.pitch); + if (tearFlags[TEAR_QUADSPLIT]) quadsplit_fire(); uint32_t seed = Random(); Entity* poof = g_game->Spawn({.position = pos, .spawner = this, .subType = splash.subType, .type = ENTITY_EFFECT, @@ -476,6 +646,43 @@ void Entity_Tear::death_update() Remove(); } +// Cricket's Body: four pieces at a random angle and its right angles, at the dying tear's speed (10 when it barely +// moved), from where it was a frame ago. They fly a little lower and slower, smaller and with half the damage. +void Entity_Tear::quadsplit_fire() +{ + float speedSquared = vector_length_squared(velocity); + Vector direction = vector_scale(random_direction(), speedSquared < QUADSPLIT_SLOW_SQUARED ? QUADSPLIT_SLOW_SPEED + : vector_length(velocity)); + TearFlags flags = tearFlags; + for (int dropped : {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_ABSORB, TEAR_HYDROBOUNCE, + TEAR_FETUS_FLAG}) + flags.reset(dropped); + + for (int i = 0; i < QUADSPLIT_PIECES; i++) + { + Vector pieceVelocity = i < 2 ? direction : vector_make(direction.y, -direction.x); + if (i & 1) pieceVelocity = vector_scale(pieceVelocity, -1); + Entity_Player* player = GetRootPlayer(); + int pieceVariant = variant == TEAR_FETUS ? TEAR_BLOOD : variant; + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = pieceVelocity, + .spawner = spawnerEntity, .type = type, .variant = pieceVariant, + .seed = Random()}); + Entity_Tear& piece = *spawned->ToTear(); + + piece.SetHeight((player ? player->tearHeight : PLAYER_TEAR_HEIGHT) * QUADSPLIT_HEIGHT_SHARE); + piece.fallingAccel = fallingAccel; + float playerFall = g_game->GetPlayer(0)->tearFallingSpeed; + if (playerFall > 0) playerFall *= QUADSPLIT_FALL_SHARE; + piece.fallingSpeed = random_unit() * TEAR_FALL_SPREAD - playerFall; + piece.SetCollisionDamage(collisionDamage * QUADSPLIT_DAMAGE); + piece.SetTearFlags(flags); + piece.SetScale(fScale * QUADSPLIT_SCALE); + piece.SetColor(sprite.color, -1, COLOR_PRIORITY_TOP, false, true); + piece.parent = parent; + piece.Update(); + } +} + // Leaves up to four faint stains around the splash, Eve's Mascara's darker and Number One's yellow. void Entity_Tear::blood_stains_spawn() { @@ -487,7 +694,7 @@ void Entity_Tear::blood_stains_spawn() uint32_t seed = Random(); Vector direction = random_direction(); float distance = random_unit() * STAIN_SPREAD; - Vector position = vector_add(pos, vector_make(direction.x * distance, direction.y * distance)); + Vector position = vector_add(pos, vector_scale(direction, distance)); Entity* stain = g_game->Spawn( {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = seed}); if (!stain) continue; @@ -502,18 +709,25 @@ void Entity_Tear::blood_stains_spawn() } } -// Flies the living tear: points it along its flight, lets it die on the floor or a wall, sizes its sprite, moves it, -// and lets it fall by its speed and acceleration. +// Flies the living tear: its flags steer and resize it, it points along its flight, dies on the floor or a wall (or +// bounces), sizes its sprite, moves, turns toward its target, and falls by its speed and acceleration. void Entity_Tear::flight_update() { - sprite.rotation = 0; - if (is_listed(TEAR_ROTATED_VARIANTS, variant)) + Entity_Player* player = GetRootPlayer(); + square_turn(); + homing_update(); + float scaleFactor = size_flags_update(); + spectral_update(); + boomerang_pull(); + if (tearFlags[TEAR_WIGGLE]) wiggle_apply(worm_multiplier_get(player, TEAR_WIGGLE)); + if (tearFlags[TEAR_SPIRAL]) spiral_apply(worm_multiplier_get(player, TEAR_SPIRAL)); + if (tearFlags[TEAR_BIG_SPIRAL]) big_spiral_apply(worm_multiplier_get(player, TEAR_BIG_SPIRAL)); + if (tearFlags[TEAR_PULSE]) { - Vector direction = velocity; - if (waitFrames >= 1) direction = continueVelocity; - else if (fallingAccel > GRAVITY_MIN_ACCEL) direction.y += fallingSpeed; - sprite.rotation = std::atan2(direction.y, direction.x) * DEGREES_PER_RADIAN; + float strength = worm_multiplier_get(player, TEAR_PULSE) * PULSE_STRENGTH; + scaleFactor *= (std::sin((float)FrameCount() * PULSE_RATE) + PULSE_OFFSET) * strength + PULSE_BASE; } + rotation_update(player); if (HasEntityFlags(FLAG_NO_SPIKE_DAMAGE)) { @@ -521,28 +735,183 @@ void Entity_Tear::flight_update() else friction *= updateTime / LAUNCH_DRAG_TIME * (1 - LAUNCH_DRAG_FRICTION) + LAUNCH_DRAG_FRICTION; } if (height > TEAR_FLOOR_HEIGHT) floor_hit(); + else if ((tearFlags[TEAR_BOUNCE] || variant == TEAR_FIRE) && !g_game->room->IsBeastDungeon()) bounce_hit(); else grid_hit(); if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Tear::Update 006670f0: the versus mode's tear reflections"); - fScale = std::max(baseScale, TEAR_SCALE_MIN); + fScale = std::max(scaleFactor * baseScale, TEAR_SCALE_MIN); ResetSpriteScale(); if (g_game->seedEffects.HasSeedEffect(SEED_BLACK_ISAAC)) reconstruction_missing("Entity_Tear::Update 006670f0: Black Isaac's tear color"); Vector previous = pos; Entity::Update(); + turn_horizontal_update(previous); posDisplacement = vector_sub(pos, previous); - if (waitFrames >= 1 || isDead || stickTarget) return; + fall_update(); +} - fallingSpeed = speedMultiplier * GRAVITY_PULL + timescale_factor(GRAVITY_FALL_DRAG, speedMultiplier) * fallingSpeed + - speedMultiplier * fallingAccel; - SetHeight(speedMultiplier * fallingSpeed + height); - if (!is_crawlspace()) return; +// Hook Worm: from its third frame the tear turns a right angle (its first one), then keeps turning left and right on +// a 22 frame loop, slowing or speeding by the worm's strength. +void Entity_Tear::square_turn() +{ + int frame = FrameCount(); + if (!tearFlags[TEAR_SQUARE] || frame < SQUARE_START_FRAME) return; - if (fallingAccel >= GRAVITY_MIN_ACCEL) velocity.y += fallingAccel; - else if (height > CRAWLSPACE_SINK_HEIGHT) velocity.y += CRAWLSPACE_SINK_SPEED; - if (g_game->room->IsBeastDungeon()) reconstruction_missing("Entity_Tear::Update 006670f0: the Beast's lava"); + float speed = worm_multiplier_get(GetRootPlayer(), TEAR_SQUARE) * SQUARE_SPEED_SHARE + SQUARE_SPEED_SHARE; + Vector right = vector_make(velocity.y, -velocity.x); + Vector left = vector_make(-velocity.y, velocity.x); + if (frame < SQUARE_LOOP_START) + { + if (frame == SQUARE_START_FRAME) velocity = vector_scale(right, speed); + return; + } + switch ((frame - SQUARE_LOOP_START) % SQUARE_LOOP_FRAMES) + { + case SQUARE_TURN_LEFT_SLOW: velocity = vector_scale(left, 1 / speed); break; + case SQUARE_TURN_LEFT: velocity = vector_scale(left, speed); break; + case SQUARE_TURN_RIGHT_SLOW: velocity = vector_scale(right, 1 / speed); break; + case SQUARE_TURN_RIGHT: velocity = vector_scale(right, speed); break; + } +} + +// The enemy a homing tear picks every fourth frame: a vulnerable one ahead of it that it has not hit, each skipped +// half the time, scored by its distance plus a random part. A tear that collides with the grid needs a clear line. +static Entity* homing_target_find(Entity_Tear& tear) +{ + Entity* best = nullptr; + float bestScore = HOMING_SCORE_NONE; + Vector ahead = vector_add(tear.pos, vector_scale(tear.velocity, HOMING_LOOK_AHEAD)); + + for (Entity* enemy : entity_query_radius(ahead, HOMING_RADIUS, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + if (tear.spawnerEntity && tear.spawnerEntity->IsDescendantOf(enemy)) continue; + if (enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + if (EntityList::HitListContains(tear.hitList, *enemy)) continue; + if (enemy->type == ENTITY_PLAYER && static_cast(enemy)->IsInvisible()) continue; + if (random_below(2) == 0) continue; + if (tear.entityGridCollisionClass == GRIDCOLL_BULLET && + !room_check_line(tear.pos, enemy->pos, LINE_MODE_PROJECTILE, 0)) + continue; + + float score = vector_length(vector_sub(ahead, enemy->pos)) + random_unit() * HOMING_RADIUS; + if (score < bestScore) + { + best = enemy; + bestScore = score; + } + } + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Tear::Update 006670f0: homing on the versus mode's familiars"); + return best; +} + +// Spoon Bender and Brain Worm: drops a target already hit, searches a new one every fourth frame, and a homing tear +// pulls toward it, its speed eased by its homing friction. +void Entity_Tear::homing_update() +{ + if (!tearFlags[TEAR_HOMING] && !tearFlags[TEAR_TURN_HORIZONTAL]) return; + if (target && EntityList::HitListContains(hitList, *target)) target = nullptr; + if (!target && IsFrame(HOMING_SEARCH_FRAMES, (int)index)) target = homing_target_find(*this); + if (!target || !tearFlags[TEAR_HOMING]) return; + + Vector away = vector_normalized(vector_sub(pos, target->pos)); + velocity = vector_sub(velocity, vector_scale(away, speedMultiplier * HOMING_PULL)); + velocity = vector_scale(velocity, timescale_factor(homingFriction, speedMultiplier)); +} + +// Lump of Coal's growth with the distance flown and Proptosis' shrinking damage, which kills the tear once it has +// none left. The factor its scale draws at. +float Entity_Tear::size_flags_update() +{ + float scaleFactor = 1; + if (tearFlags[TEAR_GROW] && waitFrames < 1) + { + collisionDamage += vector_length(posDisplacement) * GROW_DAMAGE; + baseScale += GROW_SCALE; + } + if (tearFlags[TEAR_SHRINK] && waitFrames < 1 && updateTime > SHRINK_START) + { + float rate = baseDamage / SHRINK_FAST_SHARE < collisionDamage ? SHRINK_FAST : SHRINK_SLOW; + collisionDamage = std::max(collisionDamage - rate * baseDamage, SHRINK_DAMAGE_MIN); + scaleFactor = std::sqrt(collisionDamage / baseDamage); + if (collisionDamage <= SHRINK_DAMAGE_MIN) + { + isDead = true; + deathFlags |= TEAR_DEATH_SHRUNK; + } + } + return scaleFactor; +} + +// A spectral tear flies over the grid (Bob's head and the Chaos Card only stop at walls), hurting the poop and fires +// it passes: everything under it the first time it touches any, then now and then. +void Entity_Tear::spectral_update() +{ + if (!tearFlags[TEAR_SPECTRAL]) return; + + bool isGridBound = variant == TEAR_BOBS_HEAD || variant == TEAR_CHAOS_CARD; + entityGridCollisionClass = isGridBound ? GRIDCOLL_WALLS : GRIDCOLL_NONE; + if (!isGridTouched) + { + if (try_make_bridges(pos)) + { + apply_death_flag_effects(nullptr); + isGridTouched = true; + } + } + else if (random_below(SPECTRAL_GRID_CHANCE) == 0) try_make_bridges(pos); +} + +// My Reflection: pulls the tear back toward its parent (or the target position), harder at a higher shot speed and a +// shorter range. +void Entity_Tear::boomerang_pull() +{ + if (!tearFlags[TEAR_BOOMERANG] || !parent) return; + + Vector lift = vector_make(0, BOOMERANG_ANCHOR_LIFT); + Vector anchor = vector_is_zero(targetPosition) ? vector_add(parent->pos, lift) : vector_sub(targetPosition, lift); + Entity_Player* player = GetRootPlayer(); + float reach = std::max((tearRange - BOOMERANG_RANGE_START) * BOOMERANG_REACH_SHARE, BOOMERANG_REACH_MIN); + float speed = (player ? player->shotSpeed : 1) * BOOMERANG_SPEED; + float pull = speed * speed / (reach + reach); + velocity = vector_sub(velocity, vector_scale(vector_normalized(vector_sub(pos, anchor)), pull)); +} + +// Points the tear along its flight: Flat Worm stretches it, the rotated variants and the turning layers of its tear +// effect follow the direction it moves and falls, and a boomerang Pupula Duplex tear spins. +void Entity_Tear::rotation_update(Entity_Player* player) +{ + sprite.rotation = 0; + bool isRotated = false; + bool isEffectRotated = tearEffectANM2.isLoaded && (tearEffectANM2.bitflags & TEAR_EFFECT_LAYERED); + if (tearFlags[TEAR_FLAT] && variant != TEAR_BOBS_HEAD) + { + float stretch = worm_multiplier_get(player, TEAR_FLAT) * FLAT_STRETCH + 1; + isRotated = variant != TEAR_FETUS; + sizeMulti = isRotated ? vector_make(1, stretch) : vector_make(stretch, 1); + } + if (is_gfuel_nail(variant)) sizeMulti.x = GFUEL_NAIL_WIDTH; + + bool isPupula = variant == TEAR_PUPULA || variant == TEAR_PUPULA_BLOOD; + if (isPupula && tearFlags[TEAR_BOOMERANG]) + { + sprite.rotation = updateTime * PUPULA_SPIN; + isRotated = false; + } + else if (is_listed(TEAR_ROTATED_VARIANTS, variant)) isRotated = true; + if (!isRotated && !isEffectRotated) return; + + Vector direction = velocity; + if (waitFrames >= 1) direction = continueVelocity; + else if (fallingAccel > GRAVITY_MIN_ACCEL) direction.y += fallingSpeed; + float angle = vector_angle(direction); + if (isRotated) sprite.rotation = angle; + if (!isEffectRotated) return; + for (LayerState& layer : tearEffectANM2.layerStates) + if (layer.bitflags & TEAR_EFFECT_LAYERED) layer.rotation = angle; } // The tear reached the floor: it dies there, ending its player's streak. @@ -560,8 +929,8 @@ void Entity_Tear::floor_hit() } } -// The tear hit the grid, or stands on a wall: it dies, hurting the rocks and poop it touches. Missing anything but -// poop or TNT ends its player's streak. +// The tear hit the grid, or stands on a wall: it dies, hurting the rocks and poop it touches, unless it is spectral. +// Missing anything but poop or TNT ends its player's streak. void Entity_Tear::grid_hit() { Room& room = *g_game->room; @@ -573,6 +942,7 @@ void Entity_Tear::grid_hit() if (!isCollidesWithGrid) return; if (height <= TEAR_GRID_HIT_HEIGHT && !isWall && !isPlayerWall) return; + if (tearFlags[TEAR_SPECTRAL] && variant != TEAR_BOBS_HEAD) return; isDead = true; deathFlags |= TEAR_DEATH_GRID; @@ -588,23 +958,112 @@ void Entity_Tear::grid_hit() if (player->HasCollectible(COLLECTIBLE_DEAD_EYE)) player->ClearDeadEyeCharge(); } -// 00679400 Moves the tear half a step for the frame between updates and places its sprite at the height it will -// fall to. A held tear stays at its parent. -void Entity_Tear::Interpolate() +// Rubber Cement and the flames: the tear bounces off the grid at the speed the collision left it, hurting what it +// hit, forgetting the entities it hit and the Tractor Beam. A crawlspace takes the bounce away. +void Entity_Tear::bounce_hit() { - if (holdTimer > 0) + entityGridCollisionClass = tearFlags[TEAR_SPECTRAL] ? GRIDCOLL_WALLS : GRIDCOLL_NOPITS; + if (!isCollidesWithGrid) return; + + try_make_bridges(vector_sub(pos, velocity)); + velocity = vector_scale(vector_normalized(velocity), vector_length(gridCollisionVelocity)); + tearFlags.reset(TEAR_TRACTOR_BEAM); + hitList.clear(); + Entity_Player* shooter = spawnerEntity ? spawnerEntity->ToPlayer() : nullptr; + npc_sound_play(BOUNCE_SOUND, shooter ? shooter->local_volume_get() : 1, SOUND_DELAY, 1); + if (is_crawlspace()) tearFlags.reset(TEAR_BOUNCE); +} + +// Brain Worm: once the target passes beside the tear it turns a right angle toward it, once. A tear moving away from +// a target behind it loses the target unless it homes. +void Entity_Tear::turn_horizontal_update(Vector previous) +{ + if (!target || !tearFlags[TEAR_TURN_HORIZONTAL]) return; + + Vector direction = vector_normalized(velocity); + float before = vector_dot(vector_normalized(vector_sub(vector_sub(target->pos, previous), velocity)), direction); + Vector toTarget = vector_normalized(vector_sub(vector_sub(target->pos, pos), velocity)); + float after = vector_dot(toTarget, direction); + if (after > 0 || (before <= 0 && after < TURN_AWAY)) { - if (parent) pos = vector_add(parent->pos, holdOffset); + if (after < TURN_AWAY && before < TURN_AWAY && !tearFlags[TEAR_HOMING]) target = nullptr; return; } - if (tearFlags.any()) reconstruction_missing("Entity_Tear::Interpolate 00679400: the tear flags' motion"); + Vector turned = vector_quarter_turn(direction); + if (vector_dot(turned, toTarget) < 0) turned = vector_scale(turned, -1); + velocity = vector_scale(turned, vector_length(velocity)); + tearFlags.reset(TEAR_TURN_HORIZONTAL); +} +// Lets the flying tear fall by its speed and acceleration, a crawlspace's tears dropping under gravity. +void Entity_Tear::fall_update() +{ + if (waitFrames >= 1 || isDead || stickTarget) return; + + fallingSpeed = speedMultiplier * GRAVITY_PULL + timescale_factor(GRAVITY_FALL_DRAG, speedMultiplier) * fallingSpeed + + speedMultiplier * fallingAccel; + SetHeight(speedMultiplier * fallingSpeed + height); + if (!is_crawlspace()) return; + + if (fallingAccel >= GRAVITY_MIN_ACCEL) velocity.y += fallingAccel; + else if (height > CRAWLSPACE_SINK_HEIGHT) velocity.y += CRAWLSPACE_SINK_SPEED; + if (g_game->room->IsBeastDungeon()) reconstruction_missing("Entity_Tear::Update 006670f0: the Beast's lava"); +} + +// 00679400 Moves the tear half a step for the frame between updates, sways the worms' tears, and places its sprite at +// the height it will fall to. A held tear stays at its parent. +void Entity_Tear::Interpolate() +{ + if (holdTimer > 0 && parent) pos = vector_add(parent->pos, holdOffset); + for (int flag : {TEAR_TRACTOR_BEAM, TEAR_LASER, TEAR_LUDOVICO, TEAR_HYDROBOUNCE}) + if (tearFlags[flag]) reconstruction_missing("Entity_Tear::Interpolate 00679400: the tear flags' motion"); + + Entity_Player* player = GetRootPlayer(); + if (tearFlags[TEAR_WIGGLE]) wiggle_apply(worm_multiplier_get(player, TEAR_WIGGLE)); + if (tearFlags[TEAR_SPIRAL]) spiral_apply(worm_multiplier_get(player, TEAR_SPIRAL)); + if (tearFlags[TEAR_BIG_SPIRAL]) big_spiral_apply(worm_multiplier_get(player, TEAR_BIG_SPIRAL)); Entity::Interpolate(); if (waitFrames >= 1 || isDead) return; posOffset.y = is_crawlspace() ? CRAWLSPACE_OFFSET_Y : get_height_offset_y(fallingSpeed * speedMultiplier * 0.5f + height); } +// 006668c0 Wiggle Worm: sways the tear sideways on a wave, odd tears the other way, by half its speed (at most 5). +void Entity_Tear::wiggle_apply(float strength) +{ + Vector side = vector_normalized(vector_make(velocity.y, -velocity.x)); + float sway = std::min(vector_length(velocity) * WIGGLE_SPEED_SHARE, WIGGLE_MAX); + float phase = (tearIdx & 1) == 0 ? 0 : PI_F; + float wave = std::cos(((float)(g_game->frameCount - spawnFrame) + HALF_FRAME) * WIGGLE_RATE + phase); + pos = vector_add(pos, vector_scale(side, wave * sway * strength)); +} + +// The shared spiral: a circle of a radius across and along the flight, turning at a rate, half a frame ahead on odd +// global frames. +static void spiral_move(Entity_Tear& tear, float rate, float side, float forward) +{ + float frame = (float)(g_game->frameCount - tear.spawnFrame) + (float)(g_manager->framecount % 2) * HALF_FRAME; + Vector direction = tear.velocity; + float phase = std::fabs(direction.x) <= std::fabs(direction.y) ? frame * rate : QUARTER_TURN - frame * rate; + float cosine = std::cos(phase); + float sine = std::sin(phase); + direction = vector_normalized(direction); + tear.pos.x += cosine * direction.y * side + cosine * direction.x * forward; + tear.pos.y += -direction.x * sine * side + sine * direction.y * forward; +} + +// 00666a00 Ring Worm: spins the tear in tight circles along its flight. +void Entity_Tear::spiral_apply(float strength) +{ + spiral_move(*this, SPIRAL_RATE, SPIRAL_SIDE * strength, SPIRAL_FORWARD); +} + +// 00666ba0 Ouroboros Worm: spins the tear in wide, slow circles along its flight. +void Entity_Tear::big_spiral_apply(float strength) +{ + spiral_move(*this, BIG_SPIRAL_RATE, BIG_SPIRAL_RADIUS * strength, BIG_SPIRAL_RADIUS); +} + // 006790c0 Draws the tear with its halo, its tear effect behind or in front, and Dead Eye's glow. void Entity_Tear::Render(const Vector& offset) { @@ -669,18 +1128,33 @@ Entity_Player* Entity_Tear::GetRootPlayer() return root->type == ENTITY_PLAYER ? static_cast(root) : nullptr; } -// 00666d40 Plays its fire sound unless muted, then sets up the flight its flags give it. In a crawlspace it starts -// a little higher, dropping when fired sideways. +// 00666d40 Plays its fire sound unless muted (and Little Horn's), then sets up the flight its flags give it: Tiny +// Planet's tears hover and fall faster, water bounces leap up, and My Reflection's fall slower. In a crawlspace it +// starts a little higher, dropping when fired sideways. void Entity_Tear::play_fire_sound() { isFireSoundPending = false; bool isSilent = variant == TEAR_CHAOS_CARD || variant == TEAR_FIRE || variant == TEAR_GRIDENT || isFireSoundMuted; bool isFetus = variant == TEAR_FETUS; - bool isGFuelNail = - (variant == TEAR_NAIL || variant == TEAR_NAIL_BLOOD) && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL); - if (!isSilent && !isGFuelNail) - sound_play(isFetus ? SOUND_FETUS_FIRE : SOUND_TEAR_FIRE, 1, isFetus ? FETUS_FIRE_PITCH : 1); - if (tearFlags.any()) reconstruction_missing("Entity_Tear::play_fire_sound 00666d40: the tear flags' flight"); + if (!isSilent && !is_gfuel_nail(variant)) + npc_sound_play(isFetus ? SOUND_FETUS_FIRE : SOUND_TEAR_FIRE, 1, SOUND_DELAY, isFetus ? FETUS_FIRE_PITCH : 1); + if (tearFlags[TEAR_HORN]) npc_sound_play(SOUND_LITTLE_HORN, 1, SOUND_DELAY, 1); + if (tearFlags[TEAR_ORBIT]) + { + if (fallingSpeed < 0) fallingSpeed *= ORBIT_FALL_SCALE; + isHovering = true; + } + if (tearFlags[TEAR_HYDROBOUNCE]) + { + isHovering = false; + fallingSpeed -= HYDROBOUNCE_LIFT; + fallingAccel += HYDROBOUNCE_ACCEL; + } + else if (tearFlags[TEAR_BOOMERANG]) + { + fallingSpeed *= BOOMERANG_FALL_SCALE; + fallingAccel = (fallingAccel + BOOMERANG_ACCEL_OFFSET) * BOOMERANG_ACCEL_SCALE - BOOMERANG_ACCEL_OFFSET; + } if (!is_crawlspace()) return; pos.y -= CRAWLSPACE_FIRE_RAISE; @@ -700,8 +1174,7 @@ float Entity_Tear::get_height_offset_y(float tearHeight) bool isFixed = variant == TEAR_FIRE || ((variant == TEAR_SWORD_BEAM || variant == TEAR_TECH_SWORD_BEAM) && isHovering); if (isFixed) return FIXED_HEIGHT_OFFSET; - bool isNail = variant == TEAR_NAIL || variant == TEAR_NAIL_BLOOD; - if (isNail && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && isHovering) return GFUEL_NAIL_OFFSET; + if (is_gfuel_nail(variant) && isHovering) return GFUEL_NAIL_OFFSET; if (!isHovering) return tearHeight; float aboveFloor = std::max(height + HOVER_FLOOR_DISTANCE, 0.0f); @@ -770,11 +1243,97 @@ void Entity_Tear::SetTearFlags(TearFlags flags) tearFlags = flags; } -// 00676be0 Applies what its flags do when it dies, splitting it or chaining lightning. A tear without flags does -// nothing. +// The opacity a remote player's shots fade to, or one for local shots and in versus. +static float shot_alpha_get(Entity_Tear& tear) +{ + if (!is_remote_player(tear.spawnerEntity ? tear.spawnerEntity->ToPlayer() : nullptr)) return 1; + if (g_game->deathmatchManager.is_active()) return 1; + return (float)g_manager->optionsConfig.onlinePlayerOpacity * 0.09f + 0.1f; +} + +// 00676be0 Applies what its flags do when it dies above the floor: Parasite splits it in two and Compound Fracture +// into two shards. A tear bouncing back up off water splits too, without explosions. void Entity_Tear::apply_death_flag_effects(Entity*) { - if (tearFlags.any()) reconstruction_missing("Entity_Tear::apply_death_flag_effects 00676be0"); + bool isRising = isDead && tearFlags[TEAR_HYDROBOUNCE] && fallingSpeed < 0; + bool isAbove = height < TEAR_FLOOR_HEIGHT; + if (tearFlags[TEAR_SPLIT] && collisionDamage > SPLIT_DAMAGE_MIN && (isAbove || isRising)) split_fire(isRising); + if (tearFlags[TEAR_BONE_FLAG] && isAbove) bone_shards_fire(isRising); + if (tearFlags[TEAR_JACOBS] && isAbove) + reconstruction_missing("Entity_Tear::apply_death_flag_effects 00676be0: Jacob's Ladder's lightning"); + if (tearFlags[TEAR_RIFT]) + reconstruction_missing("Entity_Tear::apply_death_flag_effects 00676be0: Ocular Rift's rift"); +} + +// What every piece a dying tear breaks into shares: its color (faded for a remote player), its flags, its parent, +// and a first update. +void Entity_Tear::child_setup(Entity_Tear& child, TearFlags flags, float alpha) +{ + ColorMod color = sprite.color; + color._tint[3] *= alpha; + child.SetColor(color, -1, COLOR_PRIORITY_TOP, false, true); + child.SetTearFlags(flags); + child.parent = parent; + child.Update(); +} + +// Parasite: two plain tears out to the sides from where the tear was a frame ago, lower and with half its damage +// and size. Rising off water they start at the floor with a quarter. +void Entity_Tear::split_fire(bool isRising) +{ + TearFlags flags = tearFlags; + for (int dropped : {TEAR_LUDOVICO, TEAR_ABSORB, TEAR_HYDROBOUNCE, TEAR_FETUS_FLAG}) flags.reset(dropped); + if (isRising) flags.reset(TEAR_EXPLOSIVE); + float alpha = shot_alpha_get(*this); + + for (int i = 0; i < 2; i++) + { + Vector side = i == 0 ? vector_make(velocity.y, -velocity.x) : vector_make(-velocity.y, velocity.x); + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = side, + .spawner = spawnerEntity, .type = ENTITY_TEAR, .variant = TEAR_BLUE, + .seed = Random()}); + Entity_Tear& piece = *spawned->ToTear(); + piece.SetHeight(isRising ? CRAWLSPACE_HEIGHT_MAX : height / SPLIT_HEIGHT_SHARE); + piece.fallingSpeed = fallingSpeed; + if (isRising) piece.fallingAccel = SPLIT_RISING_ACCEL; + piece.SetCollisionDamage(collisionDamage * (isRising ? SPLIT_RISING_DAMAGE : SPLIT_DAMAGE)); + piece.baseScale = std::max(fScale * SPLIT_SCALE, TEAR_SCALE_MIN); + piece.fScale = piece.baseScale; + piece.ResetSpriteScale(); + child_setup(piece, flags, alpha); + } +} + +// Compound Fracture: two shards (bone tears, broken looking ones from a bone tear) flying off at random at the +// tear's speed with half its damage. +void Entity_Tear::bone_shards_fire(bool isRising) +{ + TearFlags flags = tearFlags; + for (int dropped : {TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_FETUS_FLAG}) flags.reset(dropped); + if (isRising) flags.reset(TEAR_EXPLOSIVE); + float alpha = shot_alpha_get(*this); + int shardVariant = variant == TEAR_FETUS ? TEAR_BONE : variant; + + for (int i = 0; i < BONE_SHARDS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float speed = vector_length(velocity); + Vector shardVelocity = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = shardVelocity, + .spawner = spawnerEntity, .type = ENTITY_TEAR, .variant = shardVariant, + .seed = Random()}); + Entity_Tear& shard = *spawned->ToTear(); + if (shardVariant == TEAR_BONE) + { + shard.sprite.ReplaceSpritesheet(0, BROKEN_BONE_SHEET); + shard.sprite.LoadGraphics(); + } + shard.SetHeight(height); + shard.fallingSpeed = fallingSpeed; + shard.SetCollisionDamage(collisionDamage * BONE_DAMAGE); + child_setup(shard, flags, alpha); + } } // Whether a variant plays an animation sized to its scale. @@ -830,7 +1389,7 @@ float Entity_Tear::animation_update() scaleAnimNum = animationBase; } Vector direction = waitFrames > 0 ? continueVelocity : vector_make(velocity.x, fallingSpeed + velocity.y); - sprite.rotation = std::atan2(direction.y, direction.x) * DEGREES_PER_RADIAN; + sprite.rotation = vector_angle(direction); return fScale / TEAR_ANIMATION_SCALES.back(); } case TEAR_SCHYTHE: @@ -873,10 +1432,9 @@ void Entity_Tear::ResetSpriteScale() float layerScale = animation_update(); float sizeX = sizeMulti.x; float sizeY = sizeMulti.y; - bool isNail = variant == TEAR_NAIL || variant == TEAR_NAIL_BLOOD; if (variant > TEAR_FETUS) layerScale = fScale; - else if (isNail && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) sizeX /= GFUEL_SIZE_DIVISOR; + else if (is_gfuel_nail(variant)) sizeX /= GFUEL_SIZE_DIVISOR; for (LayerState& layer : sprite.layerStates) layer.size = vector_make(layerScale * sizeX, layerScale * sizeY); float effectScale = fScale * TEAR_EFFECT_SCALE; @@ -903,11 +1461,11 @@ bool Entity_Tear::is_not_familiar_spawned() return !parent || parent->type != ENTITY_TEAR; } -// 0067d560 Hurts the rocks, poop and other solid grid entities its collision points touch at a position, once each. -// Whether it touched any. +// 0067d560 Hurts the rocks, poop and other solid grid entities its collision points touch at a position, once each, +// unless the tear does no grid damage. Whether it touched any. bool Entity_Tear::try_make_bridges(const Vector& position) { - if (tearFlags.any()) reconstruction_missing("Entity_Tear::try_make_bridges 0067d560: the tear flags' grid hits"); + if (tearFlags[TEAR_NO_GRID_DAMAGE]) return false; Room& room = *g_game->room; std::vector cells; int damage = collisionDamage > STRONG_TEAR_DAMAGE ? 2 : 1; @@ -927,25 +1485,101 @@ bool Entity_Tear::try_make_bridges(const Vector& position) if (!grid || grid->collisionClass == COLLISION_NONE || grid->collisionClass == COLLISION_PIT) continue; isHitSolid = true; + if (tearFlags[TEAR_ACID] || tearFlags[TEAR_ROCK_FLAG]) + reconstruction_missing("Entity_Tear::try_make_bridges 0067d560: the acid and rock tears breaking rocks"); grid->Hurt(damage, EntityRef(this)); } return isHitSolid; } -// The rest of Entity_Tear is not reconstructed yet: the tear flags' behaviours. - -// 006668c0 -void Entity_Tear::apply_wiggle(float) +// The hit's direction draws a random one for a tear too slow to have its own. Only Backstabber, Knockout Drops and +// the coins use the direction, none of which is written yet, but the draw still advances the generator. +static void hit_direction_draw(Entity* source) { - reconstruction_missing("Entity_Tear::apply_wiggle 006668c0"); + if (source && source->type == ENTITY_TEAR && vector_length(source->velocity) < HIT_DIRECTION_MIN_SPEED) + random_direction(); } -// 00666ba0 -void Entity_Tear::update_wiggle() +// The status effects of a hit on a vulnerable enemy: Spider Bite's slowing (Ball of Tar's darker), poison, freezing, +// charm, confusion (Glaucoma's lasting), fear, burning, Midas' gold, magnetism, bait, ice, black hearts and God's +// Flesh's shrinking. +static void status_effects_apply(Entity& entity, const TearFlags& flags, Entity* source) { - reconstruction_missing("Entity_Tear::update_wiggle 00666ba0"); + EntityRef ref(source); + bool isVersus = g_game->deathmatchManager.is_active(); + + if (flags[TEAR_SLOW]) + entity.AddSlowing(ref, SLOW_DURATION, SLOW_AMOUNT, flags[TEAR_GISH] ? GISH_COLOR : SLOW_COLOR, false); + if (flags[TEAR_POISON]) entity.AddPoison(ref, isVersus ? POISON_DURATION_VERSUS : POISON_DURATION, 0, false); + if (flags[TEAR_FREEZE]) entity.AddFreeze(ref, isVersus ? FREEZE_DURATION_VERSUS : FREEZE_DURATION, false); + if (flags[TEAR_CHARM]) entity.AddCharmed(ref, CHARM_DURATION, false, false); + if (flags[TEAR_CONFUSION]) entity.AddConfusion(ref, (int)(Random() % CONFUSION_SPREAD) + CONFUSION_DURATION, false); + if (flags[TEAR_PERMANENT_CONFUSION]) + { + int duration = entity.IsBoss() ? PERMANENT_CONFUSION_BOSS : PERMANENT_CONFUSION; + if (isVersus && entity.type == ENTITY_PLAYER) duration = PERMANENT_CONFUSION_VERSUS; + entity.AddConfusion(ref, duration, false); + } + if (flags[TEAR_FEAR]) entity.AddFear(ref, FEAR_DURATION, false); + if (flags[TEAR_BURN]) + { + bool isHotFire = source && source->type == ENTITY_EFFECT && source->variant == EFFECT_FIRE_JET; + entity.AddBurn(ref, isHotFire ? BURN_DURATION_LONG : BURN_DURATION, 0, false); + } + if (flags[TEAR_MIDAS]) entity.AddMidasFreeze(ref, MIDAS_DURATION, false); + if (flags[TEAR_BACKSTAB]) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Backstabber's bleeding"); + if (flags[TEAR_MAGNETIZE]) entity.AddMagnetized(ref, MAGNETIZE_DURATION); + if (flags[TEAR_BAIT]) entity.AddBaited(ref, BAIT_DURATION); + if (flags[TEAR_ICE_FLAG]) entity.AddIce(ref, ICE_DURATION); + if (flags[TEAR_PUNCH]) reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Knockout Drops' punch"); + if (flags[TEAR_BLACK_HP_DROP]) entity.AddEntityFlags(FLAG_SPAWN_BLACK_HP); + if (flags[TEAR_GODS_FLESH_FLAG]) entity.AddShrink(ref, SHRINK_DURATION, false); + if (flags[TEAR_COIN_DROP] || (flags[TEAR_GREED_COIN] && Random() % GREED_COIN_CHANCE == 0)) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: a coin knocked out"); } +// 0067af60 What a hit's tear flags do to what it hits: the status effects on vulnerable enemies, the knockback a +// tear's mass and push give, and the gore. An explosive tear leaves the effects to its explosion, and a friendly +// target is spared. The original reads a missing target's position. This does nothing for one. +void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector&, const TearFlags& flags, Entity* source, float) +{ + if (!entity || (source && entity->IsDamageSourceFriendly(EntityRef(source)))) return; + + hit_direction_draw(source); + bool isActiveEnemy = entity->IsActiveEnemy(DEAD_EXCLUDED); + if (!source || source->type != ENTITY_TEAR || !flags[TEAR_EXPLOSIVE]) + { + if (entity->IsVulnerableEnemy(nullptr)) status_effects_apply(*entity, flags, source); + if (flags[TEAR_NEEDLE_FLAG] && isActiveEnemy && !entity->IsBoss() && entity->type != ENTITY_PLAYER) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Euthanasia's needle"); + if (flags[TEAR_HORN] && isActiveEnemy && !entity->HasEntityFlags(FLAG_NO_TARGET)) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Little Horn's hand"); + if (flags[TEAR_HP_DROP] && Random() % HP_DROP_CHANCE == 0) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: a heart knocked out"); + unhandled_check(flags, HIT_UNHANDLED_FLAGS); + if (flags[TEAR_KNOCKBACK] && !entity->HasEntityFlags(FLAG_NO_KNOCKBACK) && source) + { + if (source->type != ENTITY_TEAR) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: a knife's or effect's knockback"); + Vector push = vector_scale(vector_normalized(source->velocity), source->mass); + if (entity->mass > 0) push = vector_scale(push, 1 / entity->mass); + float multiplier = static_cast(source)->knockbackMultiplier; + entity->AddVelocity_divided(vector_scale(push, multiplier), false); + } + } + if (flags[TEAR_LIGHT_FROM_HEAVEN] && isActiveEnemy) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Holy Light's beam"); + if (flags[TEAR_EGG_FLAG]) reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Parasitoid's egg"); + + bool isGoreTarget = (g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || + Entity::is_enemy_type(entity->type); + if (flags[TEAR_EXTRA_GORE] && isGoreTarget) entity->AddEntityFlags(FLAG_EXTRA_GORE); +} + +// The rest of Entity_Tear is not reconstructed yet: the split projectiles, Dead Eye, the multidimensional copies, +// the variant change, the links and the rerolls. + // 00678080 void Entity_Tear::fire_split_projectiles(bool) { diff --git a/src/entity_tear.h b/src/entity_tear.h index 7934890..4c07819 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -4,23 +4,31 @@ #include "anm2.h" #include -// Lua's TearFlags bits that the entity code reads (bit 100, a hit through cooldowns, has no Lua name). +// Lua's TearFlags bits the game reads. Bits 84 and 101 to 103 have no Lua name: It Hurts' creep on death, flags +// swapped in on an interval, a speed reset on an interval, and steering back toward the parent. enum TearFlagBit : int { TEAR_SPECTRAL = 0, TEAR_PIERCING = 1, TEAR_HOMING = 2, + TEAR_SLOW = 3, TEAR_POISON = 4, + TEAR_FREEZE = 5, TEAR_SPLIT = 6, TEAR_GROW = 7, TEAR_BOOMERANG = 8, TEAR_PERSISTENT = 9, TEAR_WIGGLE = 10, + TEAR_MULLIGAN = 11, TEAR_EXPLOSIVE = 12, + TEAR_CHARM = 13, + TEAR_CONFUSION = 14, + TEAR_HP_DROP = 15, TEAR_ORBIT = 16, TEAR_WAIT = 17, TEAR_QUADSPLIT = 18, TEAR_BOUNCE = 19, + TEAR_FEAR = 20, TEAR_SHRINK = 21, TEAR_BURN = 22, TEAR_ATTRACTOR = 23, @@ -32,6 +40,7 @@ enum TearFlagBit : int TEAR_BUTT_BOMB = 29, TEAR_SQUARE = 30, TEAR_GLOW = 31, + TEAR_GISH = 32, TEAR_MYSTERIOUS_LIQUID_CREEP = 33, TEAR_SHIELDED = 34, TEAR_GLITTER_BOMB = 35, @@ -39,13 +48,21 @@ enum TearFlagBit : int TEAR_STICKY = 37, TEAR_CONTINUUM = 38, TEAR_LIGHT_FROM_HEAVEN = 39, + TEAR_COIN_DROP = 40, + TEAR_BLACK_HP_DROP = 41, TEAR_TRACTOR_BEAM = 42, + TEAR_GODS_FLESH_FLAG = 43, + TEAR_GREED_COIN = 44, TEAR_CROSS_BOMB = 45, TEAR_BIG_SPIRAL = 46, + TEAR_PERMANENT_CONFUSION = 47, TEAR_BOOGER_FLAG = 48, TEAR_EGG_FLAG = 49, + TEAR_ACID = 50, TEAR_BONE_FLAG = 51, TEAR_BELIAL_FLAG = 52, + TEAR_MIDAS = 53, + TEAR_NEEDLE_FLAG = 54, TEAR_JACOBS = 55, TEAR_HORN = 56, TEAR_LASER = 57, @@ -53,24 +70,52 @@ enum TearFlagBit : int TEAR_ABSORB = 59, TEAR_LASERSHOT = 60, TEAR_HYDROBOUNCE = 61, + TEAR_BURSTSPLIT = 62, TEAR_CREEP_TRAIL = 63, + TEAR_PUNCH = 64, TEAR_ICE_FLAG = 65, + TEAR_MAGNETIZE = 66, + TEAR_BAIT = 67, TEAR_OCCULT = 68, TEAR_ORBIT_ADVANCED = 69, TEAR_ROCK_FLAG = 70, TEAR_TURN_HORIZONTAL = 71, TEAR_BLOOD_BOMB = 72, + TEAR_ECOLI = 73, + TEAR_COIN_DROP_DEATH = 74, TEAR_BRIMSTONE_BOMB = 75, TEAR_RIFT = 76, TEAR_SPORE_FLAG = 77, TEAR_GHOST_BOMB = 78, + TEAR_CARD_DROP_DEATH = 79, + TEAR_RUNE_DROP_DEATH = 80, TEAR_TELEPORT = 81, + TEAR_DECELERATE = 82, + TEAR_ACCELERATE = 83, + TEAR_BLOOD_CREEP = 84, TEAR_THROUGH_COOLDOWN = 100, + TEAR_INTERVAL_FLAGS = 101, + TEAR_INTERVAL_SPEED = 102, + TEAR_PARENT_STEER = 103, + TEAR_BOUNCE_WALLSONLY = 104, TEAR_NO_GRID_DAMAGE = 105, TEAR_BACKSTAB = 106, + TEAR_FETUS_SWORD = 107, + TEAR_FETUS_BONE = 108, + TEAR_FETUS_KNIFE = 109, + TEAR_FETUS_TECHX = 110, + TEAR_FETUS_TECH = 111, + TEAR_FETUS_BRIMSTONE = 112, + TEAR_FETUS_BOMBER = 113, TEAR_FETUS_FLAG = 114, + TEAR_REROLL_ROCK_WISP = 115, + TEAR_MOM_STOMP_WISP = 116, + TEAR_ENEMY_TO_WISP = 117, + TEAR_REROLL_ENEMY = 118, TEAR_GIGA_BOMB = 119, + TEAR_EXTRA_GORE = 120, TEAR_RAINBOW = 121, + TEAR_DETONATE = 122, TEAR_CHAIN = 123, TEAR_DARK_MATTER_FLAG = 124, TEAR_GOLDEN_BOMB = 125, @@ -141,17 +186,27 @@ enum TearDeath : uint32_t TEAR_DEATH_WALL = 1 << 1, TEAR_DEATH_FLOOR = 1 << 2, TEAR_DEATH_ENTITY = 1 << 3, + TEAR_DEATH_SHRUNK = 1 << 4, TEAR_DEATH_EXPLOSION = 1 << 5, TEAR_DEATH_FORCED = 1 << 6 }; +// What tears and projectiles share: the crawlspace sink, the hover over the floor and the poofs' volumes. +constexpr float CRAWLSPACE_HEIGHT_MAX = -5.1f; +constexpr float CRAWLSPACE_SINK_HEIGHT = -10; +constexpr float CRAWLSPACE_SINK_SPEED = 0.5f; +constexpr float HOVER_FLOOR_DISTANCE = 8.5f; +constexpr float HOVER_OFFSET_LIFT = -15; +constexpr float POOF_VOLUME_SMALL = 0.85f; +constexpr float POOF_VOLUME_TINY = 0.7f; + // Construction and destruction (00665ea0, 00665cf0) are the defaults. // Field accessors (004177c0, 00431750, 00435e50, 00456440, 004aade0, 00557cd0, 0060ccb0, 0060ccc0, 0060ccd0, // 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, Interpolate and HandleCollision stop at most tear flags and special -// variants. +// The flags of the common items fly and hit. The rest of the flags and the special variants stop the game in Update, +// Interpolate and ApplyTearFlagEffects until reconstructed. struct Entity_Tear : Entity { ANM2 deadEyeANM2; @@ -197,6 +252,7 @@ struct Entity_Tear : Entity bool isCanTriggerStreakEnd = false; bool isFireSoundMuted = false; bool isFireSoundPending = false; + bool isGridTouched = false; bool isHovering = false; bool isMultidimensionalTouched = false; bool isPrismTouched = false; @@ -210,8 +266,9 @@ struct Entity_Tear : Entity bool HandleCollision(Entity* collider, bool isLow) override; Entity_Player* GetRootPlayer(); - void apply_wiggle(float strength); - void update_wiggle(); + void wiggle_apply(float strength); + void spiral_apply(float strength); + void big_spiral_apply(float strength); void play_fire_sound(); float get_height_offset_y(float tearHeight); void SetHeight(float tearHeight); @@ -236,9 +293,25 @@ private: float animation_update(); bool hold_update(); void wait_update(); + void death_creep_spawn(); void death_update(); + void quadsplit_fire(); void blood_stains_spawn(); void flight_update(); + void square_turn(); + void homing_update(); + float size_flags_update(); + void spectral_update(); + void boomerang_pull(); + void rotation_update(Entity_Player* player); void floor_hit(); void grid_hit(); + void bounce_hit(); + void turn_horizontal_update(Vector previous); + void fall_update(); + void split_fire(bool isRising); + void bone_shards_fire(bool isRising); + void child_setup(Entity_Tear& child, TearFlags flags, float alpha); }; + +float worm_multiplier_get(Entity_Player* player, int flag); diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp new file mode 100644 index 0000000..0a41459 --- /dev/null +++ b/src/familiar_ai.cpp @@ -0,0 +1,660 @@ +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "item_pool.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include + +// The items a familiar's drops and charges read. +constexpr int FISH_TAIL_TRIPLED_FACTOR = 4; +constexpr int BLUE_FLY_ACHIEVEMENT_COUNT = 20; +constexpr int ACHIEVEMENT_BLUE_FLIES = 388; +constexpr int COLLECTIBLE_MILK_ID = 436; + +// The hits that do not make Damocles fall: red heart, fake and no-penalty damage. +constexpr uint64_t DAMAGE_FAKE_HITS = 0x10200020; + +// The poof a charger leaves, and how its respawn counts. +constexpr int CHARGER_RESPAWN_FRAMES = 300; +constexpr int CHARGER_RESPAWN_STAGES = 3; +constexpr int BOBS_BRAIN_COOLDOWN = 60; + +// The chargers' dash: speed, how much of the player's motion it takes, how long a stuck one keeps hitting the wall, and +// the sounds. +constexpr float CHARGE_SPEED = 10; +constexpr float BIG_CHUBBY_CHARGE_SPEED = 3; +constexpr float KNIFE_CHARGE_SPEED = 17; +constexpr float CHARGE_INHERIT = 0.6f; +constexpr float BIG_CHUBBY_CHARGE_INHERIT = 0.2f; +constexpr int CHARGE_WALL_HITS = -10; +constexpr int CHARGE_RECOVER_FRAMES = 30; +constexpr float CHARGE_ROOM_MARGIN = -100; +constexpr int SOUND_BIG_CHUBBY_CHARGE = 835; +constexpr int SOUND_LITTLE_CHUBBY_CHARGE = 849; +constexpr int CHARGE_SOUND_DELAY = 450; + +// The blue flies' chase: how far they look (further for Wrath locusts once the room settles), how they home in. +constexpr float BLUE_FLY_RANGE = 200; +constexpr float LOCUST_RANGE = 400; +constexpr int LOCUST_SETTLE_FRAMES = 60; +constexpr int BLUE_FLY_TARGET_INTERVAL = 13; +constexpr float BLUE_FLY_PULL = 0.15f; +constexpr float BLUE_FLY_PULL_MAX = 2; +constexpr float BLUE_FLY_FRICTION = 0.8f; +constexpr float BLUE_FLY_STUN_FRICTION = 0.96f; + +// The birds' chase. +constexpr float BIRD_RANGE = 300; +constexpr int BIRD_TARGET_INTERVAL = 13; +constexpr uint32_t BIRD_TARGET_FLAGS = TARGET_RETARGET | TARGET_PREFER_HEALTHY | TARGET_PREFER_WEAK; +constexpr float BIRD_FRICTION = 0.9f; +constexpr float BIRD_RETURN_DISTANCE = 6400; + +// Demon Baby's shots. +constexpr float AUTO_SHOOTER_RANGE = 150; +constexpr int AUTO_SHOOTER_INTERVAL = 10; +constexpr int AUTO_SHOOTER_HEAD_FRAMES = 12; +constexpr float AUTO_SHOOTER_SPEED = 8; +constexpr float AUTO_SHOOTER_FALL = 1.2f; +constexpr float AUTO_SHOOTER_DAMAGE = 3; +constexpr int LINE_GRID_PATH_LIMIT = 900; + +// The target search's scoring. +constexpr int ENTITY_BLOOD_PUPPY_ENEMY = 802; +constexpr float TARGET_STICKINESS = 400; +constexpr float TARGET_CLOSENESS = 800; +constexpr float TARGET_PLAYER_CLOSENESS = 400; +constexpr float TARGET_PLAYER_WEIGHT = 3; +constexpr float TARGET_WEAKNESS = 400; +constexpr float TARGET_HEALTH_CAP = 1000; +constexpr float TARGET_CONE_WEIGHT = 2000; + +// The sacks' drops: a pickup and its chance per clear (higher with BFFS!), and the spawn's shift. +struct SackDrop +{ + int variant = 0; + int pickupVariant = 0; + int pickupSubtype = 0; + float chance = 0; + float bffsChance = 0; +}; +constexpr SackDrop SACK_DROPS[] = {{20, PICKUP_BOMB, 0, 0.35f, 0.42f}, {21, PICKUP_COIN, 0, 0.5f, 0.57f}, + {22, PICKUP_HEART, 2, 0.35f, 0.42f}, {23, PICKUP_HEART, 3, 0.125f, 0.166f}, + {91, PICKUP_TAROTCARD, 0, 0.125f, 0.166f}, {112, PICKUP_PILL, 0, 0.125f, 0.166f}, + {114, PICKUP_GRAB_BAG, 0, 0.125f, 0.166f}}; +constexpr int LIL_CHEST_DROPS[] = {PICKUP_HEART, PICKUP_COIN, PICKUP_KEY, PICKUP_BOMB, + PICKUP_LIL_BATTERY, PICKUP_TAROTCARD, PICKUP_PILL}; +constexpr int MYSTERY_SACK_DROPS[][2] = {{PICKUP_HEART, 6}, {PICKUP_COIN, 4}, {PICKUP_KEY, 3}, {PICKUP_BOMB, 2}}; +constexpr int SACK_DROP_SHIFT_2 = 17; +constexpr int SACK_DROP_SHIFT_3 = 13; +constexpr int SOUND_LITTLE_CHAD = 219; +constexpr int ROOM_CLEAR_CYCLE = 1024; + +// 00615030 Picks what to chase: the best scored enemy in reach (closer, near the player, weaker or healthier as asked, +// inside a cone if one is given, the current one preferred), checked every few frames. A pacifist room drops the +// target, an enemy given up on (a versus match's long chase) is skipped, and a charmed familiar turns on the player. +void Entity_Familiar::PickEnemyTarget(const TargetSearch& search) +{ + if (g_game->room->isPacifist) + { + target = nullptr; + return; + } + if (familiar_versus()) reconstruction_missing("Entity_Familiar::PickEnemyTarget 00615030 (a versus match)"); + + bool hasCone = !vector_is_zero(search.coneDirection); + Vector coneDirection = vector_normalized(search.coneDirection); + float coneCos = hasCone ? std::cos(search.coneAngle * PI_F / 360) : 0; + bool isRetarget = search.flags & TARGET_RETARGET; + bool isNearPlayer = !(search.flags & TARGET_NOT_NEAR_PLAYER); + auto isGivenUp = [this](Entity& entity) { + auto found = targetFrames.find(entity.index); + return found != targetFrames.end() && found->second < 0; + }; + if (target && isGivenUp(*target)) target = nullptr; + if (HasEntityFlags(FLAG_CHARM)) reconstruction_missing("Entity_Familiar::PickEnemyTarget 00615030 (a charmed one)"); + + Entity* previous = target; + Entity* kept = nullptr; + bool isChecked = search.frameInterval < 2; + if (previous) + { + if (!previous->IsVulnerableEnemy(nullptr) || previous->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET) || + (isRetarget && (search.frameInterval < 2 || IsFrame(search.frameInterval, (int)index)))) + target = nullptr; + else + { + kept = previous; + isChecked = !isRetarget && search.frameInterval < 2; + } + } + if (!isChecked && !IsFrame(search.frameInterval, (int)index)) return; + if (kept) return; + + Entity* best = nullptr; + float bestScore = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (isGivenUp(*entity) || !Entity::is_enemy_type(entity->type)) continue; + + float distance = vector_length(vector_sub(entity->pos, pos)); + float playerDistance = vector_length(vector_sub(entity->pos, player->pos)); + bool isOut = entity->entityCollisionClass == ENTCOLL_NONE || + entity->entityCollisionClass == ENTCOLL_PLAYERONLY || entity->isInvincible || entity->isDead || + entity->IsDescendantOf(spawnerEntity) || entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET) || + entity->type == ENTITY_BLOOD_PUPPY_ENEMY || + (search.range < distance && (!isNearPlayer || search.range <= playerDistance)); + if (isOut) continue; + + float score = 0; + if (hasCone) + { + float alignment = vector_dot(coneDirection, vector_normalized(vector_sub(entity->pos, pos))); + if (alignment < coneCos) continue; + score = alignment * TARGET_CONE_WEIGHT; + } + if (!(search.flags & TARGET_NO_STICKINESS) && entity == previous) score += TARGET_STICKINESS; + score += std::max(TARGET_CLOSENESS - distance, 0.0f); + if (isNearPlayer) score += std::max(TARGET_PLAYER_CLOSENESS - playerDistance, 0.0f) * TARGET_PLAYER_WEIGHT; + if (search.flags & TARGET_PREFER_WEAK) score += std::max(TARGET_WEAKNESS - entity->health, 0.0f); + if (search.flags & TARGET_PREFER_HEALTHY) score += std::min(entity->health, TARGET_HEALTH_CAP); + if (bestScore < score) + { + best = entity; + bestScore = score; + } + } + target = best; +} + +// 00619270 Demon Baby: follows, and every few frames shoots at the last enemy it sees in a clear line nearby. +void Entity_Familiar::ai_auto_shooter() +{ + FollowParent(); + if (IsFrame(familiar_lullaby_delay(*this, AUTO_SHOOTER_INTERVAL), 0)) + { + Entity* aimed = nullptr; + for (Entity* enemy : entity_query_radius(pos, AUTO_SHOOTER_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + if (spawnerEntity && spawnerEntity->IsDescendantOf(enemy)) continue; + if (enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + if (room_check_line(pos, enemy->pos, LINE_MODE_PROJECTILE, LINE_GRID_PATH_LIMIT)) aimed = enemy; + } + if (aimed) + { + Vector toward = vector_sub(aimed->pos, pos); + int direction = DIRECTION_LEFT; + if (std::fabs(toward.x) <= std::fabs(toward.y)) direction = toward.y > 0 ? DIRECTION_DOWN : DIRECTION_UP; + else if (toward.x > 0) direction = DIRECTION_RIGHT; + headFrameDelay = AUTO_SHOOTER_HEAD_FRAMES; + PlayShootAnim(direction); + + uint32_t seed = Random(); + auto* tear = static_cast( + g_game->Spawn({.position = pos, + .velocity = vector_scale(vector_normalized(toward), AUTO_SHOOTER_SPEED), + .spawner = this, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = seed})); + tear->fallingSpeed = AUTO_SHOOTER_FALL; + float damage = GetMultiplier() * AUTO_SHOOTER_DAMAGE; + float scale = std::max(GetMultiplier() * 0.35f + 0.55f, 0.01f); + tear->SetCollisionDamage(damage); + tear->baseScale = scale; + tear->fScale = scale; + tear->ResetSpriteScale(); + TryFireTear(tear); + shot_owner_convert(tear); + } + mongo_baby_pick_next_mimic(); + } + if (headFrameDelay > 0) + { + headFrameDelay--; + return; + } + if (variant != BUMBO) play_idle_anim(); +} + +// 0061b8c0 Dead Bird and its kin: flies after enemies, back to the player when it strays with none, flapping. Bird Cage +// and Lil Haunt hunt their own ways, which stops the game. +void Entity_Familiar::ai_flying_bird() +{ + if (variant == BIRD_CAGE || variant == LIL_HAUNT) + return reconstruction_missing("Entity_Familiar::ai_flying_bird 0061b8c0 (Bird Cage and Lil Haunt)"); + + PickEnemyTarget({.range = BIRD_RANGE, .frameInterval = BIRD_TARGET_INTERVAL, .flags = BIRD_TARGET_FLAGS}); + if (target) velocity = vector_add(velocity, vector_normalized(vector_sub(target->pos, pos))); + else + { + Vector home = vector_sub(player->pos, pos); + if (vector_length_squared(home) > BIRD_RETURN_DISTANCE) + velocity = vector_add(velocity, vector_normalized(home)); + } + + if (variant == DEAD_BIRD) sprite.Play("Flying"); + else if (variant == EVES_BIRD_FOOT) sprite.Play("FlyingTransparent"); + else if (variant == BEST_BUD) sprite.Play("Idle"); + sprite.isFlipX = velocity.x > 0; + velocity = vector_scale(velocity, BIRD_FRICTION); +} + +// 00615d80 A blue fly: stunned a moment after it spawns, then circles its parent (or player) until an enemy comes near, +// and homes in on it. Wrath's locust waits for the room to settle and looks further. +void Entity_Familiar::ai_blue_fly() +{ + if (state > 0) + { + state--; + entityCollisionClass = ENTCOLL_NONE; + friction *= BLUE_FLY_STUN_FRICTION; + if (state == 0) entityCollisionClass = ENTCOLL_ALL; + return; + } + + float range = subtype == 1 ? LOCUST_RANGE : BLUE_FLY_RANGE; + if (subtype == 1 && g_game->room->GetFrameCount() < LOCUST_SETTLE_FRAMES) + { + target = nullptr; + entityCollisionClass = ENTCOLL_NONE; + } + else + { + if (Random() % 3 == 0 || subtype == 1) + PickEnemyTarget({.range = range, .frameInterval = BLUE_FLY_TARGET_INTERVAL}); + entityCollisionClass = ENTCOLL_ALL; + } + + if (parent && (parent->isDead || parent->entityCollisionClass == ENTCOLL_NONE)) + { + parent = nullptr; + RemoveFromOrbit(); + } + if (!target) + { + if (orbitLayer == -1) + { + orbitLayer = 1; + orbitDistance = GetOrbitDistance(1); + RecalculateOrbitOffset(1, ORBIT_JOIN); + } + targetPosition = GetOrbitPosition(get_orbit_parent()->pos); + } + else + { + targetPosition = target->pos; + RemoveFromOrbit(); + } + + Vector toward = vector_sub(targetPosition, pos); + float distance = vector_length(toward); + float pull = distance < 0.1f ? 0 : std::min(distance * BLUE_FLY_PULL, BLUE_FLY_PULL_MAX) / distance; + velocity = vector_add(velocity, vector_scale(toward, pull)); + friction *= BLUE_FLY_FRICTION; +} + +// 007599d0 Entity_Player::AddBlueFlies: spawns blue flies beside the player (more with Fish Tail: double, sometimes +// triple when doubled, sometimes four times when tripled), chasing a target if one is given and alive. The twentieth +// unlocks its achievement. +Entity* Entity_Player::AddBlueFlies(int amount, Vector spawnPos, Entity* chased) +{ + int fishTail = GetTrinketMultiplier(TRINKET_FISH_TAIL); + if (fishTail > 0) + { + int factor = 2; + if (fishTail == 2 && Random() % 5 == 0) factor = 3; + if (fishTail == 3 && Random() % 5 == 0) factor = FISH_TAIL_TRIPLED_FACTOR; + amount *= factor; + } + + numBlueFlies += amount; + Entity* fly = nullptr; + for (; amount > 0; amount--) + { + fly = g_game->Spawn({.position = spawnPos, + .spawner = this, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::BLUE_FLY, + .seed = Random()}); + if (chased && !chased->isDead) fly->target = chased; + fly->flags &= ~FLAG_APPEAR; + } + if (numBlueFlies >= BLUE_FLY_ACHIEVEMENT_COUNT) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_BLUE_FLIES); + return fly; +} + +// A charger dashing: its look, and how it stops on a wall or out of the room, breaking what it hits (part of 006174c0). +void Entity_Familiar::charger_dash() +{ + if (variant == JAW_BONE || variant == LIL_PORTAL || variant == KNIFE_FULL) + return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger's dash)"); + + bool isShowingDash = variant == LITTLE_CHUBBY || variant == BIG_CHUBBY; + if (std::fabs(velocity.y) < std::fabs(velocity.x)) + { + if (isShowingDash) sprite.Play("FloatShootSide"); + sprite.isFlipX = velocity.x < 0; + } + else if (isShowingDash) sprite.Play(velocity.y >= 0 ? "FloatShootDown" : "FloatShootUp"); + + Room& room = *g_game->room; + if (isCollidesWithGrid || fireCooldown < -1 || !room.IsPositionInRoom(pos, CHARGE_ROOM_MARGIN)) + { + entityGridCollisionClass = GRIDCOLL_NONE; + if (GridEntity* grid = room.GetGridEntity((uint32_t)room.GetGridIndex(pos))) grid->Hurt(1, EntityRef(player)); + velocity = vector_scale(velocity, 0.5f); + if (--fireCooldown < CHARGE_WALL_HITS) fireCooldown = CHARGE_RECOVER_FRAMES; + } + entityCollisionClass = variant == BIG_CHUBBY ? ENTCOLL_ALL : ENTCOLL_ENEMIES; +} + +// A charger setting off the way the player shoots, with some of the player's motion (part of 006174c0). +void Entity_Familiar::charger_start(const Vector& aimDirection, int direction) +{ + float speed = variant == BIG_CHUBBY ? BIG_CHUBBY_CHARGE_SPEED + : variant == KNIFE_FULL ? KNIFE_CHARGE_SPEED + : CHARGE_SPEED; + fireCooldown = -1; + entityGridCollisionClass = variant == JAW_BONE || variant == KNIFE_FULL ? GRIDCOLL_WALLS : GRIDCOLL_BULLET; + + Vector inherited = player->velocity; + if (direction == DIRECTION_LEFT || direction == DIRECTION_RIGHT) inherited.x = 0; + else inherited.y = 0; + float share = variant == BIG_CHUBBY ? BIG_CHUBBY_CHARGE_INHERIT : CHARGE_INHERIT; + velocity = vector_add(vector_scale(aimDirection, speed), vector_scale(inherited, share * 2)); + if (vector_length_squared(velocity) < speed * speed) velocity = vector_scale(vector_normalized(velocity), speed); + friction = 1; + if (variant == JAW_BONE) target = nullptr; + if (variant == BIG_CHUBBY) familiar_sound_play(SOUND_BIG_CHUBBY_CHARGE, {.frameDelay = CHARGE_SOUND_DELAY}); + if (variant == LITTLE_CHUBBY) familiar_sound_play(SOUND_LITTLE_CHUBBY_CHARGE, {.frameDelay = CHARGE_SOUND_DELAY}); +} + +// 006174c0 The chargers (Little Chubby, Bob's Brain and their kin): follow, and dash the way the player shoots once +// recharged, Bob's Brain only while no other brain is out. A spent one (subtype set) hides and comes back after a +// while. Tainted Lilith's Incubus and the special chargers stop the game. +void Entity_Familiar::ai_charger() +{ + if (IsLilithBirthrightIncubus()) return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (Incubus)"); + + if (subtype != 0) + { + entityCollisionClass = ENTCOLL_NONE; + if (variant == HOLY_WATER && sprite.animState.animData && sprite.animState.isPlaying) friction *= 0.3f; + else + { + isVisible = false; + FollowParent(); + } + if (subtype > CHARGER_RESPAWN_STAGES) + { + subtype = 0; + fireCooldown = variant == BOBS_BRAIN ? BOBS_BRAIN_COOLDOWN : 0; + sprite.Play("Appear"); + return; + } + if (variant != LIL_PORTAL && state++ > CHARGER_RESPAWN_FRAMES) + { + if (subtype == 1) + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + subtype++; + } + return; + } + + isVisible = true; + state = 0; + int direction = player->fireDirection; + Vector aim = direction_unit(direction); + TryAimAtMarkedTarget(aim, direction, nullptr); + if (fireCooldown < 0) return charger_dash(); + + FollowParent(); + if (variant == JAW_BONE || variant == LIL_PORTAL || variant == KNIFE_PIECE_1 || variant == KNIFE_PIECE_2 || + variant == KNIFE_FULL) + return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger)"); + if (!sprite.IsPlaying("Float")) sprite.Play("Float"); + if (fireCooldown > 0) fireCooldown--; + + if (direction != DIRECTION_NONE) + { + sprite.isFlipX = direction == DIRECTION_LEFT; + bool isFree = true; + if (variant == BOBS_BRAIN) + for (Entity_Familiar* brain : familiar_query(BOBS_BRAIN)) + if (brain->isExists && brain->fireCooldown < 0 && brain->subtype == 0) + { + isFree = false; + break; + } + if (fireCooldown < 1 && isFree) charger_start(aim, direction); + } + entityCollisionClass = ENTCOLL_NONE; +} + +// The pickup a sack drops on a clear, or none (part of 0062aab0). Lil Chest and Mystery Sack roll theirs, Bumbo counts +// its clears. Juicy Sack and Spider Mod's spiders wait for their takeover. +static SackDrop sack_drop_roll(Entity_Familiar& familiar, bool hasBffs) +{ + for (const SackDrop& drop : SACK_DROPS) + if (drop.variant == familiar.variant) + return {.pickupVariant = drop.pickupVariant, + .pickupSubtype = drop.pickupSubtype, + .chance = hasBffs ? drop.bffsChance : drop.chance}; + + RNG& rng = familiar.dropRNG; + bool isBethanyB = familiar.player->playerType == PLAYER_BETHANY_B; + switch (familiar.variant) + { + case Entity_Familiar::JUICY_SACK: + case Entity_Familiar::SPIDER_MOD: + reconstruction_missing("Entity_Familiar::TriggerRoomClear 0062aab0 (blue spiders)"); + case Entity_Familiar::MYSTERY_SACK: + { + float chance = hasBffs ? 0.22f : 0.18f; + auto [variant, kinds] = MYSTERY_SACK_DROPS[rng.RandomInt(4)]; + return {.pickupVariant = variant, .pickupSubtype = (int)rng.RandomInt(kinds) + 1, .chance = chance}; + } + case Entity_Familiar::LIL_CHEST: + { + float roll = rng.RandomFloat() * (hasBffs ? 0.8f : 1.0f); + if (isBethanyB) roll *= 0.75f; + if (roll < 0.1f) return {.pickupVariant = PICKUP_TRINKET, .chance = 1}; + if (roll >= 0.35f) return {}; + return {.pickupVariant = LIL_CHEST_DROPS[rng.RandomInt(7)], .chance = 1}; + } + case Entity_Familiar::BUMBO: + { + if (familiar.state != 1) return {}; + int roll = (int)rng.RandomInt(hasBffs ? 80 : 100); + if (isBethanyB) roll = roll * 4 / 3; + if (roll < 33) familiar.counter++; + return {}; + } + default: return {}; + } +} + +// 0062aab0 A cleared room's reward from a familiar: the sacks drop their pickup every so many clears (the chance spread +// evenly over the clears, lowered for Tainted Bethany), the Paschal Candle burns brighter, GB Bug wakes. +void Entity_Familiar::TriggerRoomClear() +{ + if (!isExists || !player || !player->isExists) return; + + roomClearCount++; + SackDrop drop = sack_drop_roll(*this, player->HasCollectible(COLLECTIBLE_BFFS)); + float chance = drop.chance; + if (player->playerType == PLAYER_BETHANY_B) chance *= 0.75f; + int clears = roomClearCount % ROOM_CLEAR_CYCLE; + bool isDue = chance >= 1 || (int)((float)(clears + 1) * chance) > (int)((float)clears * chance); + if (drop.pickupVariant != 0 && chance > 0 && isDue && + (drop.pickupVariant != PICKUP_HEART || !player->HasTrinket(TRINKET_DAEMONS_TAIL) || Random() % 5 == 0)) + { + if (variant == RUNE_BAG) drop.pickupSubtype = ItemPool::GetCardEx((int)dropRNG.Next(), 0, -1, 0, true); + Vector spot = room_free_pickup_position_find({.position = pos}); + RNG spawnRng = {dropRNG.Next(), 5, SACK_DROP_SHIFT_2, SACK_DROP_SHIFT_3}; + g_game->Spawn({.position = spot, + .spawner = this, + .subType = drop.pickupSubtype, + .type = ENTITY_PICKUP, + .variant = drop.pickupVariant, + .seed = spawnRng.Next()}); + sprite.Play("Spawn", PLAY_FORCED); + if (variant == LITTLE_CHAD) familiar_sound_play(SOUND_LITTLE_CHAD); + } + + if (variant == GB_BUG && subtype != 0) state = 1; + if (variant == PASCHAL_CANDLE || variant == WISP) + reconstruction_missing("Entity_Familiar::TriggerRoomClear 0062aab0 " + "(Paschal Candle and the wisps)"); +} + +// 0062b750 Its player was hurt: Smart Fly turns aggressive, the Mystery Egg cracks, Damocles falls on a real hit. +// Hallowed Ground's hop, Intruder's revenge and the Paschal Candle's dimming stop the game. +void Entity_Familiar::trigger_player_damage(const DamageEvent& hit) +{ + if (variant == HALLOWED_GROUND || variant == INTRUDER || variant == PASCHAL_CANDLE) + reconstruction_missing("Entity_Familiar::trigger_player_damage 0062b750 " + "(this familiar's reaction)"); + + if (variant == SMART_FLY) subtype = 1; + else if (variant == MYSTERY_EGG && state == 0) + { + sprite.Play("Crack"); + state = 1; + } + else if (variant == DAMOCLES && hit.damage > 0 && !(hit.damageFlags & DAMAGE_FAKE_HITS)) subtype = 1; +} + +// 0062b360 A new floor: Milk refills, Guppy's Hairball shrinks, the bums forget their pickups, and the familiar joins +// its player at the start. +void Entity_Familiar::level_start() +{ + if (variant == MILK) + { + subtype = 0; + isVisible = true; + shadowSize = config->shadowSize; + sprite.Play("Idle"); + if (ItemConfig_Item* milk = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MILK_ID)) + player->temporaryEffects.RemoveEffect(milk, 1); + } + if (variant == GUPPYS_HAIRBALL) subtype >>= 1; + else if (variant == BUDDY_IN_A_BOX || variant == BUM_FRIEND) subtype = 0; + else if (variant == UMBILICAL_BABY) Remove(); + else if ((variant == LOST_SOUL && !g_game->isStartingFromState) || variant == BLOOD_OATH || + variant == PASCHAL_CANDLE || variant == WISP || variant == STAR_OF_BETHLEHEM) + reconstruction_missing("Entity_Familiar::level_start 0062b360 (this familiar's new floor)"); + + pos = GetFollowTargetPosition(FOLLOW_EXACT); + if (variant == BLOOD_PUPPY) reconstruction_missing("Entity_Familiar::level_start 0062b360 (Blood Puppy)"); + if (variant == VANISHING_TWIN) state = 0; +} + +// 0062bb70 A new room: the chargers recharge, the walkers and rooted familiars stop, the delayed ones forget the path, +// a few reset their state, and the spawned-for-a-room familiars go (unless the Glowing Hourglass rewound). +void Entity_Familiar::room_enter() +{ + switch (variant) + { + case LITTLE_CHUBBY: + case HOLY_WATER: + case GB_BUG: + case BIG_CHUBBY: + case JAW_BONE: + case KNIFE_FULL: + case LIL_PORTAL: fireCooldown = 15; break; + case BOBS_BRAIN: fireCooldown = BOBS_BRAIN_COOLDOWN; break; + case PEEPER: + case CUBE_OF_MEAT_3: + case CUBE_OF_MEAT_4: + case BALL_OF_BANDAGES_3: + case BALL_OF_BANDAGES_4: + case SUCCUBUS: + case PEEPER_2: velocity = {}; break; + case SMART_FLY: + case BBF: + subtype = 0; + fireCooldown = 0; + velocity = {}; + break; + case DRY_BABY: + case FARTING_BABY: + case ABYSS_LOCUST: fireCooldown = 0; break; + case BLUE_SPIDER: + case LIL_HARBINGERS: + case FORGOTTEN_BODY: targetPosition = {}; break; + case SWORN_PROTECTOR: coins = 0; break; + case CHARGED_BABY: + if (!g_game->isStartingFromState) coins = 0; + break; + case LOST_FLY: + targetPosition = {}; + moveDirection = DIRECTION_DOWN; + break; + case OBSESSED_FAN: + case PAPA_FLY: + case MULTIDIMENSIONAL_BABY: + case SHADE: + case MY_SHADOW: + moveDelayNum = -1; + velocity = {}; + break; + case YO_LISTEN: + targetPosition = {}; + state = 0; + break; + case LIL_DUMPY: state = 0; break; + case MYSTERY_EGG: + state = 0; + if (!isVisible) roomClearCount = 0; + isVisible = true; + sprite.Play("Idle"); + break; + case HALLOWED_GROUND: + state = 0; + targetPosition = {}; + isVisible = true; + sprite.Play("FloatDown"); + break; + case BABY_PLUM: Remove(); break; + case FRUITY_PLUM: + pos = player->pos; + velocity = {}; + sprite.Play("Fly"); + state = 3; + break; + case BLOOD_BABY: damageCountdown = 20; break; + case CUBE_BABY: + { + pos = player->pos; + Vector entry = g_game->enterDoor < 0 ? random_direction() : direction_unit((g_game->enterDoor + 2) % 4); + pos = vector_add(pos, vector_scale(entry, 15)); + velocity = {}; + break; + } + case SISSY_LONGLEGS: + case PUNCHING_BAG: + case SPIDER_MOD: + case SPIDER_BABY: + case WISP: + case ITEM_WISP: + case STAR_OF_BETHLEHEM: + case LOST_SOUL: + case UMBILICAL_BABY: + case BLOOD_PUPPY: + case VANISHING_TWIN: reconstruction_missing("Entity_Familiar::room_enter 0062bb70 (this familiar's new room)"); + } + + if (isNotCountedAsFollower && !g_game->isStartingFromState && !isHourglassRewound) Remove(); + isHourglassRewound = false; +} diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp new file mode 100644 index 0000000..f06ff24 --- /dev/null +++ b/src/familiar_collision.cpp @@ -0,0 +1,332 @@ +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_list.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "game.h" +#include "log.h" +#include "lua_engine.h" +#include "npc_ai.h" +#include "room.h" + +// The enemies a contact familiar swats outright: the flies (a Pooter only of its first kinds). +constexpr int SWATTED_TYPES[] = {13, 18, 80, 222, 256, 296, 281, 868}; +constexpr int POOTER_SUPER = 2; + +// The familiars that swat flies and otherwise hurt by touch. +constexpr int CONTACT_VARIANTS[] = {33, 60, 15, 14, 79, 77, 3, 104, 44, 45, 46, 47, + 32, 83, 121, 126, 226, 224, 210, 218, 206, 237, 229, 204}; + +// The familiars whose touch, block or hit has an effect of its own not reconstructed yet. +constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 94, 113, 243, 200, 239, 105, 127, 206, 66, 131, 204, 231, + 237, 25, 93, 42, 63, 117, 130, 106, 121, 128, 234, 232, 223}; +constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {51, 95, 83, 121, 128, 229, 234, 228, 238, 201, 216, 217, 231}; +constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201, 216, 217, 206, 237}; +constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 216, 217, 206, 237, 229, 234, 201, 238}; + +// The breakables a dashing charger bumps into, and what each bump deals. +constexpr int CHARGER_BREAKABLE_TYPES[] = {ENTITY_FIREPLACE, ENTITY_MOVABLE_TNT, ENTITY_POOP}; +constexpr float CHARGER_BUMP_DAMAGE = 3.5f; +constexpr int CHARGER_BUMP_LIMIT = -10; +constexpr int CHARGER_BUMP_RECOVER = 30; + +// Spin to Win's orbit hit, and the damage RC Remote and Friendship Necklace lend the harmless familiars. +constexpr float SPIN_HIT_PUSH = 5; +constexpr float SPIN_HIT_SCALE = 1.5f; +constexpr float SPIN_HIT_BASE = 6; +constexpr int PLAYERFORM_LORD_OF_THE_FLIES_ID = 1; +constexpr int PLAYERFORM_SPIDERBABY_ID = 12; + +// The blue flies' and spiders' pop, and the locusts' tear effects. +constexpr int SOUND_INSECT_POP = 1015; +constexpr int SOUND_POP_DELAY = 15; +constexpr float WRATH_EXPLOSION_DAMAGE = 60; +constexpr float WRATH_EXPLOSION_SCALE = 0.6f; +constexpr int PESTILENCE_POISON_FRAMES = 40; +constexpr int FAMINE_SLOW_FRAMES = 300; +constexpr float FAMINE_SLOWING = 0.9f; +constexpr ColorMod FAMINE_SLOW_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.15686275f, 0.15686275f, 0.15686275f}}; + +// Bob's Brain and BBF's explosion. +constexpr float BRAIN_EXPLOSION_DAMAGE = 100; +constexpr float BRAIN_EXPLOSION_BONUS = 50; +constexpr float BRAIN_EXPLOSION_BONUS_THRESHOLD = 1.5f; +constexpr int BRAIN_ROOM_SETTLE_FRAMES = 20; +constexpr float BRAIN_POISON_FRAMES = 80; +constexpr int BBF_RESPAWN_FRAMES = 300; + +// The blood a dying familiar spills. +constexpr float DEATH_BLOOD_HEIGHT = -10; + +// What a familiar's hit takes: the shielding damage of spikes and poop, and the count each hit adds. +constexpr uint64_t DAMAGE_ISAACS_HEART = 1ull << 11; +constexpr float PUNCHING_BAG_KNOCKBACK = 5; +constexpr float DIP_HURT_VOLUME = 0.8f; +constexpr int DIP_HURT_DELAY = 15; + +// The familiars that never yield to what they touch, unless it is a player or a bomb. +constexpr int SOLID_VARIANTS[] = {62, 67, 228, 238}; +constexpr int LIL_DUMPY_FLOATING = 1; + +// The tear flags of a blue fly's locust (Wrath, Pestilence, Famine and Death). +enum LocustKind +{ + LOCUST_NONE, + LOCUST_WRATH, + LOCUST_PESTILENCE, + LOCUST_FAMINE, + LOCUST_DEATH +}; + +// 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); +} + +// A blue fly popping on what it hit: a puff, then its locust's effect (an explosion, poison, slowing or death). +static void blue_fly_pop(Entity_Familiar& fly, Entity& collider, float damageMultiplier) +{ + g_game->Spawn({.position = fly.pos, .type = ENTITY_EFFECT, .variant = EFFECT_FLY_EXPLOSION, .seed = Random()}); + fly.Remove(); + switch (fly.subtype) + { + case LOCUST_WRATH: + explosion_effects({.tearFlags = fly.player->GetBombFlags(false), + .color = fly.sprite.color, + .position = fly.pos, + .source = &fly, + .damage = (damageMultiplier - 1) * 25 + WRATH_EXPLOSION_DAMAGE, + .radiusMultiplier = WRATH_EXPLOSION_SCALE}); + break; + case LOCUST_PESTILENCE: collider.AddPoison(EntityRef(&fly), PESTILENCE_POISON_FRAMES, 0, false); break; + case LOCUST_FAMINE: + collider.AddSlowing(EntityRef(&fly), FAMINE_SLOW_FRAMES, FAMINE_SLOWING, FAMINE_SLOW_COLOR, false); + break; + case LOCUST_DEATH: collider.Kill(EntityRef(&fly)); break; + } + familiar_sound_play(SOUND_INSECT_POP, {.frameDelay = SOUND_POP_DELAY}); +} + +// Bob's Brain and BBF going off on an enemy once the room has settled: the player's bomb effects in a big blast, Bob's +// Brain poisoning what it hit. Both then hide to come back later. +static void brain_explode(Entity_Familiar& brain, Entity& collider, float damageMultiplier) +{ + if (brain.subtype != 0 || g_game->room->GetFrameCount() <= BRAIN_ROOM_SETTLE_FRAMES) return; + + Explosion blast = {.color = brain.sprite.color, + .position = brain.pos, + .source = &brain, + .damageFlags = DAMAGE_EXPLOSION | DAMAGE_IGNORE_ARMOR, + .damage = (damageMultiplier - 1) * 25 + BRAIN_EXPLOSION_DAMAGE}; + if (brain.player) + { + blast.tearFlags = brain.player->GetBombFlags(false); + if (brain.player->check_bomb_tearflags(TearFlags{}) >= BRAIN_EXPLOSION_BONUS_THRESHOLD) + blast.damage += BRAIN_EXPLOSION_BONUS; + } + explosion_effects(blast); + brain.subtype = 1; + if (brain.variant == Entity_Familiar::BBF) brain.counter = BBF_RESPAWN_FRAMES; + if (brain.variant == Entity_Familiar::BOBS_BRAIN) + { + collider.AddPoison(EntityRef(&brain), (int)(damageMultiplier * BRAIN_POISON_FRAMES), 0, false); + brain.state = 0; + } +} + +// A familiar's hit on an enemy (part of 006261f0): swats a fly outright when it hurts by touch, else hurts it unless a +// blue fly or spider bounces off an enemy too fast for it, then the blue flies and spiders pop and the brains blow. +bool Entity_Familiar::collision_contact(Entity& collider, float damageMultiplier, float damage) +{ + hit_list_add(hitList, collider); + bool isIgnored = true; + bool isSwatted = false; + if (familiar_listed(CONTACT_VARIANTS, variant)) + { + bool isPooter = collider.type == ENTITY_POOTER && collider.variant != POOTER_SUPER; + isSwatted = isPooter || familiar_listed(SWATTED_TYPES, collider.type); + if (isSwatted) collider.Kill(EntityRef(this)); + } + if (!isSwatted && variant != FLY_ORBITAL) + { + Entity_NPC* npc = dynamic_cast(&collider); + bool isVelocityDamaging = !npc || npc->CanBeDamagedFromVelocity(velocity); + if ((variant != BLUE_FLY && variant != BLUE_SPIDER) || isVelocityDamaging) + collider.TakeDamage(damage * damageMultiplier, 0, EntityRef(this), 0); + } + + if (variant == BLUE_FLY) + { + blue_fly_pop(*this, collider, damageMultiplier); + return true; + } + if (variant == BLUE_SPIDER) + { + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_SPIDER_EXPLOSION, .seed = Random()}); + Remove(); + familiar_sound_play(SOUND_INSECT_POP, {.frameDelay = SOUND_POP_DELAY}); + return true; + } + if (variant == BBF || variant == BOBS_BRAIN) brain_explode(*this, collider, damageMultiplier); + return isIgnored; +} + +// A projectile or tear meeting a familiar (part of 006261f0): one that cannot be stopped passes, a blocking familiar +// stops it. Slipped Rib's reflection and the familiars that react to a block stop the game. +bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) +{ + if (collider.type == ENTITY_PROJECTILE && + (static_cast(collider).projectileFlags & PROJECTILE_CANT_HIT_PLAYER)) + return true; + if (!CanBlockProjectiles()) + { + if (variant != SLIPPED_RIB) return true; + reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (Slipped Rib's reflection)"); + } + if (familiar_listed(UNWRITTEN_BLOCK_VARIANTS, variant)) + reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's block)"); + collider.isDead = true; + return isIgnored; +} + +// 006261f0 What a familiar does on touching an entity, after the mods. Friendly and charmed ones, and all in a pacifist +// room, leave enemies alone. A dashing charger breaks fireplaces and poop, a spinning orbital hits, Skatole and +// Beelzebub keep the flies off the player, a familiar with contact damage hurts enemies (once per hit list) and a +// blocking one stops shots. Returns whether the touch is ignored. A versus match and the familiars with their own touch +// stop the game. +bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) +{ + if (familiar_versus()) reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (a versus match)"); + LuaResult result = lua_engine_get().PreFamiliarCollision(this, collider, isLow); + if (result == LUA_RESULT_TRUE) return true; + if (result == LUA_RESULT_FALSE) return false; + + bool isEnemy = Entity::is_enemy_type(collider->type); + if (isEnemy && (collider->HasEntityFlags(FLAG_FRIENDLY) || HasEntityFlags(FLAG_CHARM) || g_game->room->isPacifist)) + return true; + if (variant == UMBILICAL_BABY) return true; + if (familiar_listed(UNWRITTEN_TOUCH_VARIANTS, variant) || sirenHelper) + reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's touch)"); + + bool isIgnored = true; + float damageMultiplier = GetMultiplier(); + bool isCharger = variant == LITTLE_CHUBBY || variant == BOBS_BRAIN || variant == BIG_CHUBBY; + if (isCharger && subtype == 0 && fireCooldown < 0 && familiar_listed(CHARGER_BREAKABLE_TYPES, collider->type)) + { + collider->TakeDamage(CHARGER_BUMP_DAMAGE, 0, EntityRef(this), 0); + velocity = vector_scale(velocity, 0.5f); + if (--fireCooldown < CHARGER_BUMP_LIMIT) fireCooldown = CHARGER_BUMP_RECOVER; + } + + if (isLow && HasEntityFlags(FLAG_SPIN) && collider->IsVulnerableEnemy(nullptr) && + !EntityList::HitListContains(hitList, *collider)) + { + if (orbitLayer == 0) + { + Vector away = vector_scale(vector_normalized(vector_sub(collider->pos, player->pos)), SPIN_HIT_PUSH); + collider->velocity = vector_add(collider->velocity, away); + player->velocity = vector_sub(player->velocity, away); + } + collider->TakeDamage(collisionDamage * SPIN_HIT_SCALE + SPIN_HIT_BASE, 0, EntityRef(this), 0); + hit_list_add(hitList, *collider); + } + + bool isOwnersFoe = !spawnerEntity || !spawnerEntity->IsDescendantOf(collider); + if (isOwnersFoe && collider->IsActiveEnemy(DEAD_EXCLUDED) && + (collider->IsVulnerableEnemy(nullptr) || collider->CanShutDoors()) && + familiar_listed(UNWRITTEN_ENEMY_TOUCH_VARIANTS, variant)) + reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this " + "familiar's enemy touch)"); + + if (collider->type == ENTITY_PLAYER) + { + Entity_Player& touched = *static_cast(collider); + bool isFlyLord = + touched.HasCollectible(COLLECTIBLE_SKATOLE) || + (touched.variant == PLAYER_VARIANT_PLAYER && touched.HasPlayerForm(PLAYERFORM_LORD_OF_THE_FLIES_ID)); + bool isSpiderLord = touched.variant == PLAYER_VARIANT_PLAYER && touched.HasPlayerForm(PLAYERFORM_SPIDERBABY_ID); + if (isFlyLord && (variant == BLUE_FLY || variant == BLUE_SPIDER || variant == ABYSS_LOCUST)) return true; + if (isSpiderLord && (variant == BLUE_SPIDER || variant == SPIDER_BABY)) return true; + } + + float damage = collisionDamage; + if (damage == 0) + { + int remote = player->GetTrinketMultiplier(TRINKET_RC_REMOTE); + if (remote == 2) damage = 2; + else if (remote > 2) damage = 5; + if (player->GetTrinketMultiplier(TRINKET_FRIENDSHIP_NECKLACE) > 1) damage = 4; + } + if (!isLow) return solid_check(*collider, isIgnored); + + bool isTouching = + collider->IsVulnerableEnemy(nullptr) && (damage > 0 || variant == FLY_ORBITAL) && + !EntityList::HitListContains(hitList, *collider) && + (variant != DADDY_LONGLEGS || entityCollisionClass == ENTCOLL_ENEMIES || entityCollisionClass == ENTCOLL_ALL); + if (isTouching) isIgnored = collision_contact(*collider, damageMultiplier, damage); + if (collider->type == ENTITY_PROJECTILE || collider->type == ENTITY_TEAR) + isIgnored = collision_block(*collider, isIgnored); + return solid_check(*collider, isIgnored); +} + +// The end of 006261f0: Isaac's Heart, the Punching Bag, Minisaac, the Blood Baby and a floating Lil Dumpy push back +// what they touch, unless it is a player or a bomb. +bool Entity_Familiar::solid_check(Entity& collider, bool isIgnored) +{ + bool isSolid = familiar_listed(SOLID_VARIANTS, variant) || (variant == LIL_DUMPY && state == LIL_DUMPY_FLOATING); + if (isSolid && collider.type != ENTITY_PLAYER && collider.type != ENTITY_BOMB) return false; + return isIgnored; +} + +// 0062cdc0 A hit on a familiar: shielded from friends, spikes and poop (Isaac's Heart excepted), Isaac's Heart passing +// it to its player, the Punching Bag knocked back, a Dip squeaking. The wisps, the Lost Soul and Milk stop the game. +bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) +{ + if (IsDamageSourceFriendly(source) || source.IsFriendly()) return false; + if ((damageFlags & (DAMAGE_SPIKES | DAMAGE_POOP)) && variant != ISAACS_HEART) return false; + if (variant == WISP || variant == ITEM_WISP || variant == LOST_SOUL || variant == MILK) + reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0 (this familiar's hit)"); + if (variant == BLOOD_BABY && counter > 0) return false; + + bool isPassed = variant == ISAACS_HEART || (g_game->challenge == CHALLENGE_PONG && variant == PUNCHING_BAG); + bool isDamaged = isPassed ? player->TakeDamage(damage, damageFlags | DAMAGE_ISAACS_HEART, source, damageCountdown) + : Entity::TakeDamage(damage, damageFlags | DAMAGE_COUNTDOWN, source, damageCountdown); + if (!isDamaged || damage <= 0) return isDamaged; + + if (variant == PUNCHING_BAG && friction != 0) + { + Vector away = vector_normalized(vector_sub(pos, source.position)); + velocity = vector_add(velocity, vector_scale(away, PUNCHING_BAG_KNOCKBACK * speedMultiplier / friction)); + } + if (variant == DIP && (Random() & 1) == 0) + familiar_sound_play(SOUND_DIP_HURT, {.volume = DIP_HURT_VOLUME, .frameDelay = DIP_HURT_DELAY}); + return isDamaged; +} + +// 00610540 A familiar's death: blood, then the entity's own kill and its removal. The familiars that die their own way +// (the bone orbitals, the wisps, the swarm flies, the Dips, the clots) stop the game. +void Entity_Familiar::Kill(const EntityRef& source) +{ + if (!isDead) + { + if (familiar_listed(UNWRITTEN_DEATH_VARIANTS, variant)) + reconstruction_missing("Entity_Familiar::Kill 00610540 (this familiar's death)"); + + Entity* blood = g_game->Spawn({.position = pos, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->posOffset = vector_make(0, DEATH_BLOOD_HEIGHT); + blood->SetColor(splatColor, -1, 255, false, true); + blood->Update(); + BloodExplode(); + } + Entity::Kill(source); + Remove(); +} diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp new file mode 100644 index 0000000..b7e156b --- /dev/null +++ b/src/familiar_evaluate.cpp @@ -0,0 +1,286 @@ +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "lua_engine.h" +#include "manager.h" +#include + +// How a collectible's familiars are counted: copies held and in effects, copies held only (at most one), copies in +// effects only, held plus a null effect's copies, or twice the held ones. +enum FamiliarCountKind +{ + COUNT_HELD, + COUNT_OWNED, + COUNT_OWNED_ONE, + COUNT_HELD_PLUS_NULL, + COUNT_HELD_DOUBLE +}; + +// A collectible and the familiar it gives, in the order EvaluateItems checks them. +struct FamiliarSource +{ + int collectible = 0; + int variant = 0; + FamiliarCountKind kind = COUNT_HELD; + int nullItem = 0; +}; +constexpr FamiliarSource FAMILIAR_SOURCES[] = { + {8, 1}, {113, 2}, {88, 3}, {99, 4}, {100, 5}, {95, 6}, {67, 7}, {188, 8}, {163, 9}, {167, 10}, + {174, 11}, {131, 20}, {94, 21}, {96, 22}, {98, 23}, {128, 30}, {57, 31}, {112, 32}, {155, 17}, + {170, 16}, {178, 25}, {11, 41}, {187, 42}, {172, 35}, {264, 50}, {267, 53}, {206, 68}, {265, 51}, + {266, 52}, {268, 54}, {321, 75}, {271, 57}, {270, 56}, {319, 76}, {320, 77}, + {279, 65, COUNT_HELD_PLUS_NULL, 107}, + {269, 55}, {272, 58}, {273, 59}, {280, 66}, {281, 67}, {322, 74}, + {276, 62, COUNT_OWNED_ONE}, + {318, 79}, {277, 63}, {275, 61}, {360, 80}, {361, 81}, {362, 82}, {363, 83}, {364, 84}, {365, 85}, + {372, 86}, {384, 87}, {385, 88}, + {390, 92, COUNT_HELD_PLUS_NULL, 67}, + {387, 89}, {417, 96}, {389, 91}, {405, 93}, {403, 94}, {404, 95}, {435, 97}, {426, 98}, {430, 99}, + {431, 101}, {473, 104}, {469, 105}, {468, 106}, {470, 107}, {471, 108}, {472, 109}, {467, 110}, + {492, 111}, {491, 112}, {500, 114}, {509, 116}, + {508, 117, COUNT_OWNED}, + {511, 118}, {518, 119}, {526, 122}, {528, 123}, {539, 124}, {537, 125}, {542, 126}, {544, 127}, + {543, 129}, {548, 130}, + {433, 131, COUNT_OWNED_ONE}, + {655, 226}, {649, 225}, {575, 200}, {607, 208}, {608, 209}, {645, 216}, {629, 218}, + {569, 203, COUNT_OWNED_ONE}, + {567, 221, COUNT_OWNED_ONE}, + {635, 222, COUNT_OWNED_ONE}, + {581, 204}, + {612, 211, COUNT_OWNED_ONE}, + {615, 212}, {679, 230}, {681, 232}, {682, 233}, {652, 239}, + {698, 235, COUNT_HELD_DOUBLE}, + {651, 236, COUNT_OWNED_ONE}}; +constexpr FamiliarSource LATE_FAMILIAR_SOURCES[] = {{565, 241}, {697, 242}}; + +// The familiars granted another way: items whose effect alone counts, the trinkets, and the counters. +constexpr int TRINKET_APOLLYONS_BEST_FRIEND = 186; +constexpr int NULLITEM_SPIN_TO_WIN_FAMILIAR = 131; +constexpr int FAMILIAR_SPIN_TO_WIN = 244; +constexpr int COLLECTIBLE_LEPROSY = 525; +constexpr int COLLECTIBLE_MILK = 436; +constexpr int COLLECTIBLE_HALO_OF_FLIES = 10; +constexpr int PILLEFFECT_PRETTY_FLY = 10; +constexpr int NULLITEM_HALO_FLY_LOSS = 107; +constexpr int HALO_FLY_CAP = 10; +constexpr int COLLECTIBLE_BEST_BUD = 274; +constexpr int ACHIEVEMENT_CUBE_OF_MEAT_FULL = 144; +constexpr int ACHIEVEMENT_BALL_OF_BANDAGES_FULL = 19; +constexpr int COLLECTIBLE_PINKING_SHEARS = 107; +constexpr int COLLECTIBLE_BROWN_NUGGET = 504; +constexpr int COLLECTIBLE_SPRINKLER = 516; +constexpr int COLLECTIBLE_KEY_BUM = 388; +constexpr int COLLECTIBLE_BUM_FRIEND = 144; +constexpr int COLLECTIBLE_LIL_DELIRIUM = 519; +constexpr int COLLECTIBLE_BIRD_CAGE = 610; +constexpr int COLLECTIBLE_PEEPER_2 = 605; +constexpr int TRINKET_ISAACS_HEAD = 54; +constexpr int TRINKET_SOUL = 57; +constexpr int TRINKET_FOUND_SOUL_ID = 180; +constexpr int SOUL_TRINKET_CAP = 3; +constexpr int PLAYERFORM_SPIDERBABY = 12; +constexpr int FORM_RNG_SHIFT = 35; +constexpr int FAMILIAR_ACHIEVEMENT_COUNT = 4; +constexpr int ACHIEVEMENT_FAMILIARS = 355; +constexpr int CACHE_FAMILIARS_FLAG = 0x200; + +// 00763370 Entity_Player::CheckFamiliar: keeps as many of a familiar as the player should have, removing the extra ones +// (those of the player, or charmed away from it by a Siren) and spawning the missing ones beside it. +void familiar_check(Entity_Player& player, const FamiliarCount& familiars) +{ + int wanted = std::max(familiars.count, 0); + int found = 0; + for (Entity_Familiar* familiar : familiar_query(familiars.variant)) + { + if (familiar->isLilDelirium || familiar->isNotCountedAsFollower || !familiar->isExists) continue; + if (familiars.subtype >= 0 && familiar->subtype != familiars.subtype) continue; + if (familiar->player != &player && familiar->sirenOriginalPlayer != &player) continue; + + if (found < wanted) + { + found++; + familiar->item = familiars.item; + } + else familiar->Remove(); + } + + for (; found < wanted; found++) + { + auto* familiar = static_cast(g_game->Spawn({.position = player.pos, + .spawner = &player, + .subType = std::max(familiars.subtype, 0), + .type = ENTITY_FAMILIAR, + .variant = familiars.variant, + .seed = familiars.rng->Next()})); + familiar->pos = familiar->GetFollowTargetPosition(FOLLOW_SCATTERED); + familiar->item = familiars.item; + familiar->Update(); + } +} + +// Checks a collectible's familiar, counted its way, with the collectible's generator. +static void source_check(Entity_Player& p, const FamiliarSource& source) +{ + int held = p.GetCollectibleNum(source.collectible); + int effects = p.temporaryEffects.GetCollectibleEffectNum(source.collectible); + int count = held + effects; + if (source.kind == COUNT_OWNED) count = held; + if (source.kind == COUNT_OWNED_ONE) count = std::min(held, 1); + if (source.kind == COUNT_HELD_PLUS_NULL) count += p.temporaryEffects.GetNullEffectNum(source.nullItem); + if (source.kind == COUNT_HELD_DOUBLE) count *= 2; + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(source.collectible), + .rng = &p.GetCollectibleRNG(source.collectible), + .count = count, + .variant = source.variant}); +} + +// Checks a familiar granted by a collectible's effect alone. +static void effect_check(Entity_Player& p, int collectible, int variant) +{ + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(collectible), + .rng = &p.GetCollectibleRNG(collectible), + .count = p.temporaryEffects.GetCollectibleEffectNum(collectible), + .variant = variant}); +} + +// Checks a familiar granted by a trinket. +static void trinket_check(Entity_Player& p, int trinket, int variant, int count) +{ + familiar_check(p, {.item = g_manager->itemConfig.GetTrinket(trinket), + .rng = &p.GetTrinketRNG(trinket), + .count = count, + .variant = variant}); +} + +// Cube of Meat and Ball of Bandages: one familiar per stage of four copies (the Potato Peeler's counted too), a full +// one per four, with the unlock for a full one. +static void stages_check(Entity_Player& p, int collectible, int firstVariant, int extra, int achievement) +{ + int total = extra + p.GetCollectibleNum(collectible) + p.temporaryEffects.GetCollectibleEffectNum(collectible); + int stage = total % 4; + int full = total / 4; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectible); + RNG* rng = &p.GetCollectibleRNG(collectible); + for (int i = 1; i <= 3; i++) + familiar_check(p, {.item = item, .rng = rng, .count = stage == i ? 1 : 0, .variant = firstVariant + i - 1}); + familiar_check(p, {.item = item, .rng = rng, .count = full, .variant = firstVariant + 3}); + if (full > 0) g_manager->persistentGameData.TryUnlock(achievement); +} + +// The shared pieces (the key and knife pieces counted across players) and Super Bum's trio wait for their takeover. +static void shared_pieces_check(Entity_Player& p) +{ + for (Entity_Player* other : g_game->playerManager.playerList) + if (other->variant == PLAYER_VARIANT_PLAYER && + (other->GetCollectibleNum(COLLECTIBLE_KEY_PIECE_1) || other->GetCollectibleNum(COLLECTIBLE_KEY_PIECE_2) || + other->GetCollectibleNum(COLLECTIBLE_KNIFE_PIECE_1) || + other->GetCollectibleNum(COLLECTIBLE_KNIFE_PIECE_2))) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (the key and knife pieces)"); + + if (p.HasCollectible(COLLECTIBLE_KEY_BUM) && p.HasCollectible(COLLECTIBLE_DARK_BUM) && + p.HasCollectible(COLLECTIBLE_BUM_FRIEND)) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Super Bum)"); + familiar_check(p, {.rng = &p.GetCollectibleRNG(COLLECTIBLE_BUM_FRIEND), .variant = Entity_Familiar::SUPER_BUM}); + source_check(p, {COLLECTIBLE_KEY_BUM, Entity_Familiar::KEY_BUM}); + source_check(p, {COLLECTIBLE_DARK_BUM, Entity_Familiar::DARK_BUM}); + source_check(p, {COLLECTIBLE_BUM_FRIEND, Entity_Familiar::BUM_FRIEND}); +} + +// Lil Delirium's familiars, Found Soul's and the Strawman's co-op babies wait for their takeovers. +static void unwritten_familiars_check(Entity_Player& p) +{ + int delirium = p.GetCollectibleNum(COLLECTIBLE_LIL_DELIRIUM) + + p.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_LIL_DELIRIUM); + bool isDeliriumShown = std::ranges::any_of(familiar_query(-1), [](Entity_Familiar* f) { return f->isLilDelirium; }); + if (delirium > 0 || isDeliriumShown) reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Lil Delirium)"); + + bool isBabyKept = std::ranges::any_of(g_game->playerManager.playerList, + [&p](Entity_Player* other) { return other->parent == &p && !other->isDead; }); + if (p.HasTrinket(TRINKET_FOUND_SOUL_ID) || p.GetCollectibleNum(COLLECTIBLE_STRAW_MAN) > 0 || isBabyKept) + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Found Soul and the Strawman)"); +} + +// The familiars section of 00763570: every familiar item, effect, trinket and counter checked for its familiars in a +// fixed order, the mods' evaluation, then the unlock for holding five familiars. +void familiars_evaluate(Entity_Player& p) +{ + for (const FamiliarSource& source : FAMILIAR_SOURCES) source_check(p, source); + trinket_check(p, TRINKET_APOLLYONS_BEST_FRIEND, Entity_Familiar::ABYSS_LOCUST, + p.GetTrinketMultiplier(TRINKET_APOLLYONS_BEST_FRIEND)); + for (const FamiliarSource& source : LATE_FAMILIAR_SOURCES) source_check(p, source); + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_ESAU_JR), + .rng = &p.GetCollectibleRNG(COLLECTIBLE_ESAU_JR), + .count = p.temporaryEffects.GetNullEffectNum(NULLITEM_SPIN_TO_WIN_FAMILIAR), + .variant = FAMILIAR_SPIN_TO_WIN}); + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_LEPROSY), + .rng = &p.GetCollectibleRNG(COLLECTIBLE_LEPROSY), + .count = p.numLeprosy, + .variant = Entity_Familiar::LEPROSY}); + source_check(p, {COLLECTIBLE_MILK, Entity_Familiar::MILK, COUNT_OWNED}); + + bool isMistOrGhost = p.hasCurseMistEffect || p.isCoopGhost; + bool isPillCounted = !isMistOrGhost && PILLEFFECT_PRETTY_FLY < (int)p.pillEffectUses.size(); + int prettyFlies = isPillCounted ? p.pillEffectUses[PILLEFFECT_PRETTY_FLY] : 0; + int haloFlies = std::min(prettyFlies + p.GetCollectibleNum(COLLECTIBLE_HALO_OF_FLIES) * 2, HALO_FLY_CAP); + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_HALO_OF_FLIES), + .rng = &p.GetCollectibleRNG(COLLECTIBLE_HALO_OF_FLIES), + .count = haloFlies - p.temporaryEffects.GetNullEffectNum(NULLITEM_HALO_FLY_LOSS) * 2, + .variant = Entity_Familiar::FLY_ORBITAL}); + source_check(p, {COLLECTIBLE_DEAD_CAT, Entity_Familiar::DEAD_CAT, COUNT_OWNED}); + + bool isDeadBird = p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DEAD_BIRD) || + (p.HasCollectible(COLLECTIBLE_DEAD_BIRD) && p.playerType == PLAYER_EVE && + p.HasCollectible(COLLECTIBLE_BIRTHRIGHT)); + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_DEAD_BIRD), + .rng = &p.GetCollectibleRNG(COLLECTIBLE_DEAD_BIRD), + .count = isDeadBird ? 1 : 0, + .variant = Entity_Familiar::DEAD_BIRD}); + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BEST_BUD), + .rng = &p.GetCollectibleRNG(COLLECTIBLE_BEST_BUD), + .count = p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BEST_BUD) ? 1 : 0, + .variant = Entity_Familiar::BEST_BUD}); + stages_check(p, COLLECTIBLE_CUBE_OF_MEAT, Entity_Familiar::CUBE_OF_MEAT_1, p.potatoPeelerCounter, + ACHIEVEMENT_CUBE_OF_MEAT_FULL); + stages_check(p, COLLECTIBLE_BALL_OF_BANDAGES, Entity_Familiar::BALL_OF_BANDAGES_1, p.potatoPeelerBandageCounter, + ACHIEVEMENT_BALL_OF_BANDAGES_FULL); + + RNG formRng{}; + formRng.game_constructor(p.dropRNG._seed, FORM_RNG_SHIFT); + effect_check(p, COLLECTIBLE_PINKING_SHEARS, Entity_Familiar::ISAACS_BODY); + effect_check(p, COLLECTIBLE_SCISSORS, Entity_Familiar::SCISSORS); + effect_check(p, COLLECTIBLE_BROWN_NUGGET, Entity_Familiar::BROWN_NUGGET_POOTER); + effect_check(p, COLLECTIBLE_SPRINKLER, Entity_Familiar::SPRINKLER); + shared_pieces_check(p); + unwritten_familiars_check(p); + + familiar_check(p, {.rng = &formRng, + .count = p.HasPlayerForm(PLAYERFORM_SPIDERBABY) ? 1 : 0, + .variant = Entity_Familiar::SPIDER_BABY}); + trinket_check(p, TRINKET_ISAACS_HEAD, Entity_Familiar::ISAACS_HEAD, p.HasTrinket(TRINKET_ISAACS_HEAD) ? 1 : 0); + trinket_check(p, TRINKET_SOUL, Entity_Familiar::BLUE_BABY_SOUL, + std::min(p.GetTrinketMultiplier(TRINKET_SOUL), SOUL_TRINKET_CAP)); + trinket_check(p, TRINKET_EVES_BIRD_FOOT, Entity_Familiar::EVES_BIRD_FOOT, + p.temporaryEffects.HasTrinketEffect(TRINKET_EVES_BIRD_FOOT) ? 1 : 0); + familiar_check( + p, {.rng = &p.GetTrinketRNG(TRINKET_TONSIL), .count = p.tonsilCount, .variant = Entity_Familiar::TONSIL}); + familiar_check(p, {.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BIRD_CAGE), + .rng = &p.GetCollectibleRNG(COLLECTIBLE_BIRD_CAGE), + .count = p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BIRD_CAGE) ? 1 : 0, + .variant = Entity_Familiar::BIRD_CAGE}); + effect_check(p, COLLECTIBLE_PEEPER_2, Entity_Familiar::PEEPER_2); + source_check(p, {COLLECTIBLE_DAMOCLES_PASSIVE, Entity_Familiar::DAMOCLES, COUNT_OWNED_ONE}); + + lua_engine_get().EvaluateItems(&p, CACHE_FAMILIARS_FLAG); + + int familiarItems = 0; + for (int id = 1; id < COLLECTIBLE_VANILLA_COUNT; id++) + { + if (id >= (int)p.collectibleCounts.size() || p.collectibleCounts[id] == 0) continue; + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id); + if (item && item->type == ITEM_FAMILIAR) + familiarItems += p.GetCollectibleNum(item->id) + p.temporaryEffects.GetCollectibleEffectNum(item->id); + } + if (familiarItems > FAMILIAR_ACHIEVEMENT_COUNT) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_FAMILIARS); +} diff --git a/src/familiar_follow.cpp b/src/familiar_follow.cpp new file mode 100644 index 0000000..b83000f --- /dev/null +++ b/src/familiar_follow.cpp @@ -0,0 +1,526 @@ +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include + +// The items, trinkets, challenge and boss the following line answers to. +constexpr int COLLECTIBLE_BIG_FAN = 279; +constexpr int COLLECTIBLE_GELLO = 728; +constexpr int SIREN_TYPE = 904; + +// How far behind its leader a follower keeps, closer for Milk and on Child's Leash, and how hard it catches up. +constexpr float FOLLOW_DISTANCE = 20; +constexpr float MILK_FOLLOW_DISTANCE = 10; +constexpr float LEASH_FOLLOW_DISTANCE = 5; +constexpr float FOLLOW_PULL = 0.2f; +constexpr float FOLLOW_FRICTION = 0.8f; +constexpr float FOLLOW_POSITION_PULL = 0.1f; + +// The followers' places in the Duct Tape formations: a row, a V and a ring. +enum FormationMode : uint8_t +{ + FORMATION_FREE, + FORMATION_ROW, + FORMATION_V, + FORMATION_RING +}; +constexpr float FORMATION_ROW_STEP = 32; +constexpr float FORMATION_V_DEPTH = 32; +constexpr float FORMATION_V_STEP = 24; +constexpr float FORMATION_RING_RADIUS = 54; +constexpr float FORMATION_LERP = 0.1f; +constexpr float FORMATION_AIM_THRESHOLD = 0.1f; + +// The familiars the Duct Tape formation leaves where they are. +constexpr int FORMATION_EXEMPT_VARIANTS[] = {8, 13, 14, 16, 17, 24, 42, 43, 53, 56, 58, 62, 63, 64, + 66, 67, 73, 75, 85, 87, 88, 90, 94, 96, 106, 110, 111, 118, + 122, 127, 200, 210, 211, 212, 225, 233, 235, 236, 239, 241}; + +// Each orbit layer: its ellipse, its speed (faster with Guardian Angel), and where its first orbital starts. +struct OrbitLayer +{ + float distanceX = 0; + float distanceY = 0; + float speed = 0; + float guardianAngelSpeed = 0; + float angleOffset = 0; +}; +constexpr OrbitLayer ORBIT_LAYER_TABLE[] = { + {25, 20, 0.045f, 2, 1.5f}, {35, 30, 0.045f, 1.5f, 0.5f}, {60, 45, -0.03f, 1.5f, 2}, + {110, 90, 0.02f, 1.5f, 1.2f}, {85, 67.5f, 0.02f, 1.5f, 0.8f}, {35, 30, 0.045f, 1.5f, 0.5f}, + {50, 42, 0.03f, 1.5f, 0}, {28, 21, 0.04f, 1.5f, 0}, {40, 30, -0.03f, 1.5f, 0}, + {64, 50, 0.02f, 1.5f, 0}, {40, 36, 0.02f, 1.5f, 0}}; +constexpr int ORBIT_LAYER_MAX = 10; + +// The orbit speeds of the wide wisps (My Little Unicorn's and Unicorn Stump's), Big Fan's slow orbit and Best Bud. +constexpr int WISP_UNICORN = 77; +constexpr int WISP_UNICORN_STUMP = 298; +constexpr float WIDE_WISP_SPEED = 2; +constexpr float BIG_FAN_SPEED = 1.0f / 3; +constexpr float BEST_BUD_SPEED = 3; +constexpr float TWO_PI = 6.2831855f; + +// The orbitals that turn their sprite with the orbit. +constexpr int SACRIFICIAL_DAGGER_ROTATION_FRAME = 6; + +// The follower priorities, highest leading. +constexpr int PRIORITY_1_VARIANTS[] = {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 25, + 59, 76, 81, 92, 93, 97, 104, 119, 125, 209, 220, 223}; +constexpr int PRIORITY_2_VARIANTS[] = {51, 74, 89, 230}; +constexpr int PRIORITY_KING_BABY = 9999; + +// The chargers, which follow only while not dashing. +constexpr int CHARGER_VARIANTS[] = {3, 59, 25, 93, 104, 232, 223}; + +// Clamps a layer into the table. +static const OrbitLayer& orbit_layer(int layer) +{ + return ORBIT_LAYER_TABLE[std::clamp(layer, 0, ORBIT_LAYER_MAX)]; +} + +// Whether a familiar is one of the wisps whose orbit is twice as fast. +static bool is_wide_wisp(Entity_Familiar& familiar) +{ + return familiar.type == ENTITY_FAMILIAR && familiar.variant == Entity_Familiar::WISP && + (familiar.subtype == WISP_UNICORN || familiar.subtype == WISP_UNICORN_STUMP); +} + +// 00612970 Its rank in the following line: the shooters first, then Mongo Baby and its peers, the Lils, Incubus, Milk +// and King Baby at the very front. Others do not follow. +int Entity_Familiar::GetFollowerPriority() +{ + if (familiar_listed(PRIORITY_1_VARIANTS, variant)) return 1; + if (familiar_listed(PRIORITY_2_VARIANTS, variant)) return 2; + + switch (variant) + { + case LIL_BRIMSTONE: + case LIL_MONSTRO: return 3; + case INCUBUS: + case TWISTED_BABY: return 10; + case MILK: return 9; + case KING_BABY: return PRIORITY_KING_BABY; + case LIL_PORTAL: return 5; + default: return 0; + } +} + +// 00612890 Whether it keeps its place in the line now: not while a charger dashes, Milk is full, a hidden familiar +// waits or the Vanishing Twin hunts. +bool Entity_Familiar::is_following() +{ + if (!isFollower) return false; + if (familiar_listed(CHARGER_VARIANTS, variant)) return fireCooldown == 0; + + switch (variant) + { + case MILK: return subtype != maxSubtype; + case MYSTERY_EGG: + case HALLOWED_GROUND: return isVisible; + case JAW_BONE: return fireCooldown >= 0; + case VANISHING_TWIN: return isVisible && coins == 0; + default: return true; + } +} + +// 00612ad0 Whether it counts in the line (Lilith's Birthright spreads the counted followers). +bool Entity_Familiar::is_counted_follower() +{ + return GetFollowerPriority() > 0 && !isNotCountedAsFollower; +} + +// 00634920 Whether Duct Tape's formation leaves it alone: the familiars that move their own way, and permanent ones. +bool Entity_Familiar::is_formation_exempt() +{ + return familiar_listed(FORMATION_EXEMPT_VARIANTS, variant) || isSubtype55555; +} + +// 00612af0 Whether it is a following Incubus that Tainted Lilith's Birthright hides inside her whip. +bool Entity_Familiar::IsLilithBirthrightIncubus() +{ + if (player->playerType != PLAYER_LILITH_B || !player->HasCollectible(COLLECTIBLE_BIRTHRIGHT)) return false; + + Weapon* held = player->weapons[0] ? player->weapons[0].get() : player->weapons[1].get(); + return held && held->weaponType == WEAPON_UMBILICAL_WHIP && isFollower && !isNotCountedAsFollower; +} + +// 00612b50 The whip Tainted Lilith's hidden Incubus sits in. +Entity* Entity_Familiar::get_incubus_umbilical_whip() +{ + if (!IsLilithBirthrightIncubus()) return nullptr; + reconstruction_missing("Entity_Familiar::get_incubus_umbilical_whip 00612b50"); +} + +// 0062db20 Joins its player's following line by priority: behind the first familiar of higher or equal rank, ahead of +// the first lower one, at the end otherwise. The first follower starts a line of its own. +void Entity_Familiar::AddToFollowers() +{ + if (isSubtype55555) return; + if (variant == TWISTED_BABY) + return reconstruction_missing("Entity_Familiar::AddToFollowers 0062db20 (Twisted Pair)"); + + if (isFollower && parent) + { + Entity_Familiar* leader = + parent->type == ENTITY_FAMILIAR ? dynamic_cast(parent.get()) : nullptr; + bool isFamiliarLeader = leader && leader->isFollower && leader->player == player; + if (isFamiliarLeader || (parent->type == ENTITY_PLAYER && parent == player)) + { + KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] Tried to add familiar %d to followers again!\n"); + return; + } + } + + isFollower = true; + int priority = GetFollowerPriority(); + for (Entity_Familiar* other : familiar_query(-1)) + { + if (other == this || !other->isFollower || other->player != player) continue; + + Entity_Familiar* chain = other; + while (chain->parent && chain->parent->type == ENTITY_FAMILIAR) + chain = static_cast(chain->parent.get()); + while (true) + { + if (chain->GetFollowerPriority() < priority) + { + child = chain; + parent = chain->parent.get(); + if (parent && parent->type == ENTITY_FAMILIAR) parent->child = this; + chain->parent = this; + return; + } + Entity* next = chain->child; + if (!next || next->type != ENTITY_FAMILIAR) + { + chain->child = this; + parent = chain; + return; + } + chain = static_cast(next); + } + } +} + +// Unlinks an entity from the chain its parent and child hold, the neighbours joining (part of 0062d7e0 and 006141e0). +static void chain_unlink(Entity& entity) +{ + if (entity.parent) entity.parent->child = entity.child.get(); + if (entity.child) entity.child->parent = entity.parent.get(); + entity.parent = nullptr; + entity.child = nullptr; +} + +// 0062d7e0 Leaves the following line, its neighbours closing the gap. +void Entity_Familiar::RemoveFromFollowers() +{ + if (variant == TWISTED_BABY && parent) + return reconstruction_missing("Entity_Familiar::RemoveFromFollowers 0062d7e0 (Twisted Pair)"); + + if (isFollower) chain_unlink(*this); + isFollower = false; +} + +// 006141e0 Leaves the delayed line, its neighbours closing the gap. +void Entity_Familiar::RemoveFromDelayed() +{ + if (isDelayed) chain_unlink(*this); + isDelayed = false; +} + +// 00613910 Drifts toward a position, or stays pinned in place when permanent. +void Entity_Familiar::FollowPosition(const Vector& position) +{ + if (isSubtype55555) + { + pos = formationOffset; + velocity = {}; + return; + } + friction *= FOLLOW_FRICTION; + velocity = vector_scale(vector_sub(position, pos), FOLLOW_POSITION_PULL); +} + +// The leader a follower trails: the first familiar ahead that keeps its place, else the King Baby at the head of its +// line, else none (part of 00612bb0). +static Entity* follow_leader_find(Entity_Familiar& familiar, bool isLilithBirthright) +{ + for (Entity* leader = familiar.parent; leader; leader = leader->parent) + { + Entity_Familiar* ahead = dynamic_cast(leader); + if (!ahead || ahead->is_following() || (isLilithBirthright && ahead->is_counted_follower())) return leader; + } + if (familiar.variant == Entity_Familiar::KING_BABY) return nullptr; + + for (Entity_Familiar* king : familiar_query(Entity_Familiar::KING_BABY)) + { + if (!king->isExists || king->player != familiar.player || king->parent != familiar.parent) continue; + + Entity* last = king; + for (Entity* next = king->child; + next && next->type == ENTITY_FAMILIAR && next->variant == Entity_Familiar::KING_BABY; next = next->child) + last = next; + return last; + } + return nullptr; +} + +// 00612bb0 Trails its leader at a short distance, catching up the further it falls behind. Permanent familiars stay +// put. Tainted Lilith's Incubus, the Siren's charm, RC Remote, Duct Tape, Friendship Necklace and Lilith's Birthright +// arrange the line their own ways, which stops the game. +void Entity_Familiar::FollowParent() +{ + if (isSubtype55555) + { + pos = formationOffset; + velocity = {}; + return; + } + if (IsLilithBirthrightIncubus()) + return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (Tainted Lilith's Incubus)"); + if (player->spawnerEntity && player->spawnerEntity->type == SIREN_TYPE && player->spawnerEntity->variant == 0 && + player->HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) + return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (the Siren's charm)"); + if (player->HasTrinket(TRINKET_RC_REMOTE)) return predict_player_movement(); + if (player->HasTrinket(TRINKET_DUCT_TAPE)) return move_to_parent_offset(); + + if (!vector_is_zero(formationOffset)) reset_follow_target(); + if (g_game->challenge == CHALLENGE_PONG && variant == ISAACS_HEART) + return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (the punching bag challenge)"); + bool isLilithBirthright = player->playerType == PLAYER_LILITH && player->HasCollectible(COLLECTIBLE_BIRTHRIGHT); + if (isLilithBirthright && is_counted_follower()) + return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (Lilith's Birthright)"); + if (player->HasTrinket(TRINKET_FRIENDSHIP_NECKLACE) && variant != KING_BABY) + return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (Friendship Necklace)"); + + orbitDistance = {}; + Entity* leader = follow_leader_find(*this, isLilithBirthright); + Vector leaderPos = leader ? leader->pos : player->pos; + float distance = variant == MILK ? MILK_FOLLOW_DISTANCE : FOLLOW_DISTANCE; + if (player->HasTrinket(TRINKET_CHILD_LEASH)) distance = LEASH_FOLLOW_DISTANCE; + + Vector spot = vector_add(leaderPos, vector_resized(vector_sub(pos, leaderPos), distance)); + float gap = vector_length(vector_sub(leaderPos, pos)); + if (distance < gap) velocity = vector_scale(vector_sub(spot, pos), (gap - distance) / gap * FOLLOW_PULL); + friction *= FOLLOW_FRICTION; +} + +// 006348d0 Drops its place in the formation, to be given a new one. +void Entity_Familiar::reset_follow_target() +{ + formationTargetOffset = {}; + formationOffset = {}; + formationAngle = 0; + formationMode = FORMATION_NONE; +} + +// Its place among the player's formed-up followers by rank, and how many there are (part of 00634260). +static std::pair formation_slot(Entity_Familiar& familiar) +{ + std::multimap ranked; + for (Entity_Familiar* other : familiar_query(-1)) + if (!other->isDead && other->isExists && !other->is_formation_exempt() && other->player == familiar.player) + ranked.emplace(other->GetFollowerPriority(), other); + + int slot = 0; + for (auto it = ranked.begin(); it != ranked.end() && it->second != &familiar; ++it) slot++; + return {slot, (int)ranked.size()}; +} + +// The offset from the player a formation gives a slot. +static Vector formation_offset(Entity_Familiar& familiar, int slot, int count) +{ + switch (familiar.formationMode) + { + case FORMATION_ROW: + return vector_make((float)(slot / 2 + 1) * FORMATION_ROW_STEP * (slot % 2 == 0 ? 1 : -1), 0); + case FORMATION_V: + { + int side = count == 2 ? slot : slot - 1; + if (side < 0) return vector_make(0, FORMATION_V_DEPTH); + float x = (float)(side / 2 + 1) * FORMATION_V_STEP * (side % 2 == 0 ? -1 : 1); + return vector_make(x, FORMATION_V_DEPTH - std::fabs(x)); + } + case FORMATION_RING: + { + float angle = 360.0f / (float)count * (float)slot * DEGREES_TO_RADIANS; + return vector_make(-std::sin(angle) * FORMATION_RING_RADIUS, std::cos(angle) * FORMATION_RING_RADIUS); + } + default: return vector_sub(familiar.pos, familiar.player->pos); + } +} + +// 00634260 Its offset from the player in Duct Tape's formation, turned with the player's aim: a slot by rank in a row, +// a V or a ring, eased toward and refreshed when the player changes the formation. +Vector Entity_Familiar::UpdateFollowPosition() +{ + if (is_formation_exempt()) return {}; + + if ((uint32_t)player->ductTapeMode != formationMode) formationTargetOffset = {}; + if (vector_is_zero(formationTargetOffset)) + { + formationMode = (uint8_t)player->ductTapeMode; + auto [slot, count] = formationMode != FORMATION_FREE ? formation_slot(*this) : std::pair{0, 0}; + formationTargetOffset = formation_offset(*this, slot, count); + if (formationMode != FORMATION_ROW && formationMode != FORMATION_V && formationMode != FORMATION_RING) + formationOffset = formationTargetOffset; + } + if (formationOffset.x != formationTargetOffset.x || formationOffset.y != formationTargetOffset.y) + formationOffset = vector_add(formationOffset, + vector_scale(vector_sub(formationTargetOffset, formationOffset), FORMATION_LERP)); + + float aimAngle = 0; + Vector aim = player->aimDirection; + if (formationMode != FORMATION_FREE && vector_length_squared(aim) > FORMATION_AIM_THRESHOLD) + aimAngle = std::atan2(aim.y, aim.x) * RADIANS_TO_DEGREES - 90; + + float from = angle_wrap(formationAngle); + float to = angle_wrap(aimAngle); + if (std::fabs(to - from) > 180) + { + if (to <= from) to += 360; + else from += 360; + } + formationAngle = angle_wrap((to - from) * FORMATION_LERP + from); + + float radians = formationAngle * DEGREES_TO_RADIANS; + float cosine = std::cos(radians); + float sine = std::sin(radians); + return vector_make(cosine * formationOffset.x - sine * formationOffset.y, + cosine * formationOffset.y + sine * formationOffset.x); +} + +// 0063b4a0 Where it should be when it arrives with its player: its orbit spot, a free spot for the Sprinkler, or beside +// the player (scattered when it is new), kept off the walls. +Vector Entity_Familiar::GetFollowTargetPosition(FollowSpot spot) +{ + if (g_game->nbRooms == 0) return player->pos; + if (orbitLayer >= 0) return GetOrbitPosition(player->pos); + if (variant == SPRINKLER) return room_free_pickup_position_find({.position = player->pos}); + if (variant == FORGOTTEN_BODY) return pos; + if (variant == ISAACS_BODY || variant == SCISSORS || variant == DECAP_ATTACK) return player->pos; + + Vector target = player->pos; + if (spot == FOLLOW_SCATTERED) target = vector_add(target, vector_scale(random_direction(), 20)); + if (is_following() && player->HasTrinket(TRINKET_RC_REMOTE)) target = vector_add(target, random_direction()); + if (spot == FOLLOW_EXACT) + { + if (variant == BLOOD_BABY) target = vector_add(target, random_direction()); + if (variant == BLOOD_PUPPY && linkedEntity) + reconstruction_missing("Entity_Familiar::GetFollowTargetPosition " + "0063b4a0 (Blood Puppy's spot)"); + } + return g_game->room->GetClampedPositionImpl(target, 20, 20, 20, 20); +} + +// 00612330 What it orbits: a blue fly's or wisp's parent, Gello's cord for wisps with Book of Virtues, else its player. +Entity* Entity_Familiar::get_orbit_parent() +{ + if ((variant == BLUE_FLY || variant == WISP) && parent) return parent; + if (player->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && player->HasCollectible(COLLECTIBLE_GELLO)) + { + std::vector cords = familiar_query(UMBILICAL_BABY); + if (!cords.empty()) return cords.front(); + } + return player; +} + +// 00612440 Spaces the orbitals of a layer around the same centre evenly, with the familiar joining or leaving it, and +// gives them the layer's speed: faster with Guardian Angel, slower with Big Fan, doubled for the unicorn wisps and +// tripled for Best Bud. +void Entity_Familiar::RecalculateOrbitOffset(int layer, OrbitChange change) +{ + if (isSubtype55555 || layer < 0) return; + + bool isWide = is_wide_wisp(*this); + std::vector orbiters; + for (Entity_Familiar* other : familiar_query(-1)) + { + if (!other->isExists || other == this || other->orbitLayer != layer) continue; + if (other->get_orbit_parent() != get_orbit_parent()) continue; + + isWide = isWide || is_wide_wisp(*other); + orbiters.push_back(other); + } + float speedScale = isWide ? WIDE_WISP_SPEED : 1; + if (player->HasCollectible(COLLECTIBLE_BIG_FAN)) speedScale = BIG_FAN_SPEED; + if (change == ORBIT_JOIN) orbiters.push_back(this); + + const OrbitLayer& entry = orbit_layer(layer); + for (size_t i = 0; i < orbiters.size(); i++) + { + Entity_Familiar& orbiter = *orbiters[i]; + orbiter.orbitAngleOffset = (float)i * TWO_PI / (float)orbiters.size(); + float speed = + player->HasCollectible(COLLECTIBLE_GUARDIAN_ANGEL) ? entry.guardianAngelSpeed * entry.speed : entry.speed; + orbiter.orbitSpeed = speed * speedScale; + if (orbiter.variant == BEST_BUD) orbiter.orbitSpeed *= BEST_BUD_SPEED; + } +} + +// 006127b0 Moves it to another orbit layer. +void Entity_Familiar::AddToOrbit(int layer) +{ + if (orbitLayer >= 0) RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + orbitLayer = layer; + orbitDistance = GetOrbitDistance(layer); + RecalculateOrbitOffset(layer, ORBIT_JOIN); +} + +// 00612820 Leaves its orbit, the rest of the orbit closing the gap. +void Entity_Familiar::RemoveFromOrbit() +{ + if (orbitLayer < 0) return; + + RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + orbitLayer = -1; +} + +// 00612850 The ellipse of an orbit layer. +Vector Entity_Familiar::GetOrbitDistance(int layer) +{ + const OrbitLayer& entry = orbit_layer(layer); + return vector_make(entry.distanceX, entry.distanceY); +} + +// 006139b0 Its spot on its orbit around a centre this frame, half a step on between game frames. The Sacrificial Dagger +// and Slipped Rib turn their sprite with it. Not orbiting, it stays on the centre. +Vector Entity_Familiar::GetOrbitPosition(const Vector& center) +{ + if (isSubtype55555) return formationOffset; + if (player->HasTrinket(TRINKET_DUCT_TAPE) && variant != BLUE_FLY) return vector_add(UpdateFollowPosition(), center); + if (!vector_is_zero(formationOffset)) reset_follow_target(); + + float phase = (float)(g_manager->framecount % 2) * 0.5f + (float)g_game->frameCount; + float angle = std::fmod(orbitAngleOffset - phase * orbitSpeed * PI_F * 0.5f, TWO_PI); + if (variant == SACRIFICIAL_DAGGER) + { + if (sprite.SetAnimation("Rotation", SWITCH_KEEP_FRAME) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(SACRIFICIAL_DAGGER_ROTATION_FRAME); + sprite.animState.isPlaying = false; + } + sprite.GetLayer(0)->rotation = angle * 180 / PI_F; + } + if (variant == SLIPPED_RIB) sprite.GetLayer(0)->rotation = angle * 180 / PI_F; + if (orbitLayer < 0) return center; + + float layerAngle = angle + orbit_layer(orbitLayer).angleOffset; + return vector_make(std::cos(layerAngle) * orbitDistance.x + center.x, + std::sin(layerAngle) * orbitDistance.y + center.y); +} + +// 00634a40 After a change to the formation, makes the player's other formed-up followers take new places. +void Entity_Familiar::ResolveOrbitConflict() +{ + if (formationMode == FORMATION_FREE || is_formation_exempt()) return; + + for (Entity_Familiar* other : familiar_query(-1)) + if (other != this && !other->is_formation_exempt() && other->player == player) + other->formationMode = FORMATION_NONE; +} diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp new file mode 100644 index 0000000..cfb897e --- /dev/null +++ b/src/familiar_missing.cpp @@ -0,0 +1,400 @@ +#include "entity_familiar.h" +#include "log.h" + +// The rest of Entity_Familiar, which the familiars this round does not reach call: each stops the game with its name. + +// 00431be0 +void Entity_Familiar::ai_umbilical_baby(bool) +{ + reconstruction_missing("Entity_Familiar::ai_umbilical_baby 00431be0"); +} + +// 00436330 +void Entity_Familiar::WispInit() +{ + reconstruction_missing("Entity_Familiar::WispInit 00436330"); +} + +// 00436fd0 +uint32_t Entity_Familiar::wisp_kill() +{ + reconstruction_missing("Entity_Familiar::wisp_kill 00436fd0"); +} + +// 004386f0 +Entity_Tear* Entity_Familiar::fire_wisp_projectile(Vector) +{ + reconstruction_missing("Entity_Familiar::fire_wisp_projectile 004386f0"); +} + +// 0043a5e0 +uint32_t Entity_Familiar::wisp_take_damage(float*, uint32_t*, int*) +{ + reconstruction_missing("Entity_Familiar::wisp_take_damage 0043a5e0"); +} + +// 0043aa90 +void Entity_Familiar::ai_wisp() +{ + reconstruction_missing("Entity_Familiar::ai_wisp 0043aa90"); +} + +// 0043db20 +void Entity_Familiar::ai_mr_me_wisp() +{ + reconstruction_missing("Entity_Familiar::ai_mr_me_wisp 0043db20"); +} + +// 0043e4a0 +void Entity_Familiar::ai_mega_blast_wisp() +{ + reconstruction_missing("Entity_Familiar::ai_mega_blast_wisp 0043e4a0"); +} + +// 0043eb10 +int Entity_Familiar::GetRandomWisp(RNG*) +{ + reconstruction_missing("Entity_Familiar::GetRandomWisp 0043eb10"); +} + +// 005ae490 +void Entity_Familiar::ai_buddy_inbox() +{ + reconstruction_missing("Entity_Familiar::ai_buddy_inbox 005ae490"); +} + +// 0060d180 +KColor* Entity_Familiar::GetPlayerSlot(KColor*, Entity_Player*) +{ + reconstruction_missing("Entity_Familiar::GetPlayerSlot 0060d180"); +} + +// 0060ddd0 +void Entity_Familiar::set_locust_config_index(int) +{ + reconstruction_missing("Entity_Familiar::set_locust_config_index 0060ddd0"); +} + +// 00613fe0 +void Entity_Familiar::AddToDelayed() +{ + reconstruction_missing("Entity_Familiar::AddToDelayed 00613fe0"); +} + +// 006142e0 +void Entity_Familiar::PlayChargeAnim(int) +{ + reconstruction_missing("Entity_Familiar::PlayChargeAnim 006142e0"); +} + +// 006341a0 +bool Entity_Familiar::apply_baby_bender(Entity_Tear*) +{ + reconstruction_missing("Entity_Familiar::apply_baby_bender 006341a0"); +} + +// 0062a8f0 +bool Entity_Familiar::CanPlayerFire() +{ + reconstruction_missing("Entity_Familiar::CanPlayerFire 0062a8f0"); +} + +// 00616db0 +void Entity_Familiar::ai_walker() +{ + reconstruction_missing("Entity_Familiar::ai_walker 00616db0"); +} + +// 0061a240 +void Entity_Familiar::ai_blue_babys_only_friend() +{ + reconstruction_missing("Entity_Familiar::ai_blue_babys_only_friend 0061a240"); +} + +// 0061a4e0 +void Entity_Familiar::ai_pickup_sack() +{ + reconstruction_missing("Entity_Familiar::ai_pickup_sack 0061a4e0"); +} + +// 0061bd50 +void Entity_Familiar::ai_daddy_longlegs() +{ + reconstruction_missing("Entity_Familiar::ai_daddy_longlegs 0061bd50"); +} + +// 0061c150 +void Entity_Familiar::ai_orbital_variant_50() +{ + reconstruction_missing("Entity_Familiar::ai_orbital_variant_50 0061c150"); +} + +// 0061d6b0 +void Entity_Familiar::ai_key_full() +{ + reconstruction_missing("Entity_Familiar::ai_key_full 0061d6b0"); +} + +// 0062a930 +void Entity_Familiar::AddCoins(int) +{ + reconstruction_missing("Entity_Familiar::AddCoins 0062a930"); +} + +// 0062c8d0 +void Entity_Familiar::farting_baby_fart() +{ + reconstruction_missing("Entity_Familiar::farting_baby_fart 0062c8d0"); +} + +// 0062e120 +void Entity_Familiar::ai_samsons_chains() +{ + reconstruction_missing("Entity_Familiar::ai_samsons_chains 0062e120"); +} + +// 0062e620 +void Entity_Familiar::update_weapon(bool) +{ + reconstruction_missing("Entity_Familiar::update_weapon 0062e620"); +} + +// 0062ee30 +void Entity_Familiar::ai_lil_gurdy() +{ + reconstruction_missing("Entity_Familiar::ai_lil_gurdy 0062ee30"); +} + +// 00631050 +void Entity_Familiar::MoveDelayed(int) +{ + reconstruction_missing("Entity_Familiar::MoveDelayed 00631050"); +} + +// 006312f0 +void Entity_Familiar::MoveDiagonally(float) +{ + reconstruction_missing("Entity_Familiar::MoveDiagonally 006312f0"); +} + +// 00631850 +void Entity_Familiar::move_to_parent_offset() +{ + reconstruction_missing("Entity_Familiar::move_to_parent_offset 00631850"); +} + +// 00650220 +void Entity_Familiar::predict_player_movement() +{ + reconstruction_missing("Entity_Familiar::predict_player_movement 00650220"); +} + +// 00631b20 +void Entity_Familiar::delirium_morph() +{ + reconstruction_missing("Entity_Familiar::delirium_morph 00631b20"); +} + +// 006322f0 +void Entity_Familiar::init_lil_harbinger_sprite() +{ + reconstruction_missing("Entity_Familiar::init_lil_harbinger_sprite 006322f0"); +} + +// 00632820 +void Entity_Familiar::ai_lil_monstro() +{ + reconstruction_missing("Entity_Familiar::ai_lil_monstro 00632820"); +} + +// 00632d90 +void Entity_Familiar::ai_variant_111() +{ + reconstruction_missing("Entity_Familiar::ai_variant_111 00632d90"); +} + +// 00633500 +void Entity_Familiar::update_angry_fly() +{ + reconstruction_missing("Entity_Familiar::update_angry_fly 00633500"); +} + +// 00634b10 +void Entity_Familiar::ai_lil_spewer() +{ + reconstruction_missing("Entity_Familiar::ai_lil_spewer 00634b10"); +} + +// 006378c0 +void Entity_Familiar::ai_lil_harbingers() +{ + reconstruction_missing("Entity_Familiar::ai_lil_harbingers 006378c0"); +} + +// 00638c10 +Entity_Laser* Entity_Familiar::FireBrimstone(const Vector&, uint8_t) +{ + reconstruction_missing("Entity_Familiar::FireBrimstone 00638c10"); +} + +// 00639000 +Entity* Entity_Familiar::ThrowDip(int, const Vector&, Entity*) +{ + reconstruction_missing("Entity_Familiar::ThrowDip 00639000"); +} + +// 0063aef0 +Entity_Laser* Entity_Familiar::sprinkler_shoot_laser(float, float) +{ + reconstruction_missing("Entity_Familiar::sprinkler_shoot_laser 0063aef0"); +} + +// 0063b340 +void Entity_Familiar::update_idle_anim_by_size() +{ + reconstruction_missing("Entity_Familiar::update_idle_anim_by_size 0063b340"); +} + +// 0063b8b0 +void Entity_Familiar::RemoveFromPlayer(uint8_t) +{ + reconstruction_missing("Entity_Familiar::RemoveFromPlayer 0063b8b0"); +} + +// 0063c1c0 +void Entity_Familiar::ai_minisaac() +{ + reconstruction_missing("Entity_Familiar::ai_minisaac 0063c1c0"); +} + +// 0063ce20 +void Entity_Familiar::minisaac_fire() +{ + reconstruction_missing("Entity_Familiar::minisaac_fire 0063ce20"); +} + +// 0063dd60 +void Entity_Familiar::minisaac_find_target() +{ + reconstruction_missing("Entity_Familiar::minisaac_find_target 0063dd60"); +} + +// 0063f9f0 +void Entity_Familiar::ai_blood_oath() +{ + reconstruction_missing("Entity_Familiar::ai_blood_oath 0063f9f0"); +} + +// 006402f0 +void Entity_Familiar::paschal_candle_sync_effects() +{ + reconstruction_missing("Entity_Familiar::paschal_candle_sync_effects 006402f0"); +} + +// 00640ca0 +void Entity_Familiar::ai_boiled_baby() +{ + reconstruction_missing("Entity_Familiar::ai_boiled_baby 00640ca0"); +} + +// 006414c0 +void Entity_Familiar::zhl_misfit_006414c0() +{ + reconstruction_missing("Entity_Familiar::zhl_misfit_006414c0 006414c0"); +} + +// 006424d0 +void Entity_Familiar::ai_bird_cage() +{ + reconstruction_missing("Entity_Familiar::ai_bird_cage 006424d0"); +} + +// 006431d0 +void Entity_Familiar::ai_bot_fly() +{ + reconstruction_missing("Entity_Familiar::ai_bot_fly 006431d0"); +} + +// 006437a0 +void Entity_Familiar::ai_stitches() +{ + reconstruction_missing("Entity_Familiar::ai_stitches 006437a0"); +} + +// 006444d0 +Entity* Entity_Familiar::aim_reflected_projectile() +{ + reconstruction_missing("Entity_Familiar::aim_reflected_projectile 006444d0"); +} + +// 00644e80 +void Entity_Familiar::ai_shadow_intruder_damocles(bool) +{ + reconstruction_missing("Entity_Familiar::ai_shadow_intruder_damocles 00644e80"); +} + +// 006470c0 +void* Entity_Familiar::get_item_config_entry() +{ + reconstruction_missing("Entity_Familiar::get_item_config_entry 006470c0"); +} + +// 00647170 +uint8_t Entity_Familiar::abyss_locust_eat() +{ + reconstruction_missing("Entity_Familiar::abyss_locust_eat 00647170"); +} + +// 0064a2d0 +uint8_t Entity_Familiar::break_grid_ahead() +{ + reconstruction_missing("Entity_Familiar::break_grid_ahead 0064a2d0"); +} + +// 0064a830 +void Entity_Familiar::load_config_graphics() +{ + reconstruction_missing("Entity_Familiar::load_config_graphics 0064a830"); +} + +// 0064b6c0 +void Entity_Familiar::render_abyss_locust_sprite(ANM2*, float*) +{ + reconstruction_missing("Entity_Familiar::render_abyss_locust_sprite 0064b6c0"); +} + +// 0064b920 +void Entity_Familiar::siren_charm(Entity*, Entity_Player*) +{ + reconstruction_missing("Entity_Familiar::siren_charm 0064b920"); +} + +// 0064bab0 +void Entity_Familiar::RemoveFromPlayer() +{ + reconstruction_missing("Entity_Familiar::RemoveFromPlayer 0064bab0"); +} + +// 0064ca30 +void Entity_Familiar::UpdateDirtColor(uint8_t) +{ + reconstruction_missing("Entity_Familiar::UpdateDirtColor 0064ca30"); +} + +// 0064d1d0 +void Entity_Familiar::update_star_of_bethlehem_speed(bool) +{ + reconstruction_missing("Entity_Familiar::update_star_of_bethlehem_speed 0064d1d0"); +} + +// 0064e0c0 +void Entity_Familiar::ai_blood_clot(bool) +{ + reconstruction_missing("Entity_Familiar::ai_blood_clot 0064e0c0"); +} + +// 009615e0 +uint8_t Entity_Familiar::multidimensional_baby_copy_knife(Entity_Knife*, Entity*) +{ + reconstruction_missing("Entity_Familiar::multidimensional_baby_copy_knife 009615e0"); +} diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp new file mode 100644 index 0000000..1edadc3 --- /dev/null +++ b/src/familiar_shoot.cpp @@ -0,0 +1,557 @@ +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include + +// The items and trinkets the familiars' shots read. +constexpr int COLLECTIBLE_HIVE_MIND = 248; +constexpr int COLLECTIBLE_TINY_PLANET = 233; +constexpr int TRINKET_FORGOTTEN_LULLABY = 141; +constexpr int TRINKET_ISAACS_HEAD_ID = 54; + +// The config tags that make a familiar a fly or a spider, which Hive Mind strengthens. +constexpr uint64_t TAG_FAMILIAR_FLY = 1 << 0; +constexpr uint64_t TAG_FAMILIAR_SPIDER = 1 << 1; + +// How often the shooters fire, and how long their head keeps the shooting look. +constexpr int FIRE_DELAY = 22; +constexpr int FIRE_DELAY_FAST = 11; +constexpr int FIRE_DELAY_BOBBY = 16; +constexpr int FIRE_DELAY_FATES_REWARD = 44; +constexpr int FIRE_DELAY_ROTTEN_VERSUS = 33; +constexpr float FIRE_DELAY_CHARMED = 1.4f; +constexpr int HEAD_SHOOT_FRAMES = 18; +constexpr int HEAD_FLOAT_FRAME = 8; +constexpr int FAMILIAR_ABEL_TWIN = 244; +constexpr int MIMIC_ROBO_BABY = 4; +constexpr int MIMIC_ROTTEN_BABY = 9; +constexpr float ROTTEN_FLY_RANGE = 200; + +// A shot's base: its speed, how much of the player's motion it takes, damage and size. +constexpr float SHOT_SPEED = 10; +constexpr float SHOT_INHERIT = 0.6f; +constexpr float SHOT_DAMAGE = 3.5f; +constexpr float SHOT_SCALE = 0.8f; +constexpr float SHOT_SCALE_MIN = 0.01f; +constexpr float SHOT_FALL_JITTER = 0.2f; + +// The looks of the shots: ghostly, Gish's tar, charming, blood red, Seraphim's and Lil Delirium's. +constexpr ColorMod GHOST_TINT = {{1.5f, 2, 2, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod GISH_COLOR = {{0.95f, 0.8f, 0.6f, 1}, {0, 0, 0, 0}, {-0.5882353f, -0.5882353f, -0.5882353f}}; +constexpr ColorMod CHARM_COLOR = {{1, 0, 1, 1}, {0, 0, 0, 0}, {0.19607845f, 0, 0}}; +constexpr ColorMod BLOOD_TINT = {{0.9f, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod HUSHY_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0.2f, 0.4f}}; +constexpr float DELIRIUM_COLORIZE[] = {2.4f, 2.4f, 2.4f, 1}; +constexpr float HOLOGRAM_ALPHA = 0.25f; + +// Baby-Bender's homing look for tears and lasers. +constexpr ColorMod BENDER_TEAR_COLOR = { + {0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.21568628f, 0.019607844f, 0.37254903f}}; +constexpr ColorMod BENDER_LASER_COLOR = {{0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.3529412f, 0, 0.7058824f}}; +constexpr float BENDER_RANGE_BONUS = 120; +constexpr float CRAWLSPACE_TEAR_OFFSET = -18; +constexpr float CRAWLSPACE_TEAR_HEIGHT = -5.1f; + +// What a shot is made of before it spawns (FireProjectile's locals). +struct FamiliarShot +{ + TearFlags flags; + ColorMod color = COLOR_DEFAULT; + Vector velocity{}; + float damage = SHOT_DAMAGE; + float fallingAccel = 0; + float fallingSpeed = 0; + float scale = 0; + int tearVariant = TEAR_BLUE; +}; + +// apply_forgotten_lullaby 00651810: a fire delay shortened by Forgotten Lullaby, halved and more when stacked. +int familiar_lullaby_delay(Entity_Familiar& familiar, int fireDelay) +{ + if (!familiar.player->HasTrinket(TRINKET_FORGOTTEN_LULLABY)) return fireDelay; + + int multiplier = familiar.player->GetTrinketMultiplier(TRINKET_FORGOTTEN_LULLABY); + if (multiplier == 2) return (int)((float)fireDelay / 2.5f); + if (multiplier < 3) return fireDelay / 2; + return (int)((float)fireDelay / 3); +} + +// 0060dc40 How strong its attacks are: doubled by BFFS! (not for blue flies and spiders) or by Hive Mind (flies and +// spiders), a quarter more per Child's Leash, three quarters for Tainted Bethany, a quarter for Tainted Lazarus's other +// form while it is behind. +float Entity_Familiar::GetMultiplier() +{ + uint64_t tags = config->tags; + bool isBffs = player->HasCollectible(COLLECTIBLE_BFFS) && variant != BLUE_FLY && variant != BLUE_SPIDER; + bool isHiveMind = (player->HasCollectible(COLLECTIBLE_HIVE_MIND) || + player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HIVE_MIND)) && + ((tags & TAG_FAMILIAR_FLY) || (tags & TAG_FAMILIAR_SPIDER) || variant == ABYSS_LOCUST); + float multiplier = isBffs || isHiveMind ? 2.0f : 1.0f; + + int leash = player->GetTrinketMultiplier(TRINKET_CHILD_LEASH); + if (leash > 0) multiplier = (float)leash * 0.25f + multiplier; + if (player->playerType == PLAYER_BETHANY_B) multiplier *= 0.75f; + + Entity_Player* twin = static_cast(player->twinPlayer.get()); + bool isLazarusB = player->playerType == PLAYER_LAZARUS_B || player->playerType == PLAYER_LAZARUS2_B; + if (player->isExists && isLazarusB && twin && twin != player && twin->playerIndex != -1 && + twin->playerIndex < player->playerIndex) + multiplier *= 0.25f; + return multiplier; +} + +// The looks its head takes back after shooting: floating down, or King Baby's stopped look while the player aims (part +// of 00614b10 and 00619270). +void Entity_Familiar::play_idle_anim() +{ + if (variant == WISP) return reconstruction_missing("Entity_Familiar::Shoot 00614b10 (a wisp's look)"); + if (variant == ITEM_WISP) return (void)sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME); + if (variant == BLOOD_BABY) return; + + sprite.isFlipX = false; + if (variant == CAINS_OTHER_EYE) return sprite.Play("Float"); + sprite.Play(variant == KING_BABY && player->fireDirection != DIRECTION_NONE ? "StoppedDown" : "FloatDown"); +} + +// 00614500 Turns its head to shoot in a direction. +void Entity_Familiar::PlayShootAnim(int direction) +{ + if (variant == WISP) return reconstruction_missing("Entity_Familiar::PlayShootAnim 00614500 (a wisp's look)"); + if (variant == ITEM_WISP) return (void)sprite.SetAnimation("Shoot", SWITCH_KEEP_FRAME); + if (variant == BLOOD_BABY) return; + + sprite.isFlipX = false; + if (variant == CAINS_OTHER_EYE) return sprite.Play("Shoot"); + if (variant == BUMBO) + { + sprite.Play("Level3Shoot", PLAY_FORCED); + if (direction == DIRECTION_LEFT) sprite.isFlipX = true; + return; + } + + bool isRobo = variant == ROBO_BABY || variant == ROBO_BABY_2; + switch (direction) + { + case DIRECTION_LEFT: + if (isRobo) return sprite.Play("FloatShootSide2"); + sprite.isFlipX = true; + return sprite.Play("FloatShootSide"); + case DIRECTION_UP: return sprite.Play("FloatShootUp"); + case DIRECTION_RIGHT: return sprite.Play("FloatShootSide"); + case DIRECTION_DOWN: return sprite.Play("FloatShootDown"); + } +} + +// 00613df0 Turns its head toward a direction while floating, King Baby stopping while the player aims. +void Entity_Familiar::PlayFloatAnim(int direction) +{ + if (variant == BUMBO) return; + if (variant == WISP) return reconstruction_missing("Entity_Familiar::PlayFloatAnim 00613df0 (a wisp's look)"); + if (variant == ITEM_WISP) return (void)sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME); + if (variant == BLOOD_BABY) return; + + sprite.isFlipX = false; + if (variant == CAINS_OTHER_EYE) return sprite.Play("Float"); + bool isRobo = variant == ROBO_BABY || variant == ROBO_BABY_2; + bool isStopped = variant == KING_BABY && player->fireDirection != DIRECTION_NONE; + switch (direction) + { + case DIRECTION_LEFT: + if (isRobo) return sprite.Play("FloatSide2"); + sprite.isFlipX = true; + return sprite.Play(isStopped ? "StoppedSide" : "FloatSide"); + case DIRECTION_UP: return sprite.Play(isStopped ? "StoppedUp" : "FloatUp"); + case DIRECTION_RIGHT: return sprite.Play(isStopped ? "StoppedSide" : "FloatSide"); + case DIRECTION_DOWN: return sprite.Play(isStopped ? "StoppedDown" : "FloatDown"); + } +} + +// The direction a vector leans along most, vertical on a tie. +static int cardinal_direction(Vector v) +{ + if (std::fabs(v.x) <= std::fabs(v.y)) return v.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + return v.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; +} + +// Where a target is drawn this frame, half a frame back between game frames. +static Vector target_position(Entity& target) +{ + if ((g_manager->framecount & 1) == 0) return target.prevPosition; + return vector_scale(vector_add(target.prevPosition, target.pos), 0.5f); +} + +// 006146e0 Aims at what its King Baby targets, else at the mark Marked or Eye of the Occult place, with the direction +// to face. Gello's aim stops the game. +bool Entity_Familiar::TryAimAtMarkedTarget(Vector& aimDirection, int& direction, Vector* targetPosition) +{ + if (variant == UMBILICAL_BABY && updateTime > 10 && target) + reconstruction_missing("Entity_Familiar::TryAimAtMarkedTarget 006146e0 (Gello)"); + + Entity* aimed = nullptr; + if (isFollower) + { + Entity* king = IsLilithBirthrightIncubus() ? get_incubus_umbilical_whip() : nullptr; + for (Entity* ahead = this; !king && ahead && ahead->type == ENTITY_FAMILIAR; ahead = ahead->parent) + if (ahead->variant == KING_BABY) king = ahead; + if (king) aimed = king->target; + } + if (!aimed && (player->HasCollectible(COLLECTIBLE_MARKED) || player->HasCollectible(COLLECTIBLE_EYE_OF_THE_OCCULT))) + aimed = player->markedTarget; + if (!aimed) + { + if (targetPosition) *targetPosition = {}; + return false; + } + + Vector at = target_position(*aimed); + aimDirection = vector_normalized(vector_sub(at, pos)); + direction = cardinal_direction(aimDirection); + if (targetPosition) *targetPosition = at; + return true; +} + +// 00614b10 A shooting follower's turn: counts its cooldown down (twice as fast with Forgotten Lullaby), fires the way +// the player shoots (Abel back toward the player, Lil Loki four ways, Robo-Baby a laser, Rotten Baby a blue fly) or at +// a mark, and turns its head. With the player not shooting it floats again. +void Entity_Familiar::Shoot() +{ + if (player->isDead) return; + if (fireCooldown > 0) fireCooldown--; + if (player->HasTrinket(TRINKET_FORGOTTEN_LULLABY) && fireCooldown > 0) fireCooldown--; + + int fireDelay = FIRE_DELAY; + if (variant == MONGO_BABY) fireDelay = FIRE_DELAY_FAST; + if (variant == BROTHER_BOBBY || variant == ABEL) fireDelay = FIRE_DELAY_BOBBY; + if (variant == FATES_REWARD) fireDelay = FIRE_DELAY_FATES_REWARD; + if (HasEntityFlags(FLAG_CHARM)) fireDelay = (int)((float)fireDelay * FIRE_DELAY_CHARMED); + int mimic = -1; + if (variant == FAMILIAR_ABEL_TWIN) fireDelay = FIRE_DELAY_FAST; + else if (variant == MONGO_BABY) mimic = subtype; + if (familiar_versus() && variant == ROTTEN_BABY) fireDelay = FIRE_DELAY_ROTTEN_VERSUS; + + int direction = player->fireDirection; + if (direction == DIRECTION_NONE) + { + if (headFrameDelay >= 0 && --headFrameDelay < 0 && variant != BUMBO) play_idle_anim(); + return; + } + + Vector toPlayer = vector_sub(player->pos, pos); + if (variant == ABEL || variant == FAMILIAR_ABEL_TWIN) direction = cardinal_direction(toPlayer); + Vector aim = direction_unit(direction); + bool isMarked = TryAimAtMarkedTarget(aim, direction, nullptr); + FireMode mode = isMarked ? FIRE_EXACT : FIRE_INHERIT_MOTION; + sprite.isFlipX = direction == DIRECTION_LEFT; + if (fireCooldown <= 0) + { + bool isFired = true; + if (variant == LIL_LOKI) + for (int turn = 0; turn < 4; turn++) + { + float angle = (float)turn * 90 * DEGREES_TO_RADIANS; + Vector turned = vector_make(aim.x * std::cos(angle) - aim.y * std::sin(angle), + aim.y * std::cos(angle) + aim.x * std::sin(angle)); + FireProjectile(turned, mode); + } + else if (variant == ROBO_BABY || mimic == MIMIC_ROBO_BABY) fire_robo_baby_laser(aim); + else if (variant != ROTTEN_BABY && mimic != MIMIC_ROTTEN_BABY) + FireProjectile(variant == ABEL || variant == FAMILIAR_ABEL_TWIN ? vector_normalized(toPlayer) : aim, mode); + else if (!linkedEntity) + { + PickEnemyTarget({.range = ROTTEN_FLY_RANGE}); + linkedEntity = player->AddBlueFlies(1, pos, target); + shot_owner_convert(linkedEntity); + } + else isFired = false; + if (isFired) + { + fireCooldown = fireDelay; + headFrameDelay = HEAD_SHOOT_FRAMES; + } + mongo_baby_pick_next_mimic(); + } + + if (headFrameDelay <= HEAD_FLOAT_FRAME) + { + PlayFloatAnim(direction); + headFrameDelay = HEAD_FLOAT_FRAME; + return; + } + PlayShootAnim(direction); + headFrameDelay--; +} + +// 0062d290 Mongo Baby moves on to mimicking the next baby the player owns. +void Entity_Familiar::mongo_baby_pick_next_mimic() +{ + if (variant == MONGO_BABY) reconstruction_missing("Entity_Familiar::mongo_baby_pick_next_mimic 0062d290"); +} + +// The shot of a familiar by variant (or by the baby Mongo Baby mimics, or the roll of Rainbow Baby): its flags, look, +// damage and arc (part of 00639750). Returns false for the familiars whose shots wait for their takeover. +static bool shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, int mimic, int rainbow) +{ + Entity_Player& player = *familiar.player; + int variant = familiar.variant; + if (variant == Entity_Familiar::ISAACS_HEAD) + { + shot.flags.set(TEAR_PIERCING); + int heads = player.GetTrinketMultiplier(TRINKET_ISAACS_HEAD_ID); + if (heads > 1) shot.damage = heads > 2 ? (float)((double)player.damage * 1.5) : player.damage; + } + else if (variant == Entity_Familiar::GHOST_BABY || rainbow == 1 || mimic == 6) + { + shot.flags.set(TEAR_SPECTRAL); + shot.color = GHOST_TINT; + } + else if (variant == Entity_Familiar::HARLEQUIN_BABY || rainbow == 2 || mimic == 7) + { + shot.scale *= 0.9f; + shot.tearVariant = TEAR_BLOOD; + shot.damage = 4; + } + else if (rainbow == 3 || mimic == 8) + { + shot.tearVariant = TEAR_BLOOD; + shot.scale *= SHOT_SCALE; + shot.fallingSpeed = 1.2f; + shot.damage = 3; + } + else if (variant == Entity_Familiar::ROBO_BABY || rainbow == 4 || mimic == 4) + { + shot.scale *= 1.06f; + shot.tearVariant = TEAR_BLOOD; + shot.damage = 5; + } + else if (variant == Entity_Familiar::LITTLE_GISH || rainbow == 5 || mimic == 2) + { + shot.flags.set(TEAR_SLOW).set(TEAR_GISH); + shot.color = GISH_COLOR; + } + else if (variant == Entity_Familiar::LITTLE_STEVEN || rainbow == 6 || mimic == 3) + { + shot.tearVariant = TEAR_MULTIDIMENSIONAL; + shot.flags.set(TEAR_HOMING); + shot.fallingSpeed = -3; + } + else if (variant == Entity_Familiar::BLUE_BABY_SOUL || rainbow == 7) + { + shot.flags.set(TEAR_SPECTRAL).set(TEAR_HOMING); + shot.fallingSpeed = -3; + shot.color = GHOST_TINT; + } + else if (variant == Entity_Familiar::CUBE_OF_MEAT_2) shot.tearVariant = TEAR_BLOOD; + else if ((variant >= Entity_Familiar::BALL_OF_BANDAGES_2 && variant <= Entity_Familiar::BALL_OF_BANDAGES_4) || + rainbow == 8) + { + if (Random() % 10 == 0 || rainbow == 8) shot.flags.set(TEAR_CHARM); + shot.color = CHARM_COLOR; + if (variant == Entity_Familiar::BALL_OF_BANDAGES_4) shot.flags.set(TEAR_HP_DROP); + } + else if (variant == Entity_Familiar::SISTER_MAGGY || mimic == 5 || rainbow == 10) + { + shot.color = BLOOD_TINT; + shot.damage = 6; + } + else if (variant == Entity_Familiar::HUSHY) + { + shot.damage = 6; + shot.color = HUSHY_COLOR; + shot.tearVariant = TEAR_DARK_MATTER; + } + else if (variant == Entity_Familiar::LIL_LOKI || mimic == 10) shot.color = BLOOD_TINT; + else if (variant == Entity_Familiar::INCUBUS || variant == Entity_Familiar::FATES_REWARD || + variant == Entity_Familiar::CAINS_OTHER_EYE) + { + TearParams hit = + player.GetTearHitParams(WEAPON_TEARS, familiar.GetMultiplier(), Random() & 1 ? 1 : -1, nullptr); + shot.color = hit.tearColor; + shot.flags = hit.tearFlags; + shot.flags.reset(TEAR_MULLIGAN).reset(TEAR_LUDOVICO).reset(TEAR_HP_DROP); + if (player.HasCollectible(COLLECTIBLE_IPECAC)) shot.flags.set(TEAR_EXPLOSIVE); + shot.damage = hit.tearDamage; + shot.scale = hit.tearScale; + shot.fallingSpeed = -player.tearFallingSpeed; + shot.fallingAccel = player.tearFallingAcceleration; + shot.tearVariant = hit.tearVariant; + } + else if (variant == Entity_Familiar::BUMBO && familiar.state == 2 && Random() % 10 == 0) + shot.flags.set(TEAR_COIN_DROP); + else if (variant == Entity_Familiar::SERAPHIM) + { + shot.flags.set(TEAR_HOMING); + shot.color = COLOR_DEFAULT; + shot.damage = familiar_versus() ? 6.0f : 10.0f; + shot.scale = 1.1f; + shot.velocity = vector_scale(shot.velocity, 0.75f); + shot.fallingSpeed = -0.75f; + } + else if (variant == Entity_Familiar::LIL_MONSTRO) + { + shot.tearVariant = TEAR_BLOOD; + Vector direction = random_direction(); + float push = random_unit() * 2; + shot.velocity = vector_add(shot.velocity, vector_scale(direction, push)); + uint32_t size = Random(); + shot.scale *= random_unit() * 0.05f + (float)(size & 1) * 0.4f + 0.9f; + shot.fallingAccel = 0.5f; + shot.fallingSpeed = -(random_unit() * 15 + 5); + } + else if ((variant == Entity_Familiar::ABEL && + (player.playerType == PLAYER_CAIN || player.playerType == PLAYER_CAIN_B)) || + variant == FAMILIAR_ABEL_TWIN) + { + shot.tearVariant = TEAR_BLOOD; + shot.damage = 7.5f; + } + else if (variant == Entity_Familiar::INTRUDER || variant == Entity_Familiar::FRUITY_PLUM) return false; + else if (variant == Entity_Familiar::FREEZER_BABY || (variant != Entity_Familiar::ABEL && mimic == 11)) + { + shot.tearVariant = TEAR_ICE; + shot.scale *= 1.1f; + shot.flags.set(TEAR_ICE_FLAG); + if (Random() % 10 == 0) shot.flags.set(TEAR_FREEZE); + } + return true; +} + +// Spawns one of a familiar's tears and finishes it: its arc, damage, flags, size and look, the familiar as its parent, +// Baby-Bender, and an owner's charm (part of 00639750). +static Entity_Tear* shot_spawn(Entity_Familiar& familiar, const FamiliarShot& shot, Vector velocity) +{ + auto* tear = static_cast(g_game->Spawn({.position = familiar.pos, + .velocity = velocity, + .spawner = &familiar, + .type = ENTITY_TEAR, + .variant = shot.tearVariant, + .seed = Random()})); + tear->fallingSpeed = random_unit() * SHOT_FALL_JITTER + shot.fallingSpeed; + tear->fallingAccel = shot.fallingAccel; + tear->SetCollisionDamage(shot.damage); + tear->SetTearFlags(shot.flags); + tear->baseScale = shot.scale; + tear->fScale = shot.scale; + tear->ResetSpriteScale(); + tear->parent = &familiar; + tear->SetColor(shot.color, -1, 255, false, true); + tear->tearIdx = (int)(Random() & 1); + familiar.TryFireTear(tear); + familiar.shot_owner_convert(tear); + return tear; +} + +// 00639750 Fires a familiar's tear: at ten speed, with the player's motion unless aimed at a mark, its damage and size +// scaled by BFFS!, and the variant's flags and look. Harlequin Baby fires two, the wisps and Intruder their own way. +Entity_Tear* Entity_Familiar::FireProjectile(const Vector& aimDirection, FireMode mode) +{ + FamiliarShot shot; + shot.velocity = vector_scale(aimDirection, SHOT_SPEED); + if (variant == INTRUDER) reconstruction_missing("Entity_Familiar::FireProjectile 00639750 (Intruder)"); + if (mode == FIRE_INHERIT_MOTION) + { + Vector inherited = vector_scale(player->velocity, SHOT_INHERIT * 2); + shot.velocity = variant == ABEL || variant == FAMILIAR_ABEL_TWIN ? vector_sub(shot.velocity, inherited) + : vector_add(shot.velocity, inherited); + if (vector_length_squared(shot.velocity) < SHOT_SPEED * SHOT_SPEED && variant != LIL_MONSTRO) + shot.velocity = vector_scale(vector_normalized(shot.velocity), SHOT_SPEED); + } + if (variant == WISP || variant == ITEM_WISP) return fire_wisp_projectile(shot.velocity); + + float multiplier = GetMultiplier(); + shot.scale = (GetMultiplier() * 0.25f + 0.75f) * SHOT_SCALE; + int mimic = variant == MONGO_BABY ? subtype : -1; + int rainbow = variant == RAINBOW_BABY || mimic == 8 ? (int)(Random() % 10) + 1 : 0; + if (!shot_variant_apply(*this, shot, mimic, rainbow)) + reconstruction_missing("Entity_Familiar::FireProjectile 00639750 (this familiar's shot)"); + + if (isLilDelirium) + { + if (shot.tearVariant == TEAR_BLUE) shot.tearVariant = TEAR_BLOOD; + std::copy(std::begin(DELIRIUM_COLORIZE), std::end(DELIRIUM_COLORIZE), shot.color._colorize); + } + if (shot.flags[TEAR_BURSTSPLIT] && !player->HasCollectible(COLLECTIBLE_TINY_PLANET)) + { + float height = player->tearHeight; + shot.fallingSpeed = height * 0.75f / player->shotSpeed * (23.75f / -height); + shot.fallingAccel = 1.3f; + } + if (player->IsHologram()) shot.color._tint[3] *= HOLOGRAM_ALPHA; + + shot.damage *= multiplier; + shot.scale = std::max(shot.scale, SHOT_SCALE_MIN); + if (variant != HARLEQUIN_BABY && rainbow != 9 && mimic != 7) return shot_spawn(*this, shot, shot.velocity); + + Vector v = shot.velocity; + shot_spawn(*this, shot, vector_make(v.x - v.y * 0.2f, v.x * 0.2f + v.y)); + return shot_spawn(*this, shot, vector_make(v.y * 0.2f + v.x, v.y - v.x * 0.2f)); +} + +// 00633ea0 Baby-Bender's change to a familiar's shot: homing with a purple look (a laser's brighter), turning sideways +// when doubled, and slower, higher and longer when tripled. False without the trinket. +bool Entity_Familiar::apply_baby_bender_tear_params(TearFlags& flags, ColorMod& color, float* height, + float* fallingSpeed, float* range, bool isLaser) +{ + if (!player->HasTrinket(TRINKET_BABY_BENDER)) return false; + + if (!flags[TEAR_HOMING]) + { + flags.set(TEAR_HOMING); + color = isLaser ? BENDER_LASER_COLOR : BENDER_TEAR_COLOR; + } + int multiplier = player->GetTrinketMultiplier(TRINKET_BABY_BENDER); + if (multiplier > 1) flags.set(TEAR_TURN_HORIZONTAL); + if (multiplier > 2) + { + *height += *height; + *fallingSpeed *= 0.5f; + *range += BENDER_RANGE_BONUS; + } + return true; +} + +// 00634000 Applies Baby-Bender to a familiar's tear, keeping it at its height (low in a crawlspace). +bool Entity_Familiar::TryFireTear(Entity_Tear* tear) +{ + if (player->GetTrinketMultiplier(TRINKET_BABY_BENDER) <= 0) return false; + + TearFlags flags = tear->tearFlags; + ColorMod color = tear->sprite.color; + float height = tear->height; + float fallingSpeed = tear->fallingSpeed; + float range = tear->tearRange; + apply_baby_bender_tear_params(flags, color, &height, &fallingSpeed, &range, false); + tear->SetTearFlags(flags); + tear->SetColor(color, -1, 255, false, true); + tear->height = height; + tear->posOffset.y = tear->get_height_offset_y(height); + if (g_game->room->roomType == ROOM_DUNGEON) + { + tear->posOffset.y = CRAWLSPACE_TEAR_OFFSET; + if (height > CRAWLSPACE_TEAR_HEIGHT) tear->height = CRAWLSPACE_TEAR_HEIGHT; + } + tear->fallingSpeed = fallingSpeed; + tear->tearRange = range; + return true; +} + +// A shot of a familiar the Siren charmed turns on the player (Entity::convert_shot_for_enemy_owner 0064bb70, which does +// nothing for any other familiar, so it is only called then). +void Entity_Familiar::shot_owner_convert(Entity* shot) +{ + Entity* owner = player->spawnerEntity; + if (HasEntityFlags(FLAG_CHARM) && owner && Entity::is_enemy_type(owner->type)) convert_shot_for_enemy_owner(shot); +} + +// 00613c20 Robo-Baby's laser, which waits for Entity_Laser::ShootAngle's takeover. +Entity_Laser* Entity_Familiar::fire_robo_baby_laser(const Vector&) +{ + if (player->isDead) return nullptr; + reconstruction_missing("Entity_Familiar::fire_robo_baby_laser 00613c20 " + "(Entity_Laser::ShootAngle 0096f310)"); +} diff --git a/src/game.cpp b/src/game.cpp index 7e57006..f9573a0 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -39,7 +39,6 @@ constexpr int FILTER_LINEAR = 1; constexpr int BLOOM_DURATION_DEFAULT = 30; constexpr int REVIVE_MACHINE_COINS = 10; constexpr float DIZZY_CHANGE_SPEED_DEFAULT = 0.001f; -constexpr int ITEM_OVERLAY_ACTIVE = 2; constexpr int BOSS_RUSH_PAR_TIME = 36000; constexpr int BLUE_WOMB_PAR_TIME = 54000; constexpr float COLOR_CHANNEL_MAX = 255; @@ -47,7 +46,6 @@ constexpr float COLOR_CHANNEL_MAX = 255; constexpr std::array TINT_ATTRIBUTES = {"r", "g", "b", "a"}; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; -constexpr int STAGE_DARK_ROOM = 11; // The fortune generator's xorshift (shift index 35), the start's fade in speed, and the cover an instant fade starts on. constexpr uint32_t FORTUNE_RNG_SHIFT = 35; constexpr float START_FADE_SPEED = 0.04f; @@ -214,8 +212,8 @@ bool Game::load_giantbook_xml(std::string_view path) Data data; int id = GIANTBOOK_ENTRY_COUNT; - itemOverlay._state = 0; - itemOverlay._delay = 0; + itemOverlay.state = ITEM_OVERLAY_INACTIVE; + itemOverlay.delay = 0; data_load(data, path); if (!data.isLoaded) return false; @@ -579,7 +577,6 @@ constexpr float OLD_TV_TIME_SCALE = 0.05f; constexpr float ASCENT_FADE_FRAMES = 90; constexpr uint32_t DEBUG_FLAG_PLAYER_INFO = 1 << 11; constexpr uint32_t DEBUG_FLAG_LUA_MEMORY = 1 << 13; -constexpr int ITEM_OVERLAY_SHOWING = 1; constexpr float PI = std::numbers::pi_v; // Draws a whole surface over the screen in a color. @@ -734,7 +731,7 @@ static void overlays_render(Game& game) if (isFighting) game.deathmatchManager.type->FUN_0042aca0(); if (stageState == STAGE_TRANSITION_OUT || stageState == STAGE_TRANSITION_IN) game.stageTransition.Render(); else graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); - if (game.itemOverlay._state != 0 && game.itemOverlay._state != ITEM_OVERLAY_SHOWING) game.itemOverlay.Render(); + game.itemOverlay.Render(); if (game.bossOverlay._state != 0) reconstruction_missing("Game::Render 006fbc10: BossOverlay's render 00421400"); popups.render_layer(1); @@ -876,7 +873,7 @@ bool Game::IsPaused() if (console.state != CONSOLE_CLOSED && isOffline) return true; return freezeFrames > 0 || gameOver.state != GAME_OVER_HIDDEN || leaderboard.displayState != LEADERBOARD_HIDDEN || - stageTransition.state != 0 || roomTransition.mode != 0 || itemOverlay._state == ITEM_OVERLAY_ACTIVE || + stageTransition.state != 0 || roomTransition.mode != 0 || itemOverlay.state == ITEM_OVERLAY_ACTIVE || (pauseScreen.is_pausing() && isOffline) || g_manager->state != MANAGER_STATE_GAME || genericPrompt.IsActive() || onlineStatsScreen.isActive; } @@ -916,4 +913,3 @@ ChallengeParam& Game::GetChallengeParams() reconstruction_missing("Game::GetChallengeParams 00706940: the daily's params, which classes.h holds as bytes"); return g_manager->GetChallengeParams((int)challenge); } - diff --git a/src/game.h b/src/game.h index 7eec5b3..3c89435 100644 --- a/src/game.h +++ b/src/game.h @@ -1,5 +1,7 @@ #pragma once +#include "item_overlay.h" + #include "anm2.h" #include "boss_pool.h" #include "challenge_params.h" diff --git a/src/game_over.cpp b/src/game_over.cpp index fa98666..a944505 100644 --- a/src/game_over.cpp +++ b/src/game_over.cpp @@ -8,6 +8,7 @@ #include "mod_manager.h" #include "platform.h" #include "render_passes.h" +#include #include #include #include @@ -58,7 +59,6 @@ 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; diff --git a/src/game_restore.cpp b/src/game_restore.cpp index 772bb95..c354fb5 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -25,22 +25,17 @@ constexpr uint32_t FORTUNE_RNG_SHIFT = 35; constexpr uint32_t ITEM_RNG_SHIFT = 35; constexpr uint32_t GLITCH_BABY_SHIFT = 35; constexpr uint32_t ITEM_POOL_SHIFT = 3; -constexpr uint32_t TRINKET_POOL_SHIFT = 2; constexpr uint32_t DEVIL_ANGEL_SHIFT = 2; constexpr uint8_t HOLY_MANTLE_SAVED = 2; constexpr const char* ITEM_POOLS_XML = "itempools.xml"; constexpr uint32_t STAGE_CAVES_I = 3; constexpr uint32_t STAGE_CAVES_II = 4; constexpr uint32_t STAGE_DEPTHS_II = 6; -constexpr uint32_t STAGE_DARK_ROOM = 11; constexpr int DIMENSION_ALTERNATE = 1; -constexpr int LEVEL_STATE_MINESHAFT_ESCAPE = 22; constexpr int MINI_MUSH_STACKS_SECOND = 4; constexpr int MINI_MUSH_STACKS_THIRD = 7; -constexpr int NULLITEM_WAVY_CAP_1 = 71; constexpr int NULLITEM_WAVY_CAP_2 = 72; constexpr int NULLITEM_WAVY_CAP_3 = 73; -constexpr int COLLECTIBLE_WAVY_CAP = 582; constexpr double WAVY_CAP_STACKS_PER_DIZZINESS = 10; constexpr float WAVY_CAP_DIZZINESS_SPEED = 0.001f; constexpr uint32_t ALL_CACHE_FLAGS = 0xffff; diff --git a/src/game_save.cpp b/src/game_save.cpp index f2b2870..8af0403 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -9,11 +9,8 @@ #include constexpr int CHALLENGE_SPEED = 22; -constexpr int ENTITY_CHARGER = 23; constexpr int CHARGER_MY_SHADOW = 1; -constexpr int FAMILIAR_WISP = 206; constexpr int FAMILIAR_UMBILICAL_BABY = 240; -constexpr int FAMILIAR_FORGOTTEN_BODY = 900; constexpr int COLLECTIBLE_VENTRICLE_RAZOR = 396; constexpr int REWIND_DOOR_FRAMES = 15; constexpr int ROOM_REF_MODE_SHIFT = 16; @@ -329,8 +326,8 @@ static void rng_seeds_save(std::vector& rngs, std::vector& seeds) // Umbilical Baby, and a temporary one only when those are saved. static bool is_familiar_saved(Entity_Familiar& familiar, bool isSaveTemporaryFamiliars) { - bool isRazorWisp = familiar.variant == FAMILIAR_WISP && familiar.subtype == COLLECTIBLE_VENTRICLE_RAZOR; - if (familiar.variant == FAMILIAR_FORGOTTEN_BODY || isRazorWisp || familiar.variant == FAMILIAR_UMBILICAL_BABY) + bool isRazorWisp = familiar.variant == Entity_Familiar::WISP && familiar.subtype == COLLECTIBLE_VENTRICLE_RAZOR; + if (familiar.variant == Entity_Familiar::FORGOTTEN_BODY || isRazorWisp || familiar.variant == FAMILIAR_UMBILICAL_BABY) return false; return isSaveTemporaryFamiliars || !familiar.isNotCountedAsFollower; } diff --git a/src/game_transition.cpp b/src/game_transition.cpp index 571e7b6..d06bb7c 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -27,12 +27,10 @@ constexpr int MAZE_SWAP_CHANCE = 5; constexpr int MAZE_SHAKE_FRAMES = 30; constexpr int SOUND_MAZE = 22; constexpr float SOUND_MAZE_VOLUME = 0.5f; -constexpr int SOUND_ERROR_BUZZ = 187; constexpr int SOUND_TELEPORT_UP = 215; constexpr int ONLINE_STAT_ESCAPES = 9; constexpr const char* ANIMATION_TELEPORT_UP = "TeleportUp"; constexpr const char* ANIMATION_OPEN = "Open"; -constexpr uint32_t ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT = 1u << 18; constexpr uint64_t GAME_STATE_BOSSPOOL_SWITCHED = 1ull << 4; constexpr uint64_t GAME_STATE_KEY_FAMILIAR_DOOR_PASSED = 1ull << 49; constexpr int BACKWARDS_FIRST_STAGE = 1; diff --git a/src/game_update.cpp b/src/game_update.cpp index 857a3e5..f41925a 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -33,7 +33,6 @@ constexpr int ASCENT_SHAKE_DIVISOR = 6; constexpr int ASCENT_SHAKE_BASE = 2; constexpr int DEATH_CERTIFICATE_SHAKE = 10; 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 DIMENSION_DEATH_CERTIFICATE = 2; @@ -268,7 +267,7 @@ static bool overlays_update(Game& game) { bool isOffline = !g_manager->netplayManager.is_online(); - if (game.itemOverlay._state == 0) + if (game.itemOverlay.state == ITEM_OVERLAY_INACTIVE) { if (game.genericPrompt.IsActive()) { @@ -281,8 +280,8 @@ static bool overlays_update(Game& game) } if (game.pauseScreen.state != PAUSE_HIDDEN && isOffline) return false; - game.itemOverlay.Update(0); - if (game.itemOverlay._state != ITEM_OVERLAY_PLAYING) return false; + game.itemOverlay.Update(OVERLAY_UPDATE_PLAY); + if (game.itemOverlay.state != ITEM_OVERLAY_ACTIVE) return false; game.hud.PostUpdate(); if (game.pauseScreen.state != PAUSE_HIDDEN) game.pauseScreen.animation_update(); diff --git a/src/grid_entity.cpp b/src/grid_entity.cpp index f889f1b..7b95eef 100644 --- a/src/grid_entity.cpp +++ b/src/grid_entity.cpp @@ -1,4 +1,5 @@ #include "grid_entity.h" +#include "entity_effect.h" #include "game.h" #include "grid_entity_decoration.h" #include "grid_entity_door.h" @@ -23,10 +24,6 @@ #include "seeds.h" #include -// What a pit's output trigger spawns and plays as it fills. -constexpr int EFFECT_POOF01 = 15; -constexpr int SOUND_ROCK_CRUMBLE = 137; - // TNT still standing before its output trigger blows it up. constexpr int TNT_STATE_STANDING_LAST = 3; diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index c6a34d8..f223356 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -13,7 +13,6 @@ constexpr int DOOR_TARGET_MINESHAFT = -101; // The stage of the Blue Womb, the dimension of Downpour's mirror world and of Home's dark closet, and Home's stage. constexpr uint32_t STAGE_BLUE_WOMB = 9; -constexpr uint32_t STAGE_DARK_ROOM = 11; constexpr uint32_t STAGE_VOID = 12; constexpr uint32_t STAGE_HOME = 13; constexpr int DIMENSION_MIRROR = 1; @@ -37,18 +36,11 @@ constexpr float HOME_ALT_TINT[3] = {0.5f, 0.5f, 0.54f}; // Greed mode's exit stays barred until this wave, one more on Greedier. constexpr int GREED_EXIT_WAVE = 10; -// A room the blue map redirects to a blue room. -constexpr uint32_t ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT = 1 << 18; - // The run state bits doors set and read: Mega Satan's door unlocked, and Mom's Heart's exit opened. constexpr uint64_t GAME_STATE_MEGA_SATAN_DOOR_OPENED = 1ull << 49; constexpr uint64_t GAME_STATE_HEART_EXIT_OPENED = 1ull << 52; // The items, trinkets and challenge doors answer to. -constexpr int COLLECTIBLE_PAY_TO_PLAY = 380; -constexpr int TRINKET_SHINY_ROCK = 62; -constexpr int TRINKET_BROKEN_PADLOCK = 136; -constexpr int TRINKET_FLAT_FILE = 151; constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; constexpr int FAMILIAR_KEY_FULL = 236; constexpr int FAMILIAR_STATE_KEY_DOOR = 1; @@ -68,8 +60,6 @@ constexpr int SOUND_METAL_DOOR_CLOSE = 46; constexpr int SOUND_METAL_DOOR_OPEN = 47; constexpr int SOUND_HELLBOSS_GROUNDPOUND = 52; constexpr int SOUND_MEAT_FEET_SLOW = 68; -constexpr int SOUND_UNLOCK = 156; -constexpr int SOUND_SHINYROCK_SHIMMER = 1014; constexpr float GROUNDPOUND_PITCH = 0.33f; // The frames after its spawn a door shows its open or barred animation from the start. @@ -1197,21 +1187,3 @@ bool GridEntity_Door::Destroy(bool, const EntityRef& source) Player_stats_add(&g_game->onlinePlayerStats, ONLINE_STAT_SECRET_DOORS_BOMBED, (Entity_Player*)player, 1); return isBlownOpen; } - -// 0070fb60 Opens the door to an explosion or a key-free opener, cracking secret walls and breaking bars. -bool GridEntity_Door::TryBlowOpen(bool, Entity*) -{ - reconstruction_missing("GridEntity_Door::TryBlowOpen 0070fb60"); -} - -// 00710480 Unlocks the door with a player's key, coins or the golden key. -bool GridEntity_Door::TryUnlock(Entity_Player&, bool) -{ - reconstruction_missing("GridEntity_Door::TryUnlock 00710480"); -} - -// 0070f810 Puffs dust from the wall around the door. -void GridEntity_Door::SpawnDust() -{ - reconstruction_missing("GridEntity_Door::SpawnDust 0070f810"); -} diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index c2a8d8f..8d73e89 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -15,12 +15,9 @@ // 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; diff --git a/src/grid_entity_rock.cpp b/src/grid_entity_rock.cpp index abe2f13..a17198b 100644 --- a/src/grid_entity_rock.cpp +++ b/src/grid_entity_rock.cpp @@ -44,32 +44,24 @@ constexpr uint32_t MIXED_BACKDROP_ODDS = 10; // The Shiny Rock's glint: its period, faster for a stronger rock, the frames it lasts, peaking halfway, and how bright. // The Book of Secrets glows for its effect's last frames. -constexpr int TRINKET_SHINY_ROCK = 62; -constexpr int TRINKET_FLAT_FILE = 151; constexpr int COLLECTIBLE_BOOK_OF_SECRETS = 287; constexpr int COLLECTIBLE_KEEPERS_KIN = 717; -constexpr int SOUND_SHINYROCK_SHIMMER = 1014; constexpr int SHINE_PERIOD = 300; constexpr int SHINE_PERIOD_STRONG = 150; constexpr int SHINE_FRAMES = 11; constexpr int SHINE_PEAK = 5; constexpr float SHINE_OFFSET = 0.3f; constexpr float SECRETS_GLOW_FRAMES = 30; -constexpr uint32_t LEVEL_STATE_DUNGEON_ROCK_BROKEN = 1 << 13; // An event rock's countdown breaks it at this varData. Keeper's Kin lets a spider out one check in so many. constexpr int ROCK_EVENT_COUNTDOWN_END = 10; constexpr int SPIDER_CHECK_FRAMES = 15; constexpr uint32_t SPIDER_ODDS = 100; -constexpr int EFFECT_POOF01 = 15; // A bomb rock's blast, the particles a breaking rock throws, and the worms one in so many rocks hides. constexpr float BOMB_ROCK_DAMAGE = 40; constexpr float BOMB_ROCK_RADIUS = 62; constexpr float ROCK_PARTICLE_SPEED = 5; -constexpr int EFFECT_BOMB_EXPLOSION = 1; -constexpr int EFFECT_ROCK_PARTICLE = 4; -constexpr int EFFECT_WORM = 63; constexpr uint32_t WORM_ODDS = 50; constexpr uint32_t WORM_MAX = 5; constexpr float WORM_DISTANCE = 20; @@ -90,7 +82,6 @@ constexpr int EVENT_SS_ROCKS_DESTROYED = 4; // The break sounds: the alternate rocks' by their kind, the fleshy floors', and the plain one. constexpr int ALT_ROCK_SOUNDS[] = {0, 78, 79, 137, 77, 138}; -constexpr int SOUND_ROCK_CRUMBLE = 137; constexpr int FLESHY_BACKDROPS[] = {10, 11, 12, 13, 34, 43, 44, 48}; // Which alternate rock (urn, mushroom, skull, polyp, bucket) a backdrop shows: @@ -347,7 +338,7 @@ void GridEntity_Rock::Update() bool isGlinting = type == GRID_ROCKT || type == GRID_ROCK_SS; if (!isGlinting) { - int dungeonRock = g_game->levelStateFlags & LEVEL_STATE_DUNGEON_ROCK_BROKEN ? -1 : room.dungeonRockIdx; + int dungeonRock = g_game->levelStateFlags & 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN ? -1 : room.dungeonRockIdx; isGlinting = dungeonRock == gridIndex && type != GRID_ROCKB && type != GRID_PILLAR; } if (isGlinting && state != ROCK_STATE_BROKEN) @@ -684,7 +675,7 @@ bool GridEntity_Rock::TrySpawnLadder() studFinder = &player->GetTrinketRNG(TRINKET_STUD_FINDER); break; } - bool isDone = game.levelStateFlags & LEVEL_STATE_DUNGEON_ROCK_BROKEN; + bool isDone = game.levelStateFlags & 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN; bool isChosen = game.currentRoomIdx >= 0 && (isDone ? -1 : game.room->dungeonRockIdx) == gridIndex; if (!isChosen && (isDone || !studFinder)) return false; if (!isChosen) @@ -696,7 +687,7 @@ bool GridEntity_Rock::TrySpawnLadder() GridEntity* here = game.room->GetGridEntity((uint32_t)gridIndex); if (here && here->collisionClass > COLLISION_NONE) here->collisionClass = COLLISION_NONE; game.room->SpawnGridEntity(gridIndex, GRID_STAIRS, 0, Random(), 0); - game.levelStateFlags |= LEVEL_STATE_DUNGEON_ROCK_BROKEN; + game.levelStateFlags |= 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN; return true; } diff --git a/src/grid_entity_spikes.cpp b/src/grid_entity_spikes.cpp index 79d8380..cf37133 100644 --- a/src/grid_entity_spikes.cpp +++ b/src/grid_entity_spikes.cpp @@ -1,11 +1,10 @@ #include "grid_entity_spikes.h" +#include "entity_player.h" #include "game.h" #include "log.h" #include "room.h" // The items and trinket that keep spikes down, and the variants spikes of the room's own layout have. -constexpr int COLLECTIBLE_SANGUINE_BOND = 692; -constexpr int TRINKET_FLAT_FILE = 151; constexpr uint32_t SPIKES_LAYOUT_VARIANTS = 100; // 0071dfc0 Loads the spikes for the backdrop and starts their timer. diff --git a/src/grid_entity_tnt.cpp b/src/grid_entity_tnt.cpp index af14c6a..63b0f31 100644 --- a/src/grid_entity_tnt.cpp +++ b/src/grid_entity_tnt.cpp @@ -14,8 +14,6 @@ constexpr int TNT_FUSE = 3; constexpr float TNT_DAMAGE = 100; constexpr float TNT_RADIUS = 75; constexpr uint64_t DAMAGE_TNT = 1ull << 12; -constexpr int EFFECT_BOMB_EXPLOSION = 1; -constexpr int EFFECT_WOOD_PARTICLE = 27; constexpr int WOOD_COUNT_MIN = 2; constexpr uint32_t WOOD_COUNT_EXTRA = 3; constexpr float WOOD_SPEED_MIN = 2; diff --git a/src/grid_entity_trap_door.cpp b/src/grid_entity_trap_door.cpp index 54c0212..0887257 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -1,5 +1,6 @@ #include "grid_entity_trap_door.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_list.h" #include "entity_player.h" #include "game.h" @@ -38,9 +39,6 @@ constexpr int STAGE_DEPTHS_II = 6; constexpr int STAGE_CAVES_I = 3; constexpr int STAGE_LAST_CHAPTER = 10; -constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; -constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; -constexpr int COLLECTIBLE_KNIFE_PIECE_2 = 627; constexpr int GAME_STATE_BACKWARDS_PATH_INIT = 47; // Mother's boss room in the special rooms. @@ -54,7 +52,6 @@ constexpr float PLAYER_CLEARANCE = 50; constexpr float REACH = 21; constexpr float MOTHER_HOLE_REACH = 34; constexpr float FORGOTTEN_BODY_RADIUS = 20; -constexpr int FAMILIAR_FORGOTTEN_BODY = 900; constexpr int SOUND_SHOVEL_HOLE_OPEN = 917; constexpr int SOUND_TRAP_DOOR_LEVEL = 1052; @@ -166,7 +163,7 @@ static bool is_forgotten_body_on(const Vector& position) float reach = FORGOTTEN_BODY_RADIUS + entity->size; bool isNear = vector_length_squared(vector_sub(entity->pos, position)) < reach * reach; if (isNear && !entity->HasEntityFlags(FLAG_NO_QUERY) && entity->type == ENTITY_FAMILIAR && - entity->variant == FAMILIAR_FORGOTTEN_BODY) + entity->variant == Entity_Familiar::FORGOTTEN_BODY) return true; } return false; diff --git a/src/info_display.cpp b/src/info_display.cpp index ec7bbb2..fa53ff9 100644 --- a/src/info_display.cpp +++ b/src/info_display.cpp @@ -9,7 +9,6 @@ #include constexpr std::string_view DOCUMENT_TAG = "#document"; -constexpr uint32_t PILL_HORSE_FLAG = 0x800; constexpr int RED_HEARTS_ALL = 24; // The ids load_xml lists from the item config before reading info_display.xml. @@ -20,8 +19,6 @@ constexpr int DEFAULT_PILL_COUNT = 50; // Necromancer's items, which count toward it without a tag. constexpr int PLAYER_FORM_NECROMANCER = 15; -constexpr int COLLECTIBLE_NECRONOMICON = 35; -constexpr int COLLECTIBLE_MISSING_PAGE_2 = 262; // A group of info_display.xml: its element names and the kind of entry it fills. struct InfoDisplayGroup diff --git a/src/item_config.cpp b/src/item_config.cpp index fe838be..ae9f197 100644 --- a/src/item_config.cpp +++ b/src/item_config.cpp @@ -1,5 +1,6 @@ #include "item_config.h" #include "data.h" +#include "entity_player.h" #include "game.h" #include "log.h" #include "manager.h" @@ -32,7 +33,6 @@ constexpr char EXTRA_WISP_PREFIX = 's'; // Wisp ids from this on name extra wisp configs, counted from it. constexpr int EXTRA_WISP_ID_BASE = 0x10000; // Trinket ids carry the golden flag above this mask. -constexpr uint32_t TRINKET_ID_MASK = 0x7fff; constexpr int TEAR_FLAG_COUNT = 128; constexpr int LOCUST_FLAG_MASK = 31; constexpr float COLOR_CHANNEL_MAX = 255; @@ -40,22 +40,10 @@ constexpr float COLOR_CHANNEL_MAX = 255; constexpr int SPECIAL_CHARGE_SEGMENTS_LAST = 12; // Ids and values the availability and charge rules name. -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; constexpr int CARD_SUICIDE_KING = 46; -constexpr int PLAYER_THELOST = 10; -constexpr int PLAYER_KEEPER = 14; -constexpr int PLAYER_JACOB = 19; -constexpr int PLAYER_THELOST_B = 31; -constexpr int PLAYER_KEEPER_B = 33; constexpr unsigned int CHALLENGE_ONANS_STREAK = 29; -constexpr unsigned int CHALLENGE_PICA_RUN = 41; constexpr unsigned int SPECIAL_DAILY_BANNED_SET = 52; constexpr uint32_t STAGE_VANISHING_TWIN_LAST = 6; constexpr int QUALITY_LOW_LAST = 1; diff --git a/src/item_config.h b/src/item_config.h index f803890..e179224 100644 --- a/src/item_config.h +++ b/src/item_config.h @@ -161,6 +161,10 @@ using ColorPresets = std::map>; struct ItemConfig_Item; struct ModEntry; +// A pill subtype's color bits and its horse pill bit. +constexpr int PILL_COLOR_MASK = 0x7ff; +constexpr uint32_t PILL_HORSE_FLAG = 0x800; + // A costume an item, form or null item puts on the player: its .anm2 and how it draws over the others. // Assignment (00728710) is the default. struct ItemConfig_Costume diff --git a/src/item_overlay.cpp b/src/item_overlay.cpp new file mode 100644 index 0000000..2c8c1bb --- /dev/null +++ b/src/item_overlay.cpp @@ -0,0 +1,243 @@ +#include "item_overlay.h" +#include "entity_player.h" +#include "game.h" +#include "kage_graphics.h" +#include "level.h" +#include "log.h" +#include "manager.h" +#include "render_passes.h" +#include "room.h" +#include + +constexpr int SOUND_STATIC = 81; +constexpr int SLEEP_SOUL_HEARTS = 6; +constexpr int EVENT_COUNTER_SLEEPS = 202; +constexpr const char* EVENT_SOUND = "Sound"; +constexpr const char* EVENT_SLEEP_FILL_HP = "SleepFillHP"; +constexpr const char* EVENT_TRANSITION = "Transition"; +constexpr const char* EVENT_STATIC = "Static"; +constexpr const char* ANIMATION_TRANSFORM = "Transform"; + +// Home's stage and room: the bedroom that turns into the night of Dogma, and the stage bar icon it takes. +constexpr int STAGE_HOME = 13; +constexpr int STAGE_ID_HOME = 35; +constexpr int HOME_BEDROOM_SUBTYPE = 2; +constexpr int STAGE_ICON_HOME_GREED = 18; + +// Mega Mush's transformation: the dim over the screen, and where the player shows on it, nearer the middle. +constexpr float MEGA_MUSH_DIM = 0.4f; +constexpr float MEGA_MUSH_WIDTH = 338; +constexpr float MEGA_MUSH_HEIGHT = 182; +constexpr float MEGA_MUSH_ORIGIN_X = 60; +constexpr float MEGA_MUSH_ORIGIN_Y = 140; +constexpr float MEGA_MUSH_SCALE = 0.65f; + +// A sound of Mega Mush's transformation on one of its frames. +struct TransformSound +{ + int frame; + int sound; + int frameDelay; + float pitch; +}; + +constexpr TransformSound TRANSFORM_SOUNDS[] = {{1, SOUND_VAMP_GULP, 2, 1}, + {6, SOUND_THUMBSUP, 1, 0.8f}, + {11, SOUND_THUMBSUP, 1, 1}, + {16, SOUND_THUMBSUP, 1, 1.2f}}; + +// One step of an overlay sprite: a frame, or its animation's last frame when finishing. +static void sprite_step(ANM2& overlay, OverlayUpdate mode) +{ + if (mode == OVERLAY_UPDATE_PLAY) + overlay.Update(); + else if (overlay.animState.animData) + overlay.animState.AdvancePosition(overlay.animState.animData->length - 1); +} + +// Whether an overlay sprite's animation still plays. +static bool is_sprite_playing(const ANM2& overlay) +{ + return overlay.animState.animData && overlay.animState.isPlaying; +} + +// A sound at a frame delay and pitch, after the seed's fart override. +static void overlay_sound_play(int sound, int frameDelay, float pitch) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = frameDelay, .pitch = pitch}); +} + +// Sleeping's healing: each player but Tainted Soul fills its red hearts, or takes three soul hearts without heart +// containers, with a power up sound unless finishing. The game counts the sleep. +static void sleep_heal(OverlayUpdate mode) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->playerType == PLAYER_THESOUL_B) + continue; + + HealthType health = player->GetHealthType(); + bool isRedOnly = health == HEALTH_SOUL || health == HEALTH_NO_HEALTH; + int heartLimit = isRedOnly ? player->maxHearts : player->maxHearts + player->boneHearts * 2; + if (heartLimit <= 0) + player->AddSoulHearts(SLEEP_SOUL_HEARTS, false); + else if (player->redHearts < heartLimit) + player->SetFullHearts(); + else + continue; + + if (mode == OVERLAY_UPDATE_PLAY) + sound_play(SOUND_POWERUP1); + } + g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_SLEEPS, 1); +} + +// The nightmare of the bed in Home: its transition queues the nightmare (Dogma's outside Greed mode) unless finishing, +// and Home's bedroom turns to night. Its static plays the static sound and the room's music again. +static void sleep_nightmare_update(ANM2& overlay, OverlayUpdate mode) +{ + Game& game = *g_game; + Manager& manager = *g_manager; + bool isPlaying = mode == OVERLAY_UPDATE_PLAY; + + if (overlay.animState.IsEventTriggered(EVENT_TRANSITION)) + { + if (isPlaying) + { + bool isGreed = game.IsGreedMode(); + manager.nightmareScene.isDogma = !isGreed; + manager.nightmareScene.stageIcons[STAGE_HOME] = isGreed ? STAGE_ICON_HOME_GREED : STAGE_ICON_HOME; + manager.isNightmarePending = true; + manager.pendingNightmareId = 1; + } + + RoomConfig_Room* room = game.room->descriptor->data; + bool isBedroom = room && room->stageId == STAGE_ID_HOME && room->subtype == HOME_BEDROOM_SUBTYPE; + if (isBedroom && game.stage == STAGE_HOME && game.stageType == STAGETYPE_ORIGINAL) + { + game.SetStage(STAGE_HOME, STAGETYPE_WOTL); + reconstruction_missing("Room::reload_backdrop 007f2070"); + } + return; + } + if (!overlay.animState.IsEventTriggered(EVENT_STATIC) || !isPlaying) + return; + + sound_play(SOUND_STATIC); + game.room->PlayMusic(); + manager.musicManager.EnableLayer(0, LAYER_INSTANT); +} + +// 009ad210 Shows a giant book: its .anm2 with the entry's spritesheet and recolored layers, playing its animation, at +// once or after a delay. An entry without one (Mega Mush's) leaves the sprite empty. +void ItemOverlay::Show(int overlayId, int showDelay, Entity_Player* shown) +{ + if ((unsigned)overlayId >= GIANTBOOK_ENTRY_COUNT) + return; + + const GiantbookEntry& entry = g_game->giantbookEntries[overlayId]; + if (entry.anm2Path.empty()) + sprite.Reset(); + else + { + sprite.Load(entry.anm2Path, GRAPHICS_DEFER); + if (!entry.gfxPath.empty()) + sprite.ReplaceSpritesheet(0, entry.gfxPath); + sprite.LoadGraphics(); + } + overlayID = overlayId; + player = shown; + + if (sprite.isLoaded) + { + for (const GiantbookLayer& recolor : entry.layers) + for (LayerState& layer : sprite.layerStates) + if (layer.layerData && layer.layerData->name == recolor.name) + layer.color = recolor.color; + sprite.Play(entry.animation); + } + state = showDelay != 0 ? ITEM_OVERLAY_WAITING : ITEM_OVERLAY_ACTIVE; + delay = showDelay; +} + +// 009aca90 Counts down the delay, then plays the overlay: Mega Mush's transformation with its sounds (the player shows +// again once it ends), or the giant book until its animation stops, with the clicker's sound, sleeping's healing +// and the nightmare of the bed in Home. Finishing skips the animations to their end and the sounds. +void ItemOverlay::Update(OverlayUpdate mode) +{ + if (state == ITEM_OVERLAY_WAITING) + { + if (--delay < 1) + state = ITEM_OVERLAY_ACTIVE; + return; + } + if (state == ITEM_OVERLAY_INACTIVE) + return; + + bool isPlaying = mode == OVERLAY_UPDATE_PLAY; + if (megaMushPlayerSprite.isLoaded) + { + sprite_step(megaMushPlayerSprite, mode); + if (player && megaMushPlayerSprite.IsPlaying(ANIMATION_TRANSFORM) && isPlaying) + { + int frame = megaMushPlayerSprite.GetFrame(); + for (const TransformSound& sound : TRANSFORM_SOUNDS) + if (sound.frame == frame) + overlay_sound_play(sound.sound, sound.frameDelay, sound.pitch); + } + } + + if (!sprite.isLoaded) + { + if (is_sprite_playing(megaMushPlayerSprite)) + return; + if (player) + player->isVisible = true; + state = ITEM_OVERLAY_INACTIVE; + return; + } + + if (!is_sprite_playing(sprite)) + state = ITEM_OVERLAY_INACTIVE; + sprite_step(sprite, mode); + if (!sprite.animState.animData) + return; + + if (sprite.animState.IsEventTriggered(EVENT_SOUND) && overlayID == GIANTBOOK_CLICKER) + sound_play(SOUND_STATIC); + if (sprite.animState.IsEventTriggered(EVENT_SLEEP_FILL_HP)) + sleep_heal(mode); + if (overlayID == GIANTBOOK_SLEEP_NIGHTMARE) + sleep_nightmare_update(sprite, mode); +} + +// 009acfe0 Draws the playing overlay: the giant book in the middle of the screen, or for Mega Mush a dim over the +// screen with the player's transformation, nearer the middle than the player stands. +void ItemOverlay::Render() +{ + if (state == ITEM_OVERLAY_INACTIVE || state == ITEM_OVERLAY_WAITING) + return; + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Vector screen = vector_make(g_screenWidth, g_screenHeight); + if (sprite.isLoaded) + sprite.Render({.position = vector_make(screen.x * 0.5f, screen.y * 0.5f)}); + else if (overlayID == GIANTBOOK_MEGA_MUSH) + { + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + render_color_shader_pass(KAGE::Graphics::color_quad_rect({}, screen, kcolor_rgba(0, 0, 0, MEGA_MUSH_DIM))); + if (megaMushPlayerSprite.isLoaded && player) + { + float pixelScale = g_displayPixelRatio * g_screenPointScale; + Vector scroll = g_game->room->renderScrollOffset; + auto snap = [&](float value) { + return std::floor(value * pixelScale + 0.5f) / pixelScale; + }; + float x = (screen.x - MEGA_MUSH_WIDTH) * 0.5f + (player->pos.x - MEGA_MUSH_ORIGIN_X) * MEGA_MUSH_SCALE; + float y = (screen.y - MEGA_MUSH_HEIGHT) * 0.5f + (player->pos.y - MEGA_MUSH_ORIGIN_Y) * MEGA_MUSH_SCALE; + megaMushPlayerSprite.Render({.position = vector_make(snap(x) + scroll.x, snap(y) + scroll.y)}); + } + } + graphics.shader_default_set(); +} diff --git a/src/item_overlay.h b/src/item_overlay.h new file mode 100644 index 0000000..957fcc6 --- /dev/null +++ b/src/item_overlay.h @@ -0,0 +1,44 @@ +#pragma once + +#include "anm2.h" +#include "entity.h" + +// REPENTOGON's eItemOverlayState: hidden, waiting out its delay, or playing. +enum ItemOverlayState : int +{ + ITEM_OVERLAY_INACTIVE, + ITEM_OVERLAY_WAITING, + ITEM_OVERLAY_ACTIVE +}; + +// How ItemOverlay::Update steps: one frame, or straight to the animations' last frames when the game exits. +enum OverlayUpdate +{ + OVERLAY_UPDATE_PLAY, + OVERLAY_UPDATE_FINISH +}; + +// The giant book overlays of giantbook.xml (g_game->itemOverlay) that do more than play. +enum GiantbookOverlay : int +{ + GIANTBOOK_CLICKER = 39, + GIANTBOOK_SLEEP_NIGHTMARE = 44, + GIANTBOOK_MEGA_MUSH = 45 +}; + +// Destruction (009abd80) is the default. +// The full screen overlay an item or pickup plays over the game (REPENTOGON's ItemOverlay): a giant book of +// giantbook.xml in the middle of the screen, or Mega Mush's transformation of the player over a dimmed screen. +struct ItemOverlay +{ + ANM2 megaMushPlayerSprite; + ANM2 sprite; + EntityPtr player; + ItemOverlayState state = ITEM_OVERLAY_INACTIVE; + int delay = 0; + int overlayID = 0; + + void Show(int overlayId, int showDelay, Entity_Player* shown); + void Update(OverlayUpdate mode); + void Render(); +}; diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index 740ea8f..c8002ea 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -1,7 +1,9 @@ #include "item_pickup.h" #include "entity_config.h" +#include "entity_effect.h" #include "hud.h" #include "entity_pickup.h" +#include "active_items.h" #include "entity_player.h" #include "game.h" #include "grid_entity.h" @@ -9,33 +11,27 @@ #include "log.h" #include "manager.h" #include "room.h" +#include "room_grid.h" +#include "room_special.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 float RESTOCK_PEDESTAL_STEP = 10; +constexpr int RESTOCK_PEDESTAL_WAIT = 20; 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; @@ -69,15 +65,12 @@ 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_BAND_AID_PICK_UP = 169; 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; @@ -150,9 +143,10 @@ 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}) + for (int quest : std::initializer_list{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; } @@ -370,8 +364,8 @@ bool Entity_Pickup::is_collectible_refused(Entity_Player& player) } // 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. +// and name play, the player lifts it in the pedestal's sprite and queues it to be added, and the pedestal empties, or +// takes the active it was exchanged for. Whether it was taken. bool Entity_Pickup::collectible_collect(Entity_Player& player) { Game& game = *g_game; @@ -418,8 +412,8 @@ bool Entity_Pickup::collectible_collect(Entity_Player& player) 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)) + bool isExchanged = item->type == ITEM_ACTIVE && active_pedestal_swap(*this, player); + if (item->type != ITEM_ACTIVE && 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"); @@ -429,13 +423,27 @@ bool Entity_Pickup::collectible_collect(Entity_Player& player) 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(); + if (isExchanged) + { + isTouched = true; + sprite.Play("Idle"); + if (altPedestalANM2.isLoaded) altPedestalANM2.Play("Idle"); + } + else + { + 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"); + bool isRestocked = game.playerManager.AnyoneHasCollectible(COLLECTIBLE_RESTOCK) || game.IsGreedMode(); + if (price == 0 || !isRestocked || game.room->roomType != ROOM_SHOP) return true; + + room_restock_trigger(*game.room, game.room->GetGridIndex(pos), shopItemId); + pos = room_free_pickup_position_find({pos, RESTOCK_PEDESTAL_STEP}); + targetPosition = pos; + wait = RESTOCK_PEDESTAL_WAIT; return true; } @@ -455,7 +463,7 @@ void Entity_Pickup::collectible_sound_play() 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; + sound = subtype == COLLECTIBLE_SUPER_BANDAGE ? SOUND_BAND_AID_PICK_UP : SOUND_1UP; play.frameDelay = ONE_UP_FRAME_DELAY; } else diff --git a/src/item_pool.cpp b/src/item_pool.cpp index da7a59d..5852644 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -50,7 +50,6 @@ constexpr std::array GREED_ROOM_POOLS = [] { constexpr uint32_t POOL_SHIFT = 35; constexpr uint32_t ITEM_POOL_SHIFT = 3; -constexpr uint32_t TRINKET_POOL_SHIFT = 2; constexpr uint32_t CHAOS_SHIFT = 22; constexpr uint32_t DRAW_SHIFT = 4; constexpr uint32_t DAILY_SHIFT = 2; @@ -79,22 +78,10 @@ constexpr int BOSS_THE_FALLEN = 23; constexpr int STAGE_HOME = 35; constexpr int HOME_CHEST_SUBTYPE = 2; -constexpr int COLLECTIBLE_BREAKFAST = 25; constexpr int COLLECTIBLE_ROTTEN_MEAT = 26; -constexpr int COLLECTIBLE_BIBLE = 33; constexpr int COLLECTIBLE_ROSARY = 72; -constexpr int COLLECTIBLE_PHD = 75; -constexpr int COLLECTIBLE_PYROMANIAC = 223; constexpr int COLLECTIBLE_VIRGO = 303; -constexpr int COLLECTIBLE_HOST_HAT = 375; constexpr int COLLECTIBLE_CHAOS = 402; -constexpr int COLLECTIBLE_APPLE = 443; -constexpr int COLLECTIBLE_MAGIC_SKIN = 642; -constexpr int COLLECTIBLE_FALSE_PHD = 654; -constexpr int COLLECTIBLE_TMTRAINER = 721; -constexpr int TRINKET_ROSARY_BEAD = 7; -constexpr int TRINKET_NO = 88; -constexpr int TRINKET_PERFECTION = 145; constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; constexpr int ACHIEVEMENT_GOLDEN_TRINKETS = 617; constexpr int ACHIEVEMENT_GOLD_PILLS = 603; @@ -119,7 +106,6 @@ constexpr int DAILY_TREASURE_RANDOM_PASSIVES = 20; constexpr int DAILY_TREASURE_FOUR_ITEMS[] = {334, 335, 333, 331}; constexpr int ONANS_STREAK_BANNED[] = {68, 118, 329, 52, 168, 114, 395, 394, 55, 87, 229}; -constexpr int PILL_COLOR_MASK = 0x7ff; constexpr int PILL_HORSE = 0x800; constexpr int PILL_COLORS = 13; constexpr int PILL_GOLD = 14; diff --git a/src/kage_sound.cpp b/src/kage_sound.cpp index 8313c90..e6b0edb 100644 --- a/src/kage_sound.cpp +++ b/src/kage_sound.cpp @@ -280,14 +280,17 @@ void Manager::voice_start(SoundSource& source) SDL_UnlockAudioStream(output); } -// (00a7d790) Takes a source off its voice. +// (00a7d790) Takes a source off its voice. The voice is read under the lock, as the audio thread frees ended ones. void Manager::voice_stop(SoundSource& source) { - if (!output || source.voice < 0) return; + if (!output) return; SDL_LockAudioStream(output); - voices[source.voice].source = nullptr; - source.voice = -1; - source.isPaused = false; + if (source.voice >= 0) + { + voices[source.voice].source = nullptr; + source.voice = -1; + source.isPaused = false; + } SDL_UnlockAudioStream(output); } diff --git a/src/level.cpp b/src/level.cpp index c051793..2bc05c3 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -58,7 +58,6 @@ constexpr int STAGE_ID_CHEST = 17; constexpr int STAGE_ID_ASHPIT = 30; constexpr int STAGE_ID_MAUSOLEUM = 31; constexpr int STAGE_ID_BACKWARDS = 36; -constexpr int STAGE_ID_BLUE_WOMB = 13; constexpr int STAGE_ID_MINES = 29; constexpr int STAGE_ID_CORPSE = 33; constexpr int STAGE_ID_DOWNPOUR = 27; @@ -71,9 +70,7 @@ constexpr uint32_t CHALLENGE_XXXXXXXXL = 21; constexpr int ALT_PATH_LAYER_FIRST = 3; constexpr int STAGE_ID_HOME = 35; constexpr int DIMENSION_MINESHAFT = 2; -constexpr int ENEMY_TYPE_FIRST = 10; constexpr int ENEMY_TYPE_LAST = 999; -constexpr int COLLECTIBLE_BERSERK = 704; // The enemies' health that makes a room's music intense, growing with the floor (a Greed floor counting as two). constexpr float INTENSE_HEALTH_BASE = 40; @@ -122,26 +119,15 @@ constexpr int ACHIEVEMENT_PLANETARIUMS = 406; constexpr int EVENT_COUNTER_SUPER_SINS_A = 24; constexpr int EVENT_COUNTER_SUPER_SINS_B = 25; constexpr int EVENT_COUNTER_CURSE_ODDS = 11; -constexpr int COLLECTIBLE_BLACK_CANDLE = 260; constexpr int COLLECTIBLE_XRAY_VISION = 76; -constexpr int COLLECTIBLE_SPELUNKER_HAT = 91; constexpr int COLLECTIBLE_CRYSTAL_BALL = 158; constexpr int COLLECTIBLE_MAGIC_8_BALL = 194; -constexpr int COLLECTIBLE_MORE_OPTIONS = 414; -constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; constexpr int COLLECTIBLE_MOMS_SHOVEL = 552; -constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; -constexpr int COLLECTIBLE_SAUSAGE = 669; constexpr int TRINKET_GOLDEN_HORSE_SHOE = 82; -constexpr int TRINKET_RIB_OF_GREED = 84; constexpr int TRINKET_FRAGMENTED_CARD = 102; constexpr int TRINKET_SILVER_DOLLAR = 110; -constexpr int TRINKET_BLOODY_CROWN = 111; constexpr int TRINKET_PAY_TO_WIN = 112; constexpr int TRINKET_TELESCOPE_LENS = 152; -constexpr int TRINKET_HOLY_CROWN = 155; -constexpr int TRINKET_WICKED_CROWN = 161; -constexpr int TRINKET_BROKEN_GLASSES = 187; constexpr int COLLECTIBLE_VOODOO_HEAD = 599; constexpr int TRINKET_MYOSOTIS = 137; constexpr int TRINKET_DEVILS_CROWN = 146; @@ -2852,12 +2838,6 @@ bool Level::MakeRedRoomDoor(int, int) reconstruction_missing("Level::MakeRedRoomDoor 0074d010"); } -// 0074a1b0 Opens a hidden door. -void Level::UncoverHiddenDoor(int, int) -{ - reconstruction_missing("Level::UncoverHiddenDoor 0074a1b0"); -} - // 0074d780 Adds a second boss room. bool Level::TryInitializeExtraBossRoom(uint32_t) { @@ -3001,7 +2981,7 @@ bool Level::UpdateBackwardsPathStages() for (Entity* entity : room->entityList.updateEL) { bool isCounted = (game.deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || - (entity->type >= ENEMY_TYPE_FIRST && entity->type <= ENEMY_TYPE_LAST); + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENEMY_TYPE_LAST); if (isCounted && entity->CanShutDoors() && !entity->isDead && !entity->HasEntityFlags(FLAG_NO_TARGET)) health += entity->health; } diff --git a/src/level.h b/src/level.h index 8835794..8861f62 100644 --- a/src/level.h +++ b/src/level.h @@ -59,7 +59,22 @@ enum OffMapRoom : int // The floor's own state flags (Lua's LevelStateFlag) the curated code reads, by bit. enum LevelStateFlag : int { + LEVEL_STATE_BUM_KILLED = 0, LEVEL_STATE_REDHEART_DAMAGED = 2, + LEVEL_STATE_DAMAGED = 5, + LEVEL_STATE_SHOPKEEPER_KILLED = 6, + LEVEL_STATE_GREED_MONSTRO_SPAWNED = 12, + LEVEL_STATE_DUNGEON_ROCK_BROKEN = 13, + LEVEL_STATE_MAMA_MEGA = 14, + LEVEL_STATE_SHOVEL_QUEST_TRIGGERED = 16, + LEVEL_STATE_SATANIC_BIBLE_USED = 17, + LEVEL_STATE_SOL = 18, + LEVEL_STATE_LEVEL_START_TRIGGERED = 19, + LEVEL_STATE_VOID_DOOR_DISABLED = 21, + LEVEL_STATE_MINESHAFT_ESCAPE = 22, + LEVEL_STATE_MIRROR_BROKEN = 23, + LEVEL_STATE_BROKEN_WATCH_SLOW = 24, + LEVEL_STATE_BROKEN_WATCH_FAST = 25, LEVEL_STATE_LAST = 25 }; @@ -85,6 +100,11 @@ enum StageType : uint32_t STAGETYPE_REPENTANCE_B }; +// Home's night stage type, the Dark Room's stage and the Blue Womb's stage id. +constexpr int STAGE_TYPE_HOME_NIGHT = 1; +constexpr int STAGE_DARK_ROOM = 11; +constexpr int STAGE_ID_BLUE_WOMB = 13; + // What get_stage_display_name names: a stage and its type, the curses (a labyrinth's XL), the endless basement's // numeral, dyslexia's scrambling, and the mode to number it in (the game's by default). struct StageNameQuery diff --git a/src/level_stage.cpp b/src/level_stage.cpp index 471ce45..a7d2f16 100644 --- a/src/level_stage.cpp +++ b/src/level_stage.cpp @@ -1,3 +1,4 @@ +#include "entity_player.h" #include "game.h" #include "log.h" #include "manager.h" @@ -15,7 +16,6 @@ constexpr int STAGE_WOMB_I = 7; constexpr int STAGE_WOMB_II = 8; constexpr int STAGE_BLUE_WOMB = 9; constexpr int STAGE_SHEOL = 10; -constexpr int STAGE_DARK_ROOM = 11; constexpr int STAGE_VOID = 12; constexpr int STAGE_HOME = 13; constexpr int STAGE_GREED_SHOP = 7; @@ -26,10 +26,6 @@ constexpr int GRID_ROOM_BLUE_WOMB = -8; constexpr int GRID_ROOM_THE_VOID = -9; constexpr int GRID_ROOM_GENESIS = -12; -constexpr uint32_t CHALLENGE_BACKASSWARDS = 31; -constexpr uint32_t CHALLENGE_RED_REDEMPTION = 44; -constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; -constexpr int COLLECTIBLE_KNIFE_PIECE_2 = 627; constexpr uint32_t AFTERBIRTH_STAGE_ODDS = 3; constexpr uint32_t WOTL_SEED_BIT = 1; constexpr uint32_t REPENTANCE_B_SEED_BIT = 2; diff --git a/src/manager.cpp b/src/manager.cpp index 56dfb04..091d1cf 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -189,7 +189,6 @@ constexpr int CURSOR_VISIBLE_FRAMES = 300; constexpr const char* CURSOR_CLICKED_ANIMATION = "Clicked"; constexpr int SCREENSHOT_KEY = 298; constexpr const char* SCREENSHOTS_FOLDER = "screenshots"; -constexpr int MUSIC_TITLE_REPENTANCE = 63; // The stage bar's icon for a stage not reached. constexpr int STAGE_ICON_EMPTY = 17; // The rerun unlock, which keeps a slot's last run to play again. @@ -203,7 +202,6 @@ constexpr const char* LOAD_IMAGE_PATHS[] = {"gfx/ui/loadimages/loadimages-%03u.p constexpr const char* LOAD_IMAGE_GREED_PATHS[] = {"gfx/ui/loadimages/greedmode/loadimages-g%03u.png", "gfx/ui/loadimages/greedmode/loadimages-g%03u_2.png"}; // The fart sounds seed's farts: the plain one, and one in twenty times the gurgling one, drawn from their own xorshift. -constexpr int SOUND_FART = 37; constexpr int SOUND_FART_GURG = 301; constexpr uint32_t FART_GURG_CHANCE = 20; constexpr uint32_t FART_RNG_SEED = 0x69696969; diff --git a/src/menu_bestiary.cpp b/src/menu_bestiary.cpp index 83d16ea..9996324 100644 --- a/src/menu_bestiary.cpp +++ b/src/menu_bestiary.cpp @@ -31,7 +31,6 @@ constexpr int DIARY_BOSS_LAYER = 3; constexpr int DIARY_ENEMY_LAYER = 5; constexpr int UNKNOWN_FRAME = 152; constexpr int ANGEL_VARIANT_FALLEN = 1; -constexpr int ENTITY_DOGMA = 950; constexpr unsigned int DOGMA_RENDER_FLAGS = ANIM_RENDER_STATIC | ANIM_RENDER_IGNORE_GAME_TIME; constexpr float NAME_WIDTH = 200; constexpr float DETAIL_TEXT_SCALE = 0.5f; diff --git a/src/menu_character.cpp b/src/menu_character.cpp index 386147c..c7c1b06 100644 --- a/src/menu_character.cpp +++ b/src/menu_character.cpp @@ -122,7 +122,6 @@ constexpr int EVENT_EDEN_TOKENS = 21; constexpr int EVENT_STREAK_COUNTER = 22; constexpr int EVENT_NEGATIVE_STREAK_COUNTER = 113; constexpr int ACHIEVEMENT_GREEDIER = 341; -constexpr int SOUND_ERROR_BUZZ = 187; constexpr int SOUND_CHARACTER_SELECT_LEFT = 194; constexpr int SOUND_CHARACTER_SELECT_RIGHT = 195; constexpr int SOUND_MENU_FLIP_LIGHT = 569; diff --git a/src/menu_collection.cpp b/src/menu_collection.cpp index 4872bbc..f5dd3d1 100644 --- a/src/menu_collection.cpp +++ b/src/menu_collection.cpp @@ -1,4 +1,5 @@ #include "menu_collection.h" +#include "entity_player.h" #include "manager.h" #include "menu_manager.h" #include "render_passes.h" @@ -27,7 +28,6 @@ constexpr int UNSEEN_FRAME = 2; constexpr int BULLET_NULL = 0; constexpr int BIG_ICON_NULL = 1; constexpr int COLLECTIBLE_NONE = 0; -constexpr int COLLECTIBLE_DOGMA = 633; constexpr int DOGMA_PULSE_MASK = 0xff; constexpr float DOGMA_PULSE_SCALE = 1.0f / 256; constexpr float ICON_SIZE = 16; diff --git a/src/menu_custom_challenge.cpp b/src/menu_custom_challenge.cpp index 83f35ed..404990a 100644 --- a/src/menu_custom_challenge.cpp +++ b/src/menu_custom_challenge.cpp @@ -11,7 +11,6 @@ constexpr const char* ANIMATION_CURSOR = "Cursor"; constexpr const char* ENTRY_FORMAT = "{}.{}"; constexpr const char* PIECE_FORMAT = "Piece{}"; constexpr uint32_t BLACK_ARGB = 0xff000000; -constexpr int SOUND_ERROR_BUZZ = 187; constexpr int SOUND_DELAY = 2; constexpr int FIRST_MOD_CHALLENGE = CHALLENGE_COUNT; constexpr float CHALLENGE_VIEW_Y = -216; diff --git a/src/menu_cutscenes.cpp b/src/menu_cutscenes.cpp index 42d41b5..baffaa8 100644 --- a/src/menu_cutscenes.cpp +++ b/src/menu_cutscenes.cpp @@ -8,7 +8,6 @@ constexpr ColorMod UNSEEN_COLOR = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int CURSOR_LAYER = 25; constexpr int CUTSCENE_SLOTS = 24; constexpr int CUTSCENE_ROWS = 6; -constexpr int SOUND_ERROR_BUZZ = 187; constexpr int SOUND_DELAY = 2; // A slot of the page: the sprite layer drawing it and the cutscene it plays. diff --git a/src/menu_key_config.cpp b/src/menu_key_config.cpp index d66a41d..5adaeb1 100644 --- a/src/menu_key_config.cpp +++ b/src/menu_key_config.cpp @@ -13,7 +13,6 @@ constexpr int KEYBOARD_ID = 0; constexpr int RESET_ROW = 19; constexpr int SLOT_PRIMARY = 0; constexpr int SLOT_SECONDARY = 1; -constexpr int SOUND_ERROR_BUZZ = 187; constexpr int SOUND_DELAY = 2; constexpr int SCROLL_TOP_ROW = 2; constexpr float VIEW_TOP = -1890; diff --git a/src/menu_manager.cpp b/src/menu_manager.cpp index 40f9324..2073518 100644 --- a/src/menu_manager.cpp +++ b/src/menu_manager.cpp @@ -42,7 +42,6 @@ constexpr int FLY_LAYER = 0; constexpr int FLY_SHADOW_LAYER = 1; constexpr float FADE_STEP = 0.025f; -constexpr int MUSIC_TITLE_REPENTANCE = 63; constexpr int MUSIC_JINGLE_GAME_START_ALT = 64; constexpr int MUSIC_JINGLE_GAME_START = 95; constexpr float WIDGET_OFFSET_Y = 90; diff --git a/src/menu_manager.h b/src/menu_manager.h index 6262aac..178eda0 100644 --- a/src/menu_manager.h +++ b/src/menu_manager.h @@ -111,7 +111,6 @@ constexpr const char* ANIMATION_IDLE = "Idle"; constexpr float MENU_HEIGHT = 270; constexpr float MENU_WIDTH = 480; constexpr int DEVICE_NONE = -1; -constexpr int SOUND_BOOK_PAGE_TURN_12 = 8; constexpr int SOUND_MENU_SCROLL = 282; constexpr int SOUND_MENU_NOTE_APPEAR = 283; constexpr int SOUND_MENU_NOTE_HIDE = 284; diff --git a/src/menu_options.cpp b/src/menu_options.cpp index 5b4743e..0344047 100644 --- a/src/menu_options.cpp +++ b/src/menu_options.cpp @@ -68,7 +68,6 @@ constexpr int ONLINE_LEVEL_MAX = 10; constexpr int INPUT_DELAY_MIN = 1; constexpr int INPUT_DELAY_MAX = 5; constexpr int ACHIEVEMENT_ITEM_INFO = 641; -constexpr int SOUND_PLOP = 237; constexpr int CONTROLLER_UNSET = -1; // How a row draws: its animation, and the layer its value picks the frame of (none when it shows its value otherwise). diff --git a/src/minimap.cpp b/src/minimap.cpp index 66c1a37..c82b776 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -85,7 +85,6 @@ constexpr int ICON_BLUE_MAP = 1; constexpr int ICON_TREASURE_MAP = 2; constexpr int ICON_RESTOCK = 4; constexpr int ICON_MIND = 5; -constexpr int COLLECTIBLE_RESTOCK = 376; constexpr int STAGE_HOME = 35; constexpr int CHALLENGE_SPEED = 22; @@ -223,7 +222,6 @@ constexpr int GOLDEN_KEY_SUBTYPE = 2; constexpr int CHARGED_KEY_SUBTYPE = 4; constexpr int MEGA_BATTERY_SUBTYPE = 4; constexpr int GOLD_PILL = 14; -constexpr int PILL_COLOR_MASK = 0x7ff; constexpr int GRAB_BAG_SACK = 2; // What refresh's passes share: the current room, the first cell drawn and the step from one cell to the next. diff --git a/src/music_manager.cpp b/src/music_manager.cpp index d0763cf..e149505 100644 --- a/src/music_manager.cpp +++ b/src/music_manager.cpp @@ -17,8 +17,6 @@ constexpr float JINGLE_DUCK_RATE = 0.08f; constexpr float JINGLE_RESTORE_RATE = 0.04f; constexpr float JINGLE_RESTORE_STEP = 0.033333335f; // Tracks a jingle does not interrupt (MUSIC_BOSS_OVER_TWISTED, MUSIC_REVERSE_GENESIS). -constexpr int MUSIC_BOSS_OVER_TWISTED = 52; -constexpr int MUSIC_REVERSE_GENESIS = 118; // How the pitch slides toward its target, and how close counts as there. constexpr float PITCH_SLIDE_RATE = 0.1f; constexpr float PITCH_SLIDE_EPSILON = 0.001f; diff --git a/src/music_manager.h b/src/music_manager.h index 2aca2d4..fd39dfe 100644 --- a/src/music_manager.h +++ b/src/music_manager.h @@ -41,6 +41,47 @@ enum SilenceMode SILENCE_STOP }; +// The music.xml tracks PlayMusic picks from. +enum MusicId : int +{ + MUSIC_NULL = 0, + MUSIC_BOSS = 9, + MUSIC_MOM_BOSS = 20, + MUSIC_MOMS_HEART_BOSS = 21, + MUSIC_ISAAC_BOSS = 22, + MUSIC_DARK_ROOM_BOSS = 24, + MUSIC_CHEST_BOSS = 25, + MUSIC_BOSS2 = 26, + MUSIC_ULTRA_GREED_BOSS = 28, + MUSIC_LIBRARY_ROOM = 30, + MUSIC_SECRET_ROOM = 31, + MUSIC_SECRET_ROOM_ALT = 32, + MUSIC_DEVIL_ROOM = 33, + MUSIC_ANGEL_ROOM = 34, + MUSIC_SHOP_ROOM = 35, + MUSIC_ARCADE_ROOM = 36, + MUSIC_BOSS_OVER = 37, + MUSIC_CHALLENGE_FIGHT = 38, + MUSIC_BOSS3 = 41, + MUSIC_MOTHER_BOSS = 43, + MUSIC_DOGMA_BOSS = 44, + MUSIC_BEAST_BOSS = 45, + MUSIC_PLANETARIUM = 50, + MUSIC_SECRET_ROOM_ALT_ALT = 51, + MUSIC_BOSS_OVER_TWISTED = 52, + MUSIC_TITLE_REPENTANCE = 63, + MUSIC_REVERSE_GENESIS_START = 64, + MUSIC_HUSH_TRANSITION = 65, + MUSIC_ECHOES_REVERSE = 69, + MUSIC_TREASURE_JINGLE_FIRST = 87, + MUSIC_GAME_START_JINGLE = 95, + MUSIC_VOID_BOSS = 103, + MUSIC_DOWNPOUR = 104, + MUSIC_DOWNPOUR_REVERSED = 114, + MUSIC_ABANDONED_MINESHAFT = 116, + MUSIC_REVERSE_GENESIS = 118 +}; + // Construction and destruction (007e1430) are the defaults. // A layer music.xml gives a track: its file, the intro played before it, and its volume. struct MusicLayer diff --git a/src/nightmare_scene.cpp b/src/nightmare_scene.cpp index d56bb41..0c2e568 100644 --- a/src/nightmare_scene.cpp +++ b/src/nightmare_scene.cpp @@ -40,8 +40,6 @@ constexpr uint32_t SCENE_END_GRACE = 2; constexpr int STAGE_TYPE_REPENTANCE = 4; constexpr int STAGE_TYPE_REPENTANCE_B = 5; constexpr int STAGE_HOME = 13; -constexpr int STAGE_TYPE_HOME_NIGHT = 1; -constexpr int STAGE_ICON_HOME = 27; constexpr int STAGE_ICONS_PER_CHAPTER = 3; constexpr int STAGE_ICONS_PER_ALT_CHAPTER = 2; // The stage whose icon the void's slot shows again. diff --git a/src/nightmare_scene.h b/src/nightmare_scene.h index ede6e97..fa75480 100644 --- a/src/nightmare_scene.h +++ b/src/nightmare_scene.h @@ -11,6 +11,9 @@ // The stage bar holds an icon for each stage, by stage number. constexpr int STAGE_ICON_COUNT = 14; +// Home's icon on the nightmare's stage strip. +constexpr int STAGE_ICON_HOME = 27; + // Destruction (00950f10) is the default. // The nightmare between floors (g_manager->nightmareScene): a nightmare of nightmares.xml in its bubble over the // background (the player's portrait on the floor's spot), the stage bar of the floors so far with Isaac walking to the diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 80d0400..b045a1b 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -4,6 +4,7 @@ #include "game.h" #include "manager.h" #include "npc_fireplace.h" +#include "room_special.h" #include "sfx_manager.h" // The Beast's forms, by variant: its stalactites, rocks and soul, the four ultra horsemen and their summons, and @@ -107,14 +108,14 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 16: return npc_mulligan_update(npc); case 17: - return (void)NpcAI::ENTITY_SHOPKEEPER(&npc); + return npc_shopkeeper_update(npc); case 19: case 89: case 239: return (void)NpcAI::ENTITY_LARRYJR(&npc); case 20: case 43: - return (void)NpcAI::ENTITY_MONSTRO(&npc); + return boss_monstro_update(npc); case 21: case 23: case 31: @@ -125,7 +126,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 22: case 205: case 817: - return (void)NpcAI::ENTITY_HIVE(&npc); + return npc_hive_update(npc); case 24: case 278: return (void)NpcAI::ENTITY_GLOBIN(&npc); @@ -145,7 +146,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 246: case 305: case 840: - return (void)NpcAI::ENTITY_HOPPER(&npc); + return npc_hopper_update(npc); case 30: return (void)NpcAI::ENTITY_BOIL(&npc); case 32: @@ -232,7 +233,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 76: return (void)NpcAI::ENTITY_BLASTOCYST_BIG(&npc); case 77: - return (void)NpcAI::ENTITY_EMBRYO(&npc); + return npc_embryo_update(npc); case 78: return (void)NpcAI::ENTITY_MOMS_HEART(&npc); case 79: @@ -249,7 +250,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 215: case 250: case 869: - return (void)NpcAI::ENTITY_SPIDER(&npc); + return npc_spider_update(npc); case 87: return (void)NpcAI::ENTITY_GURGLE(&npc); case 88: @@ -343,7 +344,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 245: return (void)NpcAI::ENTITY_POOP(&npc); case 256: - return (void)NpcAI::ENTITY_DART_FLY(&npc); + return npc_dart_fly_update(npc); case 258: return (void)NpcAI::ENTITY_FAT_BAT(&npc); case 260: diff --git a/src/npc_ai.h b/src/npc_ai.h index 5615703..23b4208 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -120,3 +120,6 @@ void npc_fly_update(Entity_NPC& npc); void npc_gaper_update(Entity_NPC& npc); void npc_horf_update(Entity_NPC& npc); void npc_dip_update(Entity_NPC& npc); + +// The corn dip's variant. +constexpr int DIP_CORN = 1; diff --git a/src/npc_basement.h b/src/npc_basement.h index d7abf7a..68d587e 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -6,6 +6,11 @@ void npc_gusher_update(Entity_NPC& npc); void npc_clotty_update(Entity_NPC& npc); void npc_mulligan_update(Entity_NPC& npc); +void npc_hopper_update(Entity_NPC& npc); +void npc_spider_update(Entity_NPC& npc); +void npc_hive_update(Entity_NPC& npc); +void npc_dart_fly_update(Entity_NPC& npc); +void npc_embryo_update(Entity_NPC& npc); // Keeps an overlay animation playing, restarting it once it ends or another shows. inline void npc_overlay_loop(ANM2& sprite, std::string_view name) @@ -17,3 +22,11 @@ inline void npc_overlay_loop(ANM2& sprite, std::string_view name) sprite.overlayAnimState.Rewind(); sprite.overlayAnimState.isPlaying = true; } + +// Room::GetFloorColorAt: the floor's color under a world position, sampled over a radius when it has one. +KColor room_floor_color_get(Room& room, const Vector& position, float radius); + + +// The shoot action a controlled enemy reads, and the flags that keep an enemy off its target. +constexpr int CONTROLLER_ACTION_SHOOT = 9; +constexpr uint64_t FLAG_DISTRACTED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; diff --git a/src/npc_clotty.cpp b/src/npc_clotty.cpp index f21d42f..e4f0ed8 100644 --- a/src/npc_clotty.cpp +++ b/src/npc_clotty.cpp @@ -3,9 +3,9 @@ #include "entity_effect.h" #include "entity_player.h" #include "room_grid.h" +#include // The clotties this AI runs: the Clotty with its Clot, I.Blob and Grilled variants, the Mega Clotty and the Cloggy. -constexpr int ENTITY_CLOTTY = 15; constexpr int ENTITY_GLOBIN_SPAWN = 24; constexpr int ENTITY_MEGA_CLOTTY = 282; constexpr int ENTITY_CLOGGY = 872; @@ -13,12 +13,7 @@ constexpr int CLOT = 1; constexpr int I_BLOB = 2; constexpr int GRILLED_CLOTTY = 3; -constexpr int SOUND_FORESTBOSS_STOMPS = 48; constexpr int SOUND_ANIMAL_SQUISH = 166; -constexpr int CONTROLLER_ACTION_SHOOT = 9; -constexpr int PROJECTILE_PUKE = 3; -constexpr uint64_t PROJECTILE_CURVE_LEFT = 1ull << 18; -constexpr uint64_t PROJECTILE_CURVE_RIGHT = 1ull << 19; constexpr int BLOOD_EXPLOSION_SPURT = 2; // They hop around (a Mega Clotty wading through more friction) and attack once a hop ends while the target is in diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp new file mode 100644 index 0000000..86dcdf9 --- /dev/null +++ b/src/npc_collision.cpp @@ -0,0 +1,899 @@ +#include "entity_effect.h" +#include "npc_basement.h" +#include "deathmatch_manager.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "boss_ai.h" +#include "game.h" +#include "room.h" +#include +#include +#include + +// The NPC types whose contacts differ from the generic ones. +constexpr int ENTITY_MAGGOT = 21; +constexpr int ENTITY_SPITTY = 31; +constexpr int ENTITY_BRAIN = 32; +constexpr int ENTITY_DEATH = 66; +constexpr int ENTITY_HORSEMAN_HEAD = 83; +constexpr int ENTITY_MOMS_HAND = 213; +constexpr int ENTITY_GURGLING = 237; +constexpr int ENTITY_CONJOINED_SPITTY = 243; +constexpr int ENTITY_BEGOTTEN = 251; +constexpr int ENTITY_DART_FLY = 256; +constexpr int ENTITY_THE_HAUNT = 260; +constexpr int ENTITY_DINGLE = 261; +constexpr int ENTITY_MEGA_MAW = 262; +constexpr int ENTITY_CAGE = 265; +constexpr int ENTITY_SWARM = 281; +constexpr int ENTITY_ULCER = 289; +constexpr int ENTITY_ULTRA_COIN = 293; +constexpr int ENTITY_CORN_MINE = 295; +constexpr int ENTITY_FISTULOID = 308; +constexpr int ENTITY_STAIN = 401; +constexpr int ENTITY_BROWNIE = 402; +constexpr int ENTITY_SISTERS_VIS = 410; +constexpr int ENTITY_MATRIARCH = 413; +constexpr int ENTITY_BOMB_GRIMACE = 809; +constexpr int ENTITY_FISSURE = 815; +constexpr int ENTITY_BLASTER = 821; +constexpr int ENTITY_BOUNCER = 822; +constexpr int ENTITY_SMALL_MAGGOT = 853; +constexpr int ENTITY_GASBAG = 856; +constexpr int ENTITY_ARMYFLY = 868; +constexpr int ENTITY_DRIP = 870; +constexpr int ENTITY_BUTT_SLICKER = 878; +constexpr int ENTITY_NEEDLE = 881; +constexpr int ENTITY_CLICKETY_CLACK = 889; +constexpr int ENTITY_CHIMERA = 910; +constexpr int ENTITY_NERVE_ENDING_2 = 964; + +// The variants and states some contacts depend on. +constexpr int FIREPLACE_WHITE = 4; +constexpr int FIREPLACE_FRIENDLY_FIRST = 10; +constexpr int FIREPLACE_MOVABLE = 11; +constexpr int FIREPLACE_FRIENDLY_RED = 12; +constexpr int FIREPLACE_FRIENDLY_BLUE = 13; +constexpr int KNIGHT_BLACK = 4; +constexpr int MINECART_EXIT = 10; +constexpr int LARRY_SEGMENT_VARIANT = 3; +constexpr int VIS_CHUBBER_VARIANT = 22; +constexpr int DEATH_SCYTHE_VARIANT = 20; +constexpr int PIN_SCOLEX_VARIANT = 3; +constexpr int SUCKER_BULB_FIRST = 5; +constexpr int SUCKER_BULB_LAST = 6; +constexpr int ROCK_SPIDER_TINTED = 2; +constexpr int BEAST_SOUL_VARIANT = 10; +constexpr int SCOURGE_CHAIN_VARIANT = 10; +constexpr int SMALL_MAGGOT_FALLING = 2; +constexpr int SMALL_MAGGOT_LANDED = 1; +constexpr int HAND_GRAB_STATE = NPC_STATE_STOMP; +constexpr int ULTRA_GREED_COIN_STATE = 310; +constexpr int GREED_GAPER_FAMILIAR_VARIANT = 900; +constexpr int PICKUP_ULTRA_GREED_COIN = 100; +constexpr int SOUND_CHUB_BITE = 142; +constexpr int POOP_CORNY_GOLDEN = 1; +constexpr int COIN_VARIANT = 20; +constexpr int PENNY_SUBTYPE = 1; +constexpr int COLLECTIBLE_E_COLI = 236; + +// Contact damages, counted in hearts of half a heart, and the frames they hold the target for. +constexpr int CONTACT_COUNTDOWN = 30; +constexpr float ROCK_SPIDER_CRUSH = 100; +constexpr float FLY_BOMB_DAMAGE = 40; +constexpr float FLY_BOMB_RADIUS = 60; +constexpr float TURDLET_DIP_DAMAGE = 10; +constexpr int TURDLET_DIP_GRACE = 8; +constexpr float BALL_DAMAGE = 25; +constexpr float BALL_SPEED = 10; +constexpr float BEAST_SOUL_DAMAGE = 200; +constexpr float BEAST_SOUL_SPEED_SQUARED = 225; +constexpr float SCOURGE_CHAIN_DAMAGE = 5; +constexpr float SCOURGE_CHAIN_AGE = 60; +constexpr float CRUSH_DAMAGE = 10; +constexpr float FRIENDLY_FIRE_DAMAGE = 10; +constexpr float FIREPLACE_BURN = 16; +constexpr float FAMINE_RAM = 10; +constexpr float CHUB_BITE = 20; +constexpr float DEATH_SCYTHE_DAMAGE = 20; +constexpr float POKY_HEAD_DAMAGE = 10; +constexpr float GREED_PUSH_DAMAGE = 25; +constexpr float GREED_PUSH_SPEED = 1; +constexpr float GRUDGE_DAMAGE = 5; +constexpr float BLOOD_PUPPY_BITE = 7.5f; +constexpr float BLOOD_PUPPY_BIG_BITE = 15; +constexpr float ULTRA_COIN_PUSH = 9; +constexpr float SISTER_ROLL_PUSH = 0.3f; +constexpr float CHARMED_DAMAGE_BASE = 110; +constexpr float CHARMED_DAMAGE_SCALE = 100; +constexpr float CHARMED_DAMAGE_LOG = 33; +constexpr float CHUBBER_DAMAGE = 12; +constexpr float FRIENDLY_TARGET_SHARE = 0.25f; +constexpr float FRIENDLY_TARGET_MAX = 3.5f; +constexpr float BAITED_SHARE = 0.5f; +constexpr float KNOCKBACK_IMPACT_SPEED = 6; +constexpr float ICE_SHATTER_DAMAGE = 35; +constexpr float IMPACT_DAMAGE_BASE = 10; +constexpr float SPAWN_GRACE_FRAMES = 10; +constexpr int DARK_ESAU_GRACE = 16; +constexpr int DARK_ESAU_CHARGE_STATE = NPC_STATE_SUICIDE; +constexpr int DARK_ESAU_STUN_STATE = NPC_STATE_SUMMON; +constexpr int SCATTER_COINS = 3; +constexpr float COIN_SPEED_MIN = 2; +constexpr float COIN_SPEED_RANGE = 5; +constexpr int BIG_HORN_BOUNCE_FRAMES = 30; +constexpr int MOVABLE_TNT_PUSH_LIMIT = -4; +constexpr uint64_t DAMAGE_ULTRA_GREED = 1ull << 6; +constexpr uint64_t DAMAGE_ICE_SHATTER = 1ull << 24; +constexpr ColorMod E_COLI_POOP_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {39 / 255.0f, 25 / 255.0f, 22 / 255.0f}}; + +// The enemies with bodies of segments, which their own segments pass through. +constexpr std::array SEGMENT_KINDS = {ENTITY_SPITTY, ENTITY_MAGGOT, ENTITY_CHARGER, ENTITY_LEECH, + ENTITY_CONJOINED_SPITTY}; +constexpr std::array WORM_KINDS = {ENTITY_LARRYJR, ENTITY_BUTTLICKER, ENTITY_GRUB, ENTITY_TURDLET}; + +// What a contact decided: whether it is ignored, or nothing yet. +using Verdict = std::optional; + +// A contact being worked out: the two, the types it compares (Delirium standing for the boss it mimics), whether it +// is the low call of the pair, its default verdict and whether the two are tied. +struct Contact +{ + Entity_NPC& npc; + Entity& collider; + int npcType = 0; + int npcVariant = 0; + int colliderType = 0; + int colliderVariant = 0; + bool isIgnored = true; + bool isLow = false; + bool isRelated = false; +}; + +static bool is_in(std::span kinds, int kind) +{ + return std::ranges::find(kinds, kind) != kinds.end(); +} + +// 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); +} + +static void damage_deal(Entity& target, float damage, uint64_t damageFlags, Entity* source) +{ + target.TakeDamage(damage, damageFlags, source ? EntityRef(source) : EntityRef(), CONTACT_COUNTDOWN); +} + +static bool is_same_friendliness(Entity& first, Entity& second) +{ + return first.IsFriendly() == second.IsFriendly(); +} + +// The first contacts, before the AI's collision call: Dark Esau passes shots, a white fire spares a player it cannot +// hurt, a magnetized enemy collides with the enemies of another target and minecarts pass each other. +static Verdict contact_early(Contact& contact) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + if (npc.type == ENTITY_DARK_ESAU && + (collider.type == ENTITY_TEAR || collider.type == ENTITY_PROJECTILE || collider.type == ENTITY_BOMB)) + return true; + + if (collider.type == ENTITY_PLAYER && npc.type == ENTITY_FIREPLACE && npc.variant == FIREPLACE_WHITE) + { + Entity_Player& player = *collider.ToPlayer(); + if (player.GetHealthType() == HEALTH_NO_HEALTH || player.HasInstantDeathCurse() || player.isCoopGhost) + return true; + } + if (collider.type == ENTITY_TEAR && npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_BLACK) + { + TearFlags& flags = collider.ToTear()->tearFlags; + if (!flags[TEAR_EXPLOSIVE] && !flags[TEAR_LUDOVICO]) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: the Black Knight's tear reflection"); + } + if (collider.type == ENTITY_PLAYER && npc.type == ENTITY_MINECART && npc.variant == MINECART_EXIT) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a minecart leaving the room"); + + bool isVersusPlayer = g_game->deathmatchManager.is_active() && collider.type == ENTITY_PLAYER; + bool isMagnetized = npc.HasEntityFlags(FLAG_MAGNETIZED) || collider.HasEntityFlags(FLAG_MAGNETIZED); + if ((isVersusPlayer || Entity::is_enemy_type(collider.type)) && isMagnetized && + collider.GetStatusEffectTarget() != npc.GetStatusEffectTarget()) + contact.isIgnored = false; + + bool isRiding = npc.type == ENTITY_MINECART || npc.minecart; + if (isRiding && (collider.type == ENTITY_MINECART || collider.minecart)) return true; + return std::nullopt; +} + +// The fly bomb goes off on its target, a foe if friendly, and passes Blasters and Hornfel. +static Verdict fly_bomb_contact(Entity_NPC& npc, Entity& collider) +{ + bool isTargetHit = (collider.type == ENTITY_PLAYER && !npc.IsFriendly()) || &collider == npc.target.get(); + bool isFoeHit = npc.IsFriendly() && collider.IsEnemy() && !collider.IsFriendly(); + if ((isTargetHit || isFoeHit) && !npc.HasEntityFlags(FLAG_SHRINK)) + { + explosion_damage({.position = npc.pos, .source = &npc, .damage = FLY_BOMB_DAMAGE, .radius = FLY_BOMB_RADIUS}); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + npc.Remove(); + return false; + } + if (collider.type == ENTITY_BLASTER || collider.type == ENTITY_HORNFEL) return true; + return std::nullopt; +} + +// The type pairs that ignore each other or act on touch before the generic rules: a landed maggot, Raglich's fire, +// rock spiders crushed or lit, the fly bomb going off, the Turdlet hurting dips, and the bosses' rams and chains. +static Verdict contact_pairs(Contact& contact) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + if (npc.type == ENTITY_SMALL_MAGGOT && npc.i1 == SMALL_MAGGOT_FALLING) + { + if (collider.type == ENTITY_BOMB || collider.type == ENTITY_TEAR || collider.type == ENTITY_PROJECTILE) + return true; + npc.i1 = SMALL_MAGGOT_LANDED; + npc.sprite.GetLayer(0)->color = COLOR_DEFAULT; + npc.velocity = vector_scale(npc.velocity, 0.5f); + npc.ClearEntityFlags(FLAG_NO_KNOCKBACK); + } + if ((npc.type == ENTITY_RAGLICH && collider.type == ENTITY_FIREPLACE) || + (npc.type == ENTITY_FIREPLACE && collider.type == ENTITY_RAGLICH)) + return true; + + bool isRockSpider = npc.type == ENTITY_ROCK_SPIDER && (npc.variant == 0 || npc.variant == 1); + if (isRockSpider && collider.type == ENTITY_PLAYER && collider.ToPlayer()->CanCrushRocks()) + { + damage_deal(npc, ROCK_SPIDER_CRUSH, 0, &collider); + return false; + } + + bool isMovableFire = npc.type == ENTITY_FIREPLACE && npc.variant == FIREPLACE_MOVABLE; + bool isColliderMovableFire = collider.type == ENTITY_FIREPLACE && collider.variant == FIREPLACE_MOVABLE; + if (isMovableFire && collider.IsEnemy() && !isColliderMovableFire && is_same_friendliness(npc, collider)) + return true; + if (npc.type == ENTITY_ROCK_SPIDER && npc.variant == 0 && collider.type == ENTITY_FIREPLACE) + { + npc.Morph(ENTITY_ROCK_SPIDER, ROCK_SPIDER_TINTED, npc.subtype, -1); + return false; + } + bool isRockKind = collider.type == ENTITY_ROCK_SPIDER || isColliderMovableFire; + if ((isMovableFire || npc.type == ENTITY_ROCK_SPIDER) && isRockKind && is_same_friendliness(npc, collider)) + return true; + + if (npc.type == ENTITY_FLY_BOMB) + { + Verdict verdict = fly_bomb_contact(npc, collider); + if (verdict) return verdict; + } + if (npc.type == ENTITY_LARRYJR && npc.variant == LARRY_SEGMENT_VARIANT && collider.type == ENTITY_BOMB_GRIMACE) + return true; + if (npc.type == ENTITY_TURDLET && npc.state == NPC_STATE_JUMP && + (collider.type == ENTITY_DIP || collider.type == ENTITY_DRIP) && + g_game->frameCount - collider.spawnFrame > TURDLET_DIP_GRACE) + damage_deal(collider, TURDLET_DIP_DAMAGE, 0, &npc); + + if (npc.type == ENTITY_BOUNCER && npc.state == NPC_STATE_SPECIAL && + (collider.type == ENTITY_PLAYER || &collider == npc.target.get())) + npc.Kill(EntityRef()); + if (npc.type == ENTITY_HORNFEL) + { + if (npc.variant == 1 && collider.type == ENTITY_PLAYER) npc.Kill(EntityRef()); + if (npc.minecart) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Hornfel's minecart ramming"); + } + + bool isBall = (npc.type == ENTITY_SINGE && npc.variant == 1) || npc.type == ENTITY_BALL_AND_CHAIN; + if (isBall && collider.IsVulnerableEnemy(nullptr) && vector_length(npc.velocity) > BALL_SPEED && + !EntityList::HitListContains(npc.hitList, collider)) + { + hit_list_add(npc.hitList, collider); + damage_deal(collider, BALL_DAMAGE, 0, &npc); + } + if (npc.type == ENTITY_VISAGE) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Visage's contacts"); + + if (npc.type == ENTITY_MOTHER && collider.type == ENTITY_MOTHER) return true; + if (npc.type == ENTITY_BEAST && collider.type == ENTITY_BEAST) + { + bool isRammed = npc.variant == BEAST_SOUL_VARIANT && !collider.IsBoss() && + vector_length_squared(npc.velocity) > BEAST_SOUL_SPEED_SQUARED; + if (isRammed) damage_deal(collider, BEAST_SOUL_DAMAGE, 0, nullptr); + return true; + } + if (npc.type == ENTITY_BOOMFLY && npc.state == NPC_STATE_SUICIDE && collider.type == ENTITY_PLAYER) + { + npc.Kill(EntityRef()); + return false; + } + if (npc.type == ENTITY_CHIMERA && collider.type == ENTITY_SMALL_MAGGOT && collider.IsVulnerableEnemy(nullptr) && + collider.posOffset.y >= 0) + collider.Kill(EntityRef(&npc)); + + if (npc.type == ENTITY_SCOURGE) + { + if (collider.type == ENTITY_SCOURGE) return true; + bool isChain = npc.variant == SCOURGE_CHAIN_VARIANT && npc.subtype != 0; + if (isChain && collider.IsVulnerableEnemy(nullptr) && collider.updateTime > SCOURGE_CHAIN_AGE) + { + if (collider.type == ENTITY_SMALL_MAGGOT) collider.Kill(EntityRef(&npc)); + else damage_deal(collider, SCOURGE_CHAIN_DAMAGE, 0, &npc); + return true; + } + } + + if (npc.type == ENTITY_FLY_BOMB && npc.variant == 1 && &collider == npc.parent.get()) return true; + if (npc.type == ENTITY_BALL_AND_CHAIN && !vector_is_zero(npc.targetPosition) && + collider.type == ENTITY_BALL_AND_CHAIN) + return true; + if (npc.type == ENTITY_FISSURE && collider.type == ENTITY_FISSURE) + { + if (!contact.isLow) return true; + Vector normal = + vector_normalized(vector_add(vector_sub(vector_sub(npc.pos, npc.velocity), collider.pos), collider.velocity)); + npc.velocity = vector_sub(npc.velocity, vector_scale(normal, 2 * vector_dot(npc.velocity, normal))); + collider.velocity = + vector_sub(collider.velocity, vector_scale(normal, 2 * vector_dot(collider.velocity, normal))); + return true; + } + if (npc.type == ENTITY_MOTHER && collider.type == ENTITY_SMALL_MAGGOT) + { + collider.Kill(EntityRef(&npc)); + return true; + } + return std::nullopt; +} + +// The contacts by the (Delirium mimicked) type: Chubber, pushed TNT, friendly fires burning enemies, Willo, small +// leeches, army flies and rings of flies with their own, and maggots with their spawner. +static Verdict contact_kinds(Contact& contact) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + if (npc.type == ENTITY_NERVE_ENDING_2 && collider.type == ENTITY_PLAYER) + { + npc.v1.x = 0; + return std::nullopt; + } + + if (npc.type == ENTITY_DELIRIUM) + { + contact.npcType = (int)npc.deliriumBossType; + contact.npcVariant = (int)npc.deliriumBossVariant; + } + if (collider.type == ENTITY_DELIRIUM) + { + Entity_NPC& delirium = static_cast(collider); + contact.colliderType = (int)delirium.deliriumBossType; + contact.colliderVariant = (int)delirium.deliriumBossVariant; + } + + switch (contact.npcType) + { + case ENTITY_VIS: + if (contact.npcVariant != VIS_CHUBBER_VARIANT || !collider.IsActiveEnemy(DEAD_EXCLUDED)) break; + return npc.IsFriendly() ? std::nullopt : Verdict(contact.isIgnored); + case ENTITY_MOVABLE_TNT: + if (collider.type != ENTITY_PLAYER || npc.i1 <= MOVABLE_TNT_PUSH_LIMIT) break; + npc.i1 = 0; + return contact.isIgnored; + case ENTITY_FIREPLACE: + { + int fire = contact.npcVariant; + bool isFriendlyFire = + fire == FIREPLACE_FRIENDLY_FIRST || fire == FIREPLACE_FRIENDLY_RED || fire == FIREPLACE_FRIENDLY_BLUE; + if (!isFriendlyFire) break; + if (collider.type == ENTITY_BOMB) return true; + if (!collider.IsEnemy()) break; + damage_deal(collider, npc.IsFriendly() ? FRIENDLY_FIRE_DAMAGE : 0, DAMAGE_FIRE, &npc); + return contact.isIgnored; + } + case ENTITY_WILLO: + if (collider.type == ENTITY_PLAYER) + { + if (npc.projectileCooldown > 0) return contact.isIgnored; + if (npc.subtype == 0) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Willo's slot (NpcHelper::willo_slot)"); + } + if (collider.IsEnemy() || collider.type == ENTITY_BOMB) return contact.isIgnored; + break; + case ENTITY_SMALL_LEECH: + if (npc.parent.get() == &collider) return contact.isIgnored; + if (collider.type == ENTITY_SMALL_LEECH && npc.parent) return contact.isIgnored; + if (collider.type == ENTITY_TEAR && npc.entityGridCollisionClass == GRIDCOLL_NOPITS) npc.v1.x = 0; + break; + case ENTITY_ARMYFLY: + if (collider.type == ENTITY_ARMYFLY || collider.type == ENTITY_GASBAG) return contact.isIgnored; + break; + case ENTITY_RING_OF_FLIES: + if (collider.type == ENTITY_HIVE) return contact.isIgnored; + break; + case ENTITY_SMALL_MAGGOT: + if (collider.type == ENTITY_SMALL_MAGGOT || &collider == npc.spawnerEntity.get()) return contact.isIgnored; + break; + } + return std::nullopt; +} + +// The contacts of horns, Fistuloids and rolling Sisters Vis, and the generic passes: a shrunk enemy squished, friends +// and shots passing, and enemies just spawned in a challenge or ambush. +static Verdict contact_passes(Contact& contact) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + int npcType = contact.npcType; + int colliderType = contact.colliderType; + if (npc.spawnerType == ENTITY_ORBIT_SPAWNER && npc.parent && collider.IsEnemy()) return contact.isIgnored; + if (collider.type == ENTITY_PLAYER && (npcType == ENTITY_MOVABLE_TNT || npcType == ENTITY_POOP) && + collider.ToPlayer()->CanCrushRocks()) + { + damage_deal(npc, CRUSH_DAMAGE, DAMAGE_EXPLOSION, &collider); + return contact.isIgnored; + } + + if (npcType == ENTITY_FISTULOID) + { + bool isSibling = collider.type == ENTITY_FISTULOID && npc.parent && npc.parent.get() == collider.parent.get(); + if (collider.type == ENTITY_MATRIARCH || &collider == npc.parent.get() || isSibling) return contact.isIgnored; + } + else if (npcType == ENTITY_LITTLE_HORN) + { + if (collider.type == ENTITY_BIG_HORN && collider.variant != 0) return contact.isIgnored; + if (collider.type == ENTITY_BOMB && npc.spawnerType == ENTITY_BIG_HORN) return contact.isIgnored; + if (npc.spawnerType == ENTITY_BIG_HORN && colliderType == ENTITY_BIG_HORN && + npc.stateFrame > BIG_HORN_BOUNCE_FRAMES) + { + Vector normal = vector_normalized(vector_sub(npc.pos, collider.pos)); + npc.velocity = vector_sub(npc.velocity, vector_scale(normal, 2 * vector_dot(npc.velocity, normal))); + } + } + else + { + bool isRolledOver = (npcType == ENTITY_VIS || npcType == ENTITY_BEGOTTEN) && + colliderType == ENTITY_SISTERS_VIS && collider.sprite.IsPlaying("RollLoop"); + if (isRolledOver) + { + npc.Kill(EntityRef()); + return contact.isIgnored; + } + if (npcType == ENTITY_SISTERS_VIS && npc.sprite.IsPlaying("RollLoop") && colliderType == ENTITY_TEAR && + collider.spawnerType == ENTITY_PLAYER) + npc.velocity = vector_add(vector_scale(collider.velocity, SISTER_ROLL_PUSH), npc.velocity); + } + + if (npc.HasEntityFlags(FLAG_SHRINK) && colliderType == ENTITY_PLAYER && !npc.IsBoss()) + { + npc.Kill(EntityRef()); + return contact.isIgnored; + } + if (npc.IsFriendly() && npc.IsDamageSourceFriendly(EntityRef(&collider))) + { + if (colliderType == ENTITY_PLAYER || colliderType == ENTITY_FAMILIAR) return contact.isIgnored; + if (collider.IsEnemy() && collider.IsFriendly()) return contact.isIgnored; + } + if (!contact.isLow && colliderType == ENTITY_PROJECTILE) return contact.isIgnored; + + Room& room = *g_game->room; + bool isGraceRoom = room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH || + (g_game->IsGreedMode() && room.roomType == ROOM_DEFAULT) || npc.HasEntityFlags(FLAG_AMBUSH); + if (isGraceRoom && (npc.state == NPC_STATE_APPEAR || g_game->frameCount - npc.spawnFrame < SPAWN_GRACE_FRAMES)) + return contact.isIgnored; + return std::nullopt; +} + +// Whether the two are tied: either charmed or baited, a Blood Puppy, or one forced to target the other. +static bool is_related(Entity_NPC& npc, Entity& collider) +{ + constexpr uint64_t TIES = FLAG_CHARM | FLAG_BAITED; + if (npc.HasEntityFlags(TIES) || collider.HasEntityFlags(TIES)) return true; + if (npc.type == ENTITY_BLOOD_PUPPY || collider.type == ENTITY_BLOOD_PUPPY) return true; + if (npc.forcedTarget.get() == &collider) return true; + return collider.IsEnemy() && static_cast(collider).forcedTarget.get() == &npc; +} + +// The kinds that pass through their own kind unless tied: guts, wall huggers, pins, swarms, the Haunt, segmented +// bodies, long legs over spiders, swingers over their own, dart flies over ulcers and pitfalls over the rest. +static Verdict contact_kin(Contact& contact) +{ + int npcType = contact.npcType; + int colliderType = contact.colliderType; + bool isSameKind = npcType == colliderType; + if (isSameKind && (npcType == ENTITY_WALL_HUGGER || npcType == ENTITY_PIN)) return contact.isIgnored; + bool isKinPass = npcType == ENTITY_GUTS || npcType == ENTITY_SWARM || npcType == ENTITY_THE_HAUNT; + if (isSameKind && isKinPass && !contact.isRelated) return contact.isIgnored; + if (npcType == ENTITY_BOIL && colliderType == ENTITY_CHUB) return contact.isIgnored; + + bool isNpcSegment = is_in(SEGMENT_KINDS, npcType); + if (isNpcSegment && is_in(SEGMENT_KINDS, colliderType) && !contact.isRelated) return contact.isIgnored; + + bool isPitfallChecked = true; + if ((isNpcSegment || npcType == ENTITY_GURGLING) && colliderType == ENTITY_STAIN) + { + Entity_NPC& stain = static_cast(contact.collider); + if (!contact.isRelated && stain.state == NPC_STATE_SPECIAL) return contact.isIgnored; + } + else + { + bool isLegs = npcType == ENTITY_BABY_LONG_LEGS || npcType == ENTITY_CRAZY_LONG_LEGS; + bool isLegsPrey = colliderType == ENTITY_SPIDER || colliderType == ENTITY_BOIL; + if (isLegs && isLegsPrey && !contact.isRelated) return contact.isIgnored; + if (colliderType == ENTITY_SWINGER && npcType == ENTITY_SWINGER) + { + if (contact.npcVariant == 1 && contact.colliderVariant == 1) return contact.isIgnored; + if (contact.collider.parent.get() == &contact.npc) return contact.isIgnored; + isPitfallChecked = false; + } + else if (colliderType == ENTITY_ULCER && npcType == ENTITY_DART_FLY) return contact.isIgnored; + } + if (isPitfallChecked && (npcType == ENTITY_PITFALL) != (colliderType == ENTITY_PITFALL)) return contact.isIgnored; + return std::nullopt; +} + +// An orange champion that hurts a player takes a coin from it and scatters up to three more. +static void champion_coins_steal(Entity_NPC& npc, Entity_Player& player) +{ + player.AddCoins(-1); + int count = std::min((int)(Random() % SCATTER_COINS) + 1, player.numCoins); + + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + float speed = random_unit() * COIN_SPEED_RANGE + COIN_SPEED_MIN; + g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(direction, speed), + .subType = PENNY_SUBTYPE, + .type = ENTITY_PICKUP, + .variant = COIN_VARIANT, + .seed = seed}); + } + player.AddCoins(-count); +} + +// Touching a player hurts it by the collision damage (fire for a fireplace), unless Skatole spares flies or Bursting +// Sack spiders. E. Coli turns the enemy to poop and a kill-on-touch enemy dies. Dark Esau spares a player early on. +static Verdict contact_player(Contact& contact, Entity_Player& player) +{ + Entity_NPC& npc = contact.npc; + if (npc.type == ENTITY_DARK_ESAU) + { + Entity* esau = player.darkEsau.get(); + bool isOthersEsau = esau && esau != &npc && esau != npc.parent.get() && esau != npc.child.get() && + npc.spawnerEntity.get() != &player; + if (g_game->room->GetFrameCount() < DARK_ESAU_GRACE || isOthersEsau) return true; + if (npc.state == DARK_ESAU_CHARGE_STATE || npc.state == DARK_ESAU_STUN_STATE) return true; + } + + int npcType = contact.npcType; + PlayerManager& players = g_game->playerManager; + bool isTintedRockSpider = npcType == ENTITY_ROCK_SPIDER && contact.npcVariant == ROCK_SPIDER_TINTED; + bool isSpared = (npc.config->tags & ENTITY_TAG_FLY) && players.AnyoneHasCollectible(COLLECTIBLE_SKATOLE); + if (!isSpared && (npc.config->tags & ENTITY_TAG_SPIDER) && !isTintedRockSpider) + isSpared = players.AnyoneHasCollectible(COLLECTIBLE_BURSTING_SACK); + if (npcType == ENTITY_NEEDLE) isSpared = isSpared || npc.state != NPC_STATE_JUMP; + if (npcType == ENTITY_CLICKETY_CLACK) isSpared = isSpared || npc.HasEntityFlags(FLAG_NO_TARGET); + + if (!isSpared && npc.collisionDamage > 0) + { + bool isBurning = npcType == ENTITY_FIREPLACE || + (npcType == ENTITY_CLICKETY_CLACK && npc.state == NPC_STATE_SPECIAL && npc.i2 == 99); + bool isHurt = player.TakeDamage(npc.collisionDamage, isBurning ? DAMAGE_FIRE : 0, EntityRef(&npc), + CONTACT_COUNTDOWN); + if (isHurt && npc.isChampion && npc.championColorIdx == CHAMPION_ORANGE && player.numCoins > 0) + champion_coins_steal(npc, player); + } + + bool isPoopable = npcType != ENTITY_POOP && npcType != ENTITY_CHUB && npcType != ENTITY_MOMS_HAND; + if (player.HasCollectible(COLLECTIBLE_E_COLI) && npc.CanReroll() && isPoopable && npc.IsVulnerableEnemy(nullptr)) + { + npc.Remove(); + int poopVariant = player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH) ? POOP_CORNY_GOLDEN : 0; + Entity* poop = + g_game->Spawn({.position = npc.pos, .type = ENTITY_POOP, .variant = poopVariant, .seed = Random()}); + poop->splatColor = E_COLI_POOP_COLOR; + if (npc.minecart) static_cast(npc.minecart.get())->MinecartUpdateChild(poop); + } + if (npc.isKillOnTouch) npc.Kill(EntityRef()); + + bool isBulb = npc.type == ENTITY_SUCKER && npc.variant >= SUCKER_BULB_FIRST && npc.variant <= SUCKER_BULB_LAST; + if (isBulb && npc.state == NPC_STATE_ATTACK) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a Bulb draining a player"); + return std::nullopt; +} + +// The rams of bosses into enemies: Famine, Chub biting chargers and spiders, Gurdy Jr. eating Pooters, the Cage +// crushing Vis, Death's scythes and Poky's heads. Worm segments pass their own body. Whether the npc is a worm. +static Verdict contact_rams(Contact& contact, bool& isWorm) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + int npcType = contact.npcType; + int colliderType = contact.colliderType; + + if (!contact.isLow && collider.IsEnemy() && npcType == ENTITY_FAMINE) + { + if (npc.state == NPC_STATE_ATTACK) damage_deal(collider, FAMINE_RAM, 0, nullptr); + } + else if (npcType == ENTITY_CHUB) + { + if (npc.state == NPC_STATE_ATTACK && (colliderType == ENTITY_CHARGER || colliderType == ENTITY_SPIDER)) + { + damage_deal(collider, CHUB_BITE, 0, nullptr); + npc.PlaySound(SOUND_CHUB_BITE, 1, 2, false, 1); + } + isWorm = true; + } + else if (npcType == ENTITY_GURDY_JR && npc.state == NPC_STATE_ATTACK && colliderType == ENTITY_POOTER) + collider.Kill(EntityRef(&npc)); + else if (npcType == ENTITY_CAGE && npc.state == NPC_STATE_ATTACK && npc.i1 == 1 && colliderType == ENTITY_VIS) + collider.Kill(EntityRef(&npc)); + else if (npcType == ENTITY_DEATH && npc.variant == DEATH_SCYTHE_VARIANT) + { + if (colliderType == ENTITY_DEATH) return contact.isIgnored; + if (collider.IsVulnerableEnemy(nullptr)) damage_deal(collider, DEATH_SCYTHE_DAMAGE, 0, &npc); + if (colliderType != ENTITY_PLAYER) return contact.isIgnored; + } + else if (npcType == ENTITY_POKY && colliderType == ENTITY_HORSEMAN_HEAD) + damage_deal(collider, POKY_HEAD_DAMAGE, 0, &npc); + else if (npcType == ENTITY_BUTT_SLICKER && colliderType == ENTITY_BUTT_SLICKER && !contact.isRelated) + return contact.isIgnored; + else isWorm = is_in(WORM_KINDS, npcType); + return std::nullopt; +} + +// The contacts of the touch itself: players hurt, familiars hit, a charging Knight or Brain stopped by what it hits, +// fireplaces burning enemies, the bosses' rams, and worm segments passing their own. +static Verdict contact_touch(Contact& contact) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + int npcType = contact.npcType; + int colliderType = contact.colliderType; + bool isFireChecked = true; + + if (!contact.isLow && colliderType == ENTITY_PLAYER) + { + Verdict verdict = contact_player(contact, *collider.ToPlayer()); + if (verdict) return verdict; + } + else if (!contact.isLow && colliderType == ENTITY_FAMILIAR && + static_cast(collider).CanBeDamagedByEnemy()) + damage_deal(collider, npc.collisionDamage, 0, &npc); + else if (npcType == ENTITY_KNIGHT || npcType == ENTITY_BRAIN || npcType == ENTITY_GURGLING) + { + isFireChecked = npc.state == NPC_STATE_ATTACK; + bool isStopped = colliderType != ENTITY_TEAR && colliderType != ENTITY_FAMILIAR && colliderType != ENTITY_PLAYER; + if (isFireChecked && isStopped) + { + npc.state = NPC_STATE_MOVE; + npc.pathfinder.ResetMovementTarget(); + npc.targetPosition = {}; + } + } + if (isFireChecked && npcType == ENTITY_FIREPLACE && collider.IsEnemy()) + damage_deal(collider, FIREPLACE_BURN, DAMAGE_FIRE, &npc); + + bool isWorm = false; + Verdict verdict = contact_rams(contact, isWorm); + if (verdict) return verdict; + + bool isColliderWorm = is_in(WORM_KINDS, colliderType) || colliderType == ENTITY_CHUB; + if (isWorm && isColliderWorm && (npc.is_same_segmented_body(&collider) || !contact.isRelated)) + return contact.isIgnored; + if (npcType == ENTITY_MRMAW && colliderType == ENTITY_MRMAW && npc.is_same_segmented_body(&collider)) return true; + return std::nullopt; +} + +// Mom's hand grabbing, rings of flies and hoppers passing their kin, Brownie eating dips and the corn mines. +// Whether the contact skips to the enemy bumps. +static Verdict contact_late_kinds(Contact& contact, bool& isBumpNext) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + int colliderType = contact.colliderType; + switch (contact.npcType) + { + case ENTITY_MOMS_HAND: + if (npc.state == HAND_GRAB_STATE) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Mom's hand grabbing"); + break; + case ENTITY_RING_OF_FLIES: + if (colliderType != ENTITY_RING_OF_FLIES) break; + isBumpNext = true; + return contact.isRelated ? std::nullopt : Verdict(contact.isIgnored); + case ENTITY_HOPPER: + if ((colliderType == ENTITY_MEGA_MAW || colliderType == ENTITY_GATE) && !contact.isRelated) + return contact.isIgnored; + break; + case ENTITY_MEGA_SATAN: + if (colliderType == ENTITY_MEGA_SATAN) return contact.isIgnored; + break; + case ENTITY_DEATHS_HEAD: + isBumpNext = true; + return colliderType == ENTITY_DEATHS_HEAD ? std::nullopt : Verdict(contact.isIgnored); + case ENTITY_POOP: + if (collider.entityGridCollisionClass != GRIDCOLL_GROUND) return contact.isIgnored; + break; + case ENTITY_BROWNIE: + if ((npc.state == NPC_STATE_ATTACK || npc.state == NPC_STATE_MOVE) && colliderType == ENTITY_DIP) + { + npc.health += collider.health; + collider.Kill(EntityRef(&npc)); + isBumpNext = true; + return std::nullopt; + } + if (colliderType == ENTITY_CORN_MINE) return contact.isIgnored; + break; + case ENTITY_DINGLE: + if (colliderType == ENTITY_CORN_MINE) return contact.isIgnored; + break; + case ENTITY_CORN_MINE: + if (colliderType != ENTITY_PLAYER) break; + npc.Kill(EntityRef()); + isBumpNext = true; + return std::nullopt; + } + return std::nullopt; +} + +// The contacts after the touch: bosses swallowing bombs, Gurdy's own spawns, the kinds above, corn mines hit by shots, +// Ultra Greed and its coins, the Hush and its flies, and the Grudge. +static Verdict contact_late(Contact& contact) +{ + Entity_NPC& npc = contact.npc; + Entity& collider = contact.collider; + int npcType = contact.npcType; + int colliderType = contact.colliderType; + + if (!contact.isLow && colliderType == ENTITY_BOMB && (npcType == ENTITY_CHUB || npcType == ENTITY_PIN)) + { + bool isChubEating = npcType == ENTITY_CHUB && !npc.parent && npc.state == NPC_STATE_ATTACK; + bool isPinEating = npcType == ENTITY_PIN && npc.variant == PIN_SCOLEX_VARIANT && !npc.parent && + (npc.state == NPC_STATE_JUMP || npc.state == NPC_STATE_MOVE) && npc.i1 == 2; + if (isChubEating || isPinEating) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a boss swallowing a bomb"); + return std::nullopt; + } + if (!contact.isLow && npcType == ENTITY_GURDY) + { + if (collider.spawnerType == ENTITY_GURDY) return contact.isIgnored; + } + else if (!contact.isLow && npcType == ENTITY_SHOPKEEPER) return contact.isIgnored; + else + { + bool isBumpNext = false; + Verdict verdict = contact_late_kinds(contact, isBumpNext); + if (verdict || isBumpNext) return verdict; + } + + if (colliderType == ENTITY_PROJECTILE && npcType == ENTITY_CORN_MINE) npc.Kill(EntityRef()); + if (npcType == ENTITY_ULTRA_COIN && npc.variant == 0) + { + Vector away = vector_normalized(vector_sub(npc.pos, collider.pos)); + npc.AddVelocity_divided(vector_scale(away, ULTRA_COIN_PUSH * random_unit()), false); + } + else if (npcType == ENTITY_ULTRA_GREED) + { + Vector toward = vector_sub(collider.pos, npc.pos); + bool isPushed = collider.IsEnemy() && colliderType != ENTITY_ULTRA_COIN && + vector_length(npc.velocity) > GREED_PUSH_SPEED && vector_dot(toward, npc.velocity) > 0; + if (isPushed) damage_deal(collider, GREED_PUSH_DAMAGE, DAMAGE_ULTRA_GREED, nullptr); + bool isCoinStopped = (collider.type == ENTITY_FAMILIAR && collider.variant == GREED_GAPER_FAMILIAR_VARIANT) || + (collider.type == ENTITY_PLAYER && collider.mass == 1000); + if (npc.state == ULTRA_GREED_COIN_STATE && isCoinStopped) npc.stateFrame = 100; + if (collider.type == ENTITY_PICKUP && collider.variant == PICKUP_ULTRA_GREED_COIN) return contact.isIgnored; + } + else if (npcType == ENTITY_HUSH_FLY) + { + if (colliderType == ENTITY_HUSH_FLY || colliderType == ENTITY_HUSH) return contact.isIgnored; + } + else if (npcType == ENTITY_HUSH) + { + if (colliderType == ENTITY_HUSH_FLY) return contact.isIgnored; + bool isCollided = collider.IsEnemy() || colliderType == ENTITY_PLAYER || colliderType == ENTITY_FAMILIAR; + if (!isCollided) return contact.isIgnored; + } + else if (npcType == ENTITY_GRUDGE && collider.IsEnemy() && npc.collisionDamage > 0 && + !EntityList::HitListContains(npc.hitList, collider)) + { + hit_list_add(npc.hitList, collider); + damage_deal(collider, GRUDGE_DAMAGE, 0, &npc); + } + return std::nullopt; +} + +// An active enemy meets another: a Blood Puppy bites, and a charmed one (or one targeting it) bumps it for damage once +// per hit list, by its health's logarithm. +static void contact_enemy(Entity_NPC& npc, Entity& other) +{ + float damage = 0; + if (npc.type == ENTITY_BLOOD_PUPPY && other.IsEnemy()) + { + if (EntityList::HitListContains(npc.hitList, other)) return; + hit_list_add(npc.hitList, other); + damage = npc.variant == 1 ? BLOOD_PUPPY_BIG_BITE : BLOOD_PUPPY_BITE; + } + else + { + if (!other.IsEnemy() || !npc.IsActiveEnemy(DEAD_EXCLUDED) || !other.IsActiveEnemy(DEAD_EXCLUDED)) return; + bool isSameSide = npc.HasEntityFlags(FLAG_CHARM) == other.HasEntityFlags(FLAG_CHARM); + bool isTargeted = npc.target.get() == &other || npc.forcedTarget.get() == &other; + if ((isSameSide && !isTargeted) || npc.collisionDamage <= 0 || EntityList::HitListContains(npc.hitList, other)) + return; + + hit_list_add(npc.hitList, other); + damage = std::log((npc.maxHitPoints + CHARMED_DAMAGE_BASE) / CHARMED_DAMAGE_SCALE) * CHARMED_DAMAGE_LOG; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && g_game->deathmatchManager.is_active()) + damage = npc.collisionDamage; + if (npc.type == ENTITY_VIS && npc.variant == VIS_CHUBBER_VARIANT) damage = CHUBBER_DAMAGE; + if (other.HasEntityFlags(FLAG_FRIENDLY)) damage = std::min(damage * FRIENDLY_TARGET_SHARE, FRIENDLY_TARGET_MAX); + if (other.HasEntityFlags(FLAG_BAITED) && !npc.HasEntityFlags(FLAG_FRIENDLY | FLAG_CHARM) && !npc.IsBoss()) + damage *= BAITED_SHARE; + } + damage_deal(other, damage, 0, &npc); +} + +// A knocked back enemy hits what it flies into: a frozen one shatters on an enemy, and one with impact damage hurts a +// vulnerable enemy, harder on later floors. +static void contact_impact(Entity_NPC& npc, Entity& other) +{ + if (!npc.HasEntityFlags(FLAG_KNOCKED_BACK) || vector_length(npc.knockbackDirection) <= KNOCKBACK_IMPACT_SPEED) + return; + + if (!npc.HasEntityFlags(FLAG_ICE_FROZEN) || !other.IsEnemy()) + { + if (!other.IsVulnerableEnemy(nullptr) || !npc.HasEntityFlags(FLAG_APPLY_IMPACT_DAMAGE) || + EntityList::HitListContains(npc.hitList, other)) + return; + hit_list_add(npc.hitList, other); + int stage = g_game->stage; + if (g_game->stageType == STAGETYPE_REPENTANCE || g_game->stageType == STAGETYPE_REPENTANCE_B) stage++; + damage_deal(other, (float)(stage - 1) * 2 + IMPACT_DAMAGE_BASE, 0, nullptr); + return; + } + + if (other.HasEntityFlags(FLAG_ICE_FROZEN)) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a frozen enemy knocking an iced one"); + damage_deal(other, ICE_SHATTER_DAMAGE, DAMAGE_ICE_SHATTER, nullptr); + npc.Kill(EntityRef()); +} + +// 006cd410 What it does on touching another entity, and whether that contact is ignored. The special contacts of +// bosses and odd enemies come first, then the generic ones: a shrunk enemy is squished, friends and shots pass, a +// touched player is hurt, kin pass each other, and a charmed enemy bumps others. +bool Entity_NPC::HandleCollision(Entity* collider, bool isLow) +{ + LuaResult lua = lua_engine_get().PreNPCCollision(this, collider, isLow); + if (lua == LUA_RESULT_TRUE) return true; + if (lua == LUA_RESULT_FALSE) return false; + + Contact contact{*this, *collider, type, variant, collider->type, collider->variant}; + contact.isLow = isLow; + Verdict verdict = contact_early(contact); + if (verdict) return *verdict; + + if (aiCallFlags & AI_CALL_COLLISION) + { + collisionEntity = collider; + isCollisionIsLow = isLow; + collisionResult = -1; + ai_call(AI_PHASE_COLLISION); + if (collisionResult > 0) return false; + if (collisionResult == 0) return contact.isIgnored; + } + + for (auto step : {contact_pairs, contact_kinds, contact_passes}) + if ((verdict = step(contact))) return *verdict; + contact.isRelated = is_related(*this, *collider); + for (auto step : {contact_kin, contact_touch, contact_late}) + if ((verdict = step(contact))) return *verdict; + + contact_enemy(*this, *collider); + contact_impact(*this, *collider); + bool isChubberCharmed = type == ENTITY_VIS && variant == VIS_CHUBBER_VARIANT && HasEntityFlags(FLAG_CHARM); + return isChubberCharmed && collider->IsEnemy(); +} diff --git a/src/npc_dip.cpp b/src/npc_dip.cpp index fe6abea..e075602 100644 --- a/src/npc_dip.cpp +++ b/src/npc_dip.cpp @@ -5,17 +5,12 @@ #include "game.h" #include "room.h" -constexpr int ENTITY_DIP = 217; -constexpr int DIP_CORN = 1; constexpr int DIP_BROWNIE = 2; constexpr int DIP_BIG_CORN = 3; constexpr int FAMILIAR_DIP_CORN = 2; constexpr int FAMILIAR_DIP_BROWNIE = 20; constexpr int COLLECTIBLE_DIRTY_MIND_ID = 576; constexpr int TRINKET_DIPPING_TRINKET_ID = 163; -constexpr int PROJECTILE_CORN = 5; -constexpr int SOUND_DIP_HURT = 60; -constexpr int COLOR_PRIORITY_DEFAULT = 255; // How a Dip hops: one chance in ten a frame from rest, at a random speed (doubled for the corn dip), and how it // slows, splats and squeaks. diff --git a/src/npc_dirt.cpp b/src/npc_dirt.cpp new file mode 100644 index 0000000..738f9fd --- /dev/null +++ b/src/npc_dirt.cpp @@ -0,0 +1,84 @@ +#include "npc_basement.h" +#include "gl.h" +#include "kage_graphics.h" +#include "room.h" +#include "room_render.h" +#include +#include + +constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); +constexpr float CHANNEL_MAX = 255; + +// The five points a sized sample reads (the middle, left, right, above and below), in radii, and the floor's scale +// on screen. The surface's luma weights order them. +constexpr int SAMPLE_COUNT = 5; +constexpr std::array, SAMPLE_COUNT> SAMPLE_POINTS = {{{0, 0}, {-1, 0}, {1, 0}, {0, -0.65f}, {0, 0.65f}}}; +constexpr float FLOOR_SCALE = 0.65f; +constexpr float LUMA_RED = 0.212671f; +constexpr float LUMA_GREEN = 0.71516f; +constexpr float LUMA_BLUE = 0.072169f; + +// A render target's texel, read back from the GPU: white past its edges. +static KColor image_pixel_get(KAGE::Graphics::ImageBase& image, uint32_t x, uint32_t y) +{ + if (x >= (uint32_t)image.width || y >= (uint32_t)image.height) return WHITE; + + std::array texel = {}; + KAGE::Graphics::manager.render_target_push(&image, KAGE::Graphics::TARGET_OWN_SIZE, KAGE::Graphics::PRESENT_FLUSH); + gl.ReadPixels((GLint)x, (GLint)y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, texel.data()); + KAGE::Graphics::manager.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); + return kcolor_rgba(texel[0] / CHANNEL_MAX, texel[1] / CHANNEL_MAX, texel[2] / CHANNEL_MAX, texel[3] / CHANNEL_MAX); +} + +static float luma_get(const KColor& color) +{ + return color._green * LUMA_GREEN + color._red * LUMA_RED + color._blue * LUMA_BLUE; +} + +// 00823590 The floor's color under a world position, as the room shows it: the floor surface's texel (with a radius, +// the median by luma of five around it), shaded by the room's shading, tinted by its water and its floor color. +// A missing floor surface reads as white, where the original crashed. +KColor room_floor_color_get(Room& room, const Vector& position, float radius) +{ + KAGE::Graphics::ImageBase* floor = room.backdrop.floorBuffer.get(); + if (!floor) return WHITE; + + Vector screen = vector_sub(render_position_get(position, RENDER_SNAPPED), room.renderSurfaceTopLeft); + KColor color = WHITE; + if (radius <= 0) color = image_pixel_get(*floor, (uint32_t)screen.x, (uint32_t)screen.y); + else + { + std::array samples; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float reach = radius * FLOOR_SCALE; + Vector at = vector_make(screen.x + SAMPLE_POINTS[i][0] * reach, screen.y + SAMPLE_POINTS[i][1] * reach); + samples[i] = image_pixel_get(*floor, (uint32_t)at.x, (uint32_t)at.y); + } + std::ranges::stable_sort(samples, {}, luma_get); + color = samples[SAMPLE_COUNT / 2]; + } + + RoomSurfaces& surfaces = roomSurfaces; + if (surfaces.shading && surfaces.shadingSurface) + { + KColor shade = image_pixel_get(*surfaces.shadingSurface, (uint32_t)screen.x, (uint32_t)screen.y); + color._red += (shade._red - color._red) * shade._alpha; + color._green += (shade._green - color._green) * shade._alpha; + color._blue += (shade._blue - color._blue) * shade._alpha; + } + + float water = room.waterAmount; + if (water > 0) + { + const FXParams& params = room.fxLayers.fxParams; + float blend = water * water * params.waterColor._alpha; + color._red = ((params.waterColor._red - color._red) * blend + color._red) * + ((params.waterColorMultiplier._red - 1) * water + 1); + color._green = ((params.waterColor._green - color._green) * blend + color._green) * + ((params.waterColorMultiplier._green - 1) * water + 1); + color._blue = ((params.waterColor._blue - color._blue) * blend + color._blue) * + ((params.waterColorMultiplier._blue - 1) * water + 1); + } + return kcolor_apply(room.floorColor, color); +} diff --git a/src/npc_embryo.cpp b/src/npc_embryo.cpp new file mode 100644 index 0000000..aee6900 --- /dev/null +++ b/src/npc_embryo.cpp @@ -0,0 +1,39 @@ +#include "npc_basement.h" + +constexpr int SOUND_EMBRYO_LAND = 205; +constexpr float EMBRYO_FRICTION = 0.8f; +constexpr float LANDED_FRICTION = 0.7f; +constexpr float LAND_VOLUME = 0.4f; +constexpr float LAND_VOLUME_RANGE = 0.3f; + +// 0050a6b0 The Embryo's AI: it hops about at random (fleeing its target while feared), slowing as it lands with a +// soft splat. +void npc_embryo_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) npc.state = NPC_STATE_IDLE; + npc.friction *= EMBRYO_FRICTION; + + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || !anim.WasEventTriggered("Landed")) + { + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= EMBRYO_FRICTION; + } + } + if (anim.animData && anim.IsEventTriggered("Landed")) + npc.PlaySound(SOUND_EMBRYO_LAND, random_unit() * LAND_VOLUME_RANGE + LAND_VOLUME, 2, false, 1); + if (anim.animData && anim.WasEventTriggered("Landed")) npc.friction *= LANDED_FRICTION; + + const AnimationData* current = anim.animData; + bool isWalking = current && current->name == "Walk Sad" && (!current->isLooping || anim.isPlaying); + if (!isWalking && npc.sprite.SetAnimation("Walk Sad", SWITCH_KEEP_FRAME)) + { + anim.Rewind(); + anim.isPlaying = true; + } + npc.sprite.isFlipX = npc.velocity.x < 0; +} diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp index 1498c04..c10d6b6 100644 --- a/src/npc_fireplace.cpp +++ b/src/npc_fireplace.cpp @@ -1,4 +1,5 @@ #include "npc_fireplace.h" +#include "entity_effect.h" #include "entity_pickup.h" #include "entity_player.h" #include "entity_projectile.h" @@ -7,20 +8,6 @@ #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; @@ -70,11 +57,6 @@ 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; @@ -102,19 +84,12 @@ 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]) diff --git a/src/npc_fireplace.h b/src/npc_fireplace.h index 785edcf..201229c 100644 --- a/src/npc_fireplace.h +++ b/src/npc_fireplace.h @@ -2,4 +2,18 @@ struct Entity_NPC; +// 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 +}; + void npc_fireplace_update(Entity_NPC& npc); diff --git a/src/npc_fly.cpp b/src/npc_fly.cpp index f36cccb..baa4689 100644 --- a/src/npc_fly.cpp +++ b/src/npc_fly.cpp @@ -1,21 +1,42 @@ -#include "npc_ai.h" +#include "npc_basement.h" +#include "entity_bomb.h" +#include "entity_config.h" #include "entity_player.h" #include "game.h" #include "grid_entity.h" #include "room.h" #include "score_sheet.h" +#include -constexpr int ENTITY_ISAAC_BOSS = 102; -constexpr int ENTITY_ORBIT_SPAWNER = 873; +// The fly kin this AI runs: the fly, Pooter, attack fly, the Sucker's family, Moter, the level 2 fly, the full fly and +// the fly bomb. +constexpr int ENTITY_MOTER = 80; +constexpr int ENTITY_FLY_L2 = 214; +constexpr int ENTITY_FULL_FLY = 249; constexpr int SPAWNER_UNBOUNDED = 67; -constexpr int COLLECTIBLE_SKATOLE_ID = 9; -constexpr int POOTER_TRIPLE_VARIANT = 2; -constexpr int POOTER_TWO_SHOT_VARIANT = 1; -// The fly types this file covers: the fly, the Pooter and the attack fly. -constexpr int ENTITY_FLY = 13; -constexpr int ENTITY_POOTER = 14; -constexpr int ENTITY_ATTACKFLY = 18; +// The Sucker's variants: the Sucker, Spit, Soul Sucker, Ink, Mama Fly, the Bulbs and the Bloodfly. +constexpr int SUCKER_SPIT = 1; +constexpr int SUCKER_SOUL = 2; +constexpr int SUCKER_INK = 3; +constexpr int SUCKER_MAMA_FLY = 4; +constexpr int SUCKER_BULB_BLACK = 6; +constexpr int POOTER_TWO_SHOT_VARIANT = 1; +constexpr int POOTER_TRIPLE_VARIANT = 2; +constexpr int FLY_BOMB_ORBITING = 1; +constexpr int FLY_BOMB_BOMB_VARIANT = 14; + +constexpr ColorMod SPIT_SPLAT_COLOR = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {-0.19607845f, 0.50980395f, 0.19607845f}}; +constexpr ColorMod INK_SPLAT_COLOR = {{0.02f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FLY_BOMB_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.11764707f, 0.11764707f, 0.11764707f}}; + +// The Suckers' death shots: a plus, or the Bloodfly's ring of six. +constexpr float SUCKER_SHOT_SPEED = 8; +constexpr float SUCKER_HARD_SHOT_SPEED = 10; +constexpr float BLOODFLY_RING_SHOTS = 6; +constexpr float BLOODFLY_SHOT_SCALE = 1.8f; +constexpr float MOTER_SPLIT_SPEED = 10; +constexpr float MOTER_OVERKILL = -20; // How a Pooter shoots: when its target is in range (checked every 7 frames), its cooldowns, and its shot. constexpr float POOTER_RANGE = 200; @@ -27,14 +48,26 @@ constexpr float POOTER_HARD_SHOT_SPEED = 10; constexpr float POOTER_FRICTION = 0.8f; constexpr float POOTER_DRIFT_DECAY = 0.7f; constexpr int SOUND_POOTER_SHOOT = 178; -constexpr uint64_t PROJECTILE_FLAG_54 = 1ull << 54; - -// The super Pooter's shot. constexpr float SUPER_POOTER_SCALE = 1.4f; constexpr float SUPER_POOTER_FALL_ACCEL = -0.15f; constexpr float SUPER_POOTER_FALL_SPEED = 1; constexpr float SUPER_POOTER_SPREAD = 1.2f; +// The fly bomb's cannonball: shot at 10, it deploys after 45 frames or below 5, bouncing off walls. Its orbiting kind +// circles its parent at 40, and drops a bomb that blows 46 to 60 frames later. +constexpr float CANNONBALL_SPEED = 10; +constexpr float CANNONBALL_MASS = 50; +constexpr int CANNONBALL_FRAMES = 45; +constexpr float CANNONBALL_MIN_SPEED = 5; +constexpr float CANNONBALL_FRICTION = 0.85f; +constexpr int SOUND_CANNONBALL_BOUNCE = 40; +constexpr float ORBIT_TURN = 5; +constexpr float ORBIT_RADIUS = 40; +constexpr float ORBIT_DROP_SPEED = 15; +constexpr int BOMB_FUSE = 60; +constexpr int BOMB_FUSE_RANGE = 15; +constexpr int BOMB_APPEAR_FRAME = 8; + // How a fly wanders: the spot it eyes (and a poop or fireplace there), its drift and the bounds it stays within. constexpr int FLY_RETARGET_FRAMES = 3; constexpr float FLY_WANDER = 240; @@ -42,6 +75,7 @@ constexpr int FLY_FIREPLACE_ODDS = 100; constexpr int FLY_POOP_ODDS = 1000; constexpr int FLY_CHASE_ODDS = 5; constexpr float FLY_CHASE_SPEED = 0.7f; +constexpr float FLY_STEER_SPEED = 1.1f; constexpr float FLY_DRIFT_KEEP = 0.4f; constexpr float FLY_DRIFT_NEW = 0.6f; constexpr float FLY_DRIFT_STEP = 0.06f; @@ -53,6 +87,15 @@ constexpr float FLY_FRICTION = 0.6f; constexpr int FLY_DRIFT_PERIOD = 4; constexpr int FLY_STEER_PERIOD = 3; +// How a kin fly circles its parent: within 260, at 65 give or take a slow sway of 5. +constexpr float PARENT_RANGE = 260; +constexpr float PARENT_ORBIT = 65; +constexpr float PARENT_SWAY = 5; +constexpr float PARENT_SWAY_RATE = 0.02f; +constexpr float PARENT_PULL = 0.5f; +constexpr float PARENT_SPIN = 0.2f; +constexpr float PARENT_SPIN_DAMP = 2; + // How a fly flees what it fears: within 400 (at full distance under 200), aimed in a random arc around away. constexpr float FLEE_RANGE = 400; constexpr float FLEE_NEAR = 200; @@ -61,49 +104,172 @@ constexpr float FLEE_ARC = 220; constexpr float FLEE_ARC_BLOCKED = 360; constexpr uint64_t FLEE_BLOCKERS = FLAG_FREEZE | FLAG_CHARM | FLAG_CONFUSION | FLAG_MIDAS_FREEZE; -// How it flies to its target: how near it stops (an attack fly nearer), and how hard it pulls. +// How it flies to its target: how near it stops (the kin nearer, Suckers and big flies nearer still), and how hard +// it pulls. The zigzagging kin pull twice as hard, and bounce off walls now and then. constexpr float TARGET_REACH = 30; -constexpr float TARGET_REACH_ATTACK = 25; +constexpr float TARGET_REACH_KIN = 25; constexpr float TARGET_REACH_BIG = 15; constexpr float TARGET_PULL = 0.08f; constexpr float TARGET_PULL_MAX = 1.2f; constexpr float TARGET_Y_SHARE = 0.5f; constexpr float TARGET_PARENT_SHARE = 0.2f; +constexpr float CONTROLLER_REACH = 100; constexpr float BIG_FLY_SCALE = 1.1f; constexpr float KILL_ON_TOUCH_FRICTION = 0.9f; constexpr float CHARGE_INTERVAL = 2; constexpr float REGENERATION_FRAMES = 60; constexpr uint32_t GRID_COLLISION_WALL = 4; +constexpr int BOUNCE_ODDS = 3; +constexpr float BOUNCE_MIN = 2; +constexpr float BOUNCE_RANGE = 1.5f; +constexpr float BOUNCE_DECAY = 0.9f; -// The fly's sprite: Fly while it flies (restarted when it stopped), the Pooter's back to Fly after its attack. +static bool is_kin(int type) +{ + return type == ENTITY_ATTACKFLY || type == ENTITY_MOTER || type == ENTITY_FLY_L2 || type == ENTITY_FULL_FLY || + type == ENTITY_FLY_BOMB; +} + +static bool is_zigzag(int type) +{ + return type == ENTITY_FLY_L2 || type == ENTITY_FULL_FLY || type == ENTITY_FLY_BOMB; +} + +// The first frame: idle, with a Spit's green, an Ink's black and a fly bomb's dark blood. The orbiting fly bomb is +// out of reach. +static void fly_init(Entity_NPC& npc) +{ + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.v2 = {}; + npc.state = NPC_STATE_IDLE; + if (npc.type == ENTITY_SUCKER && npc.variant == SUCKER_SPIT) npc.splatColor = SPIT_SPLAT_COLOR; + else if (npc.type == ENTITY_SUCKER && npc.variant == SUCKER_INK) npc.splatColor = INK_SPLAT_COLOR; + else if (npc.type == ENTITY_FLY_BOMB) + { + npc.splatColor = FLY_BOMB_SPLAT_COLOR; + if (npc.variant == FLY_BOMB_ORBITING) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.isInvincible = true; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + } + } + npc.i1 = 0; +} + +// A dying Sucker bursts by its variant: a plus of shots, the Spit's arcing puddle shot, or the Bloodfly's ring. +static void sucker_death(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_SHRINK)) return; + + switch (npc.variant) + { + case 0: + { + ProjectileParams params; + float speed = game_is_hard_mode() ? SUCKER_HARD_SHOT_SPEED : SUCKER_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_PLUS, params); + break; + } + case SUCKER_SPIT: + reconstruction_missing("npc_fly_update 00506bd0: a Spit's death shot (FireBossProjectiles' projectile)"); + case SUCKER_SOUL: + reconstruction_missing("npc_fly_update 00506bd0: a Soul Sucker's death (spawn_tracer_effect198)"); + case SUCKER_INK: + reconstruction_missing("npc_fly_update 00506bd0: an Ink's death splash"); + case SUCKER_BLOODFLY: + { + ProjectileParams params; + params.scale = BLOODFLY_SHOT_SCALE; + params.bulletFlags = PROJECTILE_BURST8; + params.circleAngle = 0; + npc.FireProjectiles(npc.pos, vector_make(SUCKER_SHOT_SPEED, BLOODFLY_RING_SHOTS), PROJECTILES_RING, params); + break; + } + } +} + +// A Moter killed outright splits into two attack flies, flung apart across its target's line. +static void moter_split(Entity_NPC& npc) +{ + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + float distance = vector_length(toward); + Vector fling = distance > 0 + ? vector_make(-(toward.y / distance) * MOTER_SPLIT_SPEED, toward.x / distance * MOTER_SPLIT_SPEED) + : vector_scale(random_direction(), MOTER_SPLIT_SPEED); + + uint32_t seed = Random(); + Entity* first = g_game->Spawn({.position = vector_add(npc.pos, fling), + .velocity = fling, + .spawner = &npc, + .type = ENTITY_ATTACKFLY, + .seed = seed}); + seed = Random(); + Entity* second = g_game->Spawn({.position = vector_sub(npc.pos, fling), + .velocity = vector_sub({}, fling), + .spawner = &npc, + .type = ENTITY_ATTACKFLY, + .seed = seed}); + first->ClearEntityFlags(FLAG_APPEAR); + second->ClearEntityFlags(FLAG_APPEAR); + first->Update(); + second->Update(); +} + +// The fly bomb's bomb, lit to blow 46 to 60 frames later. +static void fly_bomb_drop(Entity_NPC& npc, Entity* parent) +{ + Entity_Bomb* bomb = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = npc.velocity, + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = FLY_BOMB_BOMB_VARIANT, + .seed = Random()})); + bomb->sprite.Play("Appear"); + if (bomb->sprite.animState.animData) bomb->sprite.animState.SetFrameFloat(BOMB_APPEAR_FRAME); + bomb->parent = parent; + bomb->SetExplosionCountdown(BOMB_FUSE - (int)(Random() % BOMB_FUSE_RANGE)); +} + +// The fly's sprite: Fly while it flies (restarted when it stopped, a Sucker facing its way), the Pooter's back to +// Fly after its attack, the kin idling. static void fly_animation_update(Entity_NPC& npc) { - if (npc.type == ENTITY_POOTER) + int type = npc.type; + if (type == ENTITY_FLY || type == ENTITY_MOTER || type == ENTITY_SUCKER || type == ENTITY_ATTACKFLY) + { + const AnimationData* current = npc.sprite.animState.animData; + bool isFlying = current && current->name == "Fly" && (!current->isLooping || npc.sprite.animState.isPlaying); + if (!isFlying && npc.sprite.SetAnimation("Fly", SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + if (type == ENTITY_SUCKER) npc.sprite.isFlipX = npc.velocity.x < 0; + } + else if (type == ENTITY_POOTER) { bool isAttackDone = !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; if (npc.state < NPC_STATE_SUICIDE) npc.sprite.Play("Fly"); else if (npc.state == NPC_STATE_ATTACK && isAttackDone) npc.state = NPC_STATE_MOVE; - return; - } - - const AnimationData* current = npc.sprite.animState.animData; - bool isFlying = current && current->name == "Fly" && (!current->isLooping || npc.sprite.animState.isPlaying); - if (!isFlying && npc.sprite.SetAnimation("Fly", SWITCH_KEEP_FRAME)) - { - npc.sprite.animState.Rewind(); - npc.sprite.animState.isPlaying = true; } + else if (type == ENTITY_FLY_L2 || type == ENTITY_FULL_FLY || (type == ENTITY_FLY_BOMB && npc.state == NPC_STATE_IDLE)) + npc.sprite.Play("Idle"); } -// A fly that crosses a poop (one chance in a thousand a frame) eats it and becomes a Pooter. +// A fly that crosses a poop (one chance in a thousand a frame) eats some of it and becomes a Pooter. static void fly_poop_eat(Entity_NPC& npc) { if (npc.type != ENTITY_FLY || Random() % FLY_POOP_ODDS != 0) return; Room& room = *g_game->room; int gridIndex = room.GetGridIndex(npc.pos); - GridEntity* grid = gridIndex >= 0 ? room.GetGridEntity(gridIndex) : nullptr; - if (grid && grid->type == GRID_POOP) reconstruction_missing("npc_fly_update 00506bd0: a fly eating poop"); + GridEntity* grid = gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (!grid || grid->type != GRID_POOP) return; + + grid->Hurt(1, EntityRef(&npc)); + npc.Morph(ENTITY_POOTER, 0, 0, -1); + npc.health = npc.maxHitPoints; } // A Pooter in range of its target turns to it and shoots on its Shoot event: a single shot, two for the twin @@ -137,7 +303,7 @@ static void pooter_attack_update(Entity_NPC& npc) params.fallingAccelModifier = SUPER_POOTER_FALL_ACCEL; params.fallingSpeedModifier = SUPER_POOTER_FALL_SPEED; params.spread = SUPER_POOTER_SPREAD; - params.bulletFlags = PROJECTILE_FLAG_54; + params.bulletFlags = PROJECTILE_BACK_SPLIT; params.isFallingKept = true; mode = PROJECTILES_FOUR; speed = POOTER_SHOT_SPEED; @@ -155,32 +321,104 @@ static void pooter_attack_update(Entity_NPC& npc) } } -// Every third frame a fly picks where it heads: an attack fly (or any under Skatole) its target, a plain fly or -// Pooter eyes a random spot and its poop, or now and then a fireplace, though it heads nowhere in the end. +// The fly bomb shot as a cannonball flies at 10 until it slows or 45 frames pass, bouncing off walls, then deploys. +// The orbiting one circles its parent, dropping its bomb once the parent is gone. Whether the update ends here. +static bool fly_bomb_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_SPECIAL) + { + if (npc.stateFrame == -1) + { + npc.friction *= CANNONBALL_FRICTION; + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) npc.state = NPC_STATE_IDLE; + return true; + } + if (npc.mass < CANNONBALL_MASS) + { + npc.velocity = vector_resized(npc.velocity, CANNONBALL_SPEED); + npc.mass = CANNONBALL_MASS; + } + npc.sprite.Play("Cannonball"); + npc.stateFrame++; + if (npc.stateFrame > CANNONBALL_FRAMES || vector_length(npc.velocity) < CANNONBALL_MIN_SPEED) + { + npc.sprite.Play("Deploy"); + npc.stateFrame = -1; + npc.mass = npc.config->mass; + } + if (!npc.isCollidesWithGrid) return true; + + Vector normal = npc.gridCollisionNormal; + Vector hit = npc.gridCollisionVelocity; + npc.velocity = vector_sub(hit, vector_scale(normal, 2 * vector_dot(hit, normal))); + npc_sound_play(SOUND_CANNONBALL_BOUNCE, 1, 2, 1); + return true; + } + if (npc.variant != FLY_BOMB_ORBITING) return false; + + Entity* parent = npc.parent.get(); + npc.isInvincible = true; + if (!parent) + { + npc.Kill(EntityRef()); + npc.velocity = vector_scale(vector_from_angle(npc.v1.x), ORBIT_DROP_SPEED); + fly_bomb_drop(npc, npc.parent.get()); + return true; + } + npc.v1.x = normalize_angle_degrees(npc.speedMultiplier * ORBIT_TURN + npc.v1.x); + npc.targetPosition = vector_add(parent->pos, vector_scale(vector_from_angle(npc.v1.x), ORBIT_RADIUS)); + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + return true; +} + +// A kin fly near its parent keeps a swaying distance around it and circles it. +static void fly_parent_circle(Entity_NPC& npc) +{ + Entity* parent = npc.parent.get(); + if (!parent || npc.controllerID != -1) return; + + Vector toward = vector_sub(parent->pos, npc.pos); + float distance = vector_length(toward); + if (distance >= PARENT_RANGE) return; + + float sway = std::sin((float)g_game->frameCount * PARENT_SWAY_RATE) * PARENT_SWAY + PARENT_ORBIT; + float offset = std::clamp(distance - sway, -PARENT_SWAY, PARENT_SWAY); + npc.AddVelocity_divided(vector_make(offset * toward.x * PARENT_PULL / distance, + offset * toward.y * PARENT_PULL / distance), + false); + float spin = std::abs(offset) + PARENT_SPIN_DAMP; + npc.AddVelocity_divided(vector_make(-(toward.y * PARENT_SPIN / spin) / npc.friction, + toward.x * PARENT_SPIN / spin / npc.friction), + false); +} + +// A plain fly or Pooter eyes a random spot within 240 and its poop, or now and then a fireplace. +static void fly_wander_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector direction = random_direction(); + float scaleFirst = random_unit(); + float distance = random_unit() * scaleFirst * FLY_WANDER; + int gridIndex = room.GetGridIndex(vector_add(npc.pos, vector_scale(direction, distance))); + GridEntity* grid = gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (grid && grid->type == GRID_POOP) npc.targetPosition = room.GetGridPosition(gridIndex); + if (Random() % FLY_FIREPLACE_ODDS != 0) return; + + std::vector fireplaces; + for (Entity* entity : room.entityList.mainEL) + if (entity->type == ENTITY_FIREPLACE) fireplaces.push_back(entity); + if (!fireplaces.empty()) npc.targetPosition = fireplaces[random_below((int)fireplaces.size())]->pos; +} + +// Every third frame a fly picks where it heads: the kin circle their parent, plain flies and Pooters eye a spot, +// and in the end each heads for its target (a plain fly or Pooter forgets it right after). static void fly_target_pick(Entity_NPC& npc, bool isSkatoleActive) { if (!npc.IsFrame(FLY_RETARGET_FRAMES, 0)) return; - if (npc.type == ENTITY_ATTACKFLY && npc.parent && npc.controllerID == -1) - reconstruction_missing("npc_fly_update 00506bd0: an attack fly circling its parent"); - if (npc.type != ENTITY_ATTACKFLY && !isSkatoleActive) - { - Room& room = *g_game->room; - Vector direction = random_direction(); - float scaleFirst = random_unit(); - float distance = random_unit() * scaleFirst * FLY_WANDER; - int gridIndex = room.GetGridIndex(vector_add(npc.pos, vector_scale(direction, distance))); - GridEntity* grid = gridIndex >= 0 ? room.GetGridEntity(gridIndex) : nullptr; - if (grid && grid->type == GRID_POOP) npc.targetPosition = room.GetGridPosition(gridIndex); - if (Random() % FLY_FIREPLACE_ODDS == 0) - { - std::vector fireplaces; - for (Entity* entity : room.entityList.mainEL) - if (entity->type == ENTITY_FIREPLACE) fireplaces.push_back(entity); - if (!fireplaces.empty()) npc.targetPosition = fireplaces[random_below((int)fireplaces.size())]->pos; - } - return; - } + if (is_kin(npc.type)) fly_parent_circle(npc); + bool isWanderer = npc.type != ENTITY_ATTACKFLY && npc.type != ENTITY_SUCKER && !is_kin(npc.type); + if (isWanderer && !isSkatoleActive) fly_wander_pick(npc); npc.targetPosition = npc.CalcTargetPosition(0); } @@ -205,42 +443,72 @@ static void fly_flee_update(Entity_NPC& npc) npc.v1 = vector_scale(npc.v1, 0.5f); } -// Every other tick a fly with a target pulls toward it once farther than its reach, harder the farther. -static void fly_target_follow(Entity_NPC& npc) +// Every other tick a fly with a target pulls toward it once farther than its reach, harder the farther. The level 2 +// fly and fly bomb veer one way, the full fly the other, twice as hard. +static void fly_target_follow(Entity_NPC& npc, bool isSkatoleActive) { if (vector_is_zero(npc.targetPosition) || npc.GetIntervalTicks(CHARGE_INTERVAL, 0) == 0) return; - float reach = npc.type == ENTITY_ATTACKFLY ? TARGET_REACH_ATTACK : TARGET_REACH; - if (npc.sprite.scale.x > BIG_FLY_SCALE) reach = TARGET_REACH_BIG; + int type = npc.type; + float reach = is_kin(type) ? TARGET_REACH_KIN : TARGET_REACH; + if (type == ENTITY_SUCKER || npc.sprite.scale.x > BIG_FLY_SCALE) reach = TARGET_REACH_BIG; Vector toward = vector_sub(npc.targetPosition, npc.pos); if (npc.controllerID == -1) { + bool isVeering = !isSkatoleActive; + if ((type == ENTITY_FLY_L2 || type == ENTITY_FLY_BOMB) && isVeering) + toward = vector_make(toward.x - toward.y, toward.y + toward.x); + else if (type == ENTITY_FULL_FLY && isVeering) toward = vector_make(toward.x + toward.y, toward.y - toward.x); toward.y *= TARGET_Y_SHARE; if (npc.parent) toward = vector_scale(toward, TARGET_PARENT_SHARE); } - else toward = vector_scale(npc.GetControllerInput(0), FLEE_DISTANCE); + else toward = vector_scale(npc.GetControllerInput(0), CONTROLLER_REACH); float distance = vector_length(toward); Vector direction = distance > 0 ? vector_scale(toward, 1 / distance) : toward; if (npc.isKillOnTouch) npc.friction *= KILL_ON_TOUCH_FRICTION; - if (npc.type != ENTITY_ATTACKFLY) npc.v1 = vector_scale(npc.v1, POOTER_DRIFT_DECAY); - if (distance > reach) - npc.AddVelocity_divided(vector_scale(direction, std::min((distance - reach) * TARGET_PULL, TARGET_PULL_MAX)), - false); + if (type != ENTITY_SUCKER && !is_kin(type)) npc.v1 = vector_scale(npc.v1, POOTER_DRIFT_DECAY); + if (distance <= reach) return; + + float pull = std::min((distance - reach) * TARGET_PULL, TARGET_PULL_MAX); + if (is_zigzag(type) && !isSkatoleActive) pull += pull; + npc.AddVelocity_divided(vector_scale(direction, pull), false); } -// A fly's buzzing: without a target it now and then darts toward its player, every fourth frame its drift turns, -// every third it drifts back inside the room's middle and its drift moves it. +// The zigzagging kin now and then bounce off a wall they touch, the bounce fading. +static void fly_bounce_update(Entity_NPC& npc) +{ + if (npc.isCollidesWithGrid && Random() % BOUNCE_ODDS == 0 && !npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + npc.v2 = vector_resized(npc.gridCollisionNormal, -BOUNCE_MIN - random_unit() * BOUNCE_RANGE); + + if (vector_length_squared(npc.v2) <= 1) + { + npc.v2 = {}; + return; + } + npc.AddVelocity_divided(npc.v2, false); + npc.v2 = vector_scale(npc.v2, BOUNCE_DECAY); +} + +// A fly's buzzing: without a target it now and then darts toward its player (or its player steers it), every fourth +// frame its drift turns, every third it drifts back inside the room's middle and its drift moves it. static void fly_drift_update(Entity_NPC& npc) { if (vector_is_zero(npc.targetPosition)) { - if (npc.controllerID != -1) reconstruction_missing("npc_fly_update 00506bd0: a controlled fly's steering"); - if (Random() % FLY_CHASE_ODDS == 0) + if (npc.controllerID == -1) { - Vector toward = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); - npc.velocity = vector_add(npc.velocity, vector_scale(toward, FLY_CHASE_SPEED * npc.speedMultiplier)); + if (Random() % FLY_CHASE_ODDS == 0) + { + Vector toward = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.velocity = vector_add(npc.velocity, vector_scale(toward, FLY_CHASE_SPEED * npc.speedMultiplier)); + } + } + else if (npc.GetIntervalTicks(CHARGE_INTERVAL, 0) != 0) + { + Vector input = npc.GetControllerInput(0); + npc.velocity = vector_add(npc.velocity, vector_scale(input, FLY_STEER_SPEED * npc.speedMultiplier)); } } @@ -260,31 +528,26 @@ static void fly_drift_update(Entity_NPC& npc) npc.friction *= FLY_FRICTION; } -// 00506bd0 The flies' AI (the fly, Pooter and attack fly, with Moter, Sucker and their kin left to come): Skatole -// befriends them, Lord of the Flies turns them blue, they buzz about drifting, the attack fly chases its target and -// the Pooter shoots at it. +// 00506bd0 The flies' AI: the fly, Pooter, attack fly, Moter, the Suckers, the level 2 and full flies and the fly +// bomb. Skatole befriends them, Lord of the Flies turns them blue, they buzz about drifting, the kin circle their +// parent and chase their target, the Pooter shoots at it, and the Suckers and Moter burst as they die. void npc_fly_update(Entity_NPC& npc) { - bool isCovered = npc.type == ENTITY_FLY || npc.type == ENTITY_POOTER || npc.type == ENTITY_ATTACKFLY; - if (!isCovered) reconstruction_missing("npc_fly_update 00506bd0: the Sucker, Moter and the other fly kin"); - - if (npc.state == NPC_STATE_INIT) - { - npc.entityGridCollisionClass = GRIDCOLL_WALLS; - npc.v2 = {}; - npc.state = NPC_STATE_IDLE; - npc.i1 = 0; - } + if (npc.type == ENTITY_SUCKER && (npc.variant == SUCKER_BULB || npc.variant == SUCKER_BULB_BLACK)) + return NpcAI::ENTITY_BULB(&npc); + if (npc.type == ENTITY_SUCKER && npc.variant == SUCKER_MAMA_FLY) return (void)NpcAI::ENTITY_MAMA_FLY(&npc); + if (npc.state == NPC_STATE_INIT) fly_init(npc); PlayerManager& players = g_game->playerManager; - bool isSkatoleActive = - players.FirstCollectibleOwner(COLLECTIBLE_SKATOLE_ID, LAZARUS_SHARE_CHECK) && !npc.IsFriendly(); + bool isSkatoleActive = players.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK) && !npc.IsFriendly(); if (isSkatoleActive && npc.type == ENTITY_ATTACKFLY) npc.Morph(ENTITY_FLY, 0, 0, -1); Entity_Player* beelzebub = players.GetRandomPlayer(npc.initSeed); if (beelzebub && !npc.isDead) { - if (npc.type == ENTITY_ATTACKFLY || npc.type == ENTITY_FLY) + bool isBlued = npc.type == ENTITY_ATTACKFLY || npc.type == ENTITY_FLY || npc.type == ENTITY_FLY_L2 || + npc.type == ENTITY_FULL_FLY; + if (isBlued) { g_game->scoreSheet.AddKilledEnemy(npc); npc.Remove(); @@ -292,12 +555,17 @@ void npc_fly_update(Entity_NPC& npc) } else if (!npc.IsBoss() && !npc.IsFriendly()) npc.AddCharmed(EntityRef(beelzebub), -1, true, false); } + if (npc.type == ENTITY_SUCKER && npc.controllerID != -1 && npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) + npc.Kill(EntityRef()); + if (npc.isDead && npc.type == ENTITY_SUCKER) sucker_death(npc); + else if (npc.isDead && npc.type == ENTITY_MOTER && npc.health > MOTER_OVERKILL && !isSkatoleActive) moter_split(npc); if (npc.i1 > 0) { npc.health = std::min(npc.health + npc.maxHitPoints / REGENERATION_FRAMES, npc.maxHitPoints); npc.i1--; } + if (npc.isDead && npc.type == ENTITY_FLY_BOMB) fly_bomb_drop(npc, npc.parent.get()); fly_animation_update(npc); fly_poop_eat(npc); @@ -306,14 +574,92 @@ void npc_fly_update(Entity_NPC& npc) bool isIsaacsFly = npc.spawnerType == ENTITY_ISAAC_BOSS && npc.subtype != 0; if (isIsaacsFly) NpcAI::ENTITY_FLY_isaac_spawned(&npc); else if (npc.spawnerType == ENTITY_ORBIT_SPAWNER) return NpcAI::ENTITY_FLY_orbit_parent(&npc); - else fly_target_pick(npc, isSkatoleActive); + else + { + if (npc.type == ENTITY_FLY_BOMB && fly_bomb_update(npc)) return; + fly_target_pick(npc, isSkatoleActive); + } if ((npc.type == ENTITY_FLY || npc.type == ENTITY_POOTER) && !isIsaacsFly) npc.targetPosition = {}; fly_flee_update(npc); - if (!isIsaacsFly) fly_target_follow(npc); + if (!isIsaacsFly) + { + fly_target_follow(npc, isSkatoleActive); + if (is_zigzag(npc.type)) fly_bounce_update(npc); + } if (npc.entityGridCollisionClass == GRIDCOLL_NONE && g_game->room->IsPositionInRoom(npc.pos, npc.size) && room_grid_collision_at(npc.pos) < GRID_COLLISION_WALL) npc.entityGridCollisionClass = GRIDCOLL_WALLS; fly_drift_update(npc); + + if (npc.type == ENTITY_FULL_FLY && npc.isDead && !npc.HasEntityFlags(FLAG_SHRINK)) + { + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(SUCKER_SHOT_SPEED, BLOODFLY_RING_SHOTS), PROJECTILES_RING, params); + } +} + +// The dart fly circles while it homes in on where its target is heading, at up to 8. +constexpr float DART_TURN = 0.18849558f; +constexpr float DART_FULL_TURN = 6.2831855f; +constexpr float DART_LEAD = 0.25f; +constexpr float DART_CIRCLE = 10; +constexpr float DART_HOMING = 15; +constexpr float DART_HOMING_SHARE = 0.9f; +constexpr float DART_ACCEL = 0.75f; +constexpr float DART_ACCEL_DAMP = 0.9f; +constexpr float DART_ACCEL_SHARE = 0.033333335f; +constexpr float DART_MAX_SPEED = 8; +constexpr float DART_FRICTION = 0.95f; + +// 005400d0 The dart fly's AI: Lord of the Flies turns it blue and Skatole tames it into a fly. It weaves along a +// circle while homing in on where its target is heading, at up to 8. +void npc_dart_fly_update(Entity_NPC& npc) +{ + PlayerManager& players = g_game->playerManager; + Entity_Player* beelzebub = players.GetRandomPlayer(npc.initSeed); + if (beelzebub && !npc.isDead) + { + g_game->scoreSheet.AddKilledEnemy(npc); + npc.Remove(); + beelzebub->AddBlueFlies(1, npc.pos, nullptr); + } + if (players.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK) && !npc.IsFriendly()) + { + npc.Morph(ENTITY_FLY, 0, 0, -1); + npc.v2 = {}; + npc.v1 = {}; + } + if (npc.state == NPC_STATE_INIT) + { + npc.stateFrame = 0; + npc.state = NPC_STATE_MOVE; + float turn = random_unit(); + npc.v1.x = (turn + turn) * PI_F; + } + + if (npc.state == NPC_STATE_MOVE) + { + if (npc.controllerID != -1) + reconstruction_missing("NpcAI::ENTITY_DART_FLY 005400d0: a dart fly under a player's control"); + npc.v1.x += DART_TURN; + if (npc.v1.x >= DART_FULL_TURN) npc.v1.x -= DART_FULL_TURN; + + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + float distance = vector_length(toward); + Vector lead = npc.GetPlayerTarget()->velocity; + Vector aim = vector_normalized(vector_make((lead.x + lead.x) * distance * DART_LEAD + toward.x, + (lead.y + lead.y) * distance * DART_LEAD + toward.y)); + float circleX = (float)std::cos((double)(npc.v1.x * 0.5f)); + float circleY = (float)std::sin((double)npc.v1.x); + float steerX = circleX * DART_CIRCLE + aim.x * DART_HOMING * DART_HOMING_SHARE; + float steerY = circleY * DART_CIRCLE + aim.y * DART_HOMING * DART_HOMING_SHARE; + npc.velocity.x += steerX * DART_ACCEL * DART_ACCEL_DAMP * DART_ACCEL_SHARE * npc.speedMultiplier; + npc.velocity.y += steerY * DART_ACCEL * DART_ACCEL_DAMP * DART_ACCEL_SHARE * npc.speedMultiplier; + if (vector_length(npc.velocity) > DART_MAX_SPEED) npc.velocity = vector_resized(npc.velocity, DART_MAX_SPEED); + npc.friction *= DART_FRICTION; + } + npc.sprite.Play("Fly"); + npc.sprite.isFlipX = npc.velocity.x > 0; } diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index 415d73c..d193a31 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -4,14 +4,9 @@ #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; @@ -23,13 +18,8 @@ constexpr int CONJOINED_FATTY_PLAIN = 0; constexpr int STONEY_CROSS = 10; constexpr int FIREPLACE_MOVING = 10; -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; @@ -37,9 +27,6 @@ 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; diff --git a/src/npc_gusher.cpp b/src/npc_gusher.cpp index fee38dc..ad35dc9 100644 --- a/src/npc_gusher.cpp +++ b/src/npc_gusher.cpp @@ -4,18 +4,12 @@ #include "level.h" // The headless enemies this AI runs: the Gusher and Pacer, Blubber and Half Sack, Splasher and the Black Globin's body. -constexpr int ENTITY_GUSHER = 11; -constexpr int ENTITY_BLUBBER = 210; constexpr int ENTITY_HALF_SACK = 211; constexpr int ENTITY_SPLASHER = 238; constexpr int ENTITY_BLACK_GLOBIN_BODY = 280; constexpr int SOUND_BLOBBY_WIGGLE = 3; -constexpr int SOUND_BLOODSHOOT = 178; constexpr int SOUND_BOIL_HATCH = 181; -constexpr int CONTROLLER_ACTION_SHOOT = 9; -constexpr uint64_t PROJECTILE_EXPLODE = 1ull << 1; -constexpr uint64_t FLAG_DISTRACTED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; constexpr uint64_t DAMAGE_TNT = 1ull << 12; constexpr float WALK_THRESHOLD_GUSHER = 0.1f; constexpr float GUSHER_DEADZONE = 0.1f; @@ -24,8 +18,6 @@ constexpr float GUSHER_DEADZONE = 0.1f; constexpr int STAGE_ID_FLOODED_CAVES = 6; constexpr int STAGE_ID_DOWNPOUR = 27; constexpr int STAGE_ID_DROSS = 28; -constexpr int PROJECTILE_TEAR = 4; -constexpr int PROJECTILE_PUKE = 3; // Gushers wait 20 to 39 frames to start, 40 to 59 between shots (Splashers 60 to 89), shooting at 5 along their walk // at targets within 1000. Blubbers wait 30 to 59 between bursts of three to five. diff --git a/src/npc_hive.cpp b/src/npc_hive.cpp new file mode 100644 index 0000000..15fddb5 --- /dev/null +++ b/src/npc_hive.cpp @@ -0,0 +1,252 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "game.h" +#include "room.h" +#include +#include + +// The hives this AI runs: the Hive (with its drowned, holy and tainted variants), the Nest and the Willo hive. +constexpr int ENTITY_NEST = 205; +constexpr int ENTITY_WILLO_HIVE = 817; +constexpr int HIVE_DROWNED = 1; +constexpr int HIVE_HOLY = 2; +constexpr int HIVE_TAINTED = 3; + +// What they let loose: flies (a Pooter or attack fly now and then), drowned chargers, holy babies, rings of flies, +// spiders, big spiders and Trites, Willos and leeches. +constexpr int ENTITY_EMBRYO = 77; + +// How they fidget: evading their target with a buzz now and then, and resting 20 to 69 frames once 4 to 8 enemies +// are about. Within 300 they attack, then rest 75 (the Nest 130 to 149, the tainted Hive 210), else 3. +constexpr int SOUND_HIVE_BUZZ = 143; +constexpr int SOUND_HIVE_SHOOT = 158; +constexpr int BUZZ_DELAY_MIN = 45; +constexpr int BUZZ_DELAY_RANGE = 100; +constexpr int REST_CROWD_MIN = 4; +constexpr int REST_CROWD_RANGE = 5; +constexpr int REST_MIN = 20; +constexpr int REST_RANGE = 50; +constexpr float ATTACK_RANGE = 300; +constexpr float ATTACK_REST = 75; +constexpr int NEST_REST_MIN = 55; +constexpr int NEST_REST_RANGE = 20; +constexpr float TAINTED_REST = 210; +constexpr float CALM_REST = 3; +constexpr float HIVE_FRICTION = 0.8f; +constexpr float DROWNED_FRICTION = 0.95f; +constexpr float WALK_THRESHOLD = 0.1f; + +// The holy Hive's baby flies out sideways at 8 in a burst of blood. +constexpr float BABY_SPEED = 8; +constexpr float BABY_BLOOD_RISE = -20; + +// As it dies it lets loose up to 4 (fewer the more enemies are about), scattered 2 to 6 around it. +constexpr float DEATH_SPAWNS = 4; +constexpr float DEATH_SPAWN_CROWD = 0.2f; +constexpr int DEATH_FLY_ODDS = 11; +constexpr int DEATH_FLY_POOTER = 7; +constexpr int DEATH_FLY_ATTACK = 8; +constexpr float DEATH_SCATTER_MIN = 2; +constexpr float DEATH_SCATTER = 6; +constexpr float HIVE_OVERKILL = -20; + +static Entity* spawn_free(Entity_NPC& npc, int type, int variant, const Vector& position, const Vector& velocity, + int subType) +{ + uint32_t seed = Random(); + Entity* spawned = g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .subType = subType, + .type = type, + .variant = variant, + .seed = seed}); + spawned->ClearEntityFlags(FLAG_APPEAR); + return spawned; +} + +// The first frame: walking. The Willo hive's head rises, the drowned one swims. +static void hive_init(Entity_NPC& npc) +{ + if (npc.type == ENTITY_WILLO_HIVE) + { + npc.sprite.PlayOverlay("HeadAppear"); + if (npc.variant == 1) + { + npc.posOffset.y = -6; + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + } + } + npc.state = NPC_STATE_MOVE; + npc.v1.x = 0; +} + +// Walking: it evades a hostile target (buzzing while it does) or wanders, its head bobbing along. +static void hive_walk_update(Entity_NPC& npc) +{ + if (!npc.IsHostileTo(npc.GetPlayerTarget())) npc.pathfinder.MoveRandomly(STATUS_IGNORED); + else + { + npc.pathfinder.EvadeTarget(npc.CalcTargetPosition(0), STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) + npc.PlaySound(SOUND_HIVE_BUZZ, 1, (int)(Random() % BUZZ_DELAY_RANGE) + BUZZ_DELAY_MIN, false, 1); + } + + if (npc.type == ENTITY_WILLO_HIVE && npc.variant == 1) + { + npc.sprite.Play("WalkVert"); + if (std::abs(npc.velocity.y) < std::abs(npc.velocity.x)) npc.sprite.isFlipX = npc.velocity.x < 0; + } + else npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) + { + if (npc.sprite.SetOverlayAnimation("HeadWalk", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + } + else npc.sprite.PlayOverlay("HeadWalk"); + + npc.friction *= HIVE_FRICTION; + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_DROWNED) npc.friction *= DROWNED_FRICTION; +} + +// The Shoot event of its attack lets one out: a fly (a spider from a Nest) that dies on touch, a drowned charger at +// half health, a holy baby, a ring of flies, or a Willo hive's Willo or leech. +static void hive_release(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_HIVE_SHOOT + (npc.type == ENTITY_NEST), 1, 2, false, 1); + if (npc.type == ENTITY_WILLO_HIVE) + { + spawn_free(npc, npc.variant == 1 ? ENTITY_WILLO : ENTITY_SMALL_LEECH, 0, npc.pos, {}, 0); + return; + } + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_DROWNED) + { + Entity* charger = spawn_free(npc, ENTITY_CHARGER, 1, npc.pos, {}, 0); + charger->maxHitPoints *= 0.5f; + charger->health = charger->maxHitPoints; + return; + } + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_HOLY) + { + Vector velocity = vector_make(npc.sprite.isFlipX ? -BABY_SPEED : BABY_SPEED, 0); + spawn_free(npc, ENTITY_BABY, 1, vector_add(npc.pos, velocity), velocity, 1); + blood_explosion_spawn(2, npc.pos, vector_make(0, npc.scale * BABY_BLOOD_RISE), COLOR_DEFAULT, + velocity); + return; + } + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) + reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's ring of flies"); + + Entity* fly = spawn_free(npc, npc.type == ENTITY_HIVE ? ENTITY_ATTACKFLY : ENTITY_SPIDER, 0, npc.pos, {}, 0); + fly->isKillOnTouch = true; +} + +// Off rest while evading, it attacks a target within 300 (resting a short while otherwise), facing it. +static void hive_attack_start(Entity_NPC& npc) +{ + if (npc.v1.x > 0) + { + npc.v1.x -= npc.speedMultiplier; + return; + } + + float facing = npc.GetPlayerTarget()->pos.x - npc.pos.x; + float distance = vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (distance >= ATTACK_RANGE || npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.v1.x = CALM_REST; + return; + } + + npc.v1.x = ATTACK_REST; + if (npc.type == ENTITY_NEST) npc.v1.x += (float)((int)(Random() % NEST_REST_RANGE) + NEST_REST_MIN); + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) npc.v1.x = TAINTED_REST; + npc.controllerMovement = {}; + if (npc.sprite.SetOverlayAnimation("HeadAttack", SWITCH_KEEP_FRAME)) + { + npc.sprite.overlayAnimState.Rewind(); + npc.sprite.overlayAnimState.isPlaying = true; + } + npc.state = NPC_STATE_ATTACK; + npc.sprite.isFlipX = facing < 0; +} + +// As it dies outright it lets loose its brood: flies (now and then a Pooter or attack fly) or the drowned and holy +// kinds' own, a Nest's big spider or Trite, a Willo hive's Willo. Fewer the more enemies are about. +static void hive_death(Entity_NPC& npc) +{ + int count = (int)std::ceil(DEATH_SPAWNS / ((float)npc.GetAliveEnemyCount() * DEATH_SPAWN_CROWD + 1)); + if (npc.type == ENTITY_HIVE && (npc.variant == HIVE_DROWNED || npc.variant == HIVE_HOLY)) + count = std::min((int)(Random() & 1) + 1, count); + else if ((npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) || npc.type == ENTITY_NEST) count = 1; + else if (npc.type == ENTITY_WILLO_HIVE) count = std::max(count - 1, 1); + count = std::max(count - (int)npc.championRegenCount, 0); + + for (int i = 0; i < count; i++) + { + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) + reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's ring of flies"); + if (npc.type == ENTITY_WILLO_HIVE) + { + if (npc.variant != 1) reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: a Willo hive's leech (ThrowLeech)"); + spawn_free(npc, ENTITY_WILLO, 0, npc.pos, {}, 0); + continue; + } + if (npc.type != ENTITY_HIVE) + { + int variant = (int)(Random() & 1); + spawn_free(npc, variant ? ENTITY_HOPPER : ENTITY_BIG_SPIDER, variant, npc.pos, {}, 0); + continue; + } + + uint32_t roll = Random() % DEATH_FLY_ODDS; + int type = roll >= DEATH_FLY_ATTACK ? ENTITY_ATTACKFLY : roll == DEATH_FLY_POOTER ? ENTITY_POOTER : ENTITY_FLY; + int variant = 0; + if (npc.variant == HIVE_DROWNED) + { + type = ENTITY_CHARGER; + variant = 1; + } + else if (npc.variant == HIVE_HOLY) type = ENTITY_EMBRYO; + + float angle = random_unit() * PI_F; + angle += angle; + float reach = std::max(random_unit() * DEATH_SCATTER, DEATH_SCATTER_MIN); + Vector at = vector_make(std::cos(angle) * reach + npc.pos.x, std::sin(angle) * reach + npc.pos.y); + Entity* spawned = spawn_free(npc, type, variant, at, {}, 0); + if (npc.variant != HIVE_DROWNED) continue; + spawned->maxHitPoints *= 0.5f; + spawned->health = spawned->maxHitPoints; + } +} + +// 0050c370 The hives' AI: they shuffle about evading their target, buzzing, and now and then (more often with fewer +// enemies about) stop to let a fly or spider loose at it. As they die they let their brood go. +void npc_hive_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return hive_init(npc); + if (npc.controllerID != -1) reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: a hive under a player's control"); + + if (npc.state == NPC_STATE_MOVE) hive_walk_update(npc); + else + { + if (npc.type == ENTITY_HIVE && (npc.variant == HIVE_HOLY || npc.variant == HIVE_TAINTED)) + { + npc.friction *= HIVE_FRICTION; + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + } + if (npc.sprite.overlayAnimState.IsEventTriggered("Shoot")) hive_release(npc); + if (!npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying) + npc.state = NPC_STATE_MOVE; + } + + int crowd = npc.GetAliveEnemyCount(); + if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) + reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's own flies left out of the crowd"); + if (npc.v1.x - npc.speedMultiplier <= 0 && (int)(Random() % REST_CROWD_RANGE) + REST_CROWD_MIN <= crowd) + npc.v1.x += (float)((int)(Random() % REST_RANGE) + REST_MIN); + if (npc.pathfinder.evadeMovementCountdown > 0) hive_attack_start(npc); + + if (npc.isDead && npc.health > HIVE_OVERKILL) hive_death(npc); +} diff --git a/src/npc_hopper.cpp b/src/npc_hopper.cpp new file mode 100644 index 0000000..9d15297 --- /dev/null +++ b/src/npc_hopper.cpp @@ -0,0 +1,383 @@ +#include "npc_basement.h" +#include "game.h" +#include "room.h" + +// The hoppers this AI runs: the Hopper (with the Trite, Eggy and the tainted hopper as its variants), the Leaper, +// the flaming hopper, the Keeper, Rag Man's Ragling, Ministro and Pon. +constexpr int ENTITY_KEEPER = 86; +constexpr int ENTITY_RAGLING = 246; +constexpr int ENTITY_MINISTRO = 305; +constexpr int ENTITY_PON = 840; +constexpr int HOPPER_TRITE = 1; +constexpr int HOPPER_EGGY = 2; +constexpr int HOPPER_TAINTED = 3; +constexpr int RAGLING_RAG_MAN = 1; + +constexpr ColorMod BROWN_SPLAT_COLOR = {{0.4f, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FLAMING_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.14117648f, 0.12156863f, 0.10980392f}}; +constexpr ColorMod RAGLING_SPLAT_COLOR = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; +constexpr ColorMod LEAPER_SPLAT_COLOR = {{0.02f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod RAGLING_SHOT_COLOR = {{0.5f, 0, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// How far a hopper jumps: 130 plus 1.3 times a bonus the Trite and Ragling draw anew each frame (up to 120) and the +// flaming hopper too (up to 50). Within that range it hops toward its target, else somewhere at random. +constexpr float JUMP_RANGE = 130; +constexpr float JUMP_RANGE_SCALE = 1.3f; +constexpr float JUMP_SHORT_SCALE = 0.7f; +constexpr float TRITE_BONUS_FIRST = 50; +constexpr float TRITE_BONUS_SECOND = 70; +constexpr float FLAMING_BONUS = 50; +constexpr float RANDOM_HOP_REACH = 95; +constexpr float AIM_BONUS_SCALE = 200; +constexpr float FLAMING_LEAD = 5; +constexpr float HOP_CLAMP_MARGIN = 5; +constexpr float TARGET_DISTANCE = 60; +constexpr int TRITE_JUMP_DELAY = 15; +constexpr int EGGY_JUMP_DELAY = 8; +constexpr int TAINTED_JUMP_DELAY = 26; +constexpr int RAGLING_ATTACK_ODDS = 3; +constexpr uint32_t COLLISION_BLOCKED = 3; +constexpr int HOP_SKIP_FRAMES = 9999; +constexpr float HOP_SKIP_TO_FRAME = 4; + +// How a hop moves: toward its spot (gently while on the ground), stopping near it or now and then once slow. +constexpr float HOP_PULL = 0.05f; +constexpr float HOP_NEAR = 30; +constexpr float HOP_ARRIVED = 10; +constexpr float HOP_GROUNDED_SHARE = 0.1f; +constexpr float HOP_STALL_SPEED = 0.75f; +constexpr int HOP_STALL_FRAMES = 30; +constexpr int HOP_STALL_ODDS = 10; +constexpr float HOPPER_FRICTION = 0.7f; +constexpr int SOUND_HOPPER_LAND = 69; + +// The Keeper and Ministro shoot at a target within 200 in sight, the Ministro's shots heavier; the Ragling shoots +// both ways. +constexpr float SHOOT_RANGE_SQUARED = 40000; +constexpr int SHOOT_COOLDOWN = 2; +constexpr float SHOT_SPEED = 7; +constexpr int SOUND_SHOOT = 178; +constexpr int SOUND_MINISTRO_SHOOT = 318; +constexpr float TINY_PITCH = 1.5f; +constexpr float GIANT_PITCH = 0.5f; +constexpr int MINISTRO_SHOTS = 5; +constexpr float MINISTRO_SHOT_SCALE = 0.5f; +constexpr float MINISTRO_TRAJECTORY = 10; +constexpr uint64_t RAGLING_SHOT_FLAGS = 1ull << 11 | 1ull << 13; + +// The Ragling marks its cell for the pathfinder and, once Rag Man is gone, leaves a poof as it dies. +constexpr int RAGLING_GRID_PATH = 500; +constexpr int EFFECT_POOF = 15; + +// The animations a hopper plays: its idle, hop and shot. +struct HopperAnims +{ + std::string_view idle = "Idle"; + std::string_view hop = "Hop"; + std::string_view shoot = ""; +}; + +// How a hopper jumps this frame: its bonus reach, the range it aims within and the frames it rests between hops. +struct HopperJump +{ + float bonus = 0; + float range = 0; + int delay = 0; +}; + +// The first frame: idle, with the blood of its kind. The update ends there. +static void hopper_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + if (npc.type == ENTITY_KEEPER || (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_EGGY)) + npc.splatColor = BROWN_SPLAT_COLOR; + else if (npc.type == ENTITY_FLAMING_HOPPER) npc.splatColor = FLAMING_SPLAT_COLOR; + else if (npc.type == ENTITY_RAGLING && npc.variant == RAGLING_RAG_MAN) npc.splatColor = RAGLING_SPLAT_COLOR; + else if (npc.type == ENTITY_LEAPER && npc.variant == 1) npc.splatColor = LEAPER_SPLAT_COLOR; +} + +// Fire turns a plain hopper into a flaming one (keeping its share of health), which shrugs fire off. +static void hopper_fire_absorb(Entity_NPC& npc) +{ + for (auto event = npc.damageEvents.begin(); event != npc.damageEvents.end();) + { + bool isPlainHopper = npc.type == ENTITY_HOPPER && npc.variant == 0; + if (!(event->damageFlags & DAMAGE_FIRE) || !(isPlainHopper || npc.type == ENTITY_FLAMING_HOPPER)) + { + ++event; + continue; + } + if (isPlainHopper) + { + float share = npc.health / npc.maxHitPoints; + npc.Morph(ENTITY_FLAMING_HOPPER, 0, 0, -1); + npc.splatColor = FLAMING_SPLAT_COLOR; + npc.health = share * npc.maxHitPoints; + } + event = npc.damageEvents.erase(event); + } +} + +static HopperAnims hopper_anims_get(Entity_NPC& npc) +{ + if (npc.type == ENTITY_KEEPER) return {"Down", "JumpDown", "ShootDown"}; + if (npc.type == ENTITY_MINISTRO) return {"Idle", "Hop", "Attack"}; + if (npc.type != ENTITY_HOPPER || npc.variant != HOPPER_TAINTED) return {}; + + bool isOdd = npc.i1 & 1; + return {isOdd ? "Idle2" : "Idle", isOdd ? "Hop2" : "Hop", ""}; +} + +// The reach of this frame's jump. The Trite and Ragling draw theirs every frame. +static HopperJump hopper_jump_get(Entity_NPC& npc) +{ + HopperJump jump; + bool isTrite = (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_TRITE) || npc.type == ENTITY_RAGLING; + if (isTrite) + { + float first = random_unit() * TRITE_BONUS_FIRST; + jump.bonus = first + random_unit() * TRITE_BONUS_SECOND; + jump.delay = TRITE_JUMP_DELAY; + } + else if (npc.type == ENTITY_FLAMING_HOPPER) jump.bonus = random_unit() * FLAMING_BONUS; + else if (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_EGGY) jump.delay = EGGY_JUMP_DELAY; + else if (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_TAINTED) jump.delay = TAINTED_JUMP_DELAY; + + jump.range = jump.bonus * JUMP_RANGE_SCALE + JUMP_RANGE; + bool isShort = (npc.type == ENTITY_RAGLING && npc.variant == RAGLING_RAG_MAN) || + (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_EGGY); + if (isShort) jump.range *= JUMP_SHORT_SCALE; + return jump; +} + +static void hopper_idle_reset(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.targetPosition = {}; +} + +// A resting Keeper or Ministro off cooldown with its target within 200 in sight starts shooting. +static void hopper_shoot_start(Entity_NPC& npc, const HopperAnims& anims, const Vector& aim, const Vector& toward) +{ + bool isShooter = npc.type == ENTITY_KEEPER || npc.type == ENTITY_MINISTRO; + if (!vector_is_zero(npc.targetPosition) || !isShooter || npc.HasEntityFlags(FLAG_DISTRACTED)) return; + + if (npc.projectileCooldown < 1 && vector_length_squared(toward) < SHOOT_RANGE_SQUARED && + room_check_line(npc.pos, aim, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD)) + { + npc.UpdateControllerMovement(true); + npc.projectileCooldown = SHOOT_COOLDOWN; + npc.state = NPC_STATE_ATTACK; + if (npc.sprite.SetAnimation(anims.shoot, SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + npc.stateFrame = 0; + } + npc.projectileCooldown -= npc_ticks_get(npc); +} + +// On its Shoot event a shooter fires two shots at its target, the Ministro a spray of five more, the Ragling one each +// way. It rests again once the animation ends. +static void hopper_shoot_update(Entity_NPC& npc, Vector toward) +{ + npc.controllerMovement = {}; + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + { + float pitch = 1; + if (npc.championColorIdx == CHAMPION_TINY) pitch = TINY_PITCH; + else if (npc.championColorIdx == CHAMPION_GIANT) pitch = GIANT_PITCH; + npc_sound_play(SOUND_SHOOT, 1, 2, pitch); + + Vector shot = vector_scale(vector_normalized(toward), SHOT_SPEED); + if (npc.type == ENTITY_RAGLING) + { + ProjectileParams params; + params.color = RAGLING_SHOT_COLOR; + params.bulletFlags |= RAGLING_SHOT_FLAGS; + params.targetPosition = npc.pos; + params.isGridCollision = false; + npc.FireProjectiles(npc.pos, shot, PROJECTILES_SINGLE, params); + npc.FireProjectiles(npc.pos, vector_sub({}, shot), PROJECTILES_SINGLE, params); + } + else + { + if (npc.type == ENTITY_MINISTRO) + { + npc.PlaySound(SOUND_MINISTRO_SHOOT, 1, 2, false, 1); + ProjectileParams params; + params.scale = MINISTRO_SHOT_SCALE; + npc.FireBossProjectiles(MINISTRO_SHOTS, vector_add(shot, npc.pos), MINISTRO_TRAJECTORY, params); + npc.sprite.isFlipX = shot.x < 0; + } + ProjectileParams params; + npc.FireProjectiles(npc.pos, shot, PROJECTILES_TWO, params); + } + } + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) hopper_idle_reset(npc); +} + +// A rested hopper picks its next spot: toward its target when in range (the flaming one leading it), else a random +// one, clamped into the room. It hops to the middle of a free cell there, or the Ragling attacks now and then. +static void hopper_hop_start(Entity_NPC& npc, const HopperJump& jump, const HopperAnims& anims, const Vector& aim, + const Vector& toward) +{ + if (npc.stateFrame < jump.delay || !vector_is_zero(npc.targetPosition)) return; + + Room& room = *g_game->room; + Vector spot; + if (jump.range * jump.range <= vector_length_squared(toward)) + spot = vector_add(npc.pos, vector_scale(random_direction(), jump.bonus + RANDOM_HOP_REACH)); + else + { + spot = vector_add(aim, vector_scale(toward, jump.bonus / AIM_BONUS_SCALE)); + if (npc.type == ENTITY_FLAMING_HOPPER) + spot = vector_add(spot, vector_scale(npc.GetPlayerTarget()->velocity, FLAMING_LEAD)); + } + spot = room.GetClampedPosition(spot, HOP_CLAMP_MARGIN); + uint32_t collision = vector_is_zero(spot) ? COLLISION_BLOCKED : room_grid_collision_at(spot); + + if (npc.type == ENTITY_PON) reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Pon's search for a landing spot"); + bool isAttacking = Random() % RAGLING_ATTACK_ODDS == 0; + if (isAttacking && npc.type == ENTITY_RAGLING && !npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.UpdateControllerMovement(true); + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Appear", PLAY_FORCED); + npc.stateFrame = 0; + return; + } + + int gridIndex = room.GetGridIndex(spot); + if (collision != 0 || gridIndex < 0) return; + npc.targetPosition = room.GetGridPosition(gridIndex); + npc.state = NPC_STATE_MOVE; + npc.sprite.Play(anims.hop, PLAY_FORCED); + if (npc.stateFrame >= HOP_SKIP_FRAMES) npc.sprite.SetFrame(HOP_SKIP_TO_FRAME); + npc.stateFrame = 0; +} + +// The landing of a hop: a thud, and the bursts of the kinds that land hard. +static void hopper_land(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_HOPPER_LAND, 1, 2, false, 1); + if (npc.type == ENTITY_PON) reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Pon's landing"); + if (npc.type == ENTITY_LEAPER && npc.variant == 1) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: the sticky Leaper's landing creep"); + if (npc.type == ENTITY_HOPPER && (npc.variant == HOPPER_EGGY || npc.variant == HOPPER_TAINTED)) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Eggy's and the tainted hopper's landings"); +} + +// A hop in the air (until its animation loops): it leaves the ground on its Jump event, lands with a thud, and moves +// toward its spot, gently while grounded. It rests once near the spot, or now and then once stalled. +static void hopper_hop_update(Entity_NPC& npc, const HopperAnims& anims) +{ + const AnimationData* data = npc.sprite.animState.animData; + bool isDone = data && data->isLooping; + Vector delta = vector_sub(npc.targetPosition, npc.pos); + float distance = vector_length(delta); + if (!isDone) + { + if (data && npc.sprite.animState.IsEventTriggered("Land")) hopper_land(npc); + if (data && npc.sprite.animState.WasEventTriggered("Jump")) + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + } + else + { + delta = vector_scale(delta, HOP_GROUNDED_SHARE); + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.entityCollisionClass = ENTCOLL_ALL; + } + } + + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) + { + npc.sprite.Play(anims.idle); + isDone = true; + } + bool isStalled = vector_length(npc.velocity) < HOP_STALL_SPEED || npc.stateFrame > HOP_STALL_FRAMES; + if ((distance < HOP_ARRIVED || (isStalled && Random() % HOP_STALL_ODDS == 0)) && isDone) + { + hopper_idle_reset(npc); + npc.sprite.Play(anims.idle); + } + + if (npc.friction != 0) + { + Vector pull = distance >= HOP_NEAR ? vector_scale(delta, HOP_PULL) : vector_normalized(delta); + npc.velocity.x += pull.x * npc.speedMultiplier / npc.friction; + npc.velocity.y += pull.y * npc.speedMultiplier / npc.friction; + } + if (npc.type == ENTITY_MINISTRO) npc.sprite.isFlipX = npc.velocity.x < 0; +} + +// Rag Man's Ragling marks its cell for the pathfinder, and dies in a poof once Rag Man is gone. +static void ragling_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(npc.pos); + if ((uint32_t)gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] < RAGLING_GRID_PATH) + room.gridPaths[gridIndex] = RAGLING_GRID_PATH; + + if (npc.state == NPC_STATE_SPECIAL) + { + if (npc.parent) return; + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF, .seed = Random()}); + npc.Remove(); + return; + } + if (npc.isDead && npc.parent) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: a Ragling playing dead for Rag Man"); + if (npc.state == NPC_STATE_APPEAR_CUSTOM) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: a Ragling regenerating"); +} + +// 00526470 The hoppers' AI: they rest, then hop to a cell toward their target (or anywhere when it is out of range), +// landing with a thud. Fire turns a hopper into a flaming one, the Keeper and Ministro stop to shoot, and Rag Man's +// Raglings play dead for him. +void npc_hopper_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return hopper_init(npc); + if (npc.controllerID != -1) reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: a hopper under a player's control"); + + bool isHopKnocked = npc.HasEntityFlags(FLAG_KNOCKED_BACK) && npc.knockbackCountdown == 1 && + !vector_is_zero(npc.targetPosition) && npc.state == NPC_STATE_MOVE; + if (isHopKnocked) hopper_idle_reset(npc); + hopper_fire_absorb(npc); + + HopperAnims anims = hopper_anims_get(npc); + bool isAnimDone = !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; + if (isAnimDone && npc.state == NPC_STATE_IDLE) npc.sprite.Play(anims.idle); + else if (isAnimDone && npc.state == NPC_STATE_JUMP) npc.sprite.Play("BigJumpUp"); + else if (isAnimDone && npc.state == NPC_STATE_STOMP) npc.sprite.Play("BigJumpDown"); + + HopperJump jump = hopper_jump_get(npc); + Vector aim = npc.CalcTargetPosition(TARGET_DISTANCE); + Vector toward = vector_sub(aim, npc.pos); + if (npc.state == NPC_STATE_IDLE) hopper_shoot_start(npc, anims, aim, toward); + else if (npc.state == NPC_STATE_ATTACK) hopper_shoot_update(npc, toward); + + int state = npc.state; + if (state == NPC_STATE_JUMP || state == NPC_STATE_STOMP) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: the Leaper's big jump"); + if (state == NPC_STATE_IDLE) hopper_hop_start(npc, jump, anims, aim, toward); + else if (state == NPC_STATE_MOVE) hopper_hop_update(npc, anims); + + if (npc.type == ENTITY_LEAPER && vector_is_zero(npc.targetPosition) && Random() % 7 == 0 && + !npc.HasEntityFlags(FLAG_DISTRACTED)) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: the Leaper's big jump"); + if (npc.state == NPC_STATE_IDLE) npc.entityGridCollisionClass = GRIDCOLL_GROUND; + if (npc.type == ENTITY_RAGLING && npc.variant == RAGLING_RAG_MAN) ragling_update(npc); + if (npc.state == NPC_STATE_IDLE && !vector_is_zero(npc.targetPosition)) npc.targetPosition = {}; + + bool isEggy = npc.type == ENTITY_HOPPER && npc.variant == HOPPER_EGGY; + if (isEggy && (npc.state == NPC_STATE_SUICIDE || (npc.isDead && npc.state != NPC_STATE_DEATH))) + reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Eggy bursting into spiders"); + + npc.stateFrame += npc_ticks_get(npc); + npc.friction *= HOPPER_FRICTION; +} diff --git a/src/npc_horf.cpp b/src/npc_horf.cpp index 2bea9e3..14252cd 100644 --- a/src/npc_horf.cpp +++ b/src/npc_horf.cpp @@ -3,7 +3,6 @@ #include "game.h" constexpr int ENTITY_PSY_HORF = 248; -constexpr int EFFECT_BLOOD_EXPLOSION = 2; constexpr int BLOOD_EXPLOSION_SPIT = 5; constexpr int SOUND_HORF_SHOOT = 146; constexpr float HORF_FRICTION = 0.7f; @@ -18,10 +17,8 @@ constexpr float SPIT_OFFSET_Y = -10; constexpr float SPIT_DEPTH = 1; constexpr float PITCH_TINY = 1.5f; constexpr float PITCH_GIANT = 0.5f; -constexpr int COLOR_PRIORITY_DEFAULT = 255; constexpr ColorMod SPIT_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0.6f, 0.1f, 0.1f}}; constexpr ColorMod PSY_SPIT_COLOR = {{1, 1, 1, 0.6f}, {0.8f, 0.15f, 1, 1}, {0.26f, 0.05f, 0.4f}}; -constexpr uint64_t PROJECTILE_SMART = 1; // The movement its controlling player steers, none without one, kept while the stick rests. static void horf_controller_update(Entity_NPC& npc, bool isKeptAtRest) diff --git a/src/npc_mulligan.cpp b/src/npc_mulligan.cpp index 9a2b70e..6cb9278 100644 --- a/src/npc_mulligan.cpp +++ b/src/npc_mulligan.cpp @@ -1,15 +1,13 @@ +#include "entity_effect.h" #include "npc_basement.h" #include "active_items.h" #include "entity_bomb.h" #include "game.h" #include "menu_manager.h" +#include constexpr int MULLIGOON = 1; constexpr int MULLIBOOM = 2; -constexpr int ENTITY_FLY = 13; -constexpr int ENTITY_POOTER = 14; -constexpr int ENTITY_ATTACKFLY = 18; -constexpr int EFFECT_BOMB_EXPLOSION = 1; constexpr int EFFECT_BOMB_CRATER = 18; constexpr int SOUND_SCARED_WHIMPER = 143; constexpr int CONTROLLER_ACTION_ITEM = 9; diff --git a/src/npc_spider.cpp b/src/npc_spider.cpp new file mode 100644 index 0000000..efe78cd --- /dev/null +++ b/src/npc_spider.cpp @@ -0,0 +1,279 @@ +#include "entity_effect.h" +#include "npc_basement.h" +#include "entity_bomb.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" + +// The spiders this AI runs: the spider, the big spider, and the jumping kinds (the level 2 spider, the ticking +// spider and the Migraine spider). +constexpr int ENTITY_SPIDER_L2 = 215; +constexpr int ENTITY_TICKING_SPIDER = 250; +constexpr int ENTITY_MIGRAINE_SPIDER = 869; + +// A spider rests 14 frames, then runs at its target (leading it) when near and in sight, else somewhere at random +// within 70 to 110, keeping out of the walls. The jumping kinds leap there one time in three. +constexpr int REST_FRAMES = 13; +constexpr float CHASE_RANGE = 100; +constexpr float CHASE_RANGE_RANDOM = 100; +constexpr float CHASE_LEAD = 10; +constexpr float TARGET_DISTANCE = 60; +constexpr float WANDER_MIN = 70; +constexpr float WANDER_RANGE = 40; +constexpr float WANDER_MARGIN_TOP = 70; +constexpr float WANDER_MARGIN_RIGHT = 40; +constexpr float WANDER_MARGIN_BOTTOM = 60; +constexpr float WANDER_MARGIN_LEFT = 60; +constexpr int WANDER_RUN_FRAMES = 15; +constexpr int WANDER_RETRY_ODDS = 20; +constexpr float WANDER_PROBE_NEAR = 0.1f; +constexpr float WANDER_PROBE_FAR = 0.9f; +constexpr int JUMP_ODDS = 3; + +// How it runs: at 6 (the Migraine spider 4.5), stopping at its spot or once stuck. +constexpr float RUN_SPEED = 6; +constexpr float MIGRAINE_RUN_SPEED = 4.5f; +constexpr float RUN_ARRIVED = 14; +constexpr float RUN_STUCK_SPEED = 3; +constexpr float SPIDER_FRICTION = 0.6f; +constexpr float JUMP_FRICTION = 0.8f; + +// Its leap: 8% of the way each frame, rising at 4 and falling at 0.7. +constexpr float JUMP_SHARE = 0.08f; +constexpr float JUMP_RISE = -4; +constexpr float JUMP_GRAVITY = 0.7f; + +// Its keeping off the walls, and the big spider's split into two spiders 10 apart. +constexpr float CLAMP_TOP = 20; +constexpr float CLAMP_BOTTOM = 10; +constexpr float SPLIT_SPEED = 10; +constexpr float BIG_SPIDER_OVERKILL = -20; +constexpr float TICK_DAMAGE = 40; +constexpr float TICK_RADIUS = 60; + +static bool is_jumper(int type) +{ + return type == ENTITY_SPIDER_L2 || type == ENTITY_TICKING_SPIDER || type == ENTITY_MIGRAINE_SPIDER; +} + +// A spot to run to: the target (where it will be) when near and in sight, else a random free one it can reach. +// Whether it found one, the spot it eyed either way in spot. +static void spider_spot_pick(Entity_NPC& npc, bool isPassive, const Vector& aim, Vector& spot) +{ + Room& room = *g_game->room; + if (!isPassive) + { + float distance = vector_length(vector_sub(aim, npc.pos)); + float range = random_unit() * CHASE_RANGE_RANDOM + CHASE_RANGE; + bool isFar = range <= distance && !npc.forcedTarget; + bool isHidden = !isFar && !room_check_line(npc.pos, aim, LINE_MODE_CELL, 0) && + npc.entityGridCollisionClass != GRIDCOLL_WALLS; + if (!isFar && !isHidden) + { + Vector lead = vector_add(aim, vector_scale(npc.GetPlayerTarget()->velocity, CHASE_LEAD)); + spot = room.GetClampedPositionImpl(lead, npc.size, npc.size, npc.size, npc.size); + npc.targetPosition = spot; + return; + } + } + + Vector direction = random_direction(); + float reach = random_unit() * WANDER_RANGE + WANDER_MIN; + spot = room.GetClampedPositionImpl(vector_add(npc.pos, vector_scale(direction, reach)), WANDER_MARGIN_TOP, + WANDER_MARGIN_RIGHT, WANDER_MARGIN_BOTTOM, WANDER_MARGIN_LEFT); + if (room_grid_collision_at(spot) != 0) return; + + bool isReachable = room_check_line(spot, npc.pos, LINE_MODE_GROUND, 0); + if (!isReachable && Random() % WANDER_RETRY_ODDS == 0) + { + Vector near = vector_make(spot.x * WANDER_PROBE_NEAR + npc.pos.x * WANDER_PROBE_FAR, + spot.y * WANDER_PROBE_NEAR + npc.pos.y * WANDER_PROBE_FAR); + Vector far = vector_make(spot.x * WANDER_PROBE_FAR + npc.pos.x * WANDER_PROBE_NEAR, + spot.y * WANDER_PROBE_FAR + npc.pos.y * WANDER_PROBE_NEAR); + isReachable = room_check_line(far, near, LINE_MODE_CELL, 0); + } + if (!isReachable) return; + npc.targetPosition = spot; + npc.stateFrame = WANDER_RUN_FRAMES; +} + +// Resting: idle for 14 frames, then a spot to run to, which the jumping kinds leap to one time in three. +static void spider_rest_update(Entity_NPC& npc, bool isPassive, const Vector& aim) +{ + npc.sprite.Play("Idle"); + int rested = npc.stateFrame; + npc.stateFrame += npc_ticks_get(npc); + if (rested <= REST_FRAMES) return; + + Vector spot; + spider_spot_pick(npc, isPassive, aim, spot); + if (!is_jumper(npc.type) || Random() % JUMP_ODDS != 0 || room_grid_collision_at(spot) != 0) return; + + npc.targetPosition = spot; + npc.state = NPC_STATE_JUMP; + if (npc.sprite.SetAnimation("Jump", SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } +} + +// Running to its spot, walking, until it gets there or gets stuck. +static void spider_run_update(Entity_NPC& npc) +{ + npc.stateFrame -= npc_ticks_get(npc); + const AnimationData* current = npc.sprite.animState.animData; + bool isWalking = current && current->name == "Walk" && (!current->isLooping || npc.sprite.animState.isPlaying); + if (!isWalking && npc.sprite.SetAnimation("Walk", SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + + float speed = npc.type == ENTITY_MIGRAINE_SPIDER ? MIGRAINE_RUN_SPEED : RUN_SPEED; + Vector toward = vector_sub(npc.targetPosition, npc.pos); + bool isStuck = vector_length(npc.velocity) < RUN_STUCK_SPEED && npc.stateFrame < 0; + if (vector_length(toward) < RUN_ARRIVED || isStuck) + { + npc.targetPosition = {}; + npc.stateFrame = 0; + } + Vector direction = vector_normalized(toward); + if (npc.friction != 0) + { + npc.velocity.x += npc.speedMultiplier * speed * direction.x / npc.friction; + npc.velocity.y += npc.speedMultiplier * speed * direction.y / npc.friction; + } + npc.sprite.isFlipX = npc.velocity.x < 0; +} + +// A big spider killed outright splits into two spiders, flung apart across its target's line. +static void big_spider_split(Entity_NPC& npc) +{ + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + float distance = vector_length(toward); + Vector fling = distance > 0 ? vector_make(-(toward.y / distance) * SPLIT_SPEED, toward.x / distance * SPLIT_SPEED) + : vector_scale(random_direction(), SPLIT_SPEED); + + uint32_t seed = Random(); + Entity* first = g_game->Spawn({.position = vector_add(npc.pos, fling), + .velocity = fling, + .spawner = &npc, + .type = ENTITY_SPIDER, + .seed = seed}); + seed = Random(); + Entity* second = g_game->Spawn({.position = vector_sub(npc.pos, fling), + .velocity = vector_sub({}, fling), + .spawner = &npc, + .type = ENTITY_SPIDER, + .seed = seed}); + first->ClearEntityFlags(FLAG_APPEAR); + second->ClearEntityFlags(FLAG_APPEAR); +} + +static bool is_jump_ended(const AnimationState& anim) +{ + return anim.animData && !anim.isPlaying && anim.animData->name == "Jump"; +} + +// A plain spider's leap: in the air at the leap's speed, falling back down to rest. +static void spider_leap_update(Entity_NPC& npc) +{ + if (is_jump_ended(npc.sprite.animState)) npc.sprite.Play("InAir"); + npc.velocity = npc.v1; + npc.v2.y += npc.speedMultiplier * JUMP_GRAVITY; + npc.posOffset.y += npc.speedMultiplier * npc.v2.y; + if (npc.posOffset.y <= -npc.v2.y * npc.speedMultiplier) return; + + npc.posOffset.y = 0; + npc.targetPosition = {}; + npc.stateFrame++; + npc.state = NPC_STATE_MOVE; +} + +// A jumping kind's leap, timed by its Jump and Land events: it takes off toward its spot, passing over everything +// until it lands, then rests once the animation ends. +static void spider_jump_update(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.IsEventTriggered("Jump")) + { + npc.v1 = vector_scale(vector_sub(npc.targetPosition, npc.pos), JUMP_SHARE); + npc.velocity = npc.v1; + npc.v2.y = JUMP_RISE; + npc.stateFrame = 0; + } + if (anim.animData && anim.WasEventTriggered("Jump")) + { + npc.v2.y += npc.speedMultiplier * JUMP_GRAVITY; + npc.posOffset.y += npc.speedMultiplier * npc.v2.y; + } + + bool isAirborne = anim.animData && anim.WasEventTriggered("Jump") && !anim.WasEventTriggered("Land"); + if (isAirborne) npc.velocity = npc.v1; + npc.entityGridCollisionClass = isAirborne ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + npc.entityCollisionClass = isAirborne ? ENTCOLL_NONE : ENTCOLL_ALL; + + if (anim.animData && anim.WasEventTriggered("Land") && npc.posOffset.y > -npc.v2.y * npc.speedMultiplier) + { + npc.posOffset.y = 0; + npc.targetPosition = {}; + npc.stateFrame++; + } + if (!vector_is_zero(npc.targetPosition)) return; + npc.friction *= JUMP_FRICTION; + if (is_jump_ended(anim)) npc.state = NPC_STATE_MOVE; +} + +// A dying ticking spider blows up. +static void spider_death(Entity_NPC& npc) +{ + if (npc.type == ENTITY_TICKING_SPIDER && !npc.HasEntityFlags(FLAG_SHRINK)) + { + explosion_damage({.position = npc.pos, .source = &npc, .damage = TICK_DAMAGE, .radius = TICK_RADIUS}); + bomb_crater_spawn(npc.pos, nullptr, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + } + else if (npc.type == ENTITY_MIGRAINE_SPIDER) + reconstruction_missing("NpcAI::ENTITY_SPIDER 00529da0: the Migraine spider's timer (Entity_Effect::CreateTimer)"); +} + +// 00529da0 The spiders' AI: they rest a moment, then scuttle at their target when it is near and in sight, or +// anywhere they can reach. The jumping kinds leap there instead now and then, the big spider splits in two, and the +// ticking spider blows up. Bursting Sack makes them harmless. +void npc_spider_update(Entity_NPC& npc) +{ + PlayerManager& players = g_game->playerManager; + bool isPassive = players.FirstCollectibleOwner(COLLECTIBLE_BURSTING_SACK, LAZARUS_SHARE_CHECK) && !npc.IsFriendly(); + if (isPassive && (npc.state == NPC_STATE_INIT || g_game->frameCount - npc.spawnFrame == 1)) + reconstruction_missing("NpcAI::ENTITY_SPIDER 00529da0: Bursting Sack's inert spider sheet"); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + return; + } + if (npc.controllerID != -1) reconstruction_missing("NpcAI::ENTITY_SPIDER 00529da0: a spider under a player's control"); + + Room& room = *g_game->room; + npc.pos = room.GetClampedPositionImpl(npc.pos, CLAMP_TOP, 0, CLAMP_BOTTOM, 0); + npc.entityCollisionClass = npc.state == NPC_STATE_JUMP ? ENTCOLL_NONE : ENTCOLL_ALL; + + if (npc.state == NPC_STATE_JUMP) + { + if (is_jumper(npc.type)) spider_jump_update(npc); + else spider_leap_update(npc); + } + else + { + if (npc.isDead && npc.type == ENTITY_BIG_SPIDER && npc.health > BIG_SPIDER_OVERKILL) big_spider_split(npc); + else if (npc.state == NPC_STATE_MOVE) + { + Vector aim = npc.CalcTargetPosition(TARGET_DISTANCE); + if (vector_is_zero(npc.targetPosition)) spider_rest_update(npc, isPassive, aim); + else spider_run_update(npc); + } + npc.friction *= SPIDER_FRICTION; + } + if (npc.isDead) spider_death(npc); +} diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 9b16697..8e32635 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -1,6 +1,7 @@ #include "path_finder.h" #include "game.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include #include @@ -10,6 +11,43 @@ static_assert(PATH_GRID_CELLS == ROOM_GRID_CELLS); constexpr int PATH_ENEMY_TYPE_LAST = 999; +// How an owner wanders: to a free spot 40 away, pushed at half its speed, until within 3 of it, against a wall, or +// (one time in ten) once slower than about 0.3. A friendly one paths to its target instead. +constexpr float WANDER_STEP = 40; +constexpr float WANDER_PUSH = 0.5f; +constexpr float WANDER_ARRIVED = 3; +constexpr float WANDER_STALL_SPEED_SQUARED = 0.1f; +constexpr int WANDER_GIVE_UP_ODDS = 10; +constexpr float WANDER_FRIENDLY_SPEED = 0.5f; + +// How an owner evades: within 250 of its target (170 when the target cannot walk to it) it keeps fleeing for three +// checks of every 14 frames, pushing away at 1.5 and trying up to 7 random cells 30 to 480 past a point 30 away +// (fewer as the evasion widens toward 20) that lie farther from the target than it by 100 and a third of their reach. +constexpr int EVADE_CHECK_FRAMES = 14; +constexpr int EVADE_FORGET_FRAMES = 30; +constexpr int EVADE_RECHECK_FRAMES = 10; +constexpr int EVADE_COUNTDOWN = 3; +constexpr float EVADE_RANGE_SEEN = 250; +constexpr float EVADE_RANGE_HIDDEN = 170; +constexpr float EVADE_WIDE = 20; +constexpr float EVADE_WIDEN = 0.35f; +constexpr float EVADE_DECAY = 0.9f; +constexpr float EVADE_DIAGONAL = 0.25f; +constexpr float EVADE_PUSH = 1.5f; +constexpr float EVADE_BASE_REACH = 30; +constexpr float EVADE_ATTEMPTS = 7; +constexpr float EVADE_ATTEMPT_SHARE = 0.3f; +constexpr float EVADE_REVISIT_REFUND = 0.7f; +constexpr float EVADE_REACH_MIN = 30; +constexpr float EVADE_REACH_RANGE = 450; +constexpr float EVADE_REACH_SHARE = 3; +constexpr float EVADE_FLATTEN = 0.5f; +constexpr float EVADE_MARGIN = 100; +constexpr int EVADE_BAR_STEP = 10; +constexpr float EVADE_GRID_TOP = 120; +constexpr float EVADE_SPOT_RANGE_SQUARED = 40000; +constexpr float EVADE_PATH_SPEED = 1.079f; + // 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; @@ -39,7 +77,6 @@ constexpr int STEP_COST_ROUGH = 7; 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; @@ -328,7 +365,7 @@ void PathFinder::FindGridPath(const Vector& position, float speed, int pathMarke 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); + else hasDirectPath = room_check_line(ownCenter, targetCenter, LINE_MODE_GROUND, threshold); } float directRange = mode == DIRECT_PATH_FAR ? DIRECT_RANGE_FAR : DIRECT_RANGE_NEAR; @@ -357,16 +394,160 @@ void PathFinder::FindGridPath(const Vector& position, float speed, int pathMarke path_steer(moveTarget, from, slowdown * speed); } -// 007e4940 -void PathFinder::EvadeTarget(const Vector&, StatusMode) +// Whether the owner's periodic checks run this frame: every period frames by its index, not while paused or +// interpolating. +static bool is_evade_check_frame(Entity& entity, int period) { - reconstruction_missing("PathFinder::EvadeTarget 007e4940"); + if (entity.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return false; + return ((int)entity.index + g_game->frameCount) % period == 0; } -// 007e6300 -bool PathFinder::MoveRandomly(StatusMode) +// One try at a spot to flee to: a random cell within 30 to 480 of base, not tried this half second, free and in +// walking reach. It is taken while the target cannot walk to the owner (or the evasion is wide) and it lies far +// enough from the target. Each taken spot raises the bar for the next. +static void evade_spot_try(PathFinder& finder, const Vector& targetPos, const Vector& base, float distance, + float& attempt) { - reconstruction_missing("PathFinder::MoveRandomly 007e6300"); + Entity* entity = finder.entity; + Room& room = *g_game->room; + float reach = random_unit() * EVADE_REACH_RANGE + EVADE_REACH_MIN; + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector spot = vector_make(std::cos(angle) * reach + base.x, std::sin(angle) * EVADE_FLATTEN * reach + base.y); + int column = (int)((spot.x - GRID_CELL_SIZE) / GRID_CELL_SIZE + 0.5f); + int row = (int)((spot.y - EVADE_GRID_TOP) / GRID_CELL_SIZE + 0.5f); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cell = isInside ? room.gridWidth * row + column : -1; + if (!finder.visitedGridIndices.insert(cell).second) + { + attempt -= EVADE_REVISIT_REFUND; + return; + } + + Vector center = vector_make((float)(cell % room.gridWidth) * GRID_CELL_SIZE + GRID_CELL_SIZE, + (float)(cell / room.gridWidth) * GRID_CELL_SIZE + EVADE_GRID_TOP); + if (room_grid_collision_at(center) != 0 || !room_check_line(entity->pos, center, LINE_MODE_CELL, 0)) return; + if (room_check_line(targetPos, entity->pos, LINE_MODE_CELL, 0) && finder.evadeDistance < EVADE_WIDE) + { + finder.evadeDistance += EVADE_WIDEN; + return; + } + + float bar = reach / EVADE_REACH_SHARE + distance + EVADE_MARGIN + finder.evadeDistance; + bar -= (float)finder.stuckFrames; + if (bar <= vector_length(vector_sub(targetPos, center))) + { + finder.movementTarget = center; + if (finder.evadeDistance < EVADE_WIDE) finder.evadeDistance *= 0.5f; + } + finder.stuckFrames += EVADE_BAR_STEP; +} + +// 007e4940 Flees targetPos: within 250 of it (170 out of its walking sight) it keeps evading for 3 more checks of +// every 14 frames, pushing away and seeking a cell to run to that lies well away from the target, and it wanders +// once the evasion runs out. A friendly owner paths to its target instead. stuckFrames holds the bar a spot must clear. +void PathFinder::EvadeTarget(const Vector& targetPos, StatusMode mode) +{ + if (mode == STATUS_OBEYED && is_entity_friendly()) + { + FindGridPath(static_cast(entity)->GetPlayerTarget()->pos, EVADE_PATH_SPEED, 0, DIRECT_PATH_FAR); + return; + } + + Vector delta = vector_sub(targetPos, entity->pos); + float distance = vector_length(delta); + evadeDistance = std::min(evadeDistance, EVADE_WIDE); + if (is_evade_check_frame(*entity, EVADE_CHECK_FRAMES)) + { + float range = room_check_line(entity->pos, targetPos, LINE_MODE_CELL, 0) ? EVADE_RANGE_SEEN : EVADE_RANGE_HIDDEN; + if (distance >= range) evadeMovementCountdown -= entity->update_ticks_get(); + else + { + if (evadeMovementCountdown < 1) movementTarget = {}; + evadeMovementCountdown = EVADE_COUNTDOWN; + } + } + if (is_evade_check_frame(*entity, EVADE_FORGET_FRAMES)) visitedGridIndices.clear(); + if (evadeMovementCountdown < 1) + { + stuckFrames = 0; + evadeDistance *= EVADE_DECAY; + MoveRandomly(STATUS_IGNORED); + entity->friction *= EVADE_DECAY; + return; + } + + if (vector_is_zero(movementTarget) || evadeDistance > EVADE_WIDE) + { + Vector away = distance > 0 ? vector_make(delta.x / -distance, delta.y / -distance) : Vector{}; + if (std::abs(std::abs(away.x) - std::abs(away.y)) < EVADE_DIAGONAL) + { + if ((Random() & 1) == 0) away.x *= 0.5f; + else away.y *= 0.5f; + } + if (entity->friction != 0) + { + entity->velocity.x += away.x * EVADE_PUSH * entity->speedMultiplier / entity->friction; + entity->velocity.y += away.y * EVADE_PUSH * entity->speedMultiplier / entity->friction; + } + Vector base = vector_add(entity->pos, vector_scale(away, EVADE_BASE_REACH)); + for (float attempt = 0; attempt < EVADE_ATTEMPTS - evadeDistance * EVADE_ATTEMPT_SHARE; attempt += 1) + evade_spot_try(*this, targetPos, base, distance, attempt); + } + if (vector_is_zero(movementTarget)) return; + + if (is_evade_check_frame(*entity, EVADE_RECHECK_FRAMES)) + { + bool isDropped = room_check_line(targetPos, movementTarget, LINE_MODE_CELL, 0) && evadeDistance < EVADE_WIDE; + Vector fromTarget = vector_sub(targetPos, movementTarget); + isDropped = isDropped || vector_length_squared(fromTarget) < EVADE_SPOT_RANGE_SQUARED || + std::abs(fromTarget.x) < EVADE_WIDE || std::abs(fromTarget.y) < EVADE_WIDE; + if (isDropped) movementTarget = {}; + } + if (!vector_is_zero(movementTarget)) FindGridPath(movementTarget, EVADE_PATH_SPEED, 0, DIRECT_PATH_FAR); +} + +// 007e6300 Wanders: picks a free spot 40 away when it has none and drifts toward it, dropping it once there, against a +// wall, or now and then once stalled. Unless told to ignore its status, a friendly owner paths to its target and a +// feared or shrunk one flees instead. Whether it finished a wander (or did something else). +bool PathFinder::MoveRandomly(StatusMode mode) +{ + if (entity->minecart) return true; + if (mode == STATUS_OBEYED && is_entity_friendly()) + { + FindGridPath(static_cast(entity)->CalcTargetPosition(0), WANDER_FRIENDLY_SPEED, 0, DIRECT_PATH_FAR); + return true; + } + if (mode == STATUS_OBEYED && entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + EvadeTarget(static_cast(entity)->GetPlayerTarget()->pos, STATUS_OBEYED); + return true; + } + + if (vector_is_zero(movementTarget)) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector spot = vector_make(std::cos(angle) * WANDER_STEP + entity->pos.x, + std::sin(angle) * WANDER_STEP + entity->pos.y); + if (room_grid_collision_at(spot) == 0) movementTarget = spot; + } + if (vector_is_zero(movementTarget)) return false; + + Vector delta = vector_sub(movementTarget, entity->pos); + float distance = vector_length(delta); + bool isStalled = vector_length_squared(entity->velocity) < WANDER_STALL_SPEED_SQUARED; + if (distance < WANDER_ARRIVED || entity->isCollidesWithGrid || (isStalled && Random() % WANDER_GIVE_UP_ODDS == 0)) + { + movementTarget = {}; + return true; + } + if (distance > 0 && entity->friction != 0) + { + entity->velocity.x += delta.x / distance * WANDER_PUSH * entity->speedMultiplier / entity->friction; + entity->velocity.y += delta.y / distance * WANDER_PUSH * entity->speedMultiplier / entity->friction; + } + return false; } // 007e5340 diff --git a/src/pause_screen.cpp b/src/pause_screen.cpp index c508146..216b522 100644 --- a/src/pause_screen.cpp +++ b/src/pause_screen.cpp @@ -54,7 +54,6 @@ constexpr int SOUND_PAPER_OUT = 18; constexpr float FADE_SPEED = 0.08f; constexpr int FADE_TARGET_MENU = 2; constexpr int KEYBOARD = 0; -constexpr int COLLECTIBLE_GLITCHED_CROWN = 689; // Whether an action holds on one device, as KAGE's input manager asks. bool is_controller_action(int deviceId, ButtonAction action, ActionTest test) diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index a32bf74..c229993 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -213,6 +213,8 @@ public: void IncreaseEventCounter(int eventCounter, int num); void AddToCollection(int collectibleID); void AddChallenge(int challengeID); + void AddBoss(int bossId); + void AddMiniBoss(int miniBossId); void set_run_mask(uint64_t mask); bool AddBestiaryKill(int type, int variant); diff --git a/src/player_hud.cpp b/src/player_hud.cpp index 11311e9..d608775 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -75,7 +75,6 @@ constexpr float MANTLE_SECOND_RISE = 4; constexpr float MANTLE_SECOND_ALPHA = 0.5f; constexpr int NULL_ITEM_HOLY_CARD = 46; constexpr int COLLECTIBLE_BLANKET = 535; -constexpr int COLLECTIBLE_GUPPYS_COLLAR = 212; // The extra lives text: its gap from the hearts, its rise, and the shift beside a shield or in the compact layout. constexpr float LIVES_GAP = 10; @@ -96,21 +95,15 @@ constexpr int LAST_HEART_FLASH_STEPS = 9; // colorize of a Modeling Clay copy and the golden shimmer's steps. constexpr float TRINKET_SIZE = 32; constexpr int MONKEY_PAW_FRAMES = 3; -constexpr int TRINKET_MONKEY_PAW = 20; constexpr float TRINKET_SHADOW_ALPHA = 0.3f; constexpr ColorMod TRINKET_SHADOW = {{0, 0, 0, TRINKET_SHADOW_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr std::array ERROR_TRINKET_TINT = {132 / 255.0f, 26 / 255.0f, 26 / 255.0f}; constexpr std::array CLAY_COLORIZE = {0.5976471f, 0.33411765f, 0.31058824f, 1}; constexpr int GOLD_SHIMMER_STEPS = 256; -constexpr int TRINKET_MODELING_CLAY = 166; constexpr uint32_t ERROR_TRINKET_POOL = 189; // The active items whose HUD icon is not their item icon, the books Bethany and Judas show over the first slot, and // the Necronomicon's powered icon, which needs three of the form counter it reads. -constexpr int COLLECTIBLE_NECRONOMICON = 35; -constexpr int COLLECTIBLE_BOOK_OF_BELIAL = 34; -constexpr int COLLECTIBLE_URN_OF_SOULS = 640; -constexpr int COLLECTIBLE_BAG_OF_CRAFTING = 710; constexpr int NECRONOMICON_FORM = 15; constexpr int NECRONOMICON_FORM_COUNT = 3; constexpr int POCKET_ACTIVE_SLOT = 2; @@ -143,6 +136,77 @@ constexpr const char* BOOK_OF_VIRTUES_PNG = "gfx/ui/hud_BookOfVirtues.png"; constexpr const char* BOOK_OF_BELIAL_PNG = "gfx/ui/hud_BookOfBelial.png"; constexpr const char* BOOK_OF_VIRTUES_BELIAL_PNG = "gfx/ui/hud_BookOfVirtuesWithBelial.png"; +// An active slot's icon: its frames and size, the second slot's scale, the shadow under it, the shift in a versus match, +// and the book behind the first slot, which lowers the slot and raises the item's icon over it. +constexpr float ACTIVE_ICON_SIZE = 32; +constexpr float SECOND_ACTIVE_SCALE = 0.5f; +constexpr float ACTIVE_SHADOW_ALPHA = 0.3f; +constexpr float ACTIVE_SHADOW_SHIFT = 2; +constexpr float VERSUS_ACTIVE_SHIFT = 12; +constexpr float BOOK_SLOT_DROP = 3; +constexpr float BOOK_ICON_RISE = -7; +constexpr int SUBCHARGES_PER_CHARGE = 450; + +// The actives whose icon shows a counter, a state or a glow of its own. +constexpr int COLLECTIBLE_JAR_OF_FLIES = 434; +constexpr int COLLECTIBLE_MAMA_MEGA = 483; +constexpr int COLLECTIBLE_D_INFINITY = 489; +constexpr int COLLECTIBLE_JAR_OF_WISPS = 685; +constexpr int COLLECTIBLE_HOLD = 715; +constexpr int JAR_HEARTS_SHOWN = 10; +constexpr int JAR_FLIES_SHOWN = 20; +constexpr int JAR_FLIES_PER_ROW = 11; +constexpr int HOURGLASS_USES = 3; +constexpr int HOURGLASS_FRAMES = 7; +constexpr int URN_SOULS_SHOWN = 20; +constexpr int JAR_WISPS_SHOWN = 12; +constexpr int EVERYTHING_JAR_SHOWN = 12; +constexpr float JAR_ICON_OFFSET_X = -5; +constexpr float JAR_ICON_OFFSET_Y = -10; +constexpr float URN_ICON_OFFSET_X = -1; +constexpr float URN_ICON_OFFSET_Y = -8; +constexpr float HOLD_POOP_X = 16; +constexpr float HOLD_POOP_Y = 21; +constexpr int HOLD_POOP_LAYER = 1; +constexpr const char* HOLD_POOP_ANIMATION = "IdleSmall"; + +// The charge bar beside an active: where it sits beside the first slot, the second, and both in Esau's flipped corner, +// how far its fill reaches and from where, and the overlay of its segments by the charges it holds. +constexpr float BAR_X = 34; +constexpr float BAR_X_SECOND = -2; +constexpr float BAR_X_FLIPPED = 0; +constexpr float BAR_X_FLIPPED_SECOND = 38; +constexpr float BAR_Y = 17; +constexpr float BAR_HEIGHT = 23; +constexpr float BAR_TOP = 3; +constexpr float BAR_SMALL_DROP = 4; +constexpr float BAR_SMALL_HEIGHT = 12; +constexpr float BAR_SMALL_TOP = 1; +constexpr const char* BAR_EMPTY = "BarEmpty"; +constexpr const char* BAR_FULL = "BarFull"; +constexpr const char* BAR_OVERLAY_SINGLE = "BarOverlay1"; + +// A segment overlay of the charge bar, by the charges it shows. +struct BarOverlay +{ + int charges; + const char* animation; +}; + +constexpr BarOverlay BAR_OVERLAYS[] = {{2, "BarOverlay2"}, {3, "BarOverlay3"}, {4, "BarOverlay4"}, {5, "BarOverlay5"}, + {6, "BarOverlay6"}, {8, "BarOverlay8"}, {12, "BarOverlay12"}}; + +// The charge bar's colors: Bethany's soul charge, Tainted Bethany's blood, the partial charge, the full Necronomicon of +// a Necromancer, the battery's charge (and its partial charge, at half the alpha) and Berserk's cooldown. +constexpr ColorMod BAR_SOUL = {{1, 1, 1, 1}, {0.6f, 0.85f, 1.2f, 1}, {0, 0, 0}}; +constexpr ColorMod BAR_BLOOD = {{1, 1, 1, 1}, {1, 0.2f, 0.2f, 1}, {0, 0, 0}}; +constexpr ColorMod BAR_PARTIAL = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod BAR_NECRONOMICON = {{0.6f, 0.6f, 0.6f, 1}, {1.2f, 0.6f, 1.2f, 1}, {0, 0, 0}}; +constexpr ColorMod BAR_BATTERY = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0, 0}}; +constexpr ColorMod BAR_COOLDOWN = {{1, 1, 1, 1}, {1.2f, 1.2f, 1.2f, 1}, {0, 0, 0}}; +constexpr ColorMod ICON_SHADOW = {{0, 0, 0, ACTIVE_SHADOW_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod ICON_OUTLINE = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 1, 1}}; + constexpr int PICKUP_PILL = 70; constexpr int PICKUP_TAROTCARD = 300; @@ -182,6 +246,16 @@ static int wooden_cross_shields(Entity_Player& player) return std::max(multiplier - (player.holyMantleStacks & MANTLE_STACKS_MASK), 0); } +// Whether a corner shows the online co-op's compact HUD: online, before a versus match, for the players past the +// first of each side. +static bool is_hud_compact(const PlayerHUD& hud) +{ + bool isCompactOption = + g_game->deathmatchManager.state < DEATHMATCH_INTRO && g_manager->optionsConfig.onlineHud == ONLINE_HUD_COMPACT; + return g_manager->netplayManager.is_online() && isCompactOption && hud.playerHudIndex != 0 && + hud.playerHudIndex != MAIN_PLAYER_HUD_COUNT; +} + // Shows a player in a corner that does not show it yet, emptied first and redrawn. void PlayerHUD::assign(Entity_Player* shown) { @@ -543,9 +617,7 @@ void PlayerHUD::RenderHearts(Vector& outExtent, ANM2& sprite, PlayerHudLayout la return; } - bool isCompact = g_manager->netplayManager.is_online() && game.deathmatchManager.state < DEATHMATCH_INTRO && - g_manager->optionsConfig.onlineHud == ONLINE_HUD_COMPACT && playerHudIndex != 0 && - playerHudIndex != MAIN_PLAYER_HUD_COUNT; + bool isCompact = is_hud_compact(*this); bool isFlipped = playerHudIndex >= MAIN_PLAYER_HUD_COUNT && layout == HUD_LAYOUT_JACOB_ESAU; float spacingX = isCompact ? HEART_SMALL_SPACING_X : HEART_SPACING_X; float spacingY = isCompact ? HEART_SMALL_SPACING_Y : HEART_SPACING_Y; @@ -711,12 +783,383 @@ void PlayerHUD::RenderHearts(Vector& outExtent, ANM2& sprite, PlayerHudLayout la ((float)maxRow * spacingY + spacingY + HEART_EXTENT_PAD) * heartScale); } -// 008453c0 Draws an active item with its charge bar, the book over the first slot and the item's own counters. -void PlayerHUD::RenderActiveItem(int activeSlot, Vector, PlayerHudLayout, float, float) +// What an active's icon shows: its frame in the icon sheet, how far the item rises over the book behind it, and +// whether it glows with a white outline. +struct IconLayout { - if (!player || player->isCoopGhost || activeSlot < 0 || activeSlot >= PLAYER_HUD_ACTIVE_COUNT) return; - if (player->activeItems[activeSlot].item == 0) return; - reconstruction_missing("PlayerHUD::RenderActiveItem 008453c0: an active item's icon and charge bar"); + Vector frame{}; + Vector bookOffset = vector_make(0, BOOK_ICON_RISE); + bool isOutlined = false; +}; + +// One pass of an active's icon: where and in what color, from which frame, and whether the item draws over the book. +struct IconPass +{ + ColorMod color = COLOR_DEFAULT; + Vector frame{}; + Vector position{}; + bool isItemShown = true; +}; + +// The fills of an active's charge bar, as parts of the bar: the charge, the partial charge, the soul or blood charge +// Bethany and Tainted Bethany would spend, the battery's charge and partial charge, and Berserk's cooldown. +struct ChargeFills +{ + float battery = 0; + float batteryPartial = 0; + float blood = 0; + float charge = 0; + float cooldown = 0; + float partial = 0; + float soul = 0; +}; + +// What an active slot holds of charges, with Red Redemption's key counting its uses left as its charge. +struct SlotCharge +{ + int battery = 0; + int blood = 0; + int charge = 0; + int max = 0; + int soul = 0; + int subCharge = 0; + float partial = 0; + ActiveDischarge discharge = DISCHARGE_CHARGES; +}; + +// An active slot's charges as its bar shows them. The original crashes on an item missing from the config: here it +// discharges by charges. +static SlotCharge slot_charge_get(Entity_Player& shown, int slot, ItemConfig_Item* config) +{ + ActiveItemDesc& active = shown.activeItems[slot]; + SlotCharge charge; + charge.charge = active.charge; + charge.battery = active.batteryCharge; + charge.max = shown.GetActiveMaxCharge(slot); + charge.subCharge = active.subCharge; + charge.soul = shown.playerType == PLAYER_BETHANY ? shown.effectiveSoulCharge : 0; + charge.blood = shown.playerType == PLAYER_BETHANY_B ? shown.effectiveBloodCharge : 0; + charge.partial = (float)active.partialCharge; + charge.discharge = config ? config->discharge_get() : DISCHARGE_CHARGES; + + if (g_game->challenge == CHALLENGE_RED_REDEMPTION && active.item == COLLECTIBLE_RED_KEY) + { + charge.max = active.varData; + charge.charge = std::max(charge.max - shown.temporaryEffects.GetNullEffectNum(NULLITEM_JACOBS_CURSE), 0); + charge.battery = 0; + charge.subCharge = 0; + charge.discharge = DISCHARGE_HELD; + } + return charge; +} + +// The frame and offsets of an active's icon: the counters of the jars, the urn, the hourglass, D Infinity and the bag +// of crafting, the states of the moving box and Flip. A full bag of crafting glows, whatever the charge. +static void active_icon_frame_set(IconLayout& icon, Entity_Player& shown, int slot, const SlotCharge& charge) +{ + ActiveItemDesc& active = shown.activeItems[slot]; + auto frameAt = [&](int column, int row = 0) { + icon.frame = vector_make(column * ACTIVE_ICON_SIZE, row * ACTIVE_ICON_SIZE); + }; + + switch (active.item) + { + case COLLECTIBLE_THE_JAR: + frameAt(std::min((int)std::ceil((float)shown.jarHearts * 0.5f), JAR_HEARTS_SHOWN)); + icon.bookOffset = vector_make(JAR_ICON_OFFSET_X, JAR_ICON_OFFSET_Y); + break; + case COLLECTIBLE_JAR_OF_FLIES: + { + int flies = std::min(shown.jarFlies, JAR_FLIES_SHOWN); + frameAt(flies % JAR_FLIES_PER_ROW, flies / JAR_FLIES_PER_ROW); + icon.bookOffset = vector_make(JAR_ICON_OFFSET_X, JAR_ICON_OFFSET_Y); + break; + } + case COLLECTIBLE_GLOWING_HOUR_GLASS: + frameAt(std::clamp(HOURGLASS_USES - active.varData, 0, HOURGLASS_FRAMES)); + break; + case COLLECTIBLE_D_INFINITY: + frameAt((int16_t)(active.varData >> 16)); + break; + case COLLECTIBLE_MOVING_BOX: + if (!shown.movingBoxContents.empty()) + frameAt(1); + break; + case COLLECTIBLE_URN_OF_SOULS: + { + Weapon* weapon = shown.weapons[0] ? shown.weapons[0].get() : shown.weapons[1].get(); + frameAt(std::min((int)shown.urnSouls, URN_SOULS_SHOWN), + weapon && weapon->weaponType == WEAPON_URN_OF_SOULS); + icon.bookOffset = vector_make(URN_ICON_OFFSET_X, URN_ICON_OFFSET_Y); + break; + } + case COLLECTIBLE_JAR_OF_WISPS: + frameAt(std::min(active.varData, JAR_WISPS_SHOWN)); + icon.bookOffset = vector_make(URN_ICON_OFFSET_X, URN_ICON_OFFSET_Y); + break; + case COLLECTIBLE_BAG_OF_CRAFTING: + { + if (slot == POCKET_ACTIVE_SLOT) + break; + int count = (int)std::ranges::count_if(shown.bagOfCraftingContent, [](char pickup) { return pickup != 0; }); + icon.isOutlined = count == BAG_OF_CRAFTING_SIZE; + frameAt(count); + break; + } + case COLLECTIBLE_FLIP: + frameAt(shown.playerType == PLAYER_LAZARUS2_B); + break; + case COLLECTIBLE_EVERYTHING_JAR: + frameAt(std::min(charge.soul + charge.blood + charge.battery + charge.charge, EVERYTHING_JAR_SHOWN) + 1); + break; + default: + break; + } +} + +// (008452f0) Draws an active's item icon in a quad from a frame: a glitched item through the procedural items. +static void active_item_draw(const PlayerHUDActiveItem& active, const SourceQuad& source, + const KAGE::Graphics::ColorQuad& quad, const ColorMod& color) +{ + KAGE::Graphics::manager.shader_default_set(); + if (active.id < 0) + reconstruction_missing("GlitchedCollectibleGfx::render_item 009e0240: a TMTRAINER active's icon"); + if (!active.itemImage) + return; + + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *active.itemImage); + active.itemImage->Render(source, quad, kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); +} + +// One pass of an active's icon: the book behind the first slot, then the item over it, raised by the icon's offset. +static void icon_pass_draw(const PlayerHUDActiveItem& active, const IconLayout& icon, float iconSize, + const IconPass& pass) +{ + Vector size = vector_make(ACTIVE_ICON_SIZE, ACTIVE_ICON_SIZE); + KColor tint = kcolor_rgba(pass.color._tint[0], pass.color._tint[1], pass.color._tint[2], pass.color._tint[3]); + KAGE::Graphics::ColorQuad quad = + KAGE::Graphics::color_quad_rect(pass.position, vector_make(iconSize, iconSize), kcolor_rgba(1, 1, 1, 1)); + + if (active.bookImage) + { + apply_sprite_shader_params(pass.color, SPRITE_SHADER_COLOR_APPLY, *active.bookImage); + active.bookImage->Render(KAGE::Graphics::source_quad_rect({}, size), quad, tint); + for (Vector* corner : {&quad._topLeft, &quad._topRight, &quad._bottomLeft, &quad._bottomRight}) + *corner = vector_add(*corner, icon.bookOffset); + } + if (pass.isItemShown) + active_item_draw(active, KAGE::Graphics::source_quad_rect(pass.frame, size), quad, pass.color); +} + +// The frame an active's outline glows from: the lit frames of the Jar of Wisps, the hourglass and Glass Cannon, the +// Everything Jar's first. Breath of Life outlines only its book. +static void outline_frame_set(IconPass& outline, int item) +{ + if (item == COLLECTIBLE_JAR_OF_WISPS || item == COLLECTIBLE_GLOWING_HOUR_GLASS) + outline.frame.y += ACTIVE_ICON_SIZE; + else if (item == COLLECTIBLE_EVERYTHING_JAR) + outline.frame.x = 0; + else if (item == COLLECTIBLE_GLASS_CANNON || item == COLLECTIBLE_BROKEN_GLASS_CANNON) + outline.frame.x += ACTIVE_ICON_SIZE; + else if (item == COLLECTIBLE_BREATH_OF_LIFE) + outline.isItemShown = false; +} + +// The fills of an active's charge bar. A bar item shows Bethany's charges as all or nothing, a held item not at all. +static ChargeFills charge_fills_get(PlayerHUD& hud, const SlotCharge& slot, ItemConfig_Item* config) +{ + ChargeFills fills; + float max = (float)slot.max; + + fills.charge = + slot.subCharge != 0 ? (float)slot.subCharge / (max * SUBCHARGES_PER_CHARGE) : (float)slot.charge / max; + fills.battery = std::min(1.0f, (float)slot.battery / max); + if (slot.discharge == DISCHARGE_CHARGES) + { + fills.soul = std::min(1.0f, (float)(slot.soul + slot.charge) / max); + fills.blood = std::min(1.0f, (float)(slot.blood + slot.charge) / max); + } + else if (slot.discharge == DISCHARGE_BAR) + { + fills.soul = slot.soul > 0 ? 1 : 0; + fills.blood = slot.blood > 0 ? 1 : 0; + } + + fills.partial = std::min(1.0f, ((float)slot.charge + slot.partial) / max); + if (fills.partial <= fills.charge) + fills.batteryPartial = std::min(1.0f, ((float)slot.battery + slot.partial) / max); + if (!config || config->id != COLLECTIBLE_BERSERK) + return fills; + + TemporaryEffect* berserk = hud.player->temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BERSERK); + if (berserk) + fills.cooldown = (float)berserk->cooldown / (float)config->maxCooldown; + return fills; +} + +// The charge bar as one active draws it: the sprite, where, at what alpha, and how tall its fill is. +struct ChargeBar +{ + ANM2* sprite = nullptr; + SpriteDraw draw; + float alpha = 1; + float height = BAR_HEIGHT; +}; + +// The bar's current frame drawn up to a part of it from the bottom, in the sprite's color. +static void bar_fill_render(const ChargeBar& bar, float fill) +{ + SpriteDraw clamped = bar.draw; + clamped.topLeftClamp.y += (1 - fill) * bar.height; + bar.sprite->Render(clamped); +} + +// The bar's current frame drawn up to a part of it in a color at the bar's alpha, then back in the default color. +static void bar_fill_draw(const ChargeBar& bar, float fill, ColorMod color) +{ + color._tint[3] *= bar.alpha; + bar.sprite->color = color; + bar_fill_render(bar, fill); + bar.sprite->color = COLOR_DEFAULT; +} + +// 008453c0 Draws an active slot (the second at half size): the item's icon over its shadow, with the book behind the +// first slot, outlined in white while it can be used, then its charge bar. The bar fills with Bethany's charges, the +// charge, the battery's and Berserk's cooldown, under the overlay of its segments. A flashing bar shows only its +// overlay on even frames. Hold shows the poop it holds. +void PlayerHUD::RenderActiveItem(int activeSlot, Vector at, PlayerHudLayout layout, float itemScale, float alpha) +{ + if (!player || player->isCoopGhost) + return; + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Entity_Player& shown = *player; + int item = activeSlot >= 0 && activeSlot < PLAYER_HUD_ACTIVE_COUNT ? shown.activeItems[activeSlot].item : 0; + if (item == 0) + { + graphics.shader_default_set(); + return; + } + + bool isCompact = is_hud_compact(*this); + ANM2& bar = isCompact ? hud->chargeBarSmallSprite : hud->chargeBarSprite; + ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(item); + SlotCharge charge = slot_charge_get(shown, activeSlot, config); + PlayerHUDActiveItem& active = activeItems[activeSlot]; + float scale = (activeSlot == 1 ? SECOND_ACTIVE_SCALE : 1) * itemScale; + if (g_game->deathmatchManager.state >= DEATHMATCH_INTRO) + at.x -= VERSUS_ACTIVE_SHIFT; + + if (active.itemImage || active.bookImage || active.id < 0) + { + Vector shake = g_game->screenShakeOffset; + IconLayout icon; + graphics.shader_default_set(); + icon.isOutlined = charge.max >= 1 && + shown.GetTotalActiveCharge(activeSlot) >= shown.GetActiveMinUsableCharge(activeSlot) && + alpha >= 1; + active_icon_frame_set(icon, shown, activeSlot, charge); + if (item == COLLECTIBLE_HOLD && shown.activeItems[activeSlot].varData != 0) + { + ANM2& poops = hud->poopSpellsSprite; + poops.scale = vector_make(scale, scale); + poops.SetFrame(HOLD_POOP_ANIMATION, shown.activeItems[activeSlot].varData); + poops.RenderLayer(HOLD_POOP_LAYER, {vector_make(scale * HOLD_POOP_X + at.x, scale * HOLD_POOP_Y + at.y)}); + poops.scale = vector_make(1, 1); + } + if (active.bookImage) + at.y += BOOK_SLOT_DROP; + + float iconSize = scale * ACTIVE_ICON_SIZE; + Vector origin = vector_add(at, shake); + ColorMod shadow = ICON_SHADOW; + shadow._tint[3] *= alpha; + icon_pass_draw(active, icon, iconSize, + {shadow, icon.frame, + vector_make(origin.x + scale * ACTIVE_SHADOW_SHIFT, origin.y + scale * ACTIVE_SHADOW_SHIFT)}); + + if (icon.isOutlined) + { + IconPass outline = {ICON_OUTLINE, icon.frame}; + outline.color._tint[3] = alpha; + outline_frame_set(outline, item); + for (Vector step : {vector_make(-1, 0), vector_make(0, -1), vector_make(0, 1), vector_make(1, 0)}) + { + outline.position = vector_make(origin.x - step.x * scale, origin.y - step.y * scale); + icon_pass_draw(active, icon, iconSize, outline); + } + } + + bool isFull = charge.max >= 1 && charge.charge == charge.max; + if (item == COLLECTIBLE_BREATH_OF_LIFE || item == COLLECTIBLE_SMELTER) + icon.frame.x = isFull ? ACTIVE_ICON_SIZE : 0; + else if (item == COLLECTIBLE_MAMA_MEGA) + icon.frame.x = shown.hasGoldenBomb ? ACTIVE_ICON_SIZE : 0; + IconPass main = {COLOR_DEFAULT, icon.frame, origin}; + main.color._tint[3] = alpha; + icon_pass_draw(active, icon, iconSize, main); + } + + if (charge.max < 1) + { + graphics.shader_default_set(); + return; + } + + ChargeFills fills = charge_fills_get(*this, charge, config); + bool isFlipped = playerHudIndex >= MAIN_PLAYER_HUD_COUNT && layout == HUD_LAYOUT_JACOB_ESAU; + float barX = + activeSlot == 1 ? (isFlipped ? BAR_X_FLIPPED_SECOND : BAR_X_SECOND) : (isFlipped ? BAR_X_FLIPPED : BAR_X); + ChargeBar chargeBar = {&bar, {vector_make(barX * scale + at.x, scale * BAR_Y + at.y)}, alpha}; + if (isCompact) + { + chargeBar.draw.position.y += BAR_SMALL_DROP; + chargeBar.height = BAR_SMALL_HEIGHT; + } + chargeBar.draw.topLeftClamp.y = isCompact ? BAR_SMALL_TOP : BAR_TOP; + const char* overlay = BAR_OVERLAY_SINGLE; + for (const BarOverlay& segments : BAR_OVERLAYS) + if (segments.charges == charge.max) + overlay = segments.animation; + + bar.scale = vector_make(scale, scale); + bar.SetFrame(BAR_EMPTY, 0); + bar.color._tint[3] = alpha; + bar.Render({chargeBar.draw.position}); + + int flash = active.chargeBarFlash; + if (flash < 0 || flash % 2 == 1) + { + bar.SetFrame(BAR_FULL, 0); + if (fills.charge < fills.soul) + bar_fill_draw(chargeBar, fills.soul, BAR_SOUL); + if (fills.charge < fills.blood) + bar_fill_draw(chargeBar, fills.blood, BAR_BLOOD); + if (fills.charge < fills.partial) + bar_fill_draw(chargeBar, fills.partial, BAR_PARTIAL); + + bool isNecronomiconFull = item == COLLECTIBLE_NECRONOMICON && shown.HasPlayerForm(NECRONOMICON_FORM) && + shown.activeItems[activeSlot].varData == 1; + if (isNecronomiconFull) + bar_fill_draw(chargeBar, fills.charge, BAR_NECRONOMICON); + else + bar_fill_render(chargeBar, fills.charge); + if (fills.battery < fills.batteryPartial) + { + ColorMod color = BAR_BATTERY; + color._tint[3] = BAR_PARTIAL._tint[3]; + bar_fill_draw(chargeBar, fills.batteryPartial, color); + } + if (fills.battery > 0) + bar_fill_draw(chargeBar, fills.battery, BAR_BATTERY); + if (fills.cooldown > 0) + bar_fill_draw(chargeBar, fills.cooldown, BAR_COOLDOWN); + } + + bar.SetFrame(overlay, 0); + bar.color._tint[3] = alpha; + bar.Render({chargeBar.draw.position}); + graphics.shader_default_set(); } // (0084bab0) Draws a trinket's icon at a position and size in a color: its 32 pixel frame, which for Monkey Paw is the diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 10de4ff..1da0d3c 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -1,4 +1,5 @@ #include "player_manager.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_npc.h" #include "entity_player.h" @@ -38,7 +39,6 @@ constexpr float JOIN_SPAWN_DISTANCE = 10; constexpr float LEAVE_POOF_HEIGHT = 10; constexpr float JOIN_MENU_POSITION = 1; constexpr int COOP_BABY_MIN_HEARTS = 3; -constexpr int EFFECT_POOF01 = 15; constexpr int SOUND_JOIN_REFUSED = 187; constexpr int SOUND_CAROUSEL_LEFT = 194; constexpr int SOUND_CAROUSEL_RIGHT = 195; @@ -713,7 +713,7 @@ void PlayerManager::enter_level() std::vector& entities = g_game->room->GetEntities()->updateEL; for (Entity* entity : entities) if (entity && entity->type == ENTITY_FAMILIAR) - reconstruction_missing("PlayerManager::enter_level 009bba30: Entity_Familiar::GetFollowTargetPosition 0063b4a0"); + entity->pos = static_cast(entity)->GetFollowTargetPosition(FOLLOW_EXACT); for (Entity* entity : entities) { if (!entity) continue; diff --git a/src/revive_player_menu.cpp b/src/revive_player_menu.cpp index f366ba7..d44602c 100644 --- a/src/revive_player_menu.cpp +++ b/src/revive_player_menu.cpp @@ -21,7 +21,6 @@ constexpr float SELECTOR_ABOVE = 35; constexpr float SELECTOR_BELOW = 65; constexpr float SELECTOR_BELOW_COMPACT = 50; constexpr int CLOSE_FRAMES = 8; -constexpr int SOUND_HOLY = 54; constexpr int SOUND_FRAME_DELAY = 2; constexpr uint32_t ONLINE_STAT_REVIVES = 12; constexpr uint32_t PLAYER_INDEX_NONE = UINT32_MAX; diff --git a/src/room.cpp b/src/room.cpp index 5fc3008..79f2ca7 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -63,20 +63,7 @@ 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 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_ISAACS_CARPET = 74; -constexpr int EFFECT_DICE_FLOOR = 76; constexpr int EFFECT_WOMB_TELEPORT = 82; -constexpr int EFFECT_FALLING_EMBER = 87; -constexpr int EFFECT_BROKEN_SHOVEL_SHADOW = 115; -constexpr int EFFECT_TADPOLE = 158; -constexpr int EFFECT_LIL_GHOST = 159; // The room layout spawns Init reads before spawning anything (entities2.xml types 825 to 970). constexpr int SPAWN_WATER = 825; @@ -116,7 +103,6 @@ constexpr int DUNGEON_GIDEON = 1; constexpr int DUNGEON_ROTGUT = 2; constexpr int DUNGEON_ROTGUT_HEART = 3; constexpr int DUNGEON_BEAST = 4; -constexpr int STAGE_ID_BLUE_WOMB = 13; constexpr int STAGE_BLUE_WOMB = 9; constexpr int STAGE_ID_DOWNPOUR = 27; constexpr int STAGE_ID_DROSS = 28; @@ -234,17 +220,10 @@ constexpr float DEAL_RECENT_SCALE = 0.25f; constexpr float DEAL_LAST_SCALE = 0.5f; constexpr uint32_t GREED_DEAL_WAVE = 11; constexpr int COLLECTIBLE_PENTAGRAM = 51; -constexpr int COLLECTIBLE_BOOK_OF_BELIAL = 34; -constexpr int COLLECTIBLE_BOOK_OF_REVELATIONS = 78; constexpr int COLLECTIBLE_GOAT_HEAD = 215; -constexpr int COLLECTIBLE_BLACK_CANDLE = 260; -constexpr int COLLECTIBLE_SATANIC_BIBLE = 292; constexpr int COLLECTIBLE_EUCHARIST = 499; constexpr int COLLECTIBLE_ACT_OF_CONTRITION = 601; -constexpr int COLLECTIBLE_SAUSAGE = 669; constexpr int TRINKET_NUMBER_MAGNET = 174; -constexpr int LEVEL_STATE_BUM_KILLED = 0; -constexpr int LEVEL_STATE_SHOPKEEPER_KILLED = 6; // The doors of a cleared boss room: what unlocks them and the stages they open on, the secret exit kinds, the deal // door's jingles and Greed's deal door slot, Mom's parts the Boss Rush door clears, and the run flags they set. @@ -253,21 +232,15 @@ constexpr int ACHIEVEMENT_THE_VOID = 320; constexpr int ACHIEVEMENT_SECRET_EXIT = 407; constexpr int ACHIEVEMENT_STRANGE_DOOR = 635; constexpr int STAGE_DEPTHS_II = 6; -constexpr int COLLECTIBLE_DUALITY = 498; -constexpr int TRINKET_ROSARY_BEAD = 7; -constexpr int TRINKET_STRANGE_KEY = 175; constexpr int SOUND_ANGEL_DOOR_APPEAR = 23; constexpr int SOUND_DEVIL_DOOR_APPEAR = 320; constexpr int GREED_DEAL_DOOR_SLOT = 4; -constexpr int ENTITY_MOM = 45; constexpr float MOM_DOOR_CLEARANCE = 50; constexpr uint64_t GAME_STATE_ANGEL_DOOR_BITS = 1ull << 0; constexpr uint64_t GAME_STATE_DEVILROOM_SPAWNED_BITS = 1ull << 5; -constexpr uint32_t LEVEL_STATE_VOID_DOOR_DISABLED = 1u << 21; // The dust a door throws as it appears: how many puffs at least, how fast and far, how they spin and how long they // last. -constexpr int EFFECT_DUST_CLOUD = 59; constexpr int DUST_MIN = 5; constexpr float DUST_SPEED = 5; constexpr float DUST_RADIUS = 20; @@ -284,7 +257,6 @@ constexpr int CARD_CRACKED_KEY = 78; constexpr int CARD_SOUL_OF_CAIN = 83; constexpr int SECRET_SHOP_COLUMN = 10; constexpr int EFFECT_SHOP_LADDER = 156; -constexpr int EFFECT_DOOR_OUTLINE = 154; constexpr int SOUND_SHOP_STAIRS = 916; constexpr int STAIRS_SECRET_SHOP = 2; constexpr float DOOR_OUTLINE_OFFSET = 15; @@ -297,7 +269,6 @@ constexpr int ROOM_MINESHAFT_IDX = -101; constexpr int ACHIEVEMENT_MEGA_SATAN = 155; // The effects pressure plates and rain spawn, and a minecart enemy on its rail. -constexpr int EFFECT_SPAWNER = 120; constexpr int EFFECT_RAIN_DROP = 135; constexpr int MINECART_ENEMY = 10; constexpr int MINECART_VERTICAL = 4; @@ -325,21 +296,11 @@ constexpr float LAVA_AMOUNT = 0.45f; constexpr float COLOR_MODIFIER_RATE = 0.015f; // The collectibles, trinkets, seeds and challenges Room checks. -constexpr int COLLECTIBLE_STOP_WATCH = 232; -constexpr int COLLECTIBLE_HOURGLASS = 66; constexpr int COLLECTIBLE_INFESTATION = 148; constexpr int COLLECTIBLE_INFESTATION_2 = 234; constexpr int COLLECTIBLE_THE_STAIRWAY = 586; constexpr int COLLECTIBLE_ISAACS_TOMB = 701; -constexpr int COLLECTIBLE_SANGUINE_BOND = 692; constexpr int COLLECTIBLE_CARD_READING = 660; -constexpr int COLLECTIBLE_BROKEN_SHOVEL = 550; -constexpr int COLLECTIBLE_ASTRAL_PROJECTION = 677; -constexpr int TRINKET_BROKEN_GLASSES = 187; -constexpr int TRINKET_WICKED_CROWN = 161; -constexpr int TRINKET_HOLY_CROWN = 155; -constexpr int TRINKET_BLOODY_CROWN = 111; -constexpr int COLLECTIBLE_MORE_OPTIONS = 414; constexpr int SEED_EFFECT_PRE_ITEMS = 79; constexpr int SEED_EFFECT_NO_LAST_BOSS_DOORS = 71; constexpr int SPECIAL_DAILY_SURPRISE_MINIBOSS = 17; @@ -356,10 +317,6 @@ constexpr int SHOP_LEVEL_MAX = 5; // The run state and floor state bits Init and Update read. constexpr uint64_t GAME_STATE_SURPRISE_MINIBOSS_SEEN = 1ull << 29; -constexpr uint32_t LEVEL_STATE_MINESHAFT_ESCAPE = 1u << 22; -constexpr uint32_t LEVEL_STATE_SHOVEL_QUEST_TRIGGERED = 1u << 16; -constexpr uint32_t LEVEL_STATE_BROKEN_WATCH_SLOW = 1u << 24; -constexpr uint32_t LEVEL_STATE_BROKEN_WATCH_FAST = 1u << 25; // Init's ambient decoration: how many spawn at most, and how the second door chance raises them. constexpr int AMBIENT_FLIES = 15; @@ -391,45 +348,6 @@ constexpr float MUSIC_CROSSFADE_ASCENT = 0.008f; constexpr float MUSIC_CROSSFADE_REVERSE = 0.01f; constexpr float MUSIC_CROSSFADE_INSTANT = 1; -// The music.xml tracks PlayMusic picks from. -enum MusicId : int -{ - MUSIC_NULL = 0, - MUSIC_BOSS = 9, - MUSIC_MOM_BOSS = 20, - MUSIC_MOMS_HEART_BOSS = 21, - MUSIC_ISAAC_BOSS = 22, - MUSIC_DARK_ROOM_BOSS = 24, - MUSIC_CHEST_BOSS = 25, - MUSIC_BOSS2 = 26, - MUSIC_ULTRA_GREED_BOSS = 28, - MUSIC_LIBRARY_ROOM = 30, - MUSIC_SECRET_ROOM = 31, - MUSIC_SECRET_ROOM_ALT = 32, - MUSIC_DEVIL_ROOM = 33, - MUSIC_ANGEL_ROOM = 34, - MUSIC_SHOP_ROOM = 35, - MUSIC_ARCADE_ROOM = 36, - MUSIC_BOSS_OVER = 37, - MUSIC_CHALLENGE_FIGHT = 38, - MUSIC_BOSS3 = 41, - MUSIC_MOTHER_BOSS = 43, - MUSIC_DOGMA_BOSS = 44, - MUSIC_BEAST_BOSS = 45, - MUSIC_PLANETARIUM = 50, - MUSIC_SECRET_ROOM_ALT_ALT = 51, - MUSIC_BOSS_OVER_TWISTED = 52, - MUSIC_REVERSE_GENESIS_START = 64, - MUSIC_HUSH_TRANSITION = 65, - MUSIC_ECHOES_REVERSE = 69, - MUSIC_TREASURE_JINGLE_FIRST = 87, - MUSIC_GAME_START_JINGLE = 95, - MUSIC_VOID_BOSS = 103, - MUSIC_DOWNPOUR = 104, - MUSIC_DOWNPOUR_REVERSED = 114, - MUSIC_ABANDONED_MINESHAFT = 116, - MUSIC_REVERSE_GENESIS = 118 -}; constexpr int TREASURE_JINGLE_COUNT = 4; static float random_unit() @@ -638,7 +556,7 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) Entity_Player* sanguineOwner = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SANGUINE_BOND, LAZARUS_SHARE_CHECK); if (roomType == ROOM_DEVIL && sanguineOwner && isFirstVisit) spawn_sanguine_bond_spikes(true); bool isShovelRemoved = g_game->itemPool.removedCollectibles[COLLECTIBLE_BROKEN_SHOVEL]; - if (g_game->stage == 1 && (g_game->levelStateFlags & LEVEL_STATE_SHOVEL_QUEST_TRIGGERED) && + if (g_game->stage == 1 && (g_game->levelStateFlags & 1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED) && g_game->currentRoomIdx == g_game->startingRoomIdx && !isShovelRemoved) { uint32_t seed = Random(); @@ -708,13 +626,13 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) if (bossId == BOSS_ULTRA_GREED && g_game->difficulty == DIFFICULTY_GREEDIER && IsClear()) TurnGold(); Room& current = *g_game->room; - if (g_game->levelStateFlags & LEVEL_STATE_BROKEN_WATCH_SLOW) + if (g_game->levelStateFlags & 1u << LEVEL_STATE_BROKEN_WATCH_SLOW) { current.brokenWatchState = BROKEN_WATCH_SLOW; g_manager->musicManager.targetPitch = current.time_scale_update(); current.slowdownDuration = INT_MAX; } - if (g_game->levelStateFlags & LEVEL_STATE_BROKEN_WATCH_FAST) + if (g_game->levelStateFlags & 1u << LEVEL_STATE_BROKEN_WATCH_FAST) { current.brokenWatchState = BROKEN_WATCH_FAST; g_manager->musicManager.targetPitch = current.time_scale_update(); @@ -920,7 +838,7 @@ void Room::init_first_visit(SpawnFlags& flags) } else if (backdropType == BACKDROP_MINES_SHAFT || backdropType == BACKDROP_ASHPIT_SHAFT) { - if (g_game->levelStateFlags & LEVEL_STATE_MINESHAFT_ESCAPE) + if (g_game->levelStateFlags & 1u << LEVEL_STATE_MINESHAFT_ESCAPE) { isDry = false; isWater = true; @@ -2003,7 +1921,7 @@ void Room::PlayMusic() else if (g_game->HasAbandonedMineshaft() && g_game->currentDimensionIdx == 1) { jingle = 0; - music = MUSIC_ABANDONED_MINESHAFT + (g_game->levelStateFlags & LEVEL_STATE_MINESHAFT_ESCAPE ? 1 : 0); + music = MUSIC_ABANDONED_MINESHAFT + (g_game->levelStateFlags & 1u << LEVEL_STATE_MINESHAFT_ESCAPE ? 1 : 0); } else if (g_game->stage >= 1 && g_game->stage <= 6 && g_game->GetStateFlag(GAME_STATE_BACKWARDS_PATH)) { @@ -2048,7 +1966,6 @@ void Room::PlayMusic() musicManager.targetPitch = time_scale_update(); } - // The stage of the floor for its deals, an alternate floor counting one deeper. static int deal_stage_get_unclamped() { @@ -3188,9 +3105,9 @@ bool Room::TrySpawnTheVoidDoor(bool isForce) if (params.endStage != 0) endStage = params.endStage; isClosed = params.pathType == PATH_TYPE_HOME; } - if (isClosed || endStage < STAGE_THE_VOID || game.levelStateFlags & LEVEL_STATE_VOID_DOOR_DISABLED) + if (isClosed || endStage < STAGE_THE_VOID || game.levelStateFlags & 1u << LEVEL_STATE_VOID_DOOR_DISABLED) { - game.levelStateFlags |= LEVEL_STATE_VOID_DOOR_DISABLED; + game.levelStateFlags |= 1u << LEVEL_STATE_VOID_DOOR_DISABLED; return false; } } @@ -3198,7 +3115,7 @@ bool Room::TrySpawnTheVoidDoor(bool isForce) ChallengeParam& params = game.GetChallengeParams(); if (!isForce && params.isPathTypeSet && stage >= params.endStage) { - game.levelStateFlags |= LEVEL_STATE_VOID_DOOR_DISABLED; + game.levelStateFlags |= 1u << LEVEL_STATE_VOID_DOOR_DISABLED; return false; } GridEntity_Door& door = special_door_make(*this, DOOR_UP1, ROOM_THE_VOID_IDX); @@ -3342,4 +3259,3 @@ void Room::card_against_humanity_fill() { reconstruction_missing("Room::card_against_humanity_fill 007fe220"); } - diff --git a/src/room.h b/src/room.h index 5904ea9..99ae179 100644 --- a/src/room.h +++ b/src/room.h @@ -10,6 +10,7 @@ #include "room_descriptor.h" #include "temporary_effects.h" #include +#include #include #include #include @@ -29,6 +30,7 @@ constexpr uint32_t ROOM_DESCRIPTOR_FLAG_PITCH_BLACK = 1 << 9; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_CURSED_MIST = 1 << 13; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_NO_WALLS = 1 << 15; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED = 1 << 16; +constexpr uint32_t ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT = 1 << 18; // A room's type (Lua's RoomType), as its config gives it. enum RoomType : int @@ -121,6 +123,13 @@ struct SpawnFlags bool isWater = false; }; +// A shop slot bought out with the Restock item, which ShopRestockPartial fills again (Room::shopRestocks). +struct ShopRestock +{ + int gridIndex = -1; + int shopItemId = -1; +}; + // The getters and setters of plain fields are the members themselves (0040c2e0, 00421800, 0042cc70, 0042d030, // 004360c0, 0043ef20, 004566f0, 004cdd20, 004d7780, 00505c50, 005784d0, 00592270, 005b16c0, 005cd660, 005cd670, // 0065cef0, 006b83d0, 006b83e0, 006b83f0, 006b8400, 007120c0, 007537c0, 007537d0, 007e91a0, 007e91f0, 007ea190, @@ -146,6 +155,7 @@ public: std::array, OUTPUT_GROUP_COUNT> outputGroupCallbacks; std::set litGridIndices; std::set pendingGridRemovals; + std::deque shopRestocks; EntityList entityList; FXLayers fxLayers; Backdrop backdrop; @@ -182,6 +192,7 @@ public: int backdropType = 0; int bloodFromWallsCount = 0; int bloodFromWallsDuration = 0; + int bossesRemaining = 0; int bossId = 0; int dungeonRockIdx = -1; int enterFrame = 0; @@ -305,6 +316,8 @@ public: float time_scale_update(); float GetTimeScale(Entity* entity); int boss_music_get(); + uint32_t GetBossVictoryJingle(); + void TriggerBossDeath(Entity_NPC& boss); void PlayMusic(); void Update(); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index 46ee0d1..476e538 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -29,37 +29,22 @@ constexpr int COLLECTIBLE_CONTRACT_FROM_BELOW = 241; constexpr int COLLECTIBLE_THERES_OPTIONS = 249; constexpr int COLLECTIBLE_DEEP_POCKETS_CLEAR = 416; constexpr int COLLECTIBLE_GLYPH_OF_BALANCE = 464; -constexpr int COLLECTIBLE_SMELTER = 479; -constexpr int COLLECTIBLE_BROKEN_MODEM = 514; -constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; constexpr int COLLECTIBLE_BROKEN_SHOVEL_2 = 551; -constexpr int COLLECTIBLE_4_5_VOLT = 647; constexpr int COLLECTIBLE_OPTIONS = 670; constexpr int COLLECTIBLE_SWARM = 693; constexpr int COLLECTIBLE_AZAZELS_RAGE = 699; -constexpr int COLLECTIBLE_WHITE_PONY = 181; -constexpr int COLLECTIBLE_PONY = 130; constexpr int COLLECTIBLE_LITTLE_CHAD = 96; constexpr int COLLECTIBLE_LITTLE_GISH = 99; constexpr int COLLECTIBLE_STEVEN = 50; constexpr int COLLECTIBLE_LITTLE_STEVEN = 100; -constexpr int COLLECTIBLE_CUBE_OF_MEAT = 73; -constexpr int COLLECTIBLE_BALL_OF_BANDAGES = 207; constexpr int TRINKET_AAA_BATTERY_CLEAR = 3; -constexpr int TRINKET_DAEMONS_TAIL = 22; constexpr int TRINKET_RUSTED_KEY = 36; -constexpr int TRINKET_MATCH_STICK = 41; constexpr int TRINKET_LUCKY_TOE = 42; constexpr int TRINKET_SAFETY_CAP = 44; constexpr int TRINKET_ACE_OF_SPADES = 45; constexpr int TRINKET_ISAACS_FORK = 46; constexpr int TRINKET_LOUSE = 70; -constexpr int TRINKET_WATCH_BATTERY = 72; -constexpr int TRINKET_RIB_OF_GREED = 84; constexpr int TRINKET_OLD_CAPACITOR = 143; -constexpr int TRINKET_BLUE_KEY = 150; -constexpr int TRINKET_GILDED_KEY = 159; -constexpr int TRINKET_AZAZELS_STUMP = 162; constexpr int TRINKET_DINGLE_BERRY = 163; constexpr int TRINKET_POLISHED_BONE = 167; constexpr int TRINKET_CRYSTAL_KEY = 170; @@ -74,7 +59,6 @@ constexpr int EFFECT_HEART_CLEAR = 49; constexpr int SOUND_DOOR_HEAVY_OPEN = 36; constexpr int SOUND_VAMP_GULP_CLEAR = 157; constexpr int SOUND_VAMP_DOUBLE_CLEAR = 614; -constexpr int SOUND_BATTERYCHARGE = 170; constexpr int ACHIEVEMENT_LITTLE_CHAD = 25; constexpr int ACHIEVEMENT_LITTLE_GISH = 23; constexpr int ACHIEVEMENT_LITTLE_STEVEN = 24; @@ -87,8 +71,6 @@ constexpr int STAGE_HOME_ID = 35; constexpr int STAGE_WOMB_2 = 8; constexpr int STAGE_HOME_END = 13; constexpr int GREED_WAVES = 10; -constexpr int LEVEL_STATE_SHOVEL_QUEST_TRIGGERED = 16; -constexpr int LEVEL_STATE_SATANIC_BIBLE_USED = 17; constexpr int ACHIEVEMENT_MONSTROS_LUNG = 13; constexpr int ACHIEVEMENT_LIL_CHUBBY = 14; constexpr int ACHIEVEMENT_STEVEN = 16; @@ -679,7 +661,7 @@ static bool special_award_pick(Room& room, RNG& rng, int& item, int& trinket) static const std::map BOSS_TRINKETS = {{9, 115}, {10, 114}, {11, 113}, {12, 116}, {38, 117}, {79, 141}, {101, 183}}; constexpr std::array SIN_TRINKETS = {12, 26, 9, 11, 27, 10, 64, 65, 96, 144, 66}; - constexpr int COLLECTIBLE_DAMOCLES_PASSIVE = 639; + constexpr int COLLECTIBLE_YUCK_HEART = 639; item = 0; trinket = 0; @@ -687,7 +669,7 @@ static bool special_award_pick(Room& room, RNG& rng, int& item, int& trinket) if (rng.Next() % 100 != 0) return false; bool isSin = room.bossId == 2 || room.bossId == 7 || room.bossId == 26 || room.bossId == 37; - if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED) item = COLLECTIBLE_DAMOCLES_PASSIVE; + if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED) item = COLLECTIBLE_YUCK_HEART; else if (isSin) trinket = SIN_TRINKETS[rng.RandomInt(SIN_TRINKETS.size())]; else if (auto found = BOSS_ITEMS.find(room.bossId); found != BOSS_ITEMS.end()) item = found->second; else if (auto found = BOSS_TRINKETS.find(room.bossId); found != BOSS_TRINKETS.end()) trinket = found->second; diff --git a/src/room_config.cpp b/src/room_config.cpp index c2e0edd..73bd974 100644 --- a/src/room_config.cpp +++ b/src/room_config.cpp @@ -58,10 +58,8 @@ constexpr uint32_t SPLIT_SHIFT = 55; constexpr float EXACT_DOORS_BIAS = 9.99f; constexpr float PICKED_WEIGHT_SCALE = 0.1f; constexpr float PICKED_WEIGHT_MIN = 1e-7f; -constexpr uint32_t ENTITY_GUTS = 40; constexpr uint32_t ENTITY_CONSTANT_STONE_SHOOTER = 202; constexpr uint32_t ENTITY_BRIMSTONE_HEAD = 203; -constexpr uint32_t ENTITY_WALL_HUGGER = 218; constexpr uint32_t ENTITY_QUAKE_GRIMACE = 804; constexpr uint32_t ENTITY_SPIKEBALL = 852; constexpr uint32_t ENTITY_CYST = 862; diff --git a/src/room_descriptor.h b/src/room_descriptor.h index 8cb4a81..b54f9a6 100644 --- a/src/room_descriptor.h +++ b/src/room_descriptor.h @@ -9,6 +9,7 @@ constexpr int ROOM_GRID_CELLS = 448; constexpr uint32_t GRID_SAVE_SEED_DEFAULT = 0x16a9de81; +constexpr int SHOP_SLOT_COUNT = 8; // What a room descriptor records about its room (Lua's RoomDescriptor.FLAG_*), by bit. enum RoomDescriptorFlag : uint32_t @@ -42,7 +43,8 @@ constexpr GridEntityDesc GRID_SAVE_EMPTY = {0, 0, 0, 0, GRID_SAVE_SEED_DEFAULT, // The flag getters (00436010, 00456560, 00505c30, 005cd640, 0070c550, 00738180, 007e9190) are flags tested against // RoomDescriptorFlag. // Construction (006ef590), destruction (006ef9c0), copies (00749040) and moves (007387d0, 00752e80) are the defaults. -// The original's reserve of 16 entities and 32 effects is left out. Its words at 0x94..0xab are only ever copied. +// The original's reserve of 16 entities and 32 effects is left out. A shop's slots say what each sells and how often +// it was restocked (0x94, 0xa4). struct RoomDescriptor { std::array doors = {-1, -1, -1, -1, -1, -1, -1, -1}; @@ -50,6 +52,8 @@ struct RoomDescriptor std::vector savedGridEntities = std::vector(ROOM_GRID_CELLS, GRID_SAVE_EMPTY); std::vector savedEffects; std::vector savedEntities; + std::array shopItemSlots{}; + std::array shopItemRestocks{}; RoomConfig_Room* data = nullptr; RoomConfig_Room* overrideData = nullptr; int deliriumDistance = 0; diff --git a/src/room_lighting.cpp b/src/room_lighting.cpp new file mode 100644 index 0000000..8924efa --- /dev/null +++ b/src/room_lighting.cpp @@ -0,0 +1,1022 @@ +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_fireplace.h" +#include "room.h" +#include "room_render.h" +#include "seeds.h" +#include +#include + +// The flicker of entity lights: its RNG's shifts, the seed it takes for a zero one, and RandomVector's angle. +constexpr uint32_t FLICKER_SHIFTS[] = {5, 27, 25}; +constexpr uint32_t FLICKER_SEED_ZERO = 1; + +// The player's light: the Spirit of the Night aura, the dimmer lights of the Mausoleum's heart and of a hologram, how +// it grows with the darkness, the Night Light cone's turn, and Hush's pulse. +constexpr float AURA_STACK_MAX = 5; +constexpr float AURA_ALPHA_STEP = 0.12f; +constexpr float AURA_ALPHA = 0.3f; +constexpr float AURA_SCALE = 2; +constexpr float MAUSOLEUM_LIGHT = 0.65f; +constexpr float HOLOGRAM_LIGHT = 0.3f; +constexpr float DARKNESS_LIGHT_GROWTH = 0.5f; +constexpr float HUSH_PULSE_SPEED = 0.18f; +constexpr float HUSH_PULSE_MIN_SPEED = 0.02f; +constexpr float HUSH_PULSE_BASE = 3; +constexpr float HUSH_WEAKNESS_UNHURT = 0.1f; +constexpr ColorMod LIGHT_RED = {{1, 0, 0.03f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_PURPLE = {{0.9f, 0.3f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_WARM = {{1, 0.9f, 0.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_AURA = {{0.4f, 0.6f, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int COLLECTIBLE_SPIRIT_OF_THE_NIGHT = 3; +constexpr int COLLECTIBLE_TELEPATHY_BOOK = 192; +constexpr int PLAYER_DARK_JUDAS = 12; + +// 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 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}}; + +// A tear's light: its size and how its flags and variants color it, how far it flickers, and the light frame Glow uses. +constexpr float TEAR_LIGHT_SCALE = 0.4f; +constexpr float GLOW_LIGHT_SCALE = 1.3f; +constexpr float TEAR_LIGHT_FLICKER = 2; +constexpr float JACOBS_LIGHT_FLICKER = 6; +constexpr ColorMod TEAR_LIGHT_GLOW = {{1, 1, 0.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_LIQUID = {{0.2f, 1, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_BURN = {{1, 1, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_HORN = {{1, 0.6f, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_HEAVEN = {{0.4f, 0.9f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_JACOBS = {{0.4f, 0.5f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_FIRE = {{0.8f, 0.9f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod TEAR_LIGHT_LUDOVICO = {{1, 1, 1, 0.6f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// How far above an entity its light sits: an enemy's or a bomb's, a Visage's, a familiar's and a wisp's, the +// minecart's, and those of the Willo, the Prey and the Boom Fly. +constexpr float LIGHT_RISE = 15; +constexpr float VISAGE_LIGHT_RISE = 14; +constexpr float HEART_LIGHT_RISE = 14; +constexpr float WISP_LIGHT_RISE = 9; +constexpr float MINECART_LIGHT_RISE = 12; +constexpr float FLY_LIGHT_RISE = 16; + +// The entities with lights of their own, by Lua's names: familiar, bomb, laser, effect and enemy variants. +constexpr int FAMILIAR_ISAACS_HEART = 62; +constexpr int BOOMFLY_DRAGON_FLY = 3; +constexpr int LAMB_VARIANT_LIGHT = 10; +constexpr int PREY_VARIANT_LIGHT = 1; +constexpr int ROCK_SPIDER_VARIANT_LIGHT = 2; +constexpr int VISAGE_HEART = 0; +constexpr int VISAGE_MASK = 1; +constexpr int VISAGE_CHAIN = 20; +constexpr int VISAGE_HEART_STATE_LIT = 113; +constexpr int VISAGE_HEART_STATE_FLARE = 104; +constexpr int VISAGE_MASK_STATE_LIT = 105; +constexpr int BOSS_ID_WIDOW = 51; +constexpr int BACKDROP_ASHPIT = 46; +constexpr int ENTITY_THE_LAMB = 273; +constexpr int ENTITY_PREY = 817; +constexpr int FLAMING_VARIANT = 2; +constexpr int FLAMING_TYPES[] = {10, 208, 226}; +constexpr const char* NULL_LIGHT = "Light"; +constexpr const char* LAYER_SPARKS = "sparks"; +constexpr const char* LAYER_FLAME = "flame"; + +// The laser variants by their light's color, and the effect variants with lights (Lua's EffectVariant). +enum LightVariant : int +{ + LASER_THIN_RED = 2, + LASER_SHOOP = 3, + LASER_PRIDE = 4, + LASER_LIGHT_BEAM = 5, + LASER_TRACTOR_BEAM = 7, + LASER_LIGHT_RING = 8, + LASER_ELECTRIC = 10, + EFFECT_BLUE_FLAME = 10, + EFFECT_TARGET = 30, + EFFECT_HOT_BOMB_FIRE = 51, + EFFECT_RED_CANDLE_FLAME = 52, + EFFECT_BLOOD_DROP = 70, + EFFECT_BRIMSTONE_SWIRL = 71, + EFFECT_FIREWORKS = 104, + EFFECT_ENEMY_BRIMSTONE_SWIRL = 110, + EFFECT_HAEMO_TRAIL = 111, + EFFECT_HALLOWED_GROUND = 112, + EFFECT_TECH_DOT = 126, + EFFECT_OCCULT_TARGET = 153, + EFFECT_KINETI_BEAM = 175, + EFFECT_REVERSE_EXPLOSION = 177 +}; + +// The lights' colors: lasers by variant, the explosions' grey lift, and the effects' and enemies' lights. +constexpr ColorMod LASER_LIGHT_BLUE = {{0.6f, 0.8f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LASER_LIGHT_PRIDE = {{0.9f, 0.9f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LASER_LIGHT_HOLY = {{1, 0.95f, 0.65f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LASER_LIGHT_TRACTOR = {{0.5f, 0.5f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_PINK = {{1, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_FIRE = {{1, 0.8f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_HOT = {{1, 0.3f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_SPARK = {{1, 0.8f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_DIM_BULLET = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_BLOOD = {{0.6f, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_EMBER = {{1, 0.4f, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_CANDLE = {{1, 0.5f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_GATE = {{1, 0.3f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_LAMB = {{1, 0.1f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_GOLD = {{1, 0.8f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_PALE = {{1, 1, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_HEART = {{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_TARGET = {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_MINECART = {{1, 0.4f, 0, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_HERETIC = {{0.8f, 0.2f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_CREEP = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_HALLOWED = {{0.4f, 0.7f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_BLUE_FLAME = {{0.2f, 0.5f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod LIGHT_PENTAGRAM = {{1, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float EXPLOSION_GREY = 50 / 255.0f; +constexpr std::array TARGET_LIGHT_BLEND = { + BLEND_EQUATION_ADD, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}; +constexpr std::array LIGHT_BLEND_NORMAL = {BLEND_EQUATION_ADD, BLEND_FACTOR_ONE, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, BLEND_FACTOR_ONE, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}; +constexpr int EXPLOSION_FADE_FRAMES = 6; +constexpr float EXPLOSION_BIG_SCALE = 1.5f; +constexpr KColor HAEMO_TRAIL_RED = kcolor_rgba(0.7f, 0, 0, 1); +constexpr KColor WISP_LAYER_GREY = kcolor_rgba(0.6f, 0.6f, 0.6f, 1); +constexpr float LUMA_RED = 0.2126f; +constexpr float LUMA_GREEN = 0.7152f; +constexpr float LUMA_BLUE = 0.0722f; +constexpr float WISP_LAYER_DARKER = 0.25f; + +// Lasers draw their light along their length in this many steps, and room-wide lights fade in over their first frames. +constexpr int LASER_LIGHT_STEPS = 20; +constexpr int LIGHT_FADE_IN_FRAMES = 10; +constexpr float DARK_ROOM_ALPHA = 0.5f; + +// Where the room's light sprite draws one light of an entity: from the entity's position (with its sprite offset when +// counted), raised, and moved on screen by a random flicker. frame 1 is the light sprite's small light. +struct EntityLight +{ + ColorMod color = COLOR_DEFAULT; + Vector rise{}; + Vector scale = vector_make(1, 1); + float flicker = 0; + int frame = 0; + bool isOffsetCounted = false; +}; + +// What every light of one entity shares: the room, the entity, the screen offset and the flicker's RNG. +struct LightPass +{ + Room& room; + Entity& entity; + Vector offset; + RNG flicker; +}; + +// 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_UNIT_SCALE * RANDOM_HALF_TURN; + angle += angle; + return vector_make(std::cos(angle), std::sin(angle)); +} + +// Vector::Rotated: v turned by an angle in degrees. +static Vector vector_rotated(Vector v, float degrees) +{ + float cos = std::cos(degrees * DEGREES_TO_RADIANS); + float sin = std::sin(degrees * DEGREES_TO_RADIANS); + return vector_make(v.x * cos - v.y * sin, v.y * cos + v.x * sin); +} + +static ColorMod tint_make(float red, float green, float blue, float alpha) +{ + return {{red, green, blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; +} + +// A light color multiplied by an entity's sprite color. +static ColorMod color_through(ColorMod color, const ColorMod& other) +{ + color_multiply(color, other); + return color; +} + +static Vector screen_position(const LightPass& pass, Vector world) +{ + return vector_add(render_position_get(world, RENDER_SNAPPED), pass.offset); +} + +// Draws one light of an entity with the room's light sprite. +static void light_draw(LightPass& pass, const EntityLight& light) +{ + ANM2& sprite = pass.room.lightSprite; + Entity& entity = pass.entity; + Vector world = + vector_add(light.isOffsetCounted ? vector_add(entity.pos, entity.posOffset) : entity.pos, light.rise); + + sprite.color = light.color; + sprite.scale = light.scale; + if (light.frame != 0) + sprite.SetFrame((float)light.frame); + Vector position = screen_position(pass, world); + if (light.flicker != 0) + { + Vector direction = RandomVector(pass.flicker.Next()); + position = vector_add(position, vector_scale(direction, pass.flicker.RandomFloat() * light.flicker)); + } + sprite.Render({position}); + if (light.frame != 0) + sprite.SetFrame(0.0f); +} + +static Vector uniform(float scale) +{ + return vector_make(scale, scale); +} + +// Whether an entity that belongs to a player in an online game is this machine's. Offline every one is. +static bool is_owned_locally(Entity& entity) +{ + NetplayManager& netplay = g_manager->netplayManager; + if (!netplay.is_online()) + return true; + + Entity_NPC* npc = dynamic_cast(&entity); + if (!npc) + reconstruction_missing("is_local_player_owned 006d8e10: a player's owner online"); + return npc->controllerID == -1 || netplay.IsIdxLocalPlayer(npc->controllerID); +} + +// The lights a sprite marks itself: each visible null named with a '*' lights in its color, size and turn, and the +// layers only drawn in the light pass draw into it. The light sprite turns back after. +static void sprite_lights_render(LightPass& pass) +{ + Entity& entity = pass.entity; + const ANM2& sprite = entity.sprite; + ANM2& light = pass.room.lightSprite; + Vector position = screen_position(pass, vector_add(entity.pos, entity.posOffset)); + std::array states = {&sprite.overlayAnimState, &sprite.animState}; + + if (sprite.bitflags & ANIM_RENDER_ENABLE_NULL_LAYER_LIGHTING) + { + light.SetFrame(0.0f); + for (const AnimationState* state : states) + { + if (!state->animData) + continue; + for (const AnimationNullLayer& track : state->animData->nullLayers) + { + const std::string& name = sprite.GetNullLayerName(track.nullLayerId); + if (name.empty() || name[0] != LIGHT_LAYER_PREFIX || !sprite.animState.animData) + continue; + + const NullFrame* frame = sprite.animState.GetNullFrameById(track.nullLayerId); + if (!frame || !frame->isVisible || frame->color._tint[3] <= 0) + continue; + + Vector at = vector_add(sprite.offset, frame->pos); + at = vector_rotated(vector_make(at.x * sprite.scale.x, at.y * sprite.scale.y), sprite.rotation); + if (sprite.isFlipX) + at.x = -at.x; + if (sprite.isFlipY) + at.y = -at.y; + KColor color = kcolor_apply(color_through(sprite.color, frame->color), kcolor_rgba(1, 1, 1, 1)); + light.color = tint_make(color._red, color._green, color._blue, color._alpha); + light.scale = vector_make(frame->scale.x * sprite.scale.x, frame->scale.y * sprite.scale.y); + light.rotation = sprite.rotation + frame->rotation; + light.Render({vector_add(position, at)}); + } + } + light.rotation = 0; + } + if (!(sprite.bitflags & ANIM_RENDER_ENABLE_LAYER_LIGHTING)) + return; + + for (const AnimationState* state : states) + { + if (!state->animData) + continue; + for (const AnimationLayer& track : state->animData->animLayers) + { + const LayerState* layer = + track.layerId < (int)sprite.layerStates.size() ? &sprite.layerStates[track.layerId] : nullptr; + if (layer && layer->bitflags & ANIM_RENDER_LIGHT_PASS_ONLY) + track.RenderFrame({position}, state->GetLayerFrameIdx(track.layerId), sprite); + } + } +} + +// A player's light: its Spirit of the Night aura, then the light gradient (red for Dark Judas, warm under flame +// costumes, purple under the ghostly ones, white otherwise) growing with the darkness, dimmed in the Mausoleum's heart +// and for a hologram, its Night Light cone, and in Hush's room a second light pulsing faster as Hush weakens. +static void player_light_render(Room& room, Entity_Player& player, Vector offset) +{ + ANM2& light = room.lightSprite; + ItemConfig& items = g_manager->itemConfig; + Vector position = vector_add(render_position_get(vector_add(player.pos, player.posOffset), RENDER_SNAPPED), offset); + TemporaryEffect* aura = + player.temporaryEffects.isDisabled ? nullptr : player.temporaryEffects.GetNullEffect(NULL_EFFECT_SPIRIT_AURA); + float stacks = std::min(aura ? (float)aura->count : 0.0f, AURA_STACK_MAX); + + if (player.temporaryEffects.HasNullEffect(NULL_EFFECT_SPIRIT_AURA)) + { + layer_blend_set(light, KAGE::Graphics::BLEND_ADDITIVE); + light.color = LIGHT_AURA; + light.color._tint[3] = stacks * AURA_ALPHA_STEP + AURA_ALPHA; + light.scale = uniform(stacks + AURA_SCALE); + light.Render({position}); + layer_blend_set(light, KAGE::Graphics::BLEND_NORMAL); + } + + float strength = g_game->IsMausoleumHeartStage() ? MAUSOLEUM_LIGHT : 1; + if (player.IsHologram()) + strength *= HOLOGRAM_LIGHT; + auto isCostume = [&](int collectible) { + return is_item_costume_visible(player, items.GetCollectible(collectible), -1); + }; + bool isFlame = is_item_costume_visible(player, items.GetCollectible(COLLECTIBLE_FIRE_MIND_COSTUME), 0) || + isCostume(COLLECTIBLE_FIRE_MIND) || player.IsNullItemCostumeVisible(NULL_ITEM_BRIMSTONE_FLAME, 0); + bool isGhostly = isCostume(COLLECTIBLE_SPIRIT_OF_THE_NIGHT) || isCostume(COLLECTIBLE_TELEPATHY_BOOK) || + isCostume(COLLECTIBLE_EYE_OF_THE_OCCULT); + if (isFlame || isGhostly) + light.color = player.playerType == PLAYER_DARK_JUDAS ? LIGHT_RED : isFlame ? LIGHT_WARM : LIGHT_PURPLE; + else + light.color = COLOR_DEFAULT; + light.color._tint[3] *= strength; + + float darkness = g_game->GetCurses() & CURSE_OF_DARKNESS ? 1 : g_game->darknessStrength * g_game->darknessModifier; + light.scale = uniform(darkness * DARKNESS_LIGHT_GROWTH + 1); + light.SetFrame(1.0f); + light.Render({position}); + light.SetFrame(0.0f); + + if (player.HasCollectible(COLLECTIBLE_NIGHT_LIGHT)) + { + room.spotLightSprite.rotation = player.bodyAngle - NIGHT_LIGHT_ANGLE; + room.spotLightSprite.color = COLOR_DEFAULT; + layer_blend_set(room.spotLightSprite, KAGE::Graphics::BLEND_NORMAL); + room.spotLightSprite.Render({position}); + } + if (g_game->GetStageID() != STAGE_ID_BLUE_WOMB || room.descriptor->data->type != ROOM_BOSS) + return; + + float weakness = HUSH_WEAKNESS_UNHURT; + for (Entity* entity : room.entityList.updateEL) + { + if (entity->type != ENTITY_HUSH || entity->variant != 0) + continue; + + weakness = 1 - entity->health / entity->maxHitPoints; + break; + } + float pulse = + std::sin((float)g_game->frameCount * (weakness * HUSH_PULSE_SPEED + HUSH_PULSE_MIN_SPEED)) + HUSH_PULSE_BASE; + light.scale = uniform(pulse); + light.Render({position}); +} + +// 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(LightPass& pass) +{ + Entity& fire = pass.entity; + if (fire.health <= 1) + return; + + float burnt = 1 - fire.health / fire.maxHitPoints; + EntityLight light = {FIRE_LIGHT, {}, uniform(FIRE_LIGHT_SCALE - burnt * FIRE_LIGHT_SHRINK), FIRE_LIGHT_FLICKER}; + 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; + light.scale = uniform(light.scale.x * COAL_LIGHT_SCALE); + break; + default: + break; + } + light.color._tint[3] = 1 - burnt * FIRE_LIGHT_FADE; + light_draw(pass, light); +} + +// A tear's light, colored by its first lighting flag: Glow (larger, the small light), Mysterious Liquid, burning, +// Horn, Light from Heaven, Jacob's Ladder (flickering further), then fire tears, glowing or G-FUEL nail tears in the +// tear's color, and a Ludovico tear in a pitch black room. Dead Eye's intensity reddens and brightens it. +// Without any the light sprite keeps its last color with no alpha, so only Dead Eye shows it. +static void tear_light_render(LightPass& pass) +{ + Entity_Tear& tear = static_cast(pass.entity); + ANM2& light = pass.room.lightSprite; + TearFlags flags = tear.tearFlags; + Seeds& seeds = g_game->seedEffects; + float scale = TEAR_LIGHT_SCALE; + float flicker = 0; + int frame = 0; + + light.color._tint[3] = 0; + if (flags.test(TEAR_GLOW)) + { + light.color = TEAR_LIGHT_GLOW; + scale *= GLOW_LIGHT_SCALE; + flicker = TEAR_LIGHT_FLICKER; + frame = 1; + } + else if (flags.test(TEAR_MYSTERIOUS_LIQUID_CREEP)) + light.color = TEAR_LIGHT_LIQUID; + else if (flags.test(TEAR_BURN)) + light.color = TEAR_LIGHT_BURN; + else if (flags.test(TEAR_HORN)) + light.color = TEAR_LIGHT_HORN; + else if (flags.test(TEAR_LIGHT_FROM_HEAVEN)) + light.color = TEAR_LIGHT_HEAVEN; + else if (flags.test(TEAR_JACOBS)) + { + light.color = TEAR_LIGHT_JACOBS; + flicker = JACOBS_LIGHT_FLICKER; + } + else if (tear.variant == TEAR_FIRE) + { + light.color = TEAR_LIGHT_FIRE; + flicker = TEAR_LIGHT_FLICKER; + } + else if (seeds.HasSeedEffect(SEED_GLOWING_TEARS) || + ((tear.variant == TEAR_NAIL || tear.variant == TEAR_NAIL_BLOOD) && seeds.HasSeedEffect(SEED_G_FUEL))) + light.color = tear.sprite.color; + else if (flags.test(TEAR_LUDOVICO) && pass.room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK) + light.color = TEAR_LIGHT_LUDOVICO; + + if (tear.deadEyeIntensity > 0) + { + light.color._tint[0] += tear.deadEyeIntensity; + light.color._tint[3] += tear.deadEyeIntensity; + } + if (light.color._tint[3] <= 0) + return; + + light.scale = uniform(scale); + if (frame != 0) + light.SetFrame((float)frame); + Vector direction = vector_scale(RandomVector(pass.flicker.Next()), flicker); + light.Render({screen_position(pass, vector_add(vector_add(tear.pos, tear.posOffset), direction))}); + if (frame != 0) + light.SetFrame(0.0f); +} + +// A wisp's light takes the color of whichever of its two layers is brighter, the second unless the first is more +// than a quarter brighter, at the first layer's size. +static ColorMod wisp_light_color(Entity& wisp) +{ + std::array colors; + std::array lumas; + for (int i = 0; i < 2; i++) + { + colors[i] = kcolor_apply(color_through(wisp.sprite.color, wisp.sprite.GetLayer(i)->color), WISP_LAYER_GREY); + lumas[i] = colors[i]._green * LUMA_GREEN + colors[i]._red * LUMA_RED + colors[i]._blue * LUMA_BLUE; + } + KColor color = lumas[0] > lumas[1] - WISP_LAYER_DARKER ? colors[0] : colors[1]; + return tint_make(color._red, color._green, color._blue, 1); +} + +// A familiar's light: Isaac's Heart glows pink and wisps in their own color, both with the small light. +static void familiar_light_render(LightPass& pass) +{ + Entity& familiar = pass.entity; + if (!familiar.isVisible) + return; + + if (familiar.variant == FAMILIAR_ISAACS_HEART) + light_draw(pass, {LIGHT_HEART, vector_make(0, -HEART_LIGHT_RISE), uniform(0.4f), 0, 1}); + else if (familiar.variant == Entity_Familiar::WISP) + { + Vector size = familiar.sprite.GetLayer(0)->size; + light_draw(pass, + {wisp_light_color(familiar), vector_make(0, -WISP_LIGHT_RISE), vector_scale(size, 0.4f), 0, 1}); + } +} + +// A bomb's light: a hot bomb glows red and flickers, any bomb with a sparks layer lights at its visible spark. +static void bomb_light_render(LightPass& pass) +{ + Entity& bomb = pass.entity; + ANM2& sprite = bomb.sprite; + + if (bomb.variant == BOMB_HOT) + { + light_draw(pass, {LIGHT_HOT, vector_make(0, -LIGHT_RISE), uniform(0.75f), 2}); + return; + } + + const LayerState* sparks = sprite.GetLayer(LAYER_SPARKS); + if (!sparks) + return; + + const AnimationFrame* frame = sprite.animState.GetLayerFrame(sparks->layerData ? sparks->layerData->id : -1); + if (!frame || !frame->isVisible) + return; + + Vector center = vector_sub(vector_make(frame->width * 0.5f, frame->height * 0.5f), frame->pivot); + Vector at = vector_add(frame->pos, vector_make(center.x * frame->scale.x, center.y * frame->scale.y)); + at = vector_rotated(at, sprite.rotation); + at = vector_make(at.x * sprite.scale.x, at.y * sprite.scale.y); + if (sprite.isFlipX) + at.x = -at.x; + if (sprite.isFlipY) + at.y = -at.y; + + ANM2& light = pass.room.lightSprite; + light.color = LIGHT_SPARK; + light.scale = uniform(0.3f); + light.Render({vector_add(screen_position(pass, vector_add(bomb.pos, bomb.posOffset)), at)}); +} + +// A laser's color of light: its sprite's Light null, or by variant through the laser's color. A laser drawn in its +// own static colors lights in them. +static ColorMod laser_light_color(Entity& laser) +{ + switch (laser.variant) + { + case LASER_SHOOP: + case LASER_ELECTRIC: + return color_through(LASER_LIGHT_BLUE, laser.sprite.color); + case LASER_PRIDE: + return color_through(LASER_LIGHT_PRIDE, laser.sprite.color); + case LASER_LIGHT_BEAM: + case LASER_LIGHT_RING: + return color_through(LASER_LIGHT_HOLY, laser.sprite.color); + case LASER_TRACTOR_BEAM: + return color_through(LASER_LIGHT_TRACTOR, laser.sprite.color); + default: + return laser.sprite.bitflags & ANIM_RENDER_STATIC ? laser.sprite.color + : color_through(LIGHT_PINK, laser.sprite.color); + } +} + +// A laser's light along its length: from its sprite's Light null, else by variant (thin lasers smaller), in twenty +// steps from the laser to its end (Pride's widening along it). A laser with samples lights at every few of them. +// The original skips a step whose distance from the last drawn one is negative, which never happens. +static void laser_light_render(LightPass& pass) +{ + Entity_Laser& laser = static_cast(pass.entity); + ANM2& light = pass.room.lightSprite; + if (!laser.isVisible) + return; + + float spriteScale = laser.sprite.scale.x; + if (const NullFrame* frame = laser.sprite.GetNullFrame(NULL_LIGHT)) + { + light.color = color_through(laser.sprite.color, frame->color); + light.scale = vector_scale(frame->scale, spriteScale); + } + else + { + light.color = laser_light_color(laser); + bool isThin = + laser.variant == LASER_THIN_RED || laser.variant == LASER_ELECTRIC || laser.variant == LASER_TRACTOR_BEAM; + light.scale = uniform(spriteScale * (isThin ? 0.35f : 0.75f)); + } + + if (laser.isSampleLaser) + reconstruction_missing("Room::render_entity_light 00806c20: a sample laser's light"); + Vector start = vector_add(laser.pos, laser.posOffset); + for (int step = 0; step < LASER_LIGHT_STEPS; step++) + { + float along = (float)step / (LASER_LIGHT_STEPS - 1); + if (laser.variant == LASER_PRIDE) + light.scale = uniform((along * 0.7f + 0.3f) * spriteScale * 0.75f); + Vector point = vector_add(start, vector_scale(vector_sub(laser.endPoint, start), along)); + light.Render({screen_position(pass, point)}); + } +} + +// A projectile's light: a fire projectile's flickering glow, any other a faint light in dark rooms. +static void projectile_light_render(LightPass& pass) +{ + Entity& projectile = pass.entity; + + if (projectile.variant == PROJECTILE_FIRE) + light_draw(pass, {color_through(LIGHT_FIRE, projectile.sprite.color), {}, uniform(1), 3}); + else if (pass.room.GetLightingAlpha() > DARK_ROOM_ALPHA) + light_draw(pass, {LIGHT_DIM_BULLET, {}, uniform(0.1f), 0, 0, true}); +} + +// Whether a creep or smoke cell already has a light this frame. The first one of a grid cell takes it. +static bool is_grid_light_taken(LightPass& pass) +{ + int index = pass.room.GetGridIndex(pass.entity.pos); + return !pass.room.litGridIndices.insert(index).second; +} + +// The alpha of a light fading in over the entity's first frames. +static float fade_in_alpha(Entity& entity, float alpha) +{ + int frames = entity.FrameCount(); + return frames < LIGHT_FADE_IN_FRAMES ? (float)frames / LIGHT_FADE_IN_FRAMES * alpha : alpha; +} + +// A red or green creep's grey light in dark rooms, one per grid cell, sized by the creep and fading in. +static void creep_light_render(LightPass& pass) +{ + Entity& creep = pass.entity; + if (pass.room.GetLightingAlpha() <= DARK_ROOM_ALPHA || is_grid_light_taken(pass)) + return; + + ColorMod color = LIGHT_CREEP; + color._tint[3] = fade_in_alpha(creep, creep.sprite.color._tint[3]); + float size = creep.size * creep.sprite.scale.x; + light_draw(pass, {color, {}, uniform(std::max(size * 0.02f, 0.5f))}); +} + +// A light fading out as its animation ends: the part of it left, or all of it while it loops. +static float animation_left(const ANM2& sprite) +{ + const AnimationState& state = sprite.animState; + if (state.IsLoopingAnimation()) + return 1; + return 1 - state.animFrame / (float)state.GetAnimationLength(); +} + +// An explosion's light fading over its last six frames, lifted grey, larger for a big one. +static EntityLight explosion_light(Entity& effect, int framesLeft, const ColorMod& color) +{ + float fade = (float)framesLeft / EXPLOSION_FADE_FRAMES; + ColorMod lift = {{1, 1, 1, 1 - fade * fade}, {0, 0, 0, 0}, {EXPLOSION_GREY, EXPLOSION_GREY, EXPLOSION_GREY}}; + Vector scale = effect.sprite.scale; + return {color_through(lift, color), {}, vector_scale(scale, EXPLOSION_BIG_SCALE), 0, scale.x > EXPLOSION_BIG_SCALE}; +} + +// A target's red light, added, only for its owner online. +static void target_light_render(LightPass& pass) +{ + Entity& target = pass.entity; + Entity* spawner = target.spawnerEntity.get(); + bool isVersusPlayer = + g_game->deathmatchManager.state >= DEATHMATCH_INTRO && spawner && spawner->type == ENTITY_PLAYER; + bool isEnemy = spawner && (uint32_t)(spawner->type - ENTITY_FIRST_ENEMY) < ENTITY_EFFECT - ENTITY_FIRST_ENEMY; + if ((isVersusPlayer || isEnemy) && !is_owned_locally(*spawner)) + return; + + const AnimationFrame* frame = target.sprite.animState.GetLayerFrame(0); + if (!frame || !frame->isVisible) + return; + + LayerState& layer = *pass.room.lightSprite.GetLayer(0); + layer.blendMode = TARGET_LIGHT_BLEND; + light_draw(pass, {LIGHT_TARGET, {}, vector_scale(target.sprite.scale, 0.5f), 0, 1}); + layer.blendMode = LIGHT_BLEND_NORMAL; +} + +// An effect's light by variant: explosions, flames, creep, wisps, blood, brimstone, lights and the other glowing +// effects, each in its own color, size and flicker. +static void effect_light_render(LightPass& pass) +{ + Entity_Effect& effect = static_cast(pass.entity); + const ANM2& sprite = effect.sprite; + ANM2& light = pass.room.lightSprite; + + switch (effect.variant) + { + case EFFECT_BOMB_EXPLOSION: + { + int frames = g_game->frameCount - effect.spawnFrame; + if (frames <= EXPLOSION_FADE_FRAMES) + light_draw(pass, explosion_light(effect, frames, sprite.color)); + return; + } + case EFFECT_REVERSE_EXPLOSION: + { + int framesLeft = sprite.animState.GetAnimationLength() - sprite.GetFrame(); + if (effect.subtype != 0 || !effect.isVisible || framesLeft > EXPLOSION_FADE_FRAMES) + return; + light_draw(pass, explosion_light(effect, framesLeft, sprite.color)); + return; + } + case EFFECT_BLUE_FLAME: + { + ColorMod color = LIGHT_BLUE_FLAME; + color._tint[3] = sprite.color._tint[3]; + light_draw(pass, {color, vector_make(0, -LIGHT_RISE), uniform(1), 2}); + return; + } + case EFFECT_HOT_BOMB_FIRE: + case EFFECT_RED_CANDLE_FLAME: + light_draw(pass, {LIGHT_CANDLE, vector_make(0, -LIGHT_RISE), uniform(1), 2}); + return; + case EFFECT_CREEP_RED: + case EFFECT_CREEP_GREEN: + creep_light_render(pass); + return; + case EFFECT_TARGET: + case EFFECT_OCCULT_TARGET: + target_light_render(pass); + return; + case EFFECT_HEAVEN_LIGHT_DOOR: + { + const AnimationFrame* frame = effect.parent ? nullptr : sprite.animState.GetLayerFrame(0); + if (!frame) + return; + const float* tint = frame->color._tint; + light_draw(pass, {tint_make(tint[0], tint[1], tint[2], tint[3]), {}, uniform(1.5f)}); + return; + } + case EFFECT_WISP: + { + ColorMod color = effect.splatColor; + color._tint[3] = sprite.scale.x; + light_draw(pass, {color, {}, uniform(0.5f * sprite.scale.x), 0, 0, true}); + return; + } + case EFFECT_FIREWORKS: + light_draw(pass, {sprite.color, {}, uniform(0.5f * sprite.scale.x), 0, 0, true}); + return; + case EFFECT_BLOOD_DROP: + { + ColorMod color = LIGHT_PINK; + color._tint[3] = effect.isDead ? 0.25f : 1; + light_draw(pass, {color_through(color, sprite.color), {}, uniform(0.3f)}); + return; + } + case EFFECT_BRIMSTONE_SWIRL: + case EFFECT_ENEMY_BRIMSTONE_SWIRL: + { + if (!effect.isVisible) + return; + const AnimationFrame* frame = sprite.animState.GetLayerFrame(0); + float frameScale = frame ? frame->scale.x : 1; + light_draw(pass, + {color_through(LIGHT_PINK, sprite.color), {}, uniform(sprite.scale.x * frameScale), 0, 1, true}); + return; + } + case EFFECT_PENTAGRAM_BLACKPOWDER: + { + const AnimationFrame* frame = sprite.animState.GetLayerFrame(0); + if (!frame) + return; + ColorMod color = LIGHT_PENTAGRAM; + color._tint[3] = frame->color._offset[0] + 1; + light_draw(pass, {color_through(color, sprite.color), {}, vector_scale(sprite.scale, 4)}); + return; + } + case EFFECT_HAEMO_TRAIL: + { + if (effect.subtype != 1) + return; + float animFrame = sprite.animState.animData ? sprite.animState.animFrame : -1; + float left = 1 - animFrame / (float)sprite.animState.GetAnimationLength(); + KColor red = kcolor_apply(sprite.color, HAEMO_TRAIL_RED); + light_draw(pass, {tint_make(red._red, red._green, red._blue, red._alpha * left), + {}, + vector_scale(sprite.scale, 0.5f), + 0, + 0, + true}); + return; + } + case EFFECT_HALLOWED_GROUND: + { + const AnimationFrame* frame = sprite.animState.GetLayerFrame(0); + if (!frame) + return; + ColorMod color = LIGHT_HALLOWED; + color._tint[3] = frame->color._tint[3] * 6.4f; + light_draw(pass, {color, {}, sprite.scale, 2, 0, true}); + return; + } + case EFFECT_BRIMSTONE_BALL: + light_draw(pass, {color_through(LIGHT_PINK, sprite.color), {}, uniform(sprite.scale.x), 0, 1, true}); + return; + case EFFECT_BROKEN_SHOVEL_SHADOW: + { + float darkness = pass.room.GetLightingAlpha(); + if (darkness <= DARK_ROOM_ALPHA) + return; + light_draw(pass, {tint_make(1, 1, 1, (darkness - DARK_ROOM_ALPHA) * 2), {}, uniform(4), 0, 0, true}); + return; + } + case EFFECT_LIGHT: + { + if (!effect.isVisible) + return; + Vector position = screen_position(pass, vector_add(effect.pos, effect.posOffset)); + Vector direction = RandomVector(pass.flicker.Next()); + float distance = pass.flicker.RandomFloat() * effect.scale; + sprite.Render({vector_add(position, vector_scale(direction, distance))}); + return; + } + case EFFECT_TECH_DOT: + { + if (!effect.isVisible) + return; + float size = sprite.scale.x * 0.2f * animation_left(sprite); + light_draw(pass, {color_through(LIGHT_PINK, sprite.color), {}, uniform(size), 0, 1, true}); + return; + } + case EFFECT_SMOKE_CLOUD: + { + if (is_grid_light_taken(pass)) + return; + ColorMod color = sprite.color; + color._tint[3] = fade_in_alpha(effect, sprite.color._tint[3]); + light_draw(pass, {color, {}, vector_scale(sprite.scale, 0.8f), 0, 0, true}); + return; + } + case EFFECT_KINETI_BEAM: + { + Entity* target = effect.target.get(); + Entity& at = target ? *target : effect; + light.color = sprite.color; + light.scale = vector_scale(sprite.scale, 0.6f); + light.Render({screen_position(pass, vector_add(at.pos, at.posOffset))}); + return; + } + default: + return; + } +} + +// Visage's lights: its heart red in two of its states (larger in the second), its mask once lit, its chain small. +static void visage_light_render(LightPass& pass) +{ + Entity_NPC& visage = static_cast(pass.entity); + Vector rise = vector_make(0, -VISAGE_LIGHT_RISE); + bool isHeartLit = visage.variant == VISAGE_HEART && visage.state == VISAGE_HEART_STATE_LIT; + bool isMaskLit = visage.variant == VISAGE_MASK && visage.state >= VISAGE_MASK_STATE_LIT; + + if (isHeartLit || isMaskLit) + light_draw(pass, {LIGHT_TARGET, rise}); + else if (visage.variant == VISAGE_HEART && visage.state == VISAGE_HEART_STATE_FLARE) + light_draw(pass, {LIGHT_TARGET, rise, uniform(1.5f)}); + else if (visage.variant == VISAGE_CHAIN) + light_draw(pass, {LIGHT_TARGET, rise, uniform(0.6f), 0, 1}); +} + +// Heretic's purple light while its flame layer shows. +// The original also works out where on the flame the light would sit, then draws it at the Heretic. +static void heretic_light_render(LightPass& pass) +{ + const ANM2& sprite = pass.entity.sprite; + const AnimationData* data = sprite.animState.animData; + if (!data) + return; + + for (const AnimationLayer& track : data->animLayers) + { + const LayerState* layer = + track.layerId < (int)sprite.layerStates.size() ? &sprite.layerStates[track.layerId] : nullptr; + if (!layer || !layer->layerData || layer->layerData->name != LAYER_FLAME) + continue; + + const AnimationFrame* frame = sprite.animState.GetLayerFrame(track.layerId); + if (frame && frame->isVisible) + light_draw(pass, {LIGHT_HERETIC, {}, uniform(0.6f), 0.75f}); + return; + } +} + +// Whether an enemy burns or is a flaming one, which glow (the default of render_entity_light). +static bool is_enemy_burning(Entity& entity) +{ + bool isFlaming = + entity.variant == FLAMING_VARIANT && std::ranges::find(FLAMING_TYPES, entity.type) != std::end(FLAMING_TYPES); + return (entity.IsEnemy() && entity.flags & FLAG_BURN) || entity.type == ENTITY_FLAMING_HOPPER || isFlaming; +} + +// The light of an entity that is neither a player nor one of the pickups, tears and effects: enemies by type. +static void npc_light_render(LightPass& pass) +{ + Room& room = pass.room; + Entity& entity = pass.entity; + int variant = entity.variant; + + switch (entity.type) + { + case ENTITY_BOOMFLY: + if (variant == BOOMFLY_DRAGON_FLY && room.backdropType == BACKDROP_ASHPIT) + light_draw(pass, {LIGHT_EMBER, vector_make(0, -FLY_LIGHT_RISE), uniform(0.8f), 2}); + return; + case ENTITY_SPIDER: + if (room.bossId == BOSS_ID_WIDOW || room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK) + light_draw(pass, {LIGHT_BLOOD, {}, uniform(0.3f)}); + return; + case ENTITY_GATE: + light_draw(pass, {LIGHT_GATE, vector_make(0, -LIGHT_RISE), uniform(2), 1}); + return; + case ENTITY_THE_LAMB: + if (variant == LAMB_VARIANT_LIGHT) + light_draw(pass, {LIGHT_LAMB, vector_make(0, -LIGHT_RISE), uniform(1.5f), 1}); + return; + case ENTITY_WILLO: + if (entity.isVisible) + light_draw(pass, {LIGHT_GOLD, vector_make(0, -FLY_LIGHT_RISE), uniform(0.8f)}); + return; + case ENTITY_PREY: + if (variant == PREY_VARIANT_LIGHT) + light_draw(pass, {LIGHT_GOLD, vector_make(0, -FLY_LIGHT_RISE), uniform(1), 2}); + return; + case ENTITY_ROCK_SPIDER: + if (variant == ROCK_SPIDER_VARIANT_LIGHT) + light_draw(pass, {LIGHT_PALE, {}, uniform(0.6f), 3, 1}); + return; + case ENTITY_VISAGE: + visage_light_render(pass); + return; + case ENTITY_HERETIC: + heretic_light_render(pass); + return; + case ENTITY_MINECART: + if (room.backdropType == BACKDROP_ASHPIT) + light_draw(pass, {LIGHT_MINECART, vector_make(0, -MINECART_LIGHT_RISE), uniform(0.6f), 2, 1}); + return; + default: + if (is_enemy_burning(entity)) + light_draw(pass, {LIGHT_PALE, vector_make(0, -LIGHT_RISE), uniform(1), 3}); + return; + } +} + +// 00806c20 Draws an entity's light into the light overlay, flickering by the frame and the entity's seed: the lights +// its sprite marks, then by kind the players', tears', familiars', bombs', lasers', projectiles', fireplaces', effects' +// and glowing enemies' lights. An enemy a player controls online shows a light over it. A minecart's rider lights from +// the cart's null. +void entity_light_render(Room& room, Entity& entity, Vector offset) +{ + uint32_t seed = (uint32_t)g_game->frameCount + entity.initSeed; + LightPass pass = {room, + entity, + vector_add(offset, minecart_offset(entity)), + {seed ? seed : FLICKER_SEED_ZERO, FLICKER_SHIFTS[0], FLICKER_SHIFTS[1], FLICKER_SHIFTS[2]}}; + + DAT_00c7977e = 1; + if (entity.isVisible) + sprite_lights_render(pass); + switch (entity.type) + { + case ENTITY_PLAYER: + if (entity.isExists) + player_light_render(room, static_cast(entity), pass.offset); + break; + case ENTITY_TEAR: + tear_light_render(pass); + break; + case ENTITY_FAMILIAR: + familiar_light_render(pass); + break; + case ENTITY_BOMB: + bomb_light_render(pass); + break; + case ENTITY_LASER: + laser_light_render(pass); + break; + case ENTITY_PROJECTILE: + projectile_light_render(pass); + break; + case ENTITY_FIREPLACE: + fireplace_light_render(pass); + break; + case ENTITY_EFFECT: + effect_light_render(pass); + break; + default: + npc_light_render(pass); + break; + } + + Entity_NPC* npc = entity.IsEnemy() ? dynamic_cast(&entity) : nullptr; + if (npc && npc->controllerID != -1 && is_owned_locally(entity)) + light_draw(pass, {COLOR_DEFAULT, vector_make(0, -LIGHT_RISE), uniform(1), 0, 1}); + DAT_00c7977e = 0; +} diff --git a/src/room_render.cpp b/src/room_render.cpp index 78c9cb9..612540e 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -57,9 +57,6 @@ constexpr ColorMod FIRE_MIND_GLOW_COLOR = {{1, 0.6f, 0.4f, 0.7f}, {0, 0, 0, 0}, constexpr ColorMod FLAME_GLOW_COLOR = {{1, 0.8f, 0.7f, 0.7f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod BULLET_GLOW_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod WILLO_GLOW_COLOR = {{0.6f, 0.4f, 0.2f, 0.7f}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr ColorMod LIGHT_RED = {{1, 0, 0.03f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr ColorMod LIGHT_PURPLE = {{0.9f, 0.3f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr ColorMod LIGHT_WARM = {{1, 0.9f, 0.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod LIGHT_PLATE_REWARD = {{1, 0.4f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod LIGHT_PLATE_CLEAR = {{1, 1, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod LIGHT_PLATE = {{1, 1, 1, 0.2f}, {0, 0, 0, 0}, {0, 0, 0}}; @@ -69,15 +66,8 @@ constexpr float GLOW_STACK_MAX = 4; constexpr float GLOW_ALPHA_STEP = 0.07f; constexpr float GLOW_ALPHA = 0.2f; constexpr float GLOW_SCALE_STEP = 0.5f; -constexpr float AURA_STACK_MAX = 5; -constexpr float AURA_ALPHA_STEP = 0.12f; -constexpr float AURA_ALPHA = 0.3f; -constexpr float AURA_SCALE = 2; constexpr float BABY_GLOW_SCALE = 2; constexpr float FLAME_FLICKER = 2; -constexpr float MAUSOLEUM_LIGHT = 0.65f; -constexpr float HOLOGRAM_LIGHT = 0.3f; -constexpr float DARKNESS_LIGHT_GROWTH = 0.5f; constexpr float BULLET_PULSE_SPEED = 0.8f; constexpr float BULLET_PULSE_RANGE = 0.20000002f; constexpr float BULLET_PULSE_MIN = 0.1f; @@ -85,37 +75,8 @@ constexpr float WILLO_HEIGHT = 16; constexpr float WILLO_SCALE = 0.5f; constexpr float PLATE_SCALE = 0.5f; 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; @@ -126,19 +87,7 @@ constexpr float NIGHT_LIGHT_SHADOW = 0.5f; constexpr float GLAUCOMA_SHADOW = 0.1f; // The items, entities, grid states and rooms the render passes tell apart. -constexpr int COLLECTIBLE_SPIRIT_OF_THE_NIGHT = 3; -constexpr int COLLECTIBLE_GHOST_BOMBS = 192; -constexpr int COLLECTIBLE_SPIRIT_SWORD = 572; -constexpr int COLLECTIBLE_FIRE_MIND_COSTUME = 256; -constexpr int COLLECTIBLE_NIGHT_LIGHT = 425; -constexpr int COLLECTIBLE_GLAUCOMA = 460; -constexpr int COLLECTIBLE_DATAMINER = 481; -constexpr int NULL_ITEM_BRIMSTONE_FLAME = 56; -constexpr int NULL_EFFECT_SPIRIT_AURA = 74; -constexpr int PLAYER_DARK_JUDAS = 12; -constexpr int STAGE_ID_BLUE_WOMB = 13; constexpr int BABY_SKIN_GLOW = 66; -constexpr int ENTITY_WILLO = 808; constexpr int GRID_STATE_POOP_DESTROYED = 1000; constexpr int PLATE_VARIANT_REWARD = 9; constexpr int PLATE_VARIANT_ROOM_CLEAR = 3; @@ -173,42 +122,12 @@ constexpr uint32_t DEBUG_FLAG_GRID_INDICES = 1 << 10; // The backdrops with their own render passes (Lua's BackdropType). constexpr int BACKDROP_UTERO = 11; constexpr int BACKDROP_MEGA_SATAN = 18; -constexpr int BACKDROP_ASHPIT = 46; constexpr int BACKDROP_GREED_SHOP = 28; constexpr int BACKDROP_MINES = 32; constexpr int BACKDROP_DUNGEON_BEAST = 57; constexpr int BACKDROP_MINES_SHAFT = 58; constexpr int BACKDROP_ASHPIT_SHAFT = 59; -// The tear flags and seeds that light a tear (Lua's TearFlags bits). -constexpr int TEAR_BURN_BIT = 22; -constexpr int TEAR_GLOW_BIT = 31; -constexpr int TEAR_MYSTERIOUS_LIQUID_BIT = 33; -constexpr int TEAR_LIGHT_FROM_HEAVEN_BIT = 39; -constexpr int TEAR_JACOBS_BIT = 55; -constexpr int TEAR_HORN_BIT = 56; -constexpr int TEAR_LUDOVICO_BIT = 127; -constexpr int PROJECTILE_FIRE = 2; -constexpr float PROJECTILE_LIGHT_DARKNESS = 0.5f; - -// The entities render_entity_light has a light of their own for, past the player: a familiar or bomb variant, an -// enemy type (or a variant of it), and the effects that glow. -constexpr int FAMILIAR_LIGHT_VARIANTS[] = {62, 206}; -constexpr int BOMB_LIGHT_VARIANT = 8; -constexpr int LIGHT_TYPE_EMBER_FLY = 25; -constexpr int LIGHT_TYPE_SPIDER = 85; -constexpr int LIGHT_TYPE_GLOWING = 263; -constexpr int LIGHT_TYPE_VARIANT_10 = 273; -constexpr int LIGHT_TYPE_VARIANT_1 = 817; -constexpr int LIGHT_TYPE_VARIANT_2 = 818; -constexpr int LIGHT_TYPES[] = {903, 905, 965}; -constexpr int BOSS_LIGHT_SPIDER = 51; -constexpr int EFFECT_LIGHT_VARIANTS[] = {1, 10, 22, 23, 30, 39, 51, 52, 65, 70, 71, 93, 104, - 110, 111, 112, 113, 115, 121, 126, 141, 153, 175, 177}; -constexpr int BURNING_ENEMY_TYPE = 54; -constexpr std::array FLAMING_ENEMY_TYPES = {10, 208, 226}; -constexpr int FLAMING_VARIANT = 2; - // The Beast's arena draws in passes around the room's: under everything, over the floor, over the entities, last. enum BeastArenaPass { @@ -308,13 +227,8 @@ static Vector vector_add(Vector a, Vector b) return vector_make(a.x + b.x, a.y + b.y); } -static ColorMod tint_make(float red, float green, float blue, float alpha) -{ - return {{red, green, blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; -} - // Sets the blend mode of a sprite's first layer. -static void layer_blend_set(ANM2& sprite, KAGE::Graphics::BlendType type) +void layer_blend_set(ANM2& sprite, KAGE::Graphics::BlendType type) { KAGE::Graphics::BlendMode mode; @@ -387,7 +301,7 @@ static bool is_flat_grid(const GridEntity& grid) } // 006b7cc0 How far a minecart's rider sits from it: the cart sprite's first null, or nothing without a cart. -static Vector minecart_offset(Entity& entity) +Vector minecart_offset(Entity& entity) { Entity* cart = entity.minecart.get(); if (!cart || !cart->sprite.animState.animData) return {}; @@ -397,7 +311,7 @@ static Vector minecart_offset(Entity& entity) } // 0075d900 Whether an item's costume draws on a layer of the player's sprite, or on any layer for -1. -static bool is_item_costume_visible(Entity_Player& player, ItemConfig_Item* item, int layer) +bool is_item_costume_visible(Entity_Player& player, ItemConfig_Item* item, int layer) { int first = std::max(layer, 0); int last = layer < 0 ? COSTUME_LAYER_COUNT : layer + 1; @@ -854,193 +768,6 @@ void Room::Render() if (game.debugFlags & DEBUG_FLAG_ROOM_INFO) reconstruction_missing("Room::Render 0080f200: the room info text"); } -// Whether a tear glows: its glowing, creep, burning, horn, heaven light or Jacob's flags, a fire tear, Glowing Tears, -// a nail under G-Fuel, or a Ludovico tear in a pitch black room. -static bool is_tear_lit(Room& room, Entity& entity) -{ - Entity_Tear& tear = static_cast(entity); - Seeds& seeds = g_game->seedEffects; - bool isPitchBlack = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK; - - for (int bit : {TEAR_GLOW_BIT, TEAR_MYSTERIOUS_LIQUID_BIT, TEAR_BURN_BIT, TEAR_HORN_BIT, TEAR_LIGHT_FROM_HEAVEN_BIT, - TEAR_JACOBS_BIT}) - if (tear.tearFlags.test(bit)) return true; - if (tear.variant == TEAR_FIRE || seeds.HasSeedEffect(SEED_GLOWING_TEARS)) return true; - if ((tear.variant == TEAR_NAIL || tear.variant == TEAR_NAIL_BLOOD) && seeds.HasSeedEffect(SEED_G_FUEL)) return true; - return tear.tearFlags.test(TEAR_LUDOVICO_BIT) && isPitchBlack; -} - -// Whether a burning or flaming enemy glows (render_entity_light's default case). -static bool is_enemy_burning(Entity& entity) -{ - bool isFlaming = entity.variant == FLAMING_VARIANT && - std::ranges::find(FLAMING_ENEMY_TYPES, entity.type) != FLAMING_ENEMY_TYPES.end(); - return (entity.IsEnemy() && entity.flags & FLAG_BURN) || entity.type == BURNING_ENEMY_TYPE || isFlaming; -} - -// Whether render_entity_light draws a light for an entity besides a player: the kinds it has a case for (each under -// its own condition), and otherwise burning or flaming enemies. -static bool is_entity_lit(Room& room, Entity& entity) -{ - int variant = entity.variant; - bool isPitchBlack = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK; - - switch (entity.type) - { - case ENTITY_TEAR: return is_tear_lit(room, entity); - case ENTITY_FAMILIAR: - return entity.isVisible && std::ranges::find(FAMILIAR_LIGHT_VARIANTS, variant) != std::end(FAMILIAR_LIGHT_VARIANTS); - case ENTITY_BOMB: return variant == BOMB_LIGHT_VARIANT || entity.sprite.GetLayer("sparks"); - case ENTITY_LASER: return entity.isVisible; - case ENTITY_PROJECTILE: return variant == PROJECTILE_FIRE || room.GetLightingAlpha() > PROJECTILE_LIGHT_DARKNESS; - 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 LIGHT_TYPE_SPIDER: return room.bossId == BOSS_LIGHT_SPIDER || isPitchBlack; - case LIGHT_TYPE_GLOWING: return true; - case LIGHT_TYPE_VARIANT_10: return variant == 10; - case ENTITY_WILLO: return entity.isVisible; - case LIGHT_TYPE_VARIANT_1: return variant == 1; - case LIGHT_TYPE_VARIANT_2: return variant == 2; - } - if (entity.type > LIGHT_TYPE_VARIANT_2 && std::ranges::find(LIGHT_TYPES, entity.type) != std::end(LIGHT_TYPES)) - return true; - return is_enemy_burning(entity); -} - -// A player's light: its Spirit of the Night aura, then the light gradient (red for Dark Judas, warm under flame -// costumes, purple under the ghostly ones, white otherwise) growing with the darkness, dimmed in the Mausoleum's heart -// and for a hologram, its Night Light cone, and in Hush's room a second light pulsing faster as Hush weakens. -static void player_light_render(Room& room, Entity_Player& player, Vector offset) -{ - ANM2& light = room.lightSprite; - ItemConfig& items = g_manager->itemConfig; - Vector position = vector_add(render_position_get(vector_add(player.pos, player.posOffset), RENDER_SNAPPED), offset); - TemporaryEffect* aura = player.temporaryEffects.isDisabled - ? nullptr - : player.temporaryEffects.GetNullEffect(NULL_EFFECT_SPIRIT_AURA); - float stacks = std::min(aura ? (float)aura->count : 0.0f, AURA_STACK_MAX); - - if (player.temporaryEffects.HasNullEffect(NULL_EFFECT_SPIRIT_AURA)) - { - layer_blend_set(light, KAGE::Graphics::BLEND_ADDITIVE); - light.color = tint_make(0.4f, 0.6f, 1, stacks * AURA_ALPHA_STEP + AURA_ALPHA); - light.scale = vector_make(stacks + AURA_SCALE, stacks + AURA_SCALE); - sprite_draw(light, position); - layer_blend_set(light, KAGE::Graphics::BLEND_NORMAL); - } - - float strength = g_game->IsMausoleumHeartStage() ? MAUSOLEUM_LIGHT : 1; - if (player.IsHologram()) strength *= HOLOGRAM_LIGHT; - auto isCostume = [&](int collectible) { return is_item_costume_visible(player, items.GetCollectible(collectible), -1); }; - bool isFlame = is_item_costume_visible(player, items.GetCollectible(COLLECTIBLE_FIRE_MIND_COSTUME), 0) || - isCostume(COLLECTIBLE_FIRE_MIND) || player.IsNullItemCostumeVisible(NULL_ITEM_BRIMSTONE_FLAME, 0); - bool isGhostly = isCostume(COLLECTIBLE_SPIRIT_OF_THE_NIGHT) || isCostume(COLLECTIBLE_GHOST_BOMBS) || - isCostume(COLLECTIBLE_SPIRIT_SWORD); - if (isFlame || isGhostly) light.color = player.playerType == PLAYER_DARK_JUDAS ? LIGHT_RED : isFlame ? LIGHT_WARM : LIGHT_PURPLE; - else light.color = COLOR_DEFAULT; - light.color._tint[3] *= strength; - - float darkness = g_game->GetCurses() & CURSE_OF_DARKNESS ? 1 : g_game->darknessStrength * g_game->darknessModifier; - float scale = darkness * DARKNESS_LIGHT_GROWTH + 1; - light.scale = vector_make(scale, scale); - light.SetFrame(1.0f); - sprite_draw(light, position); - light.SetFrame(0.0f); - - if (player.HasCollectible(COLLECTIBLE_NIGHT_LIGHT)) - { - room.spotLightSprite.rotation = player.bodyAngle - NIGHT_LIGHT_ANGLE; - room.spotLightSprite.color = COLOR_DEFAULT; - layer_blend_set(room.spotLightSprite, KAGE::Graphics::BLEND_NORMAL); - sprite_draw(room.spotLightSprite, position); - } - if (g_game->GetStageID() != STAGE_ID_BLUE_WOMB || room.descriptor->data->type != ROOM_BOSS) return; - - float weakness = 0.1f; - for (Entity* entity : room.entityList.updateEL) - { - if (entity->type != ENTITY_HUSH || entity->variant != 0) continue; - - weakness = 1 - entity->health / entity->maxHitPoints; - break; - } - float pulse = std::sin((float)g_game->frameCount * (weakness * 0.18f + 0.02f)) + 3; - light.scale = vector_make(pulse, pulse); - 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' 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)) - reconstruction_missing("Room::render_entity_light 00806c20: the sprites' light layers"); - if (entity.type == ENTITY_PLAYER) - { - 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"); - - Entity_NPC* npc = entity.IsEnemy() ? dynamic_cast(&entity) : nullptr; - if (npc && npc->controllerID != -1) reconstruction_missing("Room::render_entity_light 00806c20: a controlled enemy"); - DAT_00c7977e = 0; -} - // The light of a door: the secret exits' and the Ascent's lit doors, doors into lit rooms, the mirror world's // mineshaft doors and angel room doors. Whether it lights before any light is drawn. static bool is_door_lit(GridEntity_Door& door) diff --git a/src/room_render.h b/src/room_render.h index bf29086..a0e12f0 100644 --- a/src/room_render.h +++ b/src/room_render.h @@ -6,6 +6,11 @@ constexpr int SHOCKWAVE_COUNT = 2; +// Night Light's cone angle and the null items whose costumes the player's light reads. +constexpr float NIGHT_LIGHT_ANGLE = 90; +constexpr int NULL_EFFECT_SPIRIT_AURA = 74; +constexpr int NULL_ITEM_BRIMSTONE_FLAME = 56; + // The surfaces and images rooms draw through, file globals of the original made once for every room. // shading is the room shape's shading image Room::LoadBackdropGraphics loads (DAT_00c797bc), drawn into shadingSurface. struct RoomSurfaces @@ -52,3 +57,7 @@ extern std::array roomShockwaves; void room_surfaces_init(); Vector RandomVector(uint32_t seed); KColor kcolor_apply(const ColorMod& color, const KColor& input); +Vector minecart_offset(Entity& entity); +bool is_item_costume_visible(Entity_Player& player, ItemConfig_Item* item, int layer); +void layer_blend_set(ANM2& sprite, KAGE::Graphics::BlendType type); +void entity_light_render(Room& room, Entity& entity, Vector offset); diff --git a/src/room_special.cpp b/src/room_special.cpp new file mode 100644 index 0000000..b094845 --- /dev/null +++ b/src/room_special.cpp @@ -0,0 +1,1078 @@ +#include "room_special.h" +#include "entity_effect_combat.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "log.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include + +constexpr int COLLECTIBLE_POUND_OF_FLESH = 672; +constexpr int TRINKET_STORE_CREDIT = 13; +constexpr int TRINKET_JUDAS_TONGUE = 56; +constexpr int TRINKET_KEEPERS_BARGAIN = 171; +constexpr int TRINKET_ADOPTION_PAPERS = 184; +constexpr int CARD_HOLY = 51; +constexpr int CARD_SOUL_LILITH = 92; +constexpr int ACHIEVEMENT_HOLY_CARD = 293; +constexpr int ACHIEVEMENT_HEART_BONE_SHOP = 391; +constexpr int ACHIEVEMENT_HEART_ROTTEN_SHOP = 411; +constexpr int ACHIEVEMENT_SOUL_LILITH = 629; + +// Shop slot kinds the shop's own counts go by. +constexpr int SHOP_LEVEL_EXTRA_ITEM = 3; +constexpr int SHOP_DISCOUNT_ODDS = 3; +constexpr int SHOP_DISCOUNT_SLOTS = 6; +constexpr int SHOP_DISCOUNT_SLOTS_WIDE = 8; +constexpr int ALT_SHOP_SUBTYPE_MIN = 100; +constexpr int ALT_SHOP_SUBTYPE_COUNT = 20; +constexpr int SHOP_ITEM_NEVER_DISCOUNTED = -2; +constexpr uint32_t PRICE_SEED_MASK = 0xfffff800; +constexpr uint8_t RESTOCKS_STOPPED = 0xff; +constexpr int RESTOCK_FRAMES = 30; +constexpr int RESTOCK_PRICE_STEP = 7; +constexpr int PRICE_CAP = 99; +constexpr int DISCOUNTED_PRICE_FLOOR = 6; +constexpr int PAPERS_DISCOUNT = 6; + +// The prices the shop gives, in coins, and the prices in health (Lua's PickupPrice). +constexpr int PRICE_CONSUMABLE = 5; +constexpr int PRICE_GRAB_BAG = 7; +constexpr int PRICE_HALF_HEART = 3; +constexpr int PRICE_GOLDEN = 10; +constexpr int PRICE_ITEM = 15; +constexpr int PRICE_ITEM_DEVIL = 30; +constexpr int PRICE_SECRET_SHOP_TRINKET = 15; +constexpr int PRICE_SECRET_SHOP_CARD = 6; +constexpr int PRICE_SECRET_SHOP_HEART_RARE = 15; +constexpr int PRICE_SECRET_SHOP_HEART_BONE = 8; +constexpr int PRICE_SECRET_SHOP_HEART_SOUL = 6; +constexpr int SECRET_SHOP_ITEM_MIN = 15; +constexpr int SECRET_SHOP_ITEM_MAX = 30; +constexpr int SECRET_SHOP_RARE_ITEM_MAX = 50; +constexpr int SECRET_SHOP_ULTRA_MIN = 20; +constexpr int SECRET_SHOP_ULTRA_SPAN = 80; +constexpr int SOUL_HEARTS_FOR_DISCOUNT = 3; +constexpr int SOUL_HEARTS_FOR_BIG_DISCOUNT = 5; +constexpr int CONTAINERS_FOR_TWO_HEARTS = 4; + +// The pickup kinds of the shop wares. +constexpr int HEART_HALF_KIND = 2; +constexpr int HEART_SOUL_KIND = 3; +constexpr int HEART_ETERNAL_KIND = 4; +constexpr int BOMB_GOLDEN_KIND = 4; +constexpr int KEY_GOLDEN_KIND = 2; + +// How a Keeper buys: in coins for everything, or a deal paid in the usual way. +enum ShopPricing +{ + PRICING_USUAL, + PRICING_KEEPER +}; + +// Shop slot kinds, by what Adoption Papers looks for: the slot it swaps for a Soul of Lilith (the first card, then +// pill, bomb, key and heart slot). +enum PapersSlot +{ + PAPERS_HEART, + PAPERS_BOMB, + PAPERS_CONSUMABLE, + PAPERS_KEY, + PAPERS_SOUL_CARD, + PAPERS_OTHER +}; + +constexpr std::array PAPERS_SLOTS = { + PAPERS_HEART, PAPERS_BOMB, PAPERS_CONSUMABLE, PAPERS_KEY, PAPERS_OTHER, PAPERS_OTHER, + PAPERS_CONSUMABLE, PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, + PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, + PAPERS_OTHER, PAPERS_OTHER, PAPERS_OTHER, PAPERS_SOUL_CARD}; + +// The Greed shop's last four slots, by a seed's last digit (Room::greed_shop_slot_type, 00813d00). +constexpr std::array GREED_SHOP_WARES = { + SHOP_WARE_KEY, SHOP_WARE_BOMB, SHOP_WARE_HEART, SHOP_WARE_SOUL_HEART, SHOP_WARE_ITEM, + SHOP_WARE_TREASURE_ITEM, SHOP_WARE_BATTERY, SHOP_WARE_PILL, SHOP_WARE_CARD, SHOP_WARE_TRINKET}; + +static bool is_devil_shop(Room& room) +{ + return room.roomType == ROOM_DEVIL || room.roomType == ROOM_BLACK_MARKET || + (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE); +} + +static bool is_greed() +{ + return g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; +} + +// Shuffles a list of wares and fills the shop's slots from its front. +static void slots_shuffle_fill(RoomDescriptor& desc, std::vector& wares, RNG& rng) +{ + RNG::Shuffle(&rng, wares.data(), wares.data() + wares.size()); + for (size_t i = 0; i < std::min(wares.size(), (size_t)SHOP_SLOT_COUNT); i++) + desc.shopItemSlots[i] = (int16_t)wares[i]; +} + +// The slot a shop discounts, if any: one of its first slots, two times in three. +static int16_t discount_slot_roll(RNG& rng, int slots) +{ + return rng.RandomInt(SHOP_DISCOUNT_ODDS) == 0 ? -1 : (int16_t)rng.RandomInt(slots); +} + +// 00813d90 Chooses what each slot of the room's shop sells, from the room's award seed: every slot an item in devil +// shops, the angel shop's items and holy wares, the alternate shops' and the Member Card shop's mixes, Greed's fixed +// slots, or a normal shop's eight kinds shuffled with one of its first two made an item. One slot may be discounted. +void room_shop_slots_init(Room& room) +{ + RoomDescriptor& desc = *room.descriptor; + RNG rng = {desc.awardSeed, 5, 9, 7}; + std::vector wares; + int discountSlots = SHOP_DISCOUNT_SLOTS_WIDE; + + desc.shopItemRestocks.fill(0); + if (is_devil_shop(room)) + { + desc.shopItemSlots.fill(SHOP_WARE_ITEM); + discountSlots = SHOP_DISCOUNT_SLOTS; + } + else if (room.roomType == ROOM_ANGEL) + { + wares = {SHOP_WARE_ITEM, SHOP_WARE_SOUL_HEART, SHOP_WARE_SOUL_HEART, SHOP_WARE_KEY, + SHOP_WARE_KEY, SHOP_WARE_ETERNAL_HEART, SHOP_WARE_ETERNAL_HEART, SHOP_WARE_CREDIT_CARD}; + slots_shuffle_fill(desc, wares, rng); + desc.shopItemSlots[1] = SHOP_WARE_ITEM; + discountSlots = SHOP_DISCOUNT_SLOTS; + } + else if (room.roomType == ROOM_SHOP && desc.data->subtype - ALT_SHOP_SUBTYPE_MIN < ALT_SHOP_SUBTYPE_COUNT && + desc.data->subtype >= ALT_SHOP_SUBTYPE_MIN) + { + wares = {SHOP_WARE_TRINKET, SHOP_WARE_KEY, SHOP_WARE_BOMB, SHOP_WARE_CARD, SHOP_WARE_BATTERY, SHOP_WARE_PILL}; + RNG::Shuffle(&rng, wares.data(), wares.data() + wares.size()); + desc.shopItemSlots[0] = (int16_t)wares[0]; + desc.shopItemSlots[1] = (int16_t)wares[1]; + desc.shopItemSlots[2] = SHOP_WARE_ITEM; + desc.shopItemSlots[3] = SHOP_WARE_BOSS_ITEM; + desc.shopItemSlots[4] = SHOP_WARE_TREASURE_ITEM; + wares[0] = SHOP_WARE_ITEM; + wares[1] = SHOP_WARE_TREASURE_ITEM; + RNG::Shuffle(&rng, wares.data(), wares.data() + wares.size()); + desc.shopItemSlots[5] = (int16_t)wares[0]; + desc.shopItemSlots[6] = (int16_t)wares[1]; + desc.shopItemSlots[7] = SHOP_WARE_TREASURE_ITEM; + } + else if (g_game->currentRoomIdx == ROOM_SECRET_SHOP_IDX) + { + wares.push_back(SHOP_WARE_ITEM); + wares.push_back(rng.RandomInt(2) != 0 ? SHOP_WARE_DEVIL_ITEM : SHOP_WARE_ANGEL_ITEM); + wares.push_back(rng.RandomInt(8) != 0 ? SHOP_WARE_BOSS_ITEM : SHOP_WARE_SECRET_ITEM); + wares.insert(wares.end(), + {SHOP_WARE_TRINKET, SHOP_WARE_TRINKET, SHOP_WARE_RARE_HEART, SHOP_WARE_CARD, SHOP_WARE_RUNE}); + slots_shuffle_fill(desc, wares, rng); + } + else if (g_game->IsGreedMode()) + { + desc.shopItemSlots[0] = SHOP_WARE_KEY; + desc.shopItemSlots[1] = SHOP_WARE_HEART; + desc.shopItemSlots[2] = SHOP_WARE_ITEM; + desc.shopItemSlots[3] = SHOP_WARE_BOSS_ITEM; + for (int i = 4; i < SHOP_SLOT_COUNT; i++) + desc.shopItemSlots[i] = GREED_SHOP_WARES[rng.Next() % GREED_SHOP_WARES.size()]; + } + else + { + for (int ware = SHOP_WARE_HEART; ware < SHOP_WARE_ITEM; ware++) wares.push_back(ware); + if (room.shopLevel > SHOP_LEVEL_EXTRA_ITEM) wares.push_back(SHOP_WARE_ITEM); + slots_shuffle_fill(desc, wares, rng); + desc.shopItemSlots[rng.Next() & 1] = SHOP_WARE_ITEM; + discountSlots = SHOP_DISCOUNT_SLOTS; + } + + desc.shopItemIdx = 0; + desc.shopItemDiscountIdx = discount_slot_roll(rng, discountSlots); + desc.awardSeed = rng._seed; +} + +// The shop slot a ware rolls for: the next restock when a bought one waits, else the room's next slot. +static int next_shop_item_id(Room& room) +{ + return room.shopRestocks.empty() ? room.descriptor->shopItemIdx : room.shopRestocks.front().shopItemId; +} + +// 00814980 Rolls the room's next shop ware from a seed: its slot (a waiting restock's, or the next of the eight the +// slots were first chosen for), its kind and its price. Returns the slot. +int room_shop_ware_roll(Room& room, ShopOffer& offer) +{ + RoomDescriptor& desc = *room.descriptor; + if (desc.shopItemIdx < 0) room_shop_slots_init(room); + + bool isRestock = !room.shopRestocks.empty(); + offer.shopItemId = next_shop_item_id(room); + shop_offer_pick(room, offer); + offer.price = room_shop_discount(room, offer.shopItemId, room_shop_item_price(room, offer, nullptr), nullptr); + if (!isRestock) desc.shopItemIdx = (int16_t)((desc.shopItemIdx + 1) & (SHOP_SLOT_COUNT - 1)); + return offer.shopItemId; +} + +// Golden Adoption Papers: the slot it gives a Soul of Lilith, the first soul card, card or pill, bomb, key or heart +// slot. +static int papers_soul_slot(RoomDescriptor& desc) +{ + std::array firsts; + firsts.fill(-1); + for (int i = 0; i < SHOP_SLOT_COUNT; i++) + { + uint16_t ware = (uint16_t)desc.shopItemSlots[i]; + PapersSlot kind = ware < PAPERS_SLOTS.size() ? PAPERS_SLOTS[ware] : PAPERS_OTHER; + if (kind != PAPERS_OTHER && firsts[kind] == -1) firsts[kind] = i; + } + for (PapersSlot kind : {PAPERS_SOUL_CARD, PAPERS_CONSUMABLE, PAPERS_BOMB, PAPERS_KEY, PAPERS_HEART}) + if (firsts[kind] != -1) return firsts[kind]; + return -1; +} + +// A card from the pools as MC_GET_CARD leaves it. +static int card_draw(uint32_t seed, const LuaCardDraw& kinds, int special, int rune, int suit) +{ + LuaCardDraw draw = kinds; + RNG cardRng = {seed, 5, 9, 7}; + draw.rng = &cardRng; + draw.card = ItemPool::GetCardEx((int)seed, special, rune, suit, true); + return lua_engine_get().GetCard(draw); +} + +// 00814a50 What a shop slot sells, rolled from the offer's seed: a heart, bomb, key, pill, card, battery, sack, +// trinket, rune, or an item of the room's pool or of another. Adoption Papers turns the room's items and shop items +// into baby shop items, and golden Papers sells a Soul of Lilith in the slot it picks. +void shop_offer_pick(Room& room, ShopOffer& offer) +{ + RoomDescriptor& desc = *room.descriptor; + ItemPool& pool = g_game->itemPool; + // The original reads one slot past the eight for an id of 8 or more: the last slot is read instead. + int slot = std::clamp(offer.shopItemId, 0, SHOP_SLOT_COUNT - 1); + bool isGreed = is_greed(); + uint32_t seed = offer.seed; + + Entity_Player* papersOwner = g_game->playerManager.FirstTrinketOwner(TRINKET_ADOPTION_PAPERS); + if (papersOwner && (room.roomType == ROOM_SHOP || room.roomType == ROOM_BLACK_MARKET)) + { + int16_t& ware = desc.shopItemSlots[slot]; + if (ware == SHOP_WARE_ITEM || ware == SHOP_WARE_SHOP_ITEM) ware = SHOP_WARE_BABY_SHOP_ITEM; + bool isGolden = papersOwner->GetTrinketMultiplier(TRINKET_ADOPTION_PAPERS) > 2 && + g_manager->persistentGameData.Unlocked(ACHIEVEMENT_SOUL_LILITH); + if (isGolden && papers_soul_slot(desc) == slot) ware = SHOP_WARE_SOUL_CARD; + } + + auto set = [&](int variant, int subType) { + offer.variant = variant; + offer.subType = subType; + }; + auto item = [&](ItemPoolType normal, ItemPoolType greed) { + set(PICKUP_COLLECTIBLE, pool.GetCollectible(isGreed ? greed : normal, seed, 0, 0, 0)); + }; + + switch (desc.shopItemSlots[slot]) + { + case SHOP_WARE_HEART: return set(PICKUP_HEART, HEART_RED); + case SHOP_WARE_BOMB: return set(PICKUP_BOMB, 1); + case SHOP_WARE_PILL: return set(PICKUP_PILL, ItemPool::GetPill(seed)); + case SHOP_WARE_KEY: return set(PICKUP_KEY, 1); + case SHOP_WARE_SOUL_HEART: return set(PICKUP_HEART, HEART_SOUL_KIND); + case SHOP_WARE_BATTERY: return set(PICKUP_LIL_BATTERY, 1); + case SHOP_WARE_CARD: return set(PICKUP_TAROTCARD, card_draw(seed, {.isPlaying = true}, 25, 0, 10)); + case SHOP_WARE_GRAB_BAG: return set(PICKUP_GRAB_BAG, 1); + case SHOP_WARE_ITEM: return set(PICKUP_COLLECTIBLE, pool.GetSeededCollectible(seed, 0, desc)); + case SHOP_WARE_BOSS_ITEM: return item(POOL_BOSS, POOL_GREED_BOSS); + case SHOP_WARE_TREASURE_ITEM: return item(POOL_TREASURE, POOL_GREED_TREASURE); + case SHOP_WARE_TRINKET: return set(PICKUP_TRINKET, (int)pool.GetTrinket(TRINKET_DRAW_TAKE)); + case SHOP_WARE_DEVIL_ITEM: return item(POOL_DEVIL, POOL_GREED_DEVIL); + case SHOP_WARE_ANGEL_ITEM: return item(POOL_ANGEL, POOL_GREED_ANGEL); + case SHOP_WARE_SECRET_ITEM: return item(POOL_SECRET, POOL_GREED_SECRET); + case SHOP_WARE_RARE_HEART: + { + RNG rng = {seed, 7, 1, 9}; + set(PICKUP_HEART, HEART_BLACK); + if (rng.RandomInt(3) == 0) offer.subType = HEART_ETERNAL_KIND; + if (rng.RandomInt(4) == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_HEART_ROTTEN_SHOP)) + offer.subType = HEART_ROTTEN; + if (rng.RandomInt(4) == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_HEART_BONE_SHOP)) + offer.subType = HEART_BONE; + return; + } + case SHOP_WARE_RUNE: + return set(PICKUP_TAROTCARD, card_draw(seed, {.isOnlyRunes = true, .isRunes = true}, 0, 1, 0)); + case SHOP_WARE_SHOP_ITEM: return item(POOL_SHOP, POOL_GREED_SHOP); + case SHOP_WARE_BABY_SHOP_ITEM: return item(POOL_BABY_SHOP, POOL_BABY_SHOP); + case SHOP_WARE_ETERNAL_HEART: return set(PICKUP_HEART, HEART_ETERNAL_KIND); + case SHOP_WARE_CREDIT_CARD: + if (g_manager->persistentGameData.Unlocked(ACHIEVEMENT_HOLY_CARD)) return set(PICKUP_TAROTCARD, CARD_HOLY); + return set(PICKUP_KEY, 1); + case SHOP_WARE_SOUL_CARD: return set(PICKUP_TAROTCARD, CARD_SOUL_LILITH); + } +} + +// Whether Keeper's prices apply: a Keeper plays, or a Keeper's Bargain owner (a single one sells half the deals for +// coins, by the price's seed). +static ShopPricing pricing_get(Entity_Player* player, uint32_t seed) +{ + PlayerManager& players = g_game->playerManager; + bool isKeeper = player ? player->playerType == PLAYER_KEEPER || player->playerType == PLAYER_KEEPER_B + : players.FirstPlayerByType(PLAYER_KEEPER) || players.FirstPlayerByType(PLAYER_KEEPER_B); + if (isKeeper) return PRICING_KEEPER; + + Entity_Player* owner = player ? player : players.FirstTrinketOwner(TRINKET_KEEPERS_BARGAIN); + if (!owner || !owner->HasTrinket(TRINKET_KEEPERS_BARGAIN)) return PRICING_USUAL; + RNG rng = {seed, 15, 1, 29}; + bool isCoinDeal = owner->GetTrinketMultiplier(TRINKET_KEEPERS_BARGAIN) >= 2 || rng.RandomInt(2) == 0; + return isCoinDeal ? PRICING_KEEPER : PRICING_USUAL; +} + +// The Member Card shop's prices: dearer wares, and items between 15 and 30 coins (50 for its devil and angel slots, +// 20 to 99 for its secret item slot). Pound of Flesh asks hearts or spikes instead. +static int secret_shop_price(Room& room, const ShopOffer& offer, bool isFleshDeal, RNG& rng) +{ + switch (offer.variant) + { + case PICKUP_TRINKET: return isFleshDeal ? PRICE_SPIKES : PRICE_SECRET_SHOP_TRINKET; + case PICKUP_TAROTCARD: return isFleshDeal ? PRICE_SPIKES : PRICE_SECRET_SHOP_CARD; + case PICKUP_HEART: + if (isFleshDeal) return PRICE_SPIKES; + if (offer.subType == HEART_ETERNAL_KIND) return PRICE_SECRET_SHOP_HEART_RARE; + if (offer.subType == HEART_BONE || offer.subType == HEART_BLACK) return PRICE_SECRET_SHOP_HEART_BONE; + return offer.subType == HEART_SOUL_KIND ? PRICE_SECRET_SHOP_HEART_SOUL : PRICE_CONSUMABLE; + case PICKUP_COLLECTIBLE: break; + default: return PRICE_CONSUMABLE; + } + if (isFleshDeal) return rng.RandomInt(2) != 0 ? PRICE_TWO_HEARTS : PRICE_ONE_HEART; + + int maxPrice = SECRET_SHOP_ITEM_MAX; + if (offer.shopItemId >= 0 && offer.shopItemId < SHOP_SLOT_COUNT) + { + int16_t ware = room.descriptor->shopItemSlots[offer.shopItemId]; + if (ware == SHOP_WARE_DEVIL_ITEM || ware == SHOP_WARE_ANGEL_ITEM) maxPrice = SECRET_SHOP_RARE_ITEM_MAX; + else if (ware == SHOP_WARE_SECRET_ITEM) + return (int)rng.RandomInt(SECRET_SHOP_ULTRA_SPAN) + SECRET_SHOP_ULTRA_MIN; + } + return (int)rng.RandomInt(maxPrice - SECRET_SHOP_ITEM_MIN + 1) + SECRET_SHOP_ITEM_MIN; +} + +// 008151e0 A ware's price before discounts, for the players (or one player): in shops coins by kind (an item its +// config's price, an angel room's items by their devil price), in devil deals red hearts by the item's devil price, +// spikes for spike offers, and coins for Keepers. Pound of Flesh turns coin prices into hearts and spikes. +int room_shop_item_price(Room& room, const ShopOffer& offer, Entity_Player* player) +{ + PlayerManager& players = g_game->playerManager; + uint32_t seed = (uint32_t)(offer.subType + offer.variant) | (room.descriptor->decorationSeed & PRICE_SEED_MASK); + RNG rng = {seed, 5, 9, 7}; + bool isFlesh = player ? player->HasCollectible(COLLECTIBLE_POUND_OF_FLESH) + : players.FirstCollectibleOwner(COLLECTIBLE_POUND_OF_FLESH, LAZARUS_SHARE_CHECK) != nullptr; + ShopPricing pricing = pricing_get(player, seed); + bool isFleshDeal = isFlesh && pricing == PRICING_USUAL; + + if (g_game->currentRoomIdx == ROOM_SECRET_SHOP_IDX) return secret_shop_price(room, offer, isFleshDeal, rng); + + bool isDevilBoss = room.roomType == ROOM_BOSS && ((g_game->levelStateFlags & 1u << LEVEL_STATE_SATANIC_BIBLE_USED) || + players.FirstPlayerByType(PLAYER_KEEPER_B)); + if (!is_devil_shop(room) && !isDevilBoss && offer.shopItemId != SHOP_ITEM_NEVER_DISCOUNTED) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(offer.subType); + switch (offer.variant) + { + case PICKUP_HEART: + if (offer.subType == HEART_RED || offer.subType == HEART_HALF_KIND) + return isFleshDeal ? PRICE_SPIKES : PRICE_HALF_HEART; + break; + case PICKUP_BOMB: + if (offer.subType == BOMB_GOLDEN_KIND) return isFleshDeal ? PRICE_SPIKES : PRICE_GOLDEN; + break; + case PICKUP_KEY: + if (offer.subType == KEY_GOLDEN_KIND) return isFleshDeal ? PRICE_SPIKES : PRICE_GOLDEN; + break; + case PICKUP_COLLECTIBLE: + if (isFleshDeal) return item ? -item->devilPrice : PRICE_ONE_HEART; + if (!item) + { + log_printf(LOG_INFO, "[warn] Room::GetShopItemPrice: no config for collectible %d.\n", + offer.subType); + return PRICE_ITEM; + } + if (room.roomType != ROOM_ANGEL || item->shopPrice != PRICE_ITEM) return item->shopPrice; + return item->devilPrice == 2 ? PRICE_ITEM_DEVIL : PRICE_ITEM; + } + if (isFleshDeal) return PRICE_SPIKES; + return offer.variant == PICKUP_GRAB_BAG ? PRICE_GRAB_BAG : PRICE_CONSUMABLE; + } + + bool isSoulOffer = false; + if (!player) isSoulOffer = players.AnyoneHasTrinket(TRINKET_YOUR_SOUL); + else + isSoulOffer = player->HasTrinket(TRINKET_YOUR_SOUL) || player->GetHealthType() == HEALTH_NO_HEALTH || + player->playerType == PLAYER_JACOB2_B || + player->temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE); + bool isCoins = (pricing == PRICING_KEEPER && !isSoulOffer) || isFlesh; + + if (offer.variant != PICKUP_COLLECTIBLE) return isCoins ? PRICE_CONSUMABLE : PRICE_SPIKES; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(offer.subType); + int price = 0; + if (item) price = item->devilPrice < 2 ? PRICE_ONE_HEART : PRICE_TWO_HEARTS; + else + { + log_printf(LOG_INFO, "[warn] Room::GetShopItemPrice: no config for collectible %d.\n", offer.subType); + price = (rng.Next() & 1) ? PRICE_TWO_HEARTS : PRICE_ONE_HEART; + } + if (isCoins) return price == PRICE_TWO_HEARTS ? PRICE_ITEM_DEVIL : PRICE_ITEM; + if (item && item->HasTags(TAG_DEVIL_SACRIFICE)) return PRICE_SPIKES_OFFER; + return price; +} + +// The health the players could pay with: the most soul hearts and the most heart containers any main player has, +// one soul heart each for a player without health. Whether a Blue Baby plays. +struct HealthOnHand +{ + int containers = 0; + int soulHearts = 0; + bool isBlueBaby = false; +}; + +static HealthOnHand health_on_hand(Entity_Player* player) +{ + HealthOnHand health; + if (player) + { + bool isNoHealth = player->GetHealthType() == HEALTH_NO_HEALTH || player->HasInstantDeathCurse(); + health.soulHearts = isNoHealth ? 1 : std::max(player->soulHearts, 0); + health.containers = isNoHealth ? 0 : std::max(player->GetEffectiveMaxHearts(), 0); + health.isBlueBaby = player->playerType == PLAYER_BLUEBABY; + return health; + } + + for (int i = 0; i < (int)g_game->playerManager.playerList.size(); i++) + { + Entity_Player& one = *g_game->GetPlayer(i); + Entity_Player* twin = one.twin_get(); + bool isSecondTwin = one.isExists && (one.playerType == PLAYER_JACOB || one.playerType == PLAYER_ESAU) && twin && + twin->playerIndex != -1 && twin->playerIndex < one.playerIndex && twin != &one; + if (one.variant != 0 || one.isCoopGhost || isSecondTwin || one.parent) continue; + + int soulHearts = 1; + if (one.GetHealthType() != HEALTH_NO_HEALTH && !one.HasInstantDeathCurse()) + { + HealthType type = one.GetHealthType(); + int containers = + type == HEALTH_SOUL || type == HEALTH_NO_HEALTH ? one.maxHearts : one.maxHearts + one.boneHearts * 2; + health.containers = std::max(health.containers, containers); + soulHearts = one.soulHearts; + } + health.soulHearts = std::max(health.soulHearts, soulHearts); + } + health.isBlueBaby = g_game->playerManager.FirstPlayerByType(PLAYER_BLUEBABY) != nullptr; + return health; +} + +// A heart price fitted to what the players hold: soul hearts for Blue Baby, three soul hearts for those without +// containers, cheaper hearts for the discounted slot or a full soul bar, then Judas' Tongue. +static int heart_price_fit(Room& room, int shopItemId, int price, Entity_Player* player) +{ + HealthOnHand health = health_on_hand(player); + bool isDiscounted = shopItemId >= 0 && room.descriptor->shopItemDiscountIdx == shopItemId; + + if (health.isBlueBaby) + { + if (price == PRICE_ONE_HEART) price = PRICE_ONE_SOUL_HEART; + else if (price == PRICE_TWO_HEARTS) price = PRICE_TWO_SOUL_HEARTS; + } + else if (health.containers < 1) price = PRICE_THREE_SOULHEARTS; + else if (price == PRICE_TWO_HEARTS && ((isDiscounted && health.soulHearts > SOUL_HEARTS_FOR_DISCOUNT) || + health.containers < CONTAINERS_FOR_TWO_HEARTS)) + price = PRICE_ONE_HEART_AND_TWO_SOULHEARTS; + else if (price == PRICE_ONE_HEART && isDiscounted && health.soulHearts > SOUL_HEARTS_FOR_BIG_DISCOUNT) + price = PRICE_THREE_SOULHEARTS; + + if (!g_game->playerManager.AnyoneHasTrinket(TRINKET_JUDAS_TONGUE)) return price; + if (price == PRICE_TWO_HEARTS) price = PRICE_ONE_HEART; + if (g_game->playerManager.GetTrinketMultiplier(TRINKET_JUDAS_TONGUE) < 2) return price; + switch (price) + { + case PRICE_THREE_SOULHEARTS: return PRICE_TWO_SOUL_HEARTS; + case PRICE_TWO_SOUL_HEARTS: return PRICE_ONE_SOUL_HEART; + case PRICE_ONE_HEART_AND_TWO_SOULHEARTS: return PRICE_ONE_HEART_AND_ONE_SOUL_HEART; + case PRICE_ONE_HEART_AND_ONE_SOUL_HEART: return PRICE_ONE_HEART; + } + return price; +} + +// A coin price after the discounts: Adoption Papers on its baby shop slots, Steam Sales (or the room's discounted +// slot, a Steam Sale effect, golden Keeper's Bargain in devil rooms) dividing it, Store Credit making the shop free, +// and every restock of the slot raising it. +static int coin_price_fit(Room& room, int shopItemId, int price) +{ + PlayerManager& players = g_game->playerManager; + RoomDescriptor& desc = *room.descriptor; + int basePrice = price; + + Entity_Player* papersOwner = players.FirstTrinketOwner(TRINKET_ADOPTION_PAPERS); + if (papersOwner && shopItemId >= 0 && shopItemId < SHOP_SLOT_COUNT && + desc.shopItemSlots[shopItemId] == SHOP_WARE_BABY_SHOP_ITEM) + basePrice = papersOwner->GetTrinketMultiplier(TRINKET_ADOPTION_PAPERS) < 2 ? price * 2 / 3 : PAPERS_DISCOUNT; + + int sales = players.GetNumCollectibles(COLLECTIBLE_STEAM_SALE); + bool isDiscounted = shopItemId >= 0 && desc.shopItemDiscountIdx == shopItemId; + if (sales == 0 && (isDiscounted || room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STEAM_SALE))) sales = 1; + Entity_Player* bargainOwner = players.FirstTrinketOwner(TRINKET_KEEPERS_BARGAIN); + if (room.roomType == ROOM_DEVIL && bargainOwner && bargainOwner->GetTrinketMultiplier(TRINKET_KEEPERS_BARGAIN) > 2) + { + RNG rng; + rng.game_constructor(desc.awardSeed, (uint32_t)shopItemId); + if (rng.RandomInt(3) == 0) sales++; + } + + if (room.roomType == ROOM_SHOP && players.AnyoneHasTrinket(TRINKET_STORE_CREDIT)) price = PRICE_FREE; + else + { + price = basePrice; + if (sales > 0 && basePrice > 0) + { + if (basePrice >= DISCOUNTED_PRICE_FLOOR && sales == 1) price = basePrice / 2; + else price = (int)std::ceil((float)basePrice / (float)(sales + 1)); + } + } + if (is_greed() || price < 0 || shopItemId < 0) return price; + + uint8_t restocks = desc.shopItemRestocks[shopItemId]; + if (restocks == 0) return price; + int step = std::max(basePrice / RESTOCK_PRICE_STEP, 1); + return std::min(step * (restocks + 1) * restocks / 2 + price, PRICE_CAP); +} + +// 00816250 A price after the room's discounts and the players' health (Room::TryGetShopDiscount): coin prices are +// discounted, heart prices fit what the players can pay, and Your Soul or a player without health pays with the soul. +int room_shop_discount(Room& room, int shopItemId, int price, Entity_Player* player) +{ + bool isSpikes = price == PRICE_SPIKES || price == PRICE_SPIKES_OFFER; + if (price > 0) price = coin_price_fit(room, shopItemId, price); + else if (price < 0 && !isSpikes) price = heart_price_fit(room, shopItemId, price, player); + if (price >= 0 || price == PRICE_FREE) return price; + + bool isSoul = false; + if (!player) isSoul = g_game->playerManager.AnyoneHasTrinket(TRINKET_YOUR_SOUL); + else + { + Entity_Player* twin = player->playerType == PLAYER_THESOUL_B ? player->twin_get() : nullptr; + isSoul = player->HasTrinket(TRINKET_YOUR_SOUL) || + (player->GetHealthType() == HEALTH_NO_HEALTH && player->playerType != PLAYER_THESOUL_B) || + player->playerType == PLAYER_JACOB2_B || player->temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE) || + (twin && + (twin->HasTrinket(TRINKET_YOUR_SOUL) || twin->temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE))); + } + return isSoul ? PRICE_SOUL : price; +} + +// 00815800 Queues a bought shop slot to restock on its cell in a second (Room::TriggerRestock). +void room_restock_trigger(Room& room, int gridIndex, int shopItemId) +{ + room.shopRestockTimer = RESTOCK_FRAMES; + room.shopRestocks.push_back({gridIndex, shopItemId}); +} + +// 008158a0 Restocks every queued shop slot with a new ware in a poof, each slot's restock raising its price, the +// spawns seeded from the room's spawn seed. Only shops restock. +void room_restock_partial(Room& room) +{ + if (room.roomType != ROOM_SHOP) + { + log_printf(LOG_INFO, "[warn] restock disabled for room type %d.\n", room.roomType); + return; + } + + RNG rng = {room.descriptor->spawnSeed, 2, 7, 7}; + while (!room.shopRestocks.empty()) + { + ShopRestock restock = room.shopRestocks.front(); + if (restock.shopItemId >= 0) + { + uint8_t& restocks = room.descriptor->shopItemRestocks[restock.shopItemId]; + if (restocks != RESTOCKS_STOPPED) restocks++; + } + + Vector position = room.GetGridPosition(restock.gridIndex); + if ((uint32_t)restock.gridIndex < ROOM_GRID_CELLS && room.gridEntities[restock.gridIndex]) + room.gridEntities[restock.gridIndex]->Destroy(true, EntityRef()); + Entity* ware = g_game->Spawn( + {.position = position, .type = ENTITY_PICKUP, .variant = PICKUP_SHOPITEM, .seed = rng.Next()}); + ware->spawnGridIndex = restock.gridIndex; + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + log_printf(LOG_INFO, "Spawn shop pickup (restock), Pos(%.2f,%.2f)\n", (double)position.x, (double)position.y); + room.shopRestocks.pop_front(); + } + room.descriptor->spawnSeed = rng.Next(); +} + +// 006fe3d0 Teleports a player to a random room of the floor (an error room's random room when asked). +void game_random_room_move(Game& game, bool isErrorRoom, uint32_t seed, Entity_Player* player) +{ + game.leaveDoor = -1; + game.StartRoomTransition( + {.player = player, .animation = TRANSITION_TELEPORT, .roomIndex = game.GetRandomRoomIndex(isErrorRoom, seed)}); +} + +// A pickup or enemy a shopkeeper drops when it dies (the original's LootList entry): its kind, seed and the RNG +// a thrown spider uses. +struct ShopkeeperLoot +{ + int subType = 0; + int type = 0; + int variant = 0; + uint32_t seed = 0; +}; + +// The secret room shopkeepers' rare trinkets. +constexpr std::array SHOPKEEPER_TRINKETS = {1, 24, 49, 50, 51, 52}; +constexpr int SHOPKEEPER_TRINKET_TRIES = 3; +constexpr int SHOPKEEPER_SECRET_VARIANT = 3; +constexpr int SHOPKEEPER_SECRET_GUY_VARIANT = 4; +constexpr int SHOPKEEPER_GUY_VARIANT = 1; +constexpr int SHOPKEEPER_HANGING_VARIANT = 2; +constexpr uint32_t SHOPKEEPER_GREED_MASK = 0x7f; +constexpr uint32_t SHOPKEEPER_TRINKET_MASK = 0x1f; +constexpr int SHOPKEEPER_ITEM_ODDS = 100; +constexpr int SHOPKEEPER_SKINS = 9; +constexpr int ACHIEVEMENT_COUPON = 364; +constexpr int COIN_NICKEL_KIND = 2; +constexpr int EVENT_SHOPKEEPERS_KILLED = 12; +constexpr int GAME_STATE_SHOPKEEPER_KILLED = 31; +constexpr float SHOPKEEPER_FRICTION = 0.8f; +constexpr float SHOPKEEPER_SPIDER_RANGE = 70; +constexpr float SHOPKEEPER_SPIDER_HEIGHT = -30; +constexpr float SHOPKEEPER_FLOAT_OFFSET = 8; +constexpr float SHOPKEEPER_SPLAT_GREY = 0.2f; + +// A rare trinket a secret room shopkeeper holds, tried three times from the list while the pool still has one. +static int shopkeeper_trinket_roll(RNG& rng) +{ + std::vector& trinkets = g_game->itemPool.trinketPoolItems; + for (int i = 0; i < SHOPKEEPER_TRINKET_TRIES; i++) + { + int trinket = SHOPKEEPER_TRINKETS[rng.Next() % SHOPKEEPER_TRINKETS.size()]; + if (trinkets[trinket].isAvailable && trinkets[trinket].isInPool) return trinket; + } + return 0; +} + +// 006c1ac0 What a shopkeeper drops when it dies (Entity_NPC::shopkeeper_get_loot), from its drop RNG, which only an +// advancing draw moves on: rarely Steam Sale, Head of the Keeper or Coupon, else two spiders, two coins or nothing. +// A secret room's shopkeeper rarely hides Greed, else a rare trinket or a nickel. One without a reward drops nothing. +static std::vector shopkeeper_loot_get(Entity_NPC& npc, bool isAdvance) +{ + std::vector loot; + if (npc.HasEntityFlags(FLAG_NO_REWARD)) return loot; + + RNG copy = npc.dropRNG; + RNG& rng = isAdvance ? npc.dropRNG : copy; + RemoveMode mode = isAdvance ? REMOVE_APPLY : REMOVE_QUERY; + ItemPool& pool = g_game->itemPool; + auto add = [&](int type, int variant, int subType) { + loot.push_back({subType, type, variant, rng.Next()}); + }; + + if (npc.variant == SHOPKEEPER_SECRET_VARIANT || npc.variant == SHOPKEEPER_SECRET_GUY_VARIANT) + { + if ((rng.Next() & SHOPKEEPER_GREED_MASK) == 0 && g_game->room->roomType != ROOM_BOSS) + { + add(ENTITY_GREED, 0, 0); + return loot; + } + if ((rng.Next() & SHOPKEEPER_TRINKET_MASK) == 0) + { + int trinket = shopkeeper_trinket_roll(rng); + if (trinket == 0) return loot; + if (isAdvance) pool.RemoveTrinket(trinket); + add(ENTITY_PICKUP, PICKUP_TRINKET, trinket); + return loot; + } + if (rng.Next() % 3 != 0) add(ENTITY_PICKUP, PICKUP_COIN, COIN_NICKEL_KIND); + return loot; + } + + if (rng.Next() % SHOPKEEPER_ITEM_ODDS == 0 && + pool.RemoveCollectible(COLLECTIBLE_STEAM_SALE, REMOVE_AVAILABLE, mode)) + add(ENTITY_PICKUP, PICKUP_COLLECTIBLE, COLLECTIBLE_STEAM_SALE); + else if (rng.RandomInt(SHOPKEEPER_ITEM_ODDS) == 0 && + pool.RemoveCollectible(COLLECTIBLE_HEAD_OF_THE_KEEPER, REMOVE_AVAILABLE, mode)) + add(ENTITY_PICKUP, PICKUP_COLLECTIBLE, COLLECTIBLE_HEAD_OF_THE_KEEPER); + else if (rng.RandomInt(SHOPKEEPER_ITEM_ODDS) == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_COUPON) && + pool.RemoveCollectible(COLLECTIBLE_COUPON, REMOVE_AVAILABLE, mode)) + add(ENTITY_PICKUP, PICKUP_COLLECTIBLE, COLLECTIBLE_COUPON); + else + { + uint32_t kind = rng.RandomInt(3); + if (kind == 0) return loot; + int type = kind == 1 ? ENTITY_SPIDER : ENTITY_PICKUP; + int variant = kind == 1 ? 0 : PICKUP_COIN; + add(type, variant, 0); + add(type, variant, 0); + } + return loot; +} + +// The shopkeeper's look on its first update: a random face of nine, an idle animation by variant, grey blood, and a +// float above the floor in crawlspaces. +static void shopkeeper_start(Entity_NPC& npc) +{ + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.entityCollisionClass = ENTCOLL_PLAYERONLY; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.subtype = (int)(npc.initSeed % SHOPKEEPER_SKINS + 1); + + bool isGuy = npc.variant == SHOPKEEPER_GUY_VARIANT || npc.variant == SHOPKEEPER_SECRET_GUY_VARIANT; + std::string animation = npc.variant == SHOPKEEPER_HANGING_VARIANT ? "Idle" + : isGuy ? "Guy" + std::to_string(npc.subtype) + : "Shopkeeper " + std::to_string(npc.subtype); + npc.sprite.Play(animation); + constexpr float GREY = SHOPKEEPER_SPLAT_GREY; + npc.splatColor = {{GREY, GREY, GREY, 1}, {}, {GREY, GREY, GREY}}; + if (!isGuy && g_game->room->roomType == ROOM_DUNGEON) npc.sprite.offset = vector_make(0, SHOPKEEPER_FLOAT_OFFSET); + + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_IDLE; + npc.UpdatePickupGhosts(); +} + +// 006c2220 The shopkeeper stands still where it started. Killed, it counts the kill for the run and the floor and +// drops its loot: spiders thrown at a free spot, pickups scattered when there are several. +void npc_shopkeeper_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) shopkeeper_start(npc); + + npc.pos = npc.targetPosition; + npc.friction *= SHOPKEEPER_FRICTION; + if (!npc.isDead) return; + + Game& game = *g_game; + g_manager->persistentGameData.IncreaseEventCounter(EVENT_SHOPKEEPERS_KILLED, 1); + game.gameStateFlags |= 1ull << GAME_STATE_SHOPKEEPER_KILLED; + game.levelStateFlags |= 1u << LEVEL_STATE_SHOPKEEPER_KILLED; + + std::vector loot = shopkeeper_loot_get(npc, true); + for (size_t i = 0; i < loot.size(); i++) + { + ShopkeeperLoot& drop = loot[i]; + if (drop.type == ENTITY_SPIDER) + { + Vector target = i == 0 ? room_free_pickup_position_find({npc.pos, SHOPKEEPER_SPIDER_RANGE}) : Vector{}; + Entity_NPC::ThrowSpider(npc.pos, &npc, target, false, SHOPKEEPER_SPIDER_HEIGHT); + continue; + } + if (drop.type == ENTITY_GREED) + { + reconstruction_missing("NpcAI::ENTITY_SHOPKEEPER 006c2220: Greed out of a secret room's shopkeeper"); + continue; + } + + Entity* entity = game.Spawn({.position = npc.pos, + .subType = drop.subType, + .type = drop.type, + .variant = drop.variant, + .seed = drop.seed}); + if (loot.size() > 1 && entity->type == ENTITY_PICKUP) + entity->velocity = Entity_Pickup::GetRandomPickupVelocity(npc.pos, nullptr, 0); + entity->Update(); + } + if (!loot.empty()) game.room->isPickupVisionInvalid = true; + npc.UpdatePickupGhosts(); +} + +constexpr int SOUND_BOSS_LITE_ROAR = 14; +constexpr int SOUND_COIN_SLOT = 45; +constexpr int SOUND_MEATY_DEATHS = 77; +constexpr int SOUND_WOOD_PLANK_BREAK = 481; +constexpr int SOUND_MIRROR_BREAK = 610; +constexpr int MUSIC_JINGLE_SECRETROOM_FIND = 85; +constexpr int FAMILIAR_KNIFE_FULL = 223; +constexpr int TRINKET_PAPER_CLIP_ID = 19; +constexpr int TRINKET_STORE_KEY_ID = 83; +constexpr int EVENT_DOORS_BOMBED = 199; +constexpr int MIRROR_LUCK_PENALTY = -7; +constexpr int GAME_STATE_MOMS_HEART_DOOR_CUT = 52; +constexpr int GAME_STATE_KEY_PIECE_DOOR_OPENED = 49; +constexpr uint32_t STAGE_BLUE_WOMB = 9; +constexpr int NETPLAY_DOOR_WAIT = 30; +constexpr float HUSH_DOOR_PITCH = 0.3f; +constexpr int ROOM_LIST_LAST_IDX = 168; +constexpr float DOOR_PARTICLE_SPEED = 8; +constexpr int DOOR_PARTICLES_MIN = 6; +constexpr int DOOR_PARTICLES_SPREAD = 5; +constexpr int KNIFE_PARTICLES_MIN = 9; +constexpr int KNIFE_PARTICLES_SPREAD = 6; +constexpr int KNIFE_SPLASH_SUBTYPE = 10; +constexpr float POOF_DEPTH = 5; +constexpr int DUST_MIN = 3; +constexpr float DUST_SPEED = 5; +constexpr float DUST_SIDE_SPEED = 2.5f; +constexpr float DUST_RADIUS = 20; +constexpr float DUST_SPIN = 10; +constexpr float DUST_SPIN_MIN = 2; +constexpr int DUST_LIFE_MIN = 15; +constexpr float HALF_TURN = 3.14f; +constexpr ColorMod BLUE_KEY_COLOR = {{1, 1, 1, 1}, {0.4f, 0.6f, 1, 1}, {0, 0, 0}}; + +// Throws a door's debris: a few particles of a kind from the door's cell. +static void door_particles_spawn(GridEntity_Door& door, int variant, int count, int subType) +{ + game_particles_spawn({.position = door.Position(), + .speed = DOOR_PARTICLE_SPEED, + .count = count, + .subType = subType, + .variant = variant}); +} + +static int door_particles_count() +{ + return (int)(Random() % DOOR_PARTICLES_SPREAD) + DOOR_PARTICLES_MIN; +} + +// Mom's Heart's exit, cut open by the full knife: flesh flies, a large poof plays and the way down opens. +static bool heart_exit_cut(GridEntity_Door& door, Entity* source) +{ + if (!source || source->type != ENTITY_FAMILIAR || source->variant != FAMILIAR_KNIFE_FULL) return false; + + door_particles_spawn(door, EFFECT_ROCK_PARTICLE, (int)(Random() % DOOR_PARTICLES_SPREAD) + DOOR_PARTICLES_MIN, + KNIFE_SPLASH_SUBTYPE); + door_particles_spawn(door, EFFECT_ROCK_PARTICLE + 1, (int)(Random() % KNIFE_PARTICLES_SPREAD) + KNIFE_PARTICLES_MIN, + 0); + Entity* poof = + g_game->Spawn({.position = door.Position(), .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + poof->sprite.Play("Poof_Large1"); + poof->renderDepthOffset = POOF_DEPTH; + + door.variant = DOOR_UNLOCKED; + door.isBusted = true; + door.state = DOOR_STATE_OPEN; + grid_sound_play(SOUND_MEATY_DEATHS); + grid_sound_play(SOUND_DEATH_BURST_LARGE); + door.UpdateAnimation(); + g_game->UpdateVisibility(); + g_game->gameStateFlags |= 1ull << GAME_STATE_MOMS_HEART_DOOR_CUT; + return true; +} + +// 0070fb60 Opens the door to an explosion or another opener: the mirror breaks (costing the bomber luck), Mom's Heart's +// exit takes the knife, a hidden door is uncovered (with the secret room's jingle on a first find), and a breakable +// door blows open with debris, a secret wall into its hole, a cracked lock first cracking. A door that only shows +// stays shut, barred while a miniboss holds the room. +bool GridEntity_Door::TryBlowOpen(bool isFromExplosion, Entity* source) +{ + Game& game = *g_game; + Room& room = *game.room; + bool isNetplayWait = + targetRoomIdx == game.lastRoomIdx && g_manager->netplayManager.is_online() && updateCount <= NETPLAY_DOOR_WAIT; + if (!isFromExplosion && !source && isNetplayWait) return false; + + if (doorFlags & DOOR_FLAG_MIRROR) + { + bool isRepentancePath = (game.challenge != 0 || game.dailyChallenge._id != 0) && + game.GetChallengeParams().pathType == PATH_TYPE_REPENTANCE; + if (isRepentancePath || state == DOOR_STATE_OPEN) return false; + variant = DOOR_UNLOCKED; + isBusted = true; + state = DOOR_STATE_OPEN; + UpdateAnimation(); + grid_sound_play(SOUND_MIRROR_BREAK); + game.levelStateFlags |= 1u << LEVEL_STATE_MIRROR_BROKEN; + Entity* bomber = source ? source->GetPlayerAncestor() : nullptr; + if (bomber) static_cast(bomber)->DonateLuck(MIRROR_LUCK_PENALTY); + return true; + } + if (get_secret_exit_kind() == SECRET_EXIT_MOMS_HEART) return heart_exit_cut(*this, source); + + bool isSecretTarget = + targetRoomType == ROOM_SECRET || targetRoomType == ROOM_SUPERSECRET || targetRoomType == ROOM_ULTRASECRET; + if (isSecretTarget && game.GetRoomByIdx(targetRoomIdx)->visitedCount == 0 && variant == DOOR_HIDDEN) + g_manager->musicManager.PlayJingle(MUSIC_JINGLE_SECRETROOM_FIND); + if (variant == DOOR_HIDDEN || variant == DOOR_UNSPECIFIED) game.UncoverHiddenDoor(game.currentRoomIdx, slot); + + if (!CanBlowOpen()) + { + if (variant != DOOR_HIDDEN && variant != DOOR_UNSPECIFIED) return false; + variant = currentRoomType == ROOM_MINIBOSS || room.isSurpriseMiniboss ? DOOR_LOCKED_BARRED : DOOR_UNLOCKED; + if (isFromExplosion) SpawnDust(); + UpdateAnimation(); + return false; + } + + bool isKeyLock = variant == DOOR_LOCKED || variant == DOOR_LOCKED_DOUBLE; + if (isKeyLock && game.playerManager.AnyoneHasTrinket(TRINKET_BROKEN_PADLOCK)) variant = DOOR_UNLOCKED; + if (currentRoomType == ROOM_DEFAULT && targetRoomType == ROOM_DEFAULT && variant != DOOR_LOCKED_CRACKED) + { + openAnimation = "Break"; + if (isFromExplosion) + { + door_particles_spawn(*this, EFFECT_WOOD_PARTICLE, door_particles_count(), 0); + SpawnDust(); + } + } + bool isSecretWall = currentRoomType == ROOM_SECRET || targetRoomType == ROOM_SECRET || + currentRoomType == ROOM_SUPERSECRET || targetRoomType == ROOM_SUPERSECRET || + IsRoomType(ROOM_ULTRASECRET); + if (isSecretWall) + { + openAnimation = "Opened"; + if (isFromExplosion) + { + door_particles_spawn(*this, EFFECT_ROCK_PARTICLE, door_particles_count(), 0); + SpawnDust(); + grid_sound_play(SOUND_ROCK_CRUMBLE); + } + } + if (variant == DOOR_LOCKED_CRACKED) + { + door_particles_spawn(*this, EFFECT_WOOD_PARTICLE, door_particles_count(), 0); + if (state == DOOR_STATE_CLOSED) + { + state = DOOR_STATE_DAMAGED; + UpdateAnimation(); + return false; + } + } + + if (variant != DOOR_LOCKED) + { + if ((variant == DOOR_HIDDEN && room.roomType == ROOM_MINIBOSS) || room.isSurpriseMiniboss) + variant = DOOR_LOCKED_BARRED; + else + { + if (variant == DOOR_LOCKED_CRACKED) grid_sound_play(SOUND_WOOD_PLANK_BREAK); + variant = DOOR_UNLOCKED; + isBusted = true; + state = DOOR_STATE_OPEN; + } + } + UpdateAnimation(); + game.UpdateVisibility(); + if (isFromExplosion) g_manager->persistentGameData.IncreaseEventCounter(EVENT_DOORS_BOMBED, 1); + return true; +} + +// 0070f810 Puffs three to six dust clouds from the wall around the door, drifting into the room and spinning away +// from the door's line. +void GridEntity_Door::SpawnDust() +{ + constexpr std::array, 4> STEPS = {{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}}; + Vector facing = + (uint32_t)direction < STEPS.size() ? vector_make(STEPS[direction][0], STEPS[direction][1]) : Vector{}; + Vector cell = Position(); + + for (int count = (int)(Random() & 3) + DUST_MIN; count > 0; count--) + { + uint32_t seed = Random(); + float inward = random_unit() * DUST_SPEED; + float along = random_unit() * DUST_SPEED - DUST_SIDE_SPEED; + Vector velocity = vector_make(-along * facing.y - inward * facing.x, along * facing.x - inward * facing.y); + float angle = random_unit() * HALF_TURN; + angle += angle; + float radius = random_unit() * DUST_RADIUS; + Vector position = vector_make(std::cos(angle) * radius + cell.x, std::sin(angle) * radius + cell.y); + + Entity_Effect* dust = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + float side = (dust->pos.x - cell.x) * -facing.y + (dust->pos.y - cell.y) * facing.x < 0 ? -1.0f : 1.0f; + dust->rotation = (random_unit() * DUST_SPIN + DUST_SPIN_MIN) * side; + int life = (int)(Random() % DUST_LIFE_MIN) + DUST_LIFE_MIN; + dust->timeout = life; + dust->lifespan = life; + dust->Update(); + } +} + +// Whether a key, coins, the Store Key or a strong Paper Clip pays the lock: coin locks take a coin, the Blue Womb's +// boss door is free, and key locks take a key. +static bool door_lock_pay(GridEntity_Door& door, Entity_Player& player) +{ + bool isCoinLock = door.doorFlags & DOOR_FLAG_COIN_LOCK; + if (isCoinLock && player.numCoins > 0) return true; + if (!isCoinLock && door.targetRoomType == ROOM_SHOP && player.HasTrinket(TRINKET_STORE_KEY_ID)) return true; + if (door.targetRoomType == ROOM_BOSS && door.targetRoomIdx >= 0 && g_game->stage == STAGE_BLUE_WOMB) return true; + if (isCoinLock) return false; + bool isKeyLock = door.variant == DOOR_LOCKED || door.variant == DOOR_LOCKED_DOUBLE; + if (isKeyLock && player.GetTrinketMultiplier(TRINKET_PAPER_CLIP_ID) > 2) return true; + return player.TryUseKey(); +} + +// 00710480 Unlocks the door for a player: a key (or coin) is paid unless forced, the Blue Key and a strong Strange Key +// in the Blue Womb force it. A double lock loses one chain at a time. The Blue Key's opening glows blue and redirects +// the room behind it. Co-op ghosts and the mirror never unlock. +bool GridEntity_Door::TryUnlock(Entity_Player& player, bool isForce) +{ + Game& game = *g_game; + if ((doorFlags & DOOR_FLAG_MIRROR) || player.isCoopGhost) return false; + if (!isForce && variant == DOOR_LOCKED && targetRoomType == ROOM_SECRET_EXIT && + get_secret_exit_kind() == SECRET_EXIT_MAUSOLEUM) + reconstruction_missing("GridEntity_Door::TryUnlock 00710480: the Mausoleum's heart door"); + if (isForce && variant == DOOR_LOCKED_KEYFAMILIAR) game.gameStateFlags |= 1ull << GAME_STATE_KEY_PIECE_DOOR_OPENED; + + bool isKeyLock = variant == DOOR_LOCKED || variant == DOOR_LOCKED_DOUBLE; + bool isBlueKey = isKeyLock && player.HasTrinket(TRINKET_BLUE_KEY); + if (isBlueKey || (game.stage == STAGE_BLUE_WOMB && player.GetTrinketMultiplier(TRINKET_STRANGE_KEY) >= 2)) + isForce = true; + if (!isForce) + { + if (state == DOOR_STATE_OPEN || !isKeyLock) return false; + bool isChainOpening = isExtraVisible && state == DOOR_STATE_HALF_OPEN && + (extraSprite.IsPlaying("GoldenKeyOpenChain1") || extraSprite.IsPlaying("KeyOpenChain1")); + if (isChainOpening || !door_lock_pay(*this, player)) return false; + if (doorFlags & DOOR_FLAG_COIN_LOCK) player.AddCoins(-1); + } + else isUnlockedByPlayer = true; + + if (variant == DOOR_LOCKED_DOUBLE && state != DOOR_STATE_HALF_OPEN && !isForce) + { + state = DOOR_STATE_HALF_OPEN; + UpdateAnimation(); + return true; + } + state = DOOR_STATE_OPEN; + UpdateAnimation(); + variant = DOOR_UNLOCKED; + if (targetRoomType == ROOM_BOSS && targetRoomIdx >= 0 && game.stage == STAGE_BLUE_WOMB) + grid_sound_play(SOUND_BOSS_LITE_ROAR, {.pitch = HUSH_DOOR_PITCH}); + else grid_sound_play(doorFlags & DOOR_FLAG_COIN_LOCK ? SOUND_COIN_SLOT : SOUND_UNLOCK); + if (!isBlueKey) return true; + + if (sprite.IsPlaying("GoldenKeyOpen")) sprite.Play("KeyOpen"); + if (sprite.IsPlaying("KeyOpen")) + if (LayerState* key = sprite.GetLayer("Key")) key->color = BLUE_KEY_COLOR; + RoomDescriptor* target = game.GetRoomByIdx(targetRoomIdx); + if (target->data) target->flags |= ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT; + return true; +} + +// 0074a1b0 Uncovers a hidden door from the room behind it too: the neighbour's saved cell for the facing door becomes +// an unlocked door, or unlocks a hidden one. +void Level::UncoverHiddenDoor(int roomIdx, int doorSlot) +{ + roomIdx = std::clamp(roomIdx, (int)ROOM_LIL_PORTAL_IDX, ROOM_LIST_LAST_IDX); + doorSlot = std::clamp(doorSlot, 0, DOOR_SLOT_COUNT - 1); + int neighbourIdx = GetRoomByIdx(roomIdx)->doors[doorSlot]; + RoomDescriptor* neighbour = GetRoomByIdx(neighbourIdx); + if (!neighbour->data) return; + + RoomConfig_Room& data = *neighbour->data; + int slot = GetTargetSlot(neighbourIdx, (doorSlot + 2) % 4); + int gridIndex = room_shape_get_door_grid_index(slot, data.width + 2, data.height + 2, data.shape); + GridEntityDesc& cell = neighbour->savedGridEntities[gridIndex]; + if (cell._type == GRID_NULL) + { + cell._type = GRID_DOOR; + cell._variant = DOOR_UNLOCKED; + } + else if (cell._type == GRID_DOOR && cell._variant == DOOR_HIDDEN) cell._variant = DOOR_UNLOCKED; +} diff --git a/src/room_special.h b/src/room_special.h new file mode 100644 index 0000000..ca5cbb8 --- /dev/null +++ b/src/room_special.h @@ -0,0 +1,55 @@ +#pragma once + +#include "classes.h" + +class Room; +class Game; + +// What a shop slot sells (RoomDescriptor::shopItemSlots), by the original's numbers. +enum ShopWare : int16_t +{ + SHOP_WARE_HEART, + SHOP_WARE_BOMB, + SHOP_WARE_PILL, + SHOP_WARE_KEY, + SHOP_WARE_SOUL_HEART, + SHOP_WARE_BATTERY, + SHOP_WARE_CARD, + SHOP_WARE_GRAB_BAG, + SHOP_WARE_ITEM, + SHOP_WARE_BOSS_ITEM, + SHOP_WARE_TREASURE_ITEM, + SHOP_WARE_TRINKET, + SHOP_WARE_DEVIL_ITEM, + SHOP_WARE_ANGEL_ITEM, + SHOP_WARE_SECRET_ITEM, + SHOP_WARE_RARE_HEART, + SHOP_WARE_RUNE, + SHOP_WARE_SHOP_ITEM, + SHOP_WARE_BABY_SHOP_ITEM, + SHOP_WARE_ETERNAL_HEART, + SHOP_WARE_CREDIT_CARD, + SHOP_WARE_SOUL_CARD +}; + +// A shop ware being priced or rolled: its kind, the shop slot it sells from (-1 for none, -2 for never discounted), +// the seed it rolls from and its price. +struct ShopOffer +{ + int price = 0; + int shopItemId = -1; + int subType = 0; + int variant = 0; + uint32_t seed = 0; +}; + +int room_shop_ware_roll(Room& room, ShopOffer& offer); +void room_shop_slots_init(Room& room); +void shop_offer_pick(Room& room, ShopOffer& offer); +int room_shop_item_price(Room& room, const ShopOffer& offer, Entity_Player* player); +int room_shop_discount(Room& room, int shopItemId, int price, Entity_Player* player); +void room_restock_trigger(Room& room, int gridIndex, int shopItemId); +void room_restock_partial(Room& room); +void game_random_room_move(Game& game, bool isErrorRoom, uint32_t seed, Entity_Player* player); +void npc_shopkeeper_update(Entity_NPC& npc); +Entity_Player* player_nearest_find(const Vector& position); diff --git a/src/room_state.cpp b/src/room_state.cpp index 8e53a0c..601acaf 100644 --- a/src/room_state.cpp +++ b/src/room_state.cpp @@ -11,6 +11,7 @@ #include "npc_ai.h" #include "room.h" #include "room_clear.h" +#include "room_special.h" #include #include #include @@ -21,18 +22,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; @@ -365,7 +356,7 @@ void Room::on_leave() if (shopRestockTimer > 0) { shopRestockTimer = -1; - reconstruction_missing("Room::ShopRestockPartial 008158a0"); + room_restock_partial(*this); } if (game.currentRoomIdx == ROOM_DEBUG_IDX || descriptor->visitedCount == 0) return; if (roomClearDelay >= 1 && roomClearDelay <= ROOM_CLEAR_DELAY_PENDING && !IsClear()) diff --git a/src/room_update.cpp b/src/room_update.cpp index f9e3862..df31f07 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -9,6 +9,7 @@ #include "manager.h" #include "room.h" #include "room_clear.h" +#include "room_special.h" #include "room_render.h" #include "seeds.h" #include @@ -102,17 +103,7 @@ constexpr int MAP_WIDTH = 13; // The run, room and stage values Update tells apart. constexpr ColorMod POOP_FX_COLOR = {{1, 1, 1, 3}, {0.7f, 0.1f, 0.9f, 1}, {0, 0, 0}}; -constexpr int COLLECTIBLE_FLUSH = 291; -constexpr int COLLECTIBLE_DATAMINER = 481; -constexpr int COLLECTIBLE_COUPON = 521; -constexpr int COLLECTIBLE_DEATHS_LIST = 530; -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 EFFECT_RAIN_DROP = 41; -constexpr int EFFECT_BLOOD_PARTICLE = 5; -constexpr int EFFECT_FALLING_EMBER = 87; constexpr int CHALLENGE_SEEING_DOUBLE = 40; constexpr int SOUND_BOSS_ROAR = 190; constexpr int SOUND_THUNDER = 472; @@ -134,9 +125,6 @@ constexpr int BOSS_THE_BEAST_ROOM = 91; constexpr int ROOM_IDX_DUNGEON_BEAST = -16; constexpr int GREED_LAST_STAGE = 5; constexpr int GREED_LAST_STAGE_ID = 10; -constexpr uint32_t LEVEL_STATE_GREED_MONSTRO_SPAWNED = 1u << 12; -constexpr uint32_t LEVEL_STATE_MAMA_MEGA = 1u << 14; -constexpr uint32_t LEVEL_STATE_LEVEL_START_TRIGGERED = 1u << 19; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_MAMA_MEGA = 1u << 14; constexpr int BACKDROP_DANK_DEPTHS = 9; constexpr int BACKDROP_ERROR_ROOM = 26; @@ -149,11 +137,8 @@ constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; // 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; @@ -162,7 +147,6 @@ 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), @@ -301,15 +285,15 @@ void Room::grid_paths_decay() void Room::first_frame_update() { bool isGreedBossPending = is_greed() && g_game->stage == STAGE_ULTRA_GREED && descriptor->data->subtype == 0 && - !(g_game->levelStateFlags & LEVEL_STATE_GREED_MONSTRO_SPAWNED); + !(g_game->levelStateFlags & 1u << LEVEL_STATE_GREED_MONSTRO_SPAWNED); if (roomType == ROOM_BOSS && descriptor->visitedCount == 1 && !isGreedBossPending && bossId != 0) { int sound = SOUND_BOSS_ROAR; seed_fart_sound_override(&sound); g_manager->sfxManager.Play(sound); } - if (g_game->levelStateFlags & LEVEL_STATE_LEVEL_START_TRIGGERED) return; - g_game->levelStateFlags |= LEVEL_STATE_LEVEL_START_TRIGGERED; + if (g_game->levelStateFlags & 1u << LEVEL_STATE_LEVEL_START_TRIGGERED) return; + g_game->levelStateFlags |= 1u << LEVEL_STATE_LEVEL_START_TRIGGERED; if (!g_game->myosotisPickups.empty()) reconstruction_missing("Room::Update 00802980: the Myosotis pickups"); } @@ -604,7 +588,7 @@ static void weather_update(Room& room) (isWomb && stageType == STAGE_TYPE_AFTERBIRTH && (Random() & 7) == 0) || (isBasement && stageType == STAGE_TYPE_REPENTANCE && (Random() & 3) == 0) || (isBasement && stageType == STAGE_TYPE_REPENTANCE_B && (Random() & 3) == 0); - if (isDrop) weather_drop_spawn(room, EFFECT_RAIN_DROP); + if (isDrop) weather_drop_spawn(room, EFFECT_WATER_DROPLET); else if (isBasement && stageType == STAGE_TYPE_AFTERBIRTH && Random() % DROP_CHANCE_DROSS == 0) weather_drop_spawn(room, EFFECT_FALLING_EMBER); } @@ -710,7 +694,7 @@ static void greed_wave_update(Room& room) if (!is_greed()) return; if (room.greedWaveTimer > 0) reconstruction_missing("Room::UpdateGreedWave 00801ee0: the wave timer"); if (game.stage != STAGE_ULTRA_GREED || room.roomType != ROOM_BOSS) return; - if (game.levelStateFlags & LEVEL_STATE_GREED_MONSTRO_SPAWNED) return; + if (game.levelStateFlags & 1u << LEVEL_STATE_GREED_MONSTRO_SPAWNED) return; for (size_t i = 0; i < game.playerManager.playerList.size(); i++) if (game.GetPlayer((int)i)->pos.y < 320) reconstruction_missing("Room::UpdateGreedWave 00801ee0: Ultra Greed"); } @@ -829,7 +813,7 @@ void Room::Update() } walls_bleed_update(*this); flood_update(*this); - bool isMamaMega = game.levelStateFlags & LEVEL_STATE_MAMA_MEGA && !(descriptor->flags & ROOM_DESCRIPTOR_FLAG_MAMA_MEGA); + bool isMamaMega = game.levelStateFlags & 1u << LEVEL_STATE_MAMA_MEGA && !(descriptor->flags & ROOM_DESCRIPTOR_FLAG_MAMA_MEGA); if (isMamaMega && isInitialized && game.frameCount - enterFrame == 1 && !game.IsPaused()) reconstruction_missing("Room::MamaMegaExplosion 00820910"); if (slowdownDuration > 0) slowdownDuration--; @@ -839,7 +823,7 @@ void Room::Update() if (shopRestockTimer > 0 && --shopRestockTimer < 1) { shopRestockTimer = -1; - reconstruction_missing("Room::ShopRestockPartial 008158a0"); + room_restock_partial(*this); } coupon_update(*this); if (unknown7230 > 0) diff --git a/src/seeds.cpp b/src/seeds.cpp index f9395be..dd42991 100644 --- a/src/seeds.cpp +++ b/src/seeds.cpp @@ -1,4 +1,5 @@ #include "seeds.h" +#include "entity_player.h" #include "game.h" #include "manager.h" #include "platform.h" @@ -20,7 +21,6 @@ constexpr uint32_t SEED_DIGIT_MASK = 31; constexpr int SEED_CODE_GAP = 4; constexpr size_t SEED_CODE_LENGTH = 9; -constexpr uint32_t CHALLENGE_RED_REDEMPTION = 44; constexpr uint32_t LABYRINTH_STAGE_END = 8; constexpr int LANGUAGE_ENGLISH = 0; diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 5a16648..06a45c1 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -21,6 +21,37 @@ enum SoundLoop SOUND_LOOP }; +// The sounds several files play (Lua's SoundEffect). +enum SoundId : int +{ + SOUND_BOOK_PAGE_TURN_12 = 8, + SOUND_DEATH_BURST_LARGE = 28, + SOUND_FART = 37, + SOUND_FETUS_LAND = 40, + SOUND_FIREDEATH_HISS = 43, + SOUND_FORESTBOSS_STOMPS = 48, + SOUND_HOLY = 54, + SOUND_ISAAC_HURT_GRUNT = 55, + SOUND_DIP_HURT = 60, + SOUND_POWERUP1 = 128, + SOUND_POWERUP_SPEWER = 132, + SOUND_ROCK_CRUMBLE = 137, + SOUND_TEAR_IMPACTS = 150, + SOUND_UNLOCK = 156, + SOUND_VAMP_GULP = 157, + SOUND_BATTERYCHARGE = 170, + SOUND_BEEP = 171, + SOUND_BLOODSHOOT = 178, + SOUND_ERROR_BUZZ = 187, + SOUND_PLOP = 237, + SOUND_SHELLGAME = 252, + SOUND_SPLATTER = 258, + SOUND_THUMBS_DOWN = 267, + SOUND_THUMBSUP = 268, + SOUND_GOLD_HEART_DROP = 466, + SOUND_SHINYROCK_SHIMMER = 1014 +}; + // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. // A sound the game holds (SoundInstance): its source, and whether it was asked to play or paused, since a source only // reports playing while a voice runs it. diff --git a/src/stage_transition.cpp b/src/stage_transition.cpp index e52a81d..e2ff3fc 100644 --- a/src/stage_transition.cpp +++ b/src/stage_transition.cpp @@ -11,6 +11,7 @@ #include "render_passes.h" #include "room.h" #include "seeds.h" +#include #include constexpr int START_DURATION = 50; @@ -36,10 +37,7 @@ constexpr int SOUND_ASCENT_START = 615; constexpr int ACHIEVEMENT_NO_HEARTS_STAGES = 42; constexpr int ACHIEVEMENT_NO_DAMAGE_STAGES = 67; constexpr int ACHIEVEMENT_ALT_WOMB = 411; -constexpr uint32_t LEVEL_STATE_DAMAGED = 1 << 5; -constexpr int EFFECT_POOF01 = 15; -constexpr int EFFECT_DUST_CLOUD = 99; constexpr int POOF_SMALL = 2; constexpr int DUST_SPLASH = 1; constexpr float DRY_WATER_LIMIT = 0.2f; @@ -200,7 +198,7 @@ static void trapdoor_splash(GridEntity& trapDoor) } Entity* splash = exit_effect_spawn( - {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = Random()}); + {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_SPLASH, .seed = Random()}); splash->sprite.scale = vector_scale(splash->sprite.scale, 2); splash->Update(); @@ -216,7 +214,7 @@ static void trapdoor_splash(GridEntity& trapDoor) .velocity = vector_make(std::cos(angle) * speed, speed * std::sin(angle)), .subType = DUST_SPLASH, .type = ENTITY_EFFECT, - .variant = EFFECT_DUST_CLOUD, + .variant = EFFECT_WATER_SPLASH, .seed = seed})); drop->fallingAcceleration = SPLASH_FALL; drop->sprite.scale = vector_scale(drop->sprite.scale, 2); @@ -341,7 +339,7 @@ static void floor_records_update() if (game.isHeartPicked) game.stagesWithoutHeartsPicked = 0; else if (++game.stagesWithoutHeartsPicked > 1) persistent.TryUnlock(ACHIEVEMENT_NO_HEARTS_STAGES); - if (game.levelStateFlags & LEVEL_STATE_DAMAGED) game.stagesWithoutDamage = 0; + if (game.levelStateFlags & 1u << LEVEL_STATE_DAMAGED) game.stagesWithoutDamage = 0; else if (++game.stagesWithoutDamage > 1) persistent.TryUnlock(ACHIEVEMENT_NO_DAMAGE_STAGES); if (!isGreed && (int)game.stage == STAGE_WOMB_I && game.IsAltPath()) persistent.TryUnlock(ACHIEVEMENT_ALT_WOMB); } @@ -416,7 +414,7 @@ static void landing_update(StageTransition& transition) else player.isControlsEnabled = true; }); if (isLanded) transition.state = STAGE_TRANSITION_NONE; - game.itemOverlay.Update(0); + game.itemOverlay.Update(OVERLAY_UPDATE_PLAY); } // 0092f1c0 Steps the transition a frame, the HUD redrawn in full while the screen fades. diff --git a/src/stat_hud.cpp b/src/stat_hud.cpp index f0f842c..d134e95 100644 --- a/src/stat_hud.cpp +++ b/src/stat_hud.cpp @@ -31,8 +31,6 @@ constexpr float CHANGE_SLIDE = -20; constexpr float SECOND_PLAYER_SHADE = 0.8f; constexpr float CHANGE_BRIGHT = 0.9f; constexpr float CHANGE_DIM = 0.03f; -constexpr int COLLECTIBLE_DUALITY = 498; -constexpr int TRINKET_ROSARY_BEAD = 7; constexpr const char* FORMAT_STAT = "%.2f"; constexpr const char* FORMAT_STAT_CHANGE = "+%.2f"; constexpr const char* FORMAT_PERCENT = "%.1f%%"; diff --git a/src/weapon.cpp b/src/weapon.cpp index b38e198..2265198 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -37,15 +37,8 @@ constexpr int SEEDED_VARIANT_NONE = -1; constexpr int SEEDED_VARIANT_SPEEDY = 2; constexpr int COLLECTIBLE_EYE_DROPS = 600; -constexpr int COLLECTIBLE_EYE_OF_THE_OCCULT = 572; -constexpr int COLLECTIBLE_EPIPHORA = 368; -constexpr int COLLECTIBLE_IPECAC = 149; constexpr int COLLECTIBLE_KIDNEY_STONE_WEAPON = 440; -constexpr int COLLECTIBLE_LEAD_PENCIL = 444; -constexpr int COLLECTIBLE_MARKED = 394; -constexpr int COLLECTIBLE_NUMBER_ONE = 6; constexpr int COLLECTIBLE_POLYPHEMUS = 169; -constexpr int COLLECTIBLE_STAPLER = 708; constexpr int COLLECTIBLE_ANALOG_STICK = 465; constexpr int COLLECTIBLE_TECHNOLOGY_2 = 152; constexpr int COLLECTIBLE_ISAACS_TEARS = 323;