From 8ae02a842291f672c7d271db0a75a597a65f4d65 Mon Sep 17 00:00:00 2001 From: shweet Date: Fri, 20 Nov 2026 16:32:45 -0500 Subject: [PATCH] Curation round 13: grid entities, more enemies, Caves, boss helpers and five bosses, chests and costumes, curses and alt stages, the Lua API --- generated-src/bit_set128.cpp | 147 ---- generated-src/classes.h | 142 +--- generated-src/loot_list.cpp | 72 -- generated-src/npc_helper.cpp | 31 +- generated-src/stubs.cpp | 135 ---- generated-src/vector.cpp | 7 - generated-src/weighted_outcome_picker.cpp | 107 --- src/backdrop.cpp | 34 +- src/backdrop.h | 69 +- src/beast_arena.cpp | 1 - src/bomb_explosion.cpp | 12 +- src/boss_ai.h | 30 + src/boss_baby_plum.cpp | 322 ++++++++ src/boss_death.cpp | 1 - src/boss_dingle.cpp | 391 ++++++++++ src/boss_duke.cpp | 382 +++++++++ src/boss_gemini.cpp | 1 - src/boss_larry_jr.cpp | 469 +++++++++++ src/boss_little_horn.cpp | 503 ++++++++++++ src/boss_monstro.cpp | 36 +- src/boss_pool.cpp | 8 +- src/entity.cpp | 18 - src/entity.h | 38 +- src/entity_bomb.cpp | 27 +- src/entity_bomb.h | 3 + src/entity_collision.cpp | 13 +- src/entity_combat.cpp | 45 +- src/entity_effect.h | 13 + src/entity_effect_ambient.cpp | 12 +- src/entity_effect_combat.cpp | 2 - src/entity_factory.cpp | 45 +- src/entity_familiar.cpp | 105 ++- src/entity_familiar.h | 5 +- src/entity_npc.cpp | 78 +- src/entity_npc.h | 8 +- src/entity_npc_boss.cpp | 307 ++++++++ src/entity_pickup.cpp | 63 +- src/entity_pickup.h | 8 + src/entity_pickup_chest.cpp | 574 ++++++++++++++ src/entity_pickup_shop.cpp | 5 +- src/entity_player.cpp | 10 +- src/entity_player.h | 44 +- src/entity_player_actives.cpp | 21 +- src/entity_player_costumes.cpp | 244 ++++++ src/entity_player_damage.cpp | 23 +- src/entity_player_frame.cpp | 33 +- src/entity_player_health.cpp | 315 +++++++- src/entity_player_hold.cpp | 66 ++ src/entity_player_kills.cpp | 26 +- src/entity_player_missing.cpp | 18 - src/entity_player_pockets.cpp | 3 +- src/entity_player_room.cpp | 4 +- src/entity_projectile.cpp | 3 + src/entity_tear.cpp | 21 +- src/entity_tear.h | 2 + src/familiar_missing.cpp | 6 - src/fx_layers.cpp | 19 +- src/game.cpp | 12 +- src/game.h | 4 +- src/game_exit.cpp | 147 ++++ src/game_over.cpp | 7 +- src/game_restore.cpp | 20 +- src/game_save.cpp | 3 +- src/game_state.cpp | 4 +- src/game_state_player.h | 2 +- src/game_transition.cpp | 7 +- src/game_update.cpp | 3 - src/grid_entity.cpp | 315 +++++++- src/grid_entity_decoration.cpp | 8 +- src/grid_entity_door.cpp | 25 +- src/grid_entity_lock.cpp | 88 ++- src/grid_entity_lock.h | 2 +- src/grid_entity_pit.cpp | 351 ++++++++- src/grid_entity_poop.cpp | 900 +++++++++++++++++++++- src/grid_entity_poop.h | 49 +- src/grid_entity_rock.cpp | 291 ++++++- src/grid_entity_spikes.cpp | 155 +++- src/grid_entity_spikes.h | 3 + src/grid_entity_statue.cpp | 120 ++- src/grid_entity_tnt.cpp | 1 - src/grid_entity_trap_door.cpp | 6 - src/grid_entity_wall.cpp | 3 - src/grid_entity_web.cpp | 52 +- src/hud.cpp | 2 - src/item_overlay.cpp | 2 - src/item_overlay.h | 5 +- src/item_pool.cpp | 3 +- src/level.cpp | 312 ++++---- src/level.h | 67 +- src/level_curses.cpp | 185 +++++ src/level_stage.cpp | 15 +- src/loot_list.h | 37 + src/lua_api.cpp | 175 +++++ src/lua_api.h | 361 +++++++++ src/lua_api_bit_set128.cpp | 56 ++ src/lua_api_color.cpp | 55 ++ src/lua_api_entities.cpp | 276 +++++++ src/lua_api_entity.cpp | 258 +++++++ src/lua_api_entity_player.cpp | 401 ++++++++++ src/lua_api_game.cpp | 174 +++++ src/lua_api_isaac.cpp | 650 ++++++++++++++++ src/lua_api_item_config.cpp | 131 ++++ src/lua_api_rng.cpp | 18 + src/lua_api_room.cpp | 289 +++++++ src/lua_api_sprite.cpp | 144 ++++ src/lua_api_vector.cpp | 69 ++ src/lua_callbacks.cpp | 307 +++++--- src/lua_engine.cpp | 25 +- src/lua_engine.h | 62 +- src/manager.cpp | 1 - src/minimap.cpp | 4 +- src/nightmare_scene.cpp | 12 +- src/npc_ai.cpp | 48 +- src/npc_ai.h | 4 +- src/npc_army_fly.cpp | 229 ++++++ src/npc_baby_long_legs.cpp | 151 ++++ src/npc_basement.h | 71 +- src/npc_boil.cpp | 331 ++++++++ src/npc_boom_fly.cpp | 471 +++++++++++ src/npc_brain.cpp | 206 +++++ src/npc_bulb.cpp | 231 ++++++ src/npc_caves.h | 37 + src/npc_collision.cpp | 12 - src/npc_fireplace.cpp | 3 +- src/npc_fly.cpp | 5 +- src/npc_gaper.cpp | 123 ++- src/npc_globin.cpp | 313 ++++++++ src/npc_gusher.cpp | 9 +- src/npc_host.cpp | 304 ++++++++ src/npc_maggot.cpp | 875 +++++++++++++++++++++ src/npc_mama_fly.cpp | 198 +++++ src/npc_maw.cpp | 133 ++++ src/npc_movable_tnt.cpp | 125 +++ src/npc_mushroom.cpp | 128 +++ src/npc_portal.cpp | 188 +++++ src/npc_ring_fly.cpp | 111 +++ src/npc_round_worm.cpp | 513 ++++++++++++ src/npc_skinny.cpp | 385 +++++++++ src/npc_sub_horf.cpp | 176 +++++ src/npc_swarm.cpp | 133 ++++ src/path_finder.cpp | 46 +- src/path_finder.h | 2 +- src/player_manager.h | 1 + src/player_stats.cpp | 42 + src/player_stats.h | 35 + src/rail_manager.cpp | 2 - src/revive_player_menu.cpp | 3 +- src/room.cpp | 91 +-- src/room_clear.cpp | 34 +- src/room_config.cpp | 23 +- src/room_grid.cpp | 27 + src/room_grid.h | 1 + src/room_lighting.cpp | 3 - src/room_render.cpp | 160 +++- src/room_special.cpp | 3 - src/room_state.cpp | 26 +- src/room_transition.cpp | 1 - src/room_update.cpp | 32 +- src/sfx_manager.h | 66 +- src/stage_transition.cpp | 8 +- 160 files changed, 16231 insertions(+), 1689 deletions(-) delete mode 100644 generated-src/loot_list.cpp delete mode 100644 generated-src/weighted_outcome_picker.cpp create mode 100644 src/boss_baby_plum.cpp create mode 100644 src/boss_dingle.cpp create mode 100644 src/boss_duke.cpp create mode 100644 src/boss_larry_jr.cpp create mode 100644 src/boss_little_horn.cpp create mode 100644 src/entity_npc_boss.cpp create mode 100644 src/entity_pickup_chest.cpp create mode 100644 src/entity_player_costumes.cpp create mode 100644 src/entity_player_hold.cpp create mode 100644 src/game_exit.cpp create mode 100644 src/level_curses.cpp create mode 100644 src/loot_list.h create mode 100644 src/lua_api.cpp create mode 100644 src/lua_api.h create mode 100644 src/lua_api_bit_set128.cpp create mode 100644 src/lua_api_color.cpp create mode 100644 src/lua_api_entities.cpp create mode 100644 src/lua_api_entity.cpp create mode 100644 src/lua_api_entity_player.cpp create mode 100644 src/lua_api_game.cpp create mode 100644 src/lua_api_isaac.cpp create mode 100644 src/lua_api_item_config.cpp create mode 100644 src/lua_api_rng.cpp create mode 100644 src/lua_api_room.cpp create mode 100644 src/lua_api_sprite.cpp create mode 100644 src/lua_api_vector.cpp create mode 100644 src/npc_army_fly.cpp create mode 100644 src/npc_baby_long_legs.cpp create mode 100644 src/npc_boil.cpp create mode 100644 src/npc_boom_fly.cpp create mode 100644 src/npc_brain.cpp create mode 100644 src/npc_bulb.cpp create mode 100644 src/npc_caves.h create mode 100644 src/npc_globin.cpp create mode 100644 src/npc_host.cpp create mode 100644 src/npc_maggot.cpp create mode 100644 src/npc_mama_fly.cpp create mode 100644 src/npc_maw.cpp create mode 100644 src/npc_movable_tnt.cpp create mode 100644 src/npc_mushroom.cpp create mode 100644 src/npc_portal.cpp create mode 100644 src/npc_ring_fly.cpp create mode 100644 src/npc_round_worm.cpp create mode 100644 src/npc_skinny.cpp create mode 100644 src/npc_sub_horf.cpp create mode 100644 src/npc_swarm.cpp create mode 100644 src/player_stats.cpp create mode 100644 src/player_stats.h diff --git a/generated-src/bit_set128.cpp b/generated-src/bit_set128.cpp index b444528..0c79162 100644 --- a/generated-src/bit_set128.cpp +++ b/generated-src/bit_set128.cpp @@ -70,23 +70,6 @@ BitSet128 * BitSet128::operator_or(BitSet128 *outResult, BitSet128 *a, BitSet128 return outResult; } -// 00592200 -BitSet128 * BitSet128::__bnot(BitSet128 *out) -{ - uint64_t highBits; - uint32_t highBitsUpper; - uint64_t lowBits; - - lowBits = this->_l; - *GHIDRA_CAST((GHIDRA_INT(&out->_l) + 4)) = ~*GHIDRA_CAST((GHIDRA_INT(&this->_l) + 4)); - highBits = this->_h; - highBitsUpper = *GHIDRA_CAST((GHIDRA_INT(&this->_h) + 4)); - *GHIDRA_CAST(&out->_l) = ~GHIDRA_UINT(lowBits); - *GHIDRA_CAST(&out->_h) = ~GHIDRA_UINT(highBits); - *GHIDRA_CAST((GHIDRA_INT(&out->_h) + 4)) = ~highBitsUpper; - return out; -} - // 00592230 uint8_t BitSet128::IsZero() { @@ -96,133 +79,3 @@ uint8_t BitSet128::IsZero() } return 0; } - -// 0085e490 -uint8_t * BitSet128::__tostring() -{ - sprintf_s(&DAT_00c82778,0x100,GHIDRA_CAST("BitSet128: %016llx%016llx")); - return &DAT_00c82778; -} - -// 0085e4d0 -uint32_t BitSet128::__band(BitSet128 *param_1, BitSet128 *param_2) -{ - BitSet128 *in_ECX; - uint32_t extraout_ECX; - - operator_and(param_1,in_ECX,param_2); - return extraout_ECX; -} - -// 0085e4f0 -uint32_t BitSet128::__bor(BitSet128 *param_1, BitSet128 *param_2) -{ - BitSet128 *in_ECX; - uint32_t extraout_ECX; - - operator_or(param_1,in_ECX,param_2); - return extraout_ECX; -} - -// 0085e510 -uint32_t BitSet128::__bxor(uint32_t param_1, uint32_t param_2) -{ - uint32_t extraout_ECX; - - FUN_0085dae0(param_2); - return extraout_ECX; -} - -// 0085e530 -uint8_t BitSet128::__eq(BitSet128 *other) -{ - if ((((GHIDRA_INT(this->_l) == GHIDRA_INT(other->_l)) && - (*GHIDRA_CAST((GHIDRA_INT(&this->_l) + 4)) == *GHIDRA_CAST((GHIDRA_INT(&other->_l) + 4)))) && - (GHIDRA_INT(this->_h) == GHIDRA_INT(other->_h))) && - (*GHIDRA_CAST((GHIDRA_INT(&this->_h) + 4)) == *GHIDRA_CAST((GHIDRA_INT(&other->_h) + 4)))) { - return 1; - } - return 0; -} - -// 0085e560 -uint8_t BitSet128::Get(uint32_t bit) -{ - uint32_t maskHigh; - uint32_t maskHigh; - uint32_t uVar2; - bool isClear; - - if (GHIDRA_INT(bit) < 0x40) { - uVar2 = 1 << (bit & 0x1f); - maskHigh = 0; - if (0x1f < bit) { - maskHigh = uVar2; - } - uVar2 = uVar2 ^ maskHigh; - if (0x3f < bit) { - maskHigh = uVar2; - } - isClear = (uVar2 & GHIDRA_UINT(this->_l)) == 0 && (maskHigh & *GHIDRA_CAST((GHIDRA_INT(&this->_l) + 4))) == 0; - } - else { - uVar2 = bit - 0x40; - maskHigh = 1 << (uVar2 & 0x1f); - maskHigh = 0; - if (0x1f < uVar2) { - maskHigh = maskHigh; - } - maskHigh = maskHigh ^ maskHigh; - if (0x3f < uVar2) { - maskHigh = maskHigh; - } - isClear = (maskHigh & GHIDRA_UINT(this->_h)) == 0 && (maskHigh & *GHIDRA_CAST((GHIDRA_INT(&this->_h) + 4))) == 0; - } - if (isClear) { - return 0; - } - return 1; -} - -// 0085e5c0 -void BitSet128::Set(uint32_t bit, uint8_t value) -{ - uint32_t *puVar1; - uint32_t maskHigh; - uint32_t maskHigh; - uint32_t uVar3; - - if (value != 0) { - FUN_0060cc30(bit); - return; - } - if (0x3f < bit) { - maskHigh = bit - 0x40; - maskHigh = 1 << (maskHigh & 0x1f); - uVar3 = 0; - if (0x1f < maskHigh) { - uVar3 = maskHigh; - } - maskHigh = maskHigh ^ uVar3; - if (0x3f < maskHigh) { - uVar3 = maskHigh; - } - *GHIDRA_CAST(&this->_h) = GHIDRA_UINT(this->_h) & ~maskHigh; - puVar1 = GHIDRA_CAST((GHIDRA_INT(&this->_h) + 4)); - *puVar1 = *puVar1 & ~uVar3; - return; - } - maskHigh = 1 << (bit & 0x1f); - maskHigh = 0; - if (0x1f < bit) { - maskHigh = maskHigh; - } - maskHigh = maskHigh ^ maskHigh; - if (0x3f < bit) { - maskHigh = maskHigh; - } - *GHIDRA_CAST(&this->_l) = GHIDRA_UINT(this->_l) & ~maskHigh; - puVar1 = GHIDRA_CAST((GHIDRA_INT(&this->_l) + 4)); - *puVar1 = *puVar1 & ~maskHigh; - return; -} diff --git a/generated-src/classes.h b/generated-src/classes.h index b3b1475..34f7e4c 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -149,6 +149,7 @@ struct BossPoolState; struct BossPool_Entry; struct BossPool_Pool; struct BufferedStream; +struct ButterBeanFart; struct CLIENT_ID; struct Camera; struct CameraBounds; @@ -180,6 +181,7 @@ struct CoopAward; struct CoopJoinSlot; struct CostumeItem; struct CostumeSpriteDesc; +struct CostumeWalk; struct CraftingRecipe; struct Cutscene; struct CutsceneEntry; @@ -252,6 +254,7 @@ struct FXTile; struct FXVein; struct FamiliarCount; struct FamiliarData; +struct Fart; struct File; struct FileSymbolInfo; struct FileSystem; @@ -384,13 +387,16 @@ struct LobbyPasswordPrompt; struct LobbySettings; struct LocustConfig; struct LocustEffect; +struct LootEntry; struct LootList; struct LuaCardDraw; struct LuaCollectibleDraw; struct LuaEngine; +struct LuaIgnored; struct LuaItemUse; struct LuaMod; struct LuaRef; +struct LuaRoomList; struct MTRNG; struct Manager; struct MapNodeIntInt; @@ -455,6 +461,7 @@ struct OnlineChat; struct OnlineChatMessage; struct OnlineEmotes; struct OnlineStatsScreen; +struct OnlineUserStats; struct OptionsConfig; struct PMD; struct ParticleSpawn; @@ -486,6 +493,7 @@ struct PocketItemConfig; struct Point; struct PoolDesc; struct PoolItem; +struct PoopHit; struct Popup; struct PopupButton; struct PopupButtons; @@ -3194,12 +3202,6 @@ LAYOUT32(offsetof(LobbySettings, _maxPlayers) == 0xc); LAYOUT32(offsetof(LobbySettings, _seed) == 0x18); LAYOUT32(offsetof(LobbySettings, _password) == 0x30); -struct LootList { - LootList(void *other); // 006c20e0 - LootList() = default; -}; - - struct LuaRef { void push(void *luaState); // 006a80f0 uint8_t equals(void *otherState, int otherRef); // 00897540 @@ -4371,11 +4373,6 @@ struct Weapon_UrnOfSouls { }; LAYOUT32(sizeof(Weapon_UrnOfSouls) == 0x54); -struct WeightedOutcomePicker { - uint32_t PickOutcome(RNG rng); // 0049cbf0 -}; - - struct Window { int get_framebuffer_height(); // 00a193c0 }; @@ -5982,11 +5979,6 @@ int FUN_004253d0(); // 004253d0 void FUN_00425410(); // 00425410 void online_stats_destroy(void *self); // 00425430 void online_stats_register_players(); // 004257b0 -void online_stats_add_user(void *self, uint32_t userIdLow, uint32_t userIdHigh); // 004259b0 -int FUN_00425a70(int param_1, int param_2); // 00425a70 -void Player_stats_add(void *onlineStats, uint32_t statId, Entity_Player *player, float amount); // 00425ac0 -uint64_t player_get_net_user_id(Entity_Player *player); // 004264c0 -int * FUN_00426560(int param_1, int param_2); // 00426560 void FUN_00427290(); // 00427290 int holiday_get_current(uint32_t yyyymmdd); // 00427870 void FUN_00428560(uint32_t *param_1, uint32_t param_2); // 00428560 @@ -6255,7 +6247,6 @@ void FUN_004d7450(void *param_1, int param_2); // 004d7450 void Catch_All_004d7683(); // 004d7683 void FUN_004d76c0(); // 004d76c0 bool FUN_004d7760(); // 004d7760 -Entity * spawn_small_maggot_jump(Vector *position, float yPositionOffset, Vector *targetPosition); // 004d8910 Entity * spawn_small_maggot(Vector *position, float height, Vector *velocity, float heightVelocity); // 004d8b50 void FUN_004e07a0(Vector *param_1); // 004e07a0 void FUN_004e46b0(); // 004e46b0 @@ -6880,12 +6871,9 @@ uint32_t FUN_00710f70(int param_1); // 00710f70 void FUN_00711530(int param_1); // 00711530 uint32_t FUN_00711740(); // 00711740 void FUN_007135d0(uint32_t param_1, uint8_t param_2, int *param_3); // 007135d0 -void spawn_poop_rewards(uint32_t param_1, int param_2, int param_3, char param_4, uint32_t param_5, int param_6); // 00716db0 -void FUN_00718d20(float *param_1); // 00718d20 void FUN_00718ed0(uint32_t param_1); // 00718ed0 uint32_t FUN_00718ee0(); // 00718ee0 void FUN_0071df70(uint8_t param_1); // 0071df70 -int FUN_0071df80(); // 0071df80 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 @@ -7019,7 +7007,6 @@ void input_state_reset(void *self); // 00754980 void FUN_00757980(uint32_t *param_1); // 00757980 void FUN_00757a10(); // 00757a10 uint32_t FUN_00758590(); // 00758590 -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 @@ -7321,71 +7308,44 @@ void FUN_0085e1d0(char param_1); // 0085e1d0 void FUN_0085e2a0(uint32_t *param_1); // 0085e2a0 void FUN_0085e340(uint32_t param_1); // 0085e340 void FUN_0085e3b0(uint32_t param_1); // 0085e3b0 -void lua_searcher_resources_scripts(uint8_t *param_1); // 0085f0f0 -uint32_t FUN_0085fcc0(); // 0085fcc0 -uint32_t FUN_0085fec0(uint32_t param_1); // 0085fec0 -uint32_t FUN_008601f0(uint32_t param_1); // 008601f0 -uint32_t FUN_008603d0(uint32_t param_1); // 008603d0 -void FUN_00860f00(int param_1); // 00860f00 uint32_t Catch_00860f8b(); // 00860f8b -void FUN_00860fe0(int param_1, uint32_t *param_2); // 00860fe0 uint32_t Catch_00861076(); // 00861076 -void FUN_008615e0(int param_1); // 008615e0 uint32_t Catch_0086166f(); // 0086166f -void FUN_008616c0(int param_1); // 008616c0 uint32_t Catch_0086174f(); // 0086174f -void FUN_008617a0(int param_1, uint32_t *param_2); // 008617a0 uint32_t Catch_00861837(); // 00861837 -void FUN_00861970(int param_1); // 00861970 uint32_t Catch_008619ff(); // 008619ff -void FUN_00861a50(uint32_t param_1, uint32_t *param_2); // 00861a50 uint32_t Catch_00861b88(); // 00861b88 void FUN_00861bda(); // 00861bda void FUN_00861c23(); // 00861c23 -void FUN_00861ea0(int param_1); // 00861ea0 uint32_t Catch_00861f2f(); // 00861f2f -void FUN_00861f80(int param_1); // 00861f80 uint32_t Catch_0086200f(); // 0086200f -void FUN_00862060(uint32_t param_1, uint32_t *param_2); // 00862060 uint32_t Catch_00862198(); // 00862198 void FUN_008621ea(); // 008621ea void FUN_00862233(); // 00862233 -void FUN_008624b0(int param_1); // 008624b0 uint32_t Catch_0086253f(); // 0086253f -void FUN_00862590(int param_1); // 00862590 uint32_t Catch_0086261f(); // 0086261f -void FUN_00862670(int param_1, uint32_t *param_2); // 00862670 uint32_t Catch_00862707(); // 00862707 void FUN_00862d0a(); // 00862d0a void FUN_00862d53(); // 00862d53 -void FUN_008635a0(int param_1); // 008635a0 uint32_t Catch_0086362b(); // 0086362b uint32_t Catch_00863879(); // 00863879 -void FUN_00863be0(int param_1); // 00863be0 uint32_t Catch_00863c6e(); // 00863c6e -void FUN_00863cc0(uint32_t param_1, uint32_t param_2, uint32_t param_3); // 00863cc0 uint32_t Catch_00863d4e(); // 00863d4e -void FUN_00864130(int param_1); // 00864130 uint32_t Catch_008641bb(); // 008641bb -void FUN_00864210(int param_1, uint32_t *param_2); // 00864210 uint32_t Catch_008642a4(); // 008642a4 uint32_t Catch_00864682(); // 00864682 uint8_t FUN_00864d80(uint32_t param_1, uint32_t param_2, uint32_t param_3, float *param_4); // 00864d80 uint8_t * Catch_00864e6d(); // 00864e6d -void FUN_00864fc0(uint32_t param_1); // 00864fc0 uint32_t Catch_0086504e(); // 0086504e -void FUN_008650a0(uint32_t param_1); // 008650a0 uint32_t Catch_0086512e(); // 0086512e uint8_t * Catch_008655b7(); // 008655b7 char * FUN_00865660(char *param_1, uint32_t *param_2); // 00865660 void FUN_00865aad(); // 00865aad void FUN_00865c61(); // 00865c61 -uint32_t FUN_00866220(uint32_t *param_1, uint32_t *param_2); // 00866220 uint32_t Catch_00866364(); // 00866364 uint8_t FUN_008663b6(); // 008663b6 void FUN_00866474(); // 00866474 uint8_t * Catch_0086675e(); // 0086675e -bool FUN_008667d0(Entity *param_1); // 008667d0 uint32_t Catch_008668e0(); // 008668e0 void FUN_0086e4d0(); // 0086e4d0 void FUN_00870f21(); // 00870f21 @@ -8396,7 +8356,6 @@ uint32_t FUN_008a9180(void *param_1); // 008a9180 uint32_t FUN_008a91f0(void *param_1); // 008a91f0 uint32_t FUN_008a9240(void *param_1); // 008a9240 uint32_t FUN_008a92b0(void *param_1); // 008a92b0 -uint32_t FUN_008a9360(void *param_1); // 008a9360 uint32_t FUN_008a9440(void *param_1); // 008a9440 uint32_t FUN_008a9520(void *param_1); // 008a9520 uint32_t FUN_008a95f0(void *param_1); // 008a95f0 @@ -8766,17 +8725,13 @@ int FUN_008bb070(); // 008bb070 int FUN_008bb0d0(); // 008bb0d0 bool FUN_008bb130(); // 008bb130 uint32_t FUN_008bb1c0(void *param_1); // 008bb1c0 -uint32_t FUN_008bb260(uint32_t param_1); // 008bb260 uint32_t FUN_008bb2e0(void *param_1); // 008bb2e0 uint32_t FUN_008bb340(void *param_1); // 008bb340 -uint32_t FUN_008bb3b0(uint32_t param_1); // 008bb3b0 uint32_t FUN_008bb420(void *param_1); // 008bb420 uint32_t FUN_008bb480(void *param_1); // 008bb480 uint32_t FUN_008bb4f0(uint32_t param_1); // 008bb4f0 uint32_t FUN_008bb570(uint32_t param_1); // 008bb570 -uint32_t FUN_008bb5c0(uint32_t param_1); // 008bb5c0 uint32_t FUN_008bb720(uint32_t param_1); // 008bb720 -uint32_t FUN_008bb770(void *param_1); // 008bb770 uint32_t FUN_008bb900(void *param_1); // 008bb900 uint32_t FUN_008bb960(void *param_1); // 008bb960 uint32_t FUN_008bb9c0(void *param_1); // 008bb9c0 @@ -8785,7 +8740,6 @@ uint32_t FUN_008bba80(void *param_1); // 008bba80 uint32_t FUN_008bbb20(void *param_1); // 008bbb20 uint32_t FUN_008bbbc0(void *param_1); // 008bbbc0 uint32_t FUN_008bbc60(void *param_1); // 008bbc60 -uint32_t FUN_008bbcf0(uint32_t param_1); // 008bbcf0 uint32_t FUN_008bbd60(uint32_t param_1); // 008bbd60 uint32_t FUN_008bbdb0(void *param_1); // 008bbdb0 uint32_t FUN_008bbe10(void *param_1); // 008bbe10 @@ -8799,7 +8753,6 @@ uint32_t FUN_008bc130(void *param_1); // 008bc130 uint32_t FUN_008bc1d0(void *param_1); // 008bc1d0 uint32_t FUN_008bc270(void *param_1); // 008bc270 uint32_t FUN_008bc2d0(void *param_1); // 008bc2d0 -uint32_t FUN_008bc330(uint32_t param_1); // 008bc330 uint32_t FUN_008bc3c0(void *param_1); // 008bc3c0 uint32_t FUN_008bc420(void *param_1); // 008bc420 uint32_t FUN_008bc480(void *param_1); // 008bc480 @@ -9543,7 +9496,6 @@ void level_generator_rooms_shuffle(int param_1, int param_2); // 009b1b20 void Catch_All_009b1d88(); // 009b1d88 int FUN_009b1dc0(int param_1, int param_2, int param_3); // 009b1dc0 int FUN_009b5800(); // 009b5800 -void FUN_009b9150(); // 009b9150 uint32_t FUN_009b9450(int param_1); // 009b9450 void FUN_009b9f60(Entity *param_1); // 009b9f60 void FUN_009b9fc0(int param_1); // 009b9fc0 @@ -21419,12 +21371,6 @@ Entity_Laser * sprinkler_fire_laser(Entity_Familiar *familiar, float angle, floa void fly_head_pathfind_move(Entity_Familiar *familiar); // 0063d570 } namespace Input { -void IsButtonTriggered(uint32_t param_1, uint32_t param_2); // 0086fc70 -void IsButtonPressed(uint32_t param_1, uint32_t param_2); // 0086fca0 -float GetButtonValue(int button, int controllerIndex); // 0086fcd0 -void IsActionTriggered(uint32_t param_1, uint32_t param_2); // 0086fd10 -void IsActionPressed(uint32_t param_1, uint32_t param_2); // 0086fd40 -float GetActionValue(int action, int controllerId); // 0086fd70 uint8_t IsMouseBtnPressed(int button); // 0086fdb0 Vector * GetMousePosition(Vector *outPosition, uint8_t isGameCoords); // 0086fe50 } @@ -21436,53 +21382,7 @@ int Random(int Max); // 0067f010 Vector * GetAxisAlignedUnitVectorFromDir(Vector *outVector, int direction); // 0067f1d0 Vector * GetRandomPickupVelocity(Vector *outVelocity, Vector *position, uint32_t pickupVelType, RNG *rng); // 006ee440 Vector * GetCollectibleSpawnPosition(Vector *outPosition, Vector *target); // 006eeaa0 -void DebugString(); // 0086ef30 -int GetPlayer(void *L); // 0086ef50 -int GetFrameCount(); // 0086f090 -Entity * Spawn(int type, int variant, int subType, Vector *position, Vector *velocity, Entity *spawner); // 0086f0a0 -GridEntity * GridSpawn(int type, int variant, Vector *position, uint8_t isForced); // 0086f0d0 -void RenderText(std_string *text, float x, float y, float red, float green, float blue, float alpha); // 0086f1b0 -int GetTextWidth(std_string *text); // 0086f370 -Vector * GetRandomPosition(Vector *param_1); // 0086f3a0 -Vector * GetFreeNearPosition(Vector *param_1, Vector *param_2, float param_3); // 0086f3d0 -void Explode(Vector *position, Entity *source, float damage); // 0086f400 -void SetBuiltInCallbackState(int callbackid, uint8_t enabled); // 0086f4b0 -uint8_t GetBuiltInCallbackState(int callbackid); // 0086f4f0 -int GetEntityTypeByName(std_string *name); // 0086f520 -int GetEntityVariantByName(uint8_t *param_1); // 0086f5b0 -int GetTrinketIdByName(std_string *name); // 0086f6e0 -int GetPlayerTypeByName(std_string *name, uint8_t isTainted); // 0086f760 -int GetCardIdByName(std_string *name); // 0086f800 -uint32_t GetPillEffectByName(uint8_t *param_1); // 0086f880 -int GetChallengeIdByName(std_string *name); // 0086f900 -int GetCostumeIdByPath(std_string *path); // 0086f980 -int GetCurseIdByName(std_string *name); // 0086f9f0 -int GetMusicIdByName(std_string *name); // 0086fa50 -uint32_t GetSoundIdByName(uint8_t *param_1); // 0086fab0 -void * GetRoomEntities(void *unk); // 0086fb20 -int GetChallenge(); // 0086fc30 -void AddPillEffectToPool(int param_1); // 0086fc40 -uint32_t GetTime(); // 0086ffa0 -std_string * ExecuteCommand(std_string *outResult, std_string *command); // 00870020 -void ConsoleOutput(std_string *text); // 00870130 void ScreenToWorld(float *param_1, float *param_2); // 00870160 -Vector * WorldToScreen(Vector *outScreenPos, Vector *worldPos); // 00870220 -Vector * WorldToScreenDistance(Vector *outResult, Vector *distance); // 00870390 -Vector * WorldToRenderPosition(Vector *outPos, Vector *worldPos); // 008703c0 -Vector * ScreenToWorldDistance(Vector *outResult, Vector *screenDistance); // 008704c0 -uint32_t FindInRadius(void *param_1); // 008704f0 -uint32_t FindByType(void *param_1); // 008707b0 -uint32_t CountEntities(void *param_1); // 00870b40 -int CountEnemies(); // 00870d70 -int CountBosses(); // 00870da0 -long double GetScreenWidth(); // 00870dd0 -long double GetScreenHeight(); // 00870de0 -long double GetScreenPointScale(); // 00870df0 -void RegisterMod(void *param_1, int param_2, void **param_3, int param_4); // 00870f40 -void SaveModData(void *param_1, int param_2, uint32_t *param_3); // 008711f0 -uint32_t * LoadModData(uint32_t *param_1, void *param_2, int param_3); // 00871550 -bool HasModData(void *param_1, int param_2); // 00871980 -void RemoveModData(void *param_1, int param_2); // 00871c10 void Shutdown(); // 009ab700 } namespace ItemInfo { @@ -21513,7 +21413,6 @@ namespace NetLogging { void format_callstack(uint32_t param_1, uint32_t param_2); // 00904a60 } namespace NpcAI { -void ENTITY_BABY_PLUM(Entity_NPC *npc); // 0043f0c0 void ENTITY_BEAST_background(Entity_NPC *npc); // 00440630 void ENTITY_BEAST_ultra_death(Entity_NPC *npc); // 00440f00 void ENTITY_BEAST_ultra_death_scythe(Entity_NPC *npc); // 00443e50 @@ -21547,8 +21446,6 @@ float ENTITY_ISAAC(Entity_NPC *npc); // 00463100 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_DUKE(Entity_NPC *npc); // 0046e290 void ENTITY_WIDOW(Entity_NPC *npc); // 0046fbe0 void ENTITY_BLASTOCYST_BIG(Entity_NPC *npc); // 00472c40 void ENTITY_SLOTH(Entity_NPC *npc); // 004741f0 @@ -21564,7 +21461,6 @@ void ENTITY_PEEP(Entity_NPC *npc); // 0047d8a0 Entity_NPC * ENTITY_SATAN(Entity_NPC *npc); // 0047f640 void ENTITY_THE_HAUNT(Entity_NPC *npc); // 00481410 void ENTITY_THE_LAMB(Entity_NPC *npc); // 00483710 -ColorMod * ENTITY_DINGLE(Entity_NPC *npc); // 004855b0 void ENTITY_MR_FRED(Entity_NPC *npc); // 00486db0 void ENTITY_CAGE(Entity_NPC *npc); // 004878a0 void ENTITY_POLYCEPHALUS(Entity_NPC *npc); // 00489ca0 @@ -21572,7 +21468,6 @@ void ENTITY_MAMA_GURDY(Entity_NPC *npc); // 0048ae30 void ENTITY_BROWNIE(Entity_NPC *npc); // 0048c3b0 void ENTITY_CORN_MINE(Entity_NPC *npc); // 0048ee30 void ENTITY_FORSAKEN(Entity_NPC *npc); // 0048f110 -void ENTITY_LITTLE_HORN(Entity_NPC *npc); // 00490680 void ENTITY_PITFALL(Entity_NPC *npc); // 00492550 void ENTITY_RAG_MAN(Entity_NPC *npc); // 00493200 void ENTITY_RAG_MEGA(Entity_NPC *npc); // 00495610 @@ -21612,7 +21507,6 @@ Entity_Effect * ENTITY_TWITCHY(Entity_NPC *npc); // 004db6a0 void ENTITY_SPIKEBALL(Entity_NPC *npc); // 004dc490 void ENTITY_UNBORN(Entity_NPC *npc); // 004dca90 void * ENTITY_GASBAG(Entity_NPC *npc); // 004dd7f0 -void * ENTITY_MAMA_FLY(Entity_NPC *npc); // 004ddf00 void ENTITY_PUSTULE(Entity_NPC *npc); // 004dea40 void ENTITY_EVIS(Entity_NPC *npc); // 004df3f0 void ENTITY_GUTTED_FATTY(Entity_NPC *npc); // 004e0dd0 @@ -21655,18 +21549,11 @@ 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_ETERNALFLY(Entity_NPC *npc); // 0050a8a0 -void ENTITY_GLOBIN(Entity_NPC *npc); // 0050e4d0 -uint32_t ENTITY_BOOMFLY(Entity_NPC *npc); // 0050f280 -void ENTITY_MAW(Entity_NPC *npc); // 00510ae0 -Entity * ENTITY_HOST(Entity_NPC *npc); // 005111b0 -void ENTITY_BRAIN(Entity_NPC *npc); // 00512110 void ENTITY_KNIGHT(Entity_NPC *npc); // 005135d0 uint32_t * ENTITY_GUTS(Entity_NPC *npc); // 005153b0 -void ENTITY_BOIL(Entity_NPC *npc); // 00517150 void ENTITY_MRMAW(Entity_NPC *npc); // 00517de0 void ENTITY_SWARMER(Entity_NPC *npc); // 00518e20 void ENTITY_GURGLE(Entity_NPC *npc); // 0051aaa0 -void ENTITY_WALKINGBOIL(Entity_NPC *npc); // 0051b570 void ENTITY_MEMBRAIN(Entity_NPC *npc); // 0051c040 void ENTITY_HANGER(Entity_NPC *npc); // 0051cb30 void ENTITY_GURDY_JR(Entity_NPC *npc); // 0051d300 @@ -21682,10 +21569,8 @@ void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 void ENTITY_BABY(Entity_NPC *npc); // 0052ae30 void ENTITY_VIS_chubber_projectile(Entity_NPC *npc); // 0052c2f0 void ENTITY_VIS(Entity_NPC *npc); // 0052c720 -void ENTITY_MAGGOT(Entity_NPC *npc); // 0052db50 void ENTITY_FAT_SACK(Entity_NPC *npc); // 00530a80 void ENTITY_COD_WORM(Entity_NPC *npc); // 00531350 -void ENTITY_BABY_LONG_LEGS(Entity_NPC *npc); // 00531ab0 void ENTITY_MOBILE_HOST(Entity_NPC *npc); // 005321d0 void ENTITY_DEATHS_HEAD(Entity_NPC *npc); // 00532cf0 void ENTITY_MOMS_HAND(Entity_NPC *npc); // 00533b80 @@ -21694,28 +21579,19 @@ void ENTITY_SWINGER(Entity_NPC *npc); // 00536d00 void ENTITY_WIZOOB(Entity_NPC *npc); // 005374a0 void ENTITY_NERVE_ENDING(Entity_NPC *npc); // 00537e20 void ENTITY_SKINBALL(Entity_NPC *npc); // 005381c0 -void ENTITY_SKINNY(Entity_NPC *npc); // 00538b70 void ENTITY_HOMUNCULUS(Entity_NPC *npc); // 00539b90 void ENTITY_OOB(Entity_NPC *npc); // 0053ab40 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_FAT_BAT(Entity_NPC *npc); // 00540510 -void ENTITY_SWARM(Entity_NPC *npc); // 00540df0 void ENTITY_DUKIE(Entity_NPC *npc); // 00541810 Entity_Effect * ENTITY_MEATBALL(Entity_NPC *npc); // 00541ce0 -void ENTITY_MUSHROOM(Entity_NPC *npc); // 00542be0 float ENTITY_BLISTER(Entity_NPC *npc); // 005430d0 -void ENTITY_PORTAL(Entity_NPC *npc); // 00543720 float ENTITY_TARBOY(Entity_NPC *npc); // 005442a0 void ENTITY_FISTULOID(Entity_NPC *npc); // 00545f70 void ENTITY_GUSH(Entity_NPC *npc); // 00547330 void ENTITY_LEPER(Entity_NPC *npc); // 00547b60 void ENTITY_MR_MINE(Entity_NPC *npc); // 005492c0 -void ENTITY_SKINNY_crispy(Entity_NPC *npc); // 0054a350 -void ENTITY_ARMYFLY(Entity_NPC *npc); // 0054ad80 -void ENTITY_BULB(Entity_NPC *npc); // 0054bca0 void ENTITY_BUTT_SLICKER(Entity_NPC *npc); // 0054d250 void ENTITY_NEEDLE(Entity_NPC *npc); // 0054eb80 ColorMod * ENTITY_WRINKLY_BABY(Entity_NPC *npc); // 0054fa80 @@ -21734,7 +21610,6 @@ Entity_Projectile * ENTITY_BUBBLES(Entity_NPC *npc); // 0055ad20 void ENTITY_SMALL_LEECH(Entity_NPC *npc); // 0055b740 void ENTITY_STRIDER(Entity_NPC *npc); // 0055c810 uint32_t ENTITY_POLTY(Entity_NPC *npc); // 0055d230 -void ENTITY_SUB_HORF(Entity_NPC *npc); // 0055fb60 void ENTITY_DEEP_GAPER(Entity_NPC *npc); // 00560570 void ENTITY_FLY_TRAP(Entity_NPC *npc); // 00560ca0 void ENTITY_FLY_orbit_parent(Entity_NPC *npc); // 00561580 @@ -21793,7 +21668,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_MOVABLE_TNT(Entity_NPC *npc); // 006d6690 } namespace OnlinePlayerInfo { void render_items(float *param_1); // 008d4940 diff --git a/generated-src/loot_list.cpp b/generated-src/loot_list.cpp deleted file mode 100644 index a9572ab..0000000 --- a/generated-src/loot_list.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "classes.h" - -// 006c20e0 -LootList::LootList(void *other) -{ - uint32_t uVar1; - uint32_t uVar2; - uint32_t uVar3; - uint32_t *puVar4; - int iVar5; - void *newBlock; - uint32_t endOffset; - int map; - uint32_t offset; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - uint32_t *dstEntry; - uint32_t mapSize; - - local_14 = 0xffffffff; - puStack_18 = &LAB_00afa935; - local_1c = ExceptionList; - ExceptionList = &local_1c; - *GHIDRA_CAST(this) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 4)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 8)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 0; - puVar4 = operator_new(8); - *puVar4 = this; - puVar4[1] = 0; - *GHIDRA_CAST(this) = puVar4; - offset = *GHIDRA_CAST((GHIDRA_CAST(other) + 0xc)); - endOffset = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x10)) + offset; - local_14 = 1; - if (offset != endOffset) { - iVar5 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - do { - puVar4 = *(uint32_t **) - (*GHIDRA_CAST((GHIDRA_CAST(other) + 4)) + (*GHIDRA_CAST((GHIDRA_CAST(other) + 8)) - 1U & offset) * 4); - mapSize = *GHIDRA_CAST((GHIDRA_CAST(this) + 8)); - if (mapSize <= iVar5 + 1U) { - msvc::deque::_Growmap(mapSize); - iVar5 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - mapSize = *GHIDRA_CAST((GHIDRA_CAST(this) + 8)); - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) = *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) & mapSize - 1; - map = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - iVar5 = (*GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) + iVar5 & mapSize - 1) * 4; - if (*GHIDRA_CAST((iVar5 + map)) == 0) { - newBlock = operator_new(0x14); - *(void **)(iVar5 + *GHIDRA_CAST((GHIDRA_CAST(this) + 4))) = newBlock; - map = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - } - dstEntry = *GHIDRA_CAST((iVar5 + map)); - offset = offset + 1; - uVar1 = puVar4[1]; - uVar2 = puVar4[2]; - uVar3 = puVar4[3]; - *dstEntry = *puVar4; - dstEntry[1] = uVar1; - dstEntry[2] = uVar2; - dstEntry[3] = uVar3; - dstEntry[4] = puVar4[4]; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) + 1; - iVar5 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - } while (offset != endOffset); - } - ExceptionList = local_1c; - return; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index af8df1d..99c8918 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -2268,7 +2268,7 @@ LAB_004b1488: rng._seed = uVar6 | 1; rng._shift2 = 9; rng._shift3 = 7; - uVar6 = (GHIDRA_CAST((GHIDRA_CAST(&picker))))->WeightedOutcomePicker::PickOutcome(rng); + uVar6 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); manager = g_manager; switch(uVar6) { case 0: @@ -3181,7 +3181,7 @@ LAB_004b42a6: rng._seed = uVar2 | 1; rng._shift2 = 9; rng._shift3 = 7; - uVar2 = (GHIDRA_CAST((GHIDRA_CAST(&outcomes))))->WeightedOutcomePicker::PickOutcome(rng); + uVar2 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&outcomes),rng); pEVar1 = npcLocal; if (uVar2 == 3) { *GHIDRA_CAST((GHIDRA_INT(&npcLocal->_stateFrame) + 2)) = 0; @@ -3902,7 +3902,7 @@ LAB_004b8025: rng._seed = rngSeed; rng._shift2 = 9; rng._shift3 = 7; - uVar3 = (GHIDRA_CAST((GHIDRA_CAST(&outcomes))))->WeightedOutcomePicker::PickOutcome(rng); + uVar3 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&outcomes),rng); local_14 = 0xffffffff; uStack_34 = uVar3; if (outcomes != (void *)0x0) { @@ -4494,7 +4494,7 @@ LAB_004b8df1: rng._seed = uVar1 | 1; rng._shift2 = 9; rng._shift3 = 7; - uVar1 = (GHIDRA_CAST((GHIDRA_CAST(&picker))))->WeightedOutcomePicker::PickOutcome(rng); + uVar1 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); target = Entity_NPC::GetPlayerTarget(npc); local_28 = GHIDRA_CAST(((target->_pos).x - (npc->_pos).x)); targetDirY = (target->_pos).y - (npc->_pos).y; @@ -5296,7 +5296,7 @@ LAB_004bce05: rng._seed = uVar5 | 1; rng._shift2 = 9; rng._shift3 = 7; - uVar5 = (GHIDRA_CAST((GHIDRA_CAST(&picker))))->WeightedOutcomePicker::PickOutcome(rng); + uVar5 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); bombTearFlags0 = (BitSet128)ZEXT816(0); if (uVar5 == 8) { bombTearFlags0 = g_tearFlagBurn; @@ -10533,7 +10533,7 @@ LAB_0058ebbb: rng._seed = (*GHIDRA_CAST((GHIDRA_CAST(&(local_64)) + 0x0))); rng._shift2 = 9; rng._shift3 = 7; - uVar2 = (GHIDRA_CAST((GHIDRA_CAST(&picker))))->WeightedOutcomePicker::PickOutcome(rng); + uVar2 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); if (uVar2 == 0) { *GHIDRA_CAST((GHIDRA_INT(&local_54->_projectileCooldown) + 2)) = 0; } @@ -11349,7 +11349,7 @@ LAB_0059eaaa: rng._seed = pickSeed; rng._shift2 = 9; rng._shift3 = 7; - uVar3 = (GHIDRA_CAST((GHIDRA_CAST(&picker))))->WeightedOutcomePicker::PickOutcome(rng); + uVar3 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); if ((uVar3 == 0) || (boss->_state == 0x10)) { Game::ShakeScreen(g_game,0xd); if ((float)ultraDoors._size != 0.0) { @@ -13170,23 +13170,6 @@ LAB_006d1556: return; } -// 009be990 -uint32_t NpcHelper::big_horn_is_any_hole_busy() -{ - int *hole; - uint32_t *in_ECX; - - hole = GHIDRA_CAST(*in_ECX); - while( true ) { - if (hole == GHIDRA_CAST(in_ECX[1])) { - return GHIDRA_UINT(hole) & 0xffffff00; - } - if ((*GHIDRA_CAST((*hole + 0x3fc)) != 0) && (*GHIDRA_CAST((*hole + 0x3fc)) != 3)) break; - hole = hole + 1; - } - return CONCAT31((int3)(GHIDRA_UINT(hole) >> 8),1); -} - // 009bfd40 float * NpcHelper::hush_fly_shape_build(float *outPath, int shape, float radius) { diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 4de3ab6..dc67d3e 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8234,15 +8234,7 @@ BitSet128 * BitSet128::operator_and(BitSet128 *outResult, BitSet128 *a, BitSet12 uint8_t BitSet128::IsNonZero() { generated_stub("BitSet128::IsNonZero 004171b0"); } BitSet128 * BitSet128::operator__(BitSet128 *other) { generated_stub("BitSet128::operator__ 00435bf0"); } BitSet128 * BitSet128::operator_or(BitSet128 *outResult, BitSet128 *a, BitSet128 *b) { generated_stub("BitSet128::operator_or 00435c20"); } -BitSet128 * BitSet128::__bnot(BitSet128 *out) { generated_stub("BitSet128::__bnot 00592200"); } uint8_t BitSet128::IsZero() { generated_stub("BitSet128::IsZero 00592230"); } -uint8_t * BitSet128::__tostring() { generated_stub("BitSet128::__tostring 0085e490"); } -uint32_t BitSet128::__band(BitSet128 *param_1, BitSet128 *param_2) { generated_stub("BitSet128::__band 0085e4d0"); } -uint32_t BitSet128::__bor(BitSet128 *param_1, BitSet128 *param_2) { generated_stub("BitSet128::__bor 0085e4f0"); } -uint32_t BitSet128::__bxor(uint32_t param_1, uint32_t param_2) { generated_stub("BitSet128::__bxor 0085e510"); } -uint8_t BitSet128::__eq(BitSet128 *other) { generated_stub("BitSet128::__eq 0085e530"); } -uint8_t BitSet128::Get(uint32_t bit) { generated_stub("BitSet128::Get 0085e560"); } -void BitSet128::Set(uint32_t bit, uint8_t value) { generated_stub("BitSet128::Set 0085e5c0"); } void BossOverlay::update() { generated_stub("BossOverlay::update 004212c0"); } void BossOverlay::play(int overlayType) { generated_stub("BossOverlay::play 004214b0"); } void Capsule::constructor(Vector *position, Vector *multiplier, float rotation, float size) { generated_stub("Capsule::constructor 00945190"); } @@ -8353,7 +8345,6 @@ Vector * Vector::operator_mul(Vector *outResult, float *scalar, Vector *vector) Vector * Vector::ToCardinal(Vector *outResult, Vector *vec) { generated_stub("Vector::ToCardinal 0067f170"); } Vector * Vector::mul_065(Vector *outResult, Vector *source) { generated_stub("Vector::mul_065 0067f2b0"); } Vector * Vector::operator_assign(Vector *other) { generated_stub("Vector::operator_assign 007dd3b0"); } -uint8_t * Vector::__tostring() { generated_stub("Vector::__tostring 0085e630"); } Vector::Vector(float x, float y) { generated_stub("Vector::Vector 00a0fe90"); } float Vector::Length() { generated_stub("Vector::Length 00a0fea0"); } float Vector::LengthSquared() { generated_stub("Vector::LengthSquared 00a0fed0"); } @@ -9161,7 +9152,6 @@ void LobbyPasswordPrompt::open(uint32_t param_1, uint8_t param_2, int *param_3) void LobbyPasswordPrompt::Update() { generated_stub("LobbyPasswordPrompt::Update 009c63a0"); } void LobbyPasswordPrompt::handle_direction_input() { generated_stub("LobbyPasswordPrompt::handle_direction_input 009c6650"); } void LobbySettings::reset() { generated_stub("LobbySettings::reset 0085b050"); } -LootList::LootList(void *other) { generated_stub("LootList::LootList 006c20e0"); } void LuaRef::push(void *luaState) { generated_stub("LuaRef::push 006a80f0"); } uint8_t LuaRef::equals(void *otherState, int otherRef) { generated_stub("LuaRef::equals 00897540"); } void MTRNG::Init(uint32_t seed) { generated_stub("MTRNG::Init 008fd3c0"); } @@ -9355,7 +9345,6 @@ Entity * NpcHelper::wormwood_spawn_splash(Entity_NPC *npc) { generated_stub("Npc uint8_t NpcHelper::is_target_valid(Entity *target) { generated_stub("NpcHelper::is_target_valid 006be7e0"); } void NpcHelper::ChampionDrop(Entity_NPC *npc) { generated_stub("NpcHelper::ChampionDrop 006bf120"); } void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } -uint32_t NpcHelper::big_horn_is_any_hole_busy() { generated_stub("NpcHelper::big_horn_is_any_hole_busy 009be990"); } float * NpcHelper::hush_fly_shape_build(float *outPath, int shape, float radius) { generated_stub("NpcHelper::hush_fly_shape_build 009bfd40"); } void NpcHelper::path_point_at(void *path, Vector *outPoint, float share) { generated_stub("NpcHelper::path_point_at 009bffb0"); } void OnlineChat::render(Vector *position, uint8_t isInputLine, uint8_t isCursorVisible, float alpha) { generated_stub("OnlineChat::render 0091d2b0"); } @@ -9696,7 +9685,6 @@ uint8_t Weapon_UrnOfSouls::CanTakeDamageFromTearEffects() { generated_stub("Weap uint8_t Weapon_UrnOfSouls::CanShutDoors() { generated_stub("Weapon_UrnOfSouls::CanShutDoors 005ccc00"); } void Weapon_UrnOfSouls::vfunc_15() { generated_stub("Weapon_UrnOfSouls::vfunc_15 005ccc00"); } void Weapon_UrnOfSouls::vfunc_16() { generated_stub("Weapon_UrnOfSouls::vfunc_16 005ccc00"); } -uint32_t WeightedOutcomePicker::PickOutcome(RNG rng) { generated_stub("WeightedOutcomePicker::PickOutcome 0049cbf0"); } msvc::exception::~exception() { generated_stub("msvc::exception::~exception 0040ce20"); } char * msvc::exception::FUN_0040d0d0() { generated_stub("msvc::exception::FUN_0040d0d0 0040d0d0"); } luabridge::LuaException::~LuaException() { generated_stub("luabridge::LuaException::~LuaException 0085c210"); } @@ -10003,11 +9991,6 @@ void FUN_00425410() { generated_stub("FUN_00425410 00425410"); } void online_stats_destroy(void *self) { generated_stub("online_stats_destroy 00425430"); } void OnlineStats::compute_awards() { generated_stub("OnlineStats::compute_awards 004254b0"); } void online_stats_register_players() { generated_stub("online_stats_register_players 004257b0"); } -void online_stats_add_user(void *self, uint32_t userIdLow, uint32_t userIdHigh) { generated_stub("online_stats_add_user 004259b0"); } -int FUN_00425a70(int param_1, int param_2) { generated_stub("FUN_00425a70 00425a70"); } -void Player_stats_add(void *onlineStats, uint32_t statId, Entity_Player *player, float amount) { generated_stub("Player_stats_add 00425ac0"); } -uint64_t player_get_net_user_id(Entity_Player *player) { generated_stub("player_get_net_user_id 004264c0"); } -int * FUN_00426560(int param_1, int param_2) { generated_stub("FUN_00426560 00426560"); } void FUN_00427290() { generated_stub("FUN_00427290 00427290"); } int holiday_get_current(uint32_t yyyymmdd) { generated_stub("holiday_get_current 00427870"); } void FUN_00428560(uint32_t *param_1, uint32_t param_2) { generated_stub("FUN_00428560 00428560"); } @@ -10170,7 +10153,6 @@ void FUN_0043ed20(uint32_t *param_1, int *param_2) { generated_stub("FUN_0043ed2 void FUN_0043edf0(uint32_t param_1, uint32_t param_2, uint32_t *param_3) { generated_stub("FUN_0043edf0 0043edf0"); } void FUN_0043eea0(uint32_t param_1) { generated_stub("FUN_0043eea0 0043eea0"); } void FUN_0043eed0(float *param_1) { generated_stub("FUN_0043eed0 0043eed0"); } -void NpcAI::ENTITY_BABY_PLUM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY_PLUM 0043f0c0"); } void FUN_004405e0() { generated_stub("FUN_004405e0 004405e0"); } void NpcAI::ENTITY_BEAST_background(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_background 00440630"); } void set_PlaybackSpeed(ANM2 *sprite, float speed) { generated_stub("set_PlaybackSpeed 00440e50"); } @@ -10241,8 +10223,6 @@ float NpcAI::ENTITY_ISAAC(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ISAAC void NpcAI::ENTITY_FISTULA_BIG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISTULA_BIG 00466600"); } 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_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"); } void NpcAI::ENTITY_SLOTH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SLOTH 004741f0"); } @@ -10259,7 +10239,6 @@ void NpcAI::ENTITY_PEEP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PEEP 00 Entity_NPC * NpcAI::ENTITY_SATAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SATAN 0047f640"); } void NpcAI::ENTITY_THE_HAUNT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_THE_HAUNT 00481410"); } void NpcAI::ENTITY_THE_LAMB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_THE_LAMB 00483710"); } -ColorMod * NpcAI::ENTITY_DINGLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DINGLE 004855b0"); } void NpcAI::ENTITY_MR_FRED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_FRED 00486db0"); } void NpcAI::ENTITY_CAGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CAGE 004878a0"); } void NpcAI::ENTITY_POLYCEPHALUS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POLYCEPHALUS 00489ca0"); } @@ -10267,7 +10246,6 @@ void NpcAI::ENTITY_MAMA_GURDY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_M void NpcAI::ENTITY_BROWNIE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BROWNIE 0048c3b0"); } void NpcAI::ENTITY_CORN_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CORN_MINE 0048ee30"); } void NpcAI::ENTITY_FORSAKEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FORSAKEN 0048f110"); } -void NpcAI::ENTITY_LITTLE_HORN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LITTLE_HORN 00490680"); } void NpcAI::ENTITY_PITFALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PITFALL 00492550"); } void NpcAI::ENTITY_RAG_MAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAG_MAN 00493200"); } void NpcAI::ENTITY_RAG_MEGA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAG_MEGA 00495610"); } @@ -10376,7 +10354,6 @@ void Catch_All_004d7683() { generated_stub("Catch_All_004d7683 004d7683"); } void FUN_004d76c0() { generated_stub("FUN_004d76c0 004d76c0"); } bool FUN_004d7760() { generated_stub("FUN_004d7760 004d7760"); } void NpcAI::ENTITY_SMALL_MAGGOT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SMALL_MAGGOT 004d77b0"); } -Entity * spawn_small_maggot_jump(Vector *position, float yPositionOffset, Vector *targetPosition) { generated_stub("spawn_small_maggot_jump 004d8910"); } Entity * spawn_small_maggot(Vector *position, float height, Vector *velocity, float heightVelocity) { generated_stub("spawn_small_maggot 004d8b50"); } void NpcAI::ENTITY_ADULT_LEECH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ADULT_LEECH 004d9000"); } void NpcAI::ENTITY_ROTTEN_GAPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROTTEN_GAPER 004da590"); } @@ -10384,7 +10361,6 @@ Entity_Effect * NpcAI::ENTITY_TWITCHY(Entity_NPC *npc) { generated_stub("NpcAI:: void NpcAI::ENTITY_SPIKEBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SPIKEBALL 004dc490"); } void NpcAI::ENTITY_UNBORN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_UNBORN 004dca90"); } void * NpcAI::ENTITY_GASBAG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GASBAG 004dd7f0"); } -void * NpcAI::ENTITY_MAMA_FLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAMA_FLY 004ddf00"); } void NpcAI::ENTITY_PUSTULE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PUSTULE 004dea40"); } void NpcAI::ENTITY_EVIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EVIS 004df3f0"); } void FUN_004e07a0(Vector *param_1) { generated_stub("FUN_004e07a0 004e07a0"); } @@ -10444,21 +10420,14 @@ 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_ETERNALFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ETERNALFLY 0050a8a0"); } -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"); } -Entity * NpcAI::ENTITY_HOST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HOST 005111b0"); } -void NpcAI::ENTITY_BRAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BRAIN 00512110"); } void NpcAI::ENTITY_KNIGHT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_KNIGHT 005135d0"); } uint32_t FUN_00515010() { generated_stub("FUN_00515010 00515010"); } Vector * room_grid_line_direction(Vector *outDirection, Vector *from, Vector *to) { generated_stub("room_grid_line_direction 005150b0"); } long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00515290 00515290"); } uint32_t * NpcAI::ENTITY_GUTS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUTS 005153b0"); } -void NpcAI::ENTITY_BOIL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOIL 00517150"); } void NpcAI::ENTITY_MRMAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MRMAW 00517de0"); } void NpcAI::ENTITY_SWARMER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWARMER 00518e20"); } void NpcAI::ENTITY_GURGLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GURGLE 0051aaa0"); } -void NpcAI::ENTITY_WALKINGBOIL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WALKINGBOIL 0051b570"); } void NpcAI::ENTITY_MEMBRAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEMBRAIN 0051c040"); } void NpcAI::ENTITY_HANGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HANGER 0051cb30"); } void NpcAI::ENTITY_GURDY_JR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GURDY_JR 0051d300"); } @@ -10474,10 +10443,8 @@ void NpcAI::ENTITY_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 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"); } -void NpcAI::ENTITY_MAGGOT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAGGOT 0052db50"); } void NpcAI::ENTITY_FAT_SACK(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FAT_SACK 00530a80"); } void NpcAI::ENTITY_COD_WORM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COD_WORM 00531350"); } -void NpcAI::ENTITY_BABY_LONG_LEGS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY_LONG_LEGS 00531ab0"); } void NpcAI::ENTITY_MOBILE_HOST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOBILE_HOST 005321d0"); } void NpcAI::ENTITY_DEATHS_HEAD(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEATHS_HEAD 00532cf0"); } void NpcAI::ENTITY_MOMS_HAND(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HAND 00533b80"); } @@ -10486,29 +10453,20 @@ void NpcAI::ENTITY_SWINGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWIN void NpcAI::ENTITY_WIZOOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WIZOOB 005374a0"); } void NpcAI::ENTITY_NERVE_ENDING(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_NERVE_ENDING 00537e20"); } void NpcAI::ENTITY_SKINBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SKINBALL 005381c0"); } -void NpcAI::ENTITY_SKINNY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SKINNY 00538b70"); } void NpcAI::ENTITY_HOMUNCULUS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HOMUNCULUS 00539b90"); } void NpcAI::ENTITY_OOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_OOB 0053ab40"); } void NpcAI::ENTITY_BLACK_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLACK_MAW 0053b2f0"); } -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_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"); } Entity_Effect * NpcAI::ENTITY_MEATBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEATBALL 00541ce0"); } -void NpcAI::ENTITY_MUSHROOM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MUSHROOM 00542be0"); } float NpcAI::ENTITY_BLISTER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLISTER 005430d0"); } -void NpcAI::ENTITY_PORTAL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PORTAL 00543720"); } float NpcAI::ENTITY_TARBOY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TARBOY 005442a0"); } void NpcAI::ENTITY_FISTULOID(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISTULOID 00545f70"); } void npc_distribute_orbit_angles(Entity_NPC *npc) { generated_stub("npc_distribute_orbit_angles 00547040"); } void NpcAI::ENTITY_GUSH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUSH 00547330"); } void NpcAI::ENTITY_LEPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LEPER 00547b60"); } void NpcAI::ENTITY_MR_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_MINE 005492c0"); } -void NpcAI::ENTITY_SKINNY_crispy(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SKINNY_crispy 0054a350"); } -void NpcAI::ENTITY_ARMYFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ARMYFLY 0054ad80"); } -void NpcAI::ENTITY_BULB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BULB 0054bca0"); } int FUN_0054d1b0(int param_1) { generated_stub("FUN_0054d1b0 0054d1b0"); } void NpcAI::ENTITY_BUTT_SLICKER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUTT_SLICKER 0054d250"); } void NpcAI::ENTITY_NEEDLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_NEEDLE 0054eb80"); } @@ -10534,7 +10492,6 @@ void NpcAI::ENTITY_SMALL_LEECH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ uint32_t FUN_0055c6a0(float *param_1) { generated_stub("FUN_0055c6a0 0055c6a0"); } void NpcAI::ENTITY_STRIDER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_STRIDER 0055c810"); } uint32_t NpcAI::ENTITY_POLTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POLTY 0055d230"); } -void NpcAI::ENTITY_SUB_HORF(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SUB_HORF 0055fb60"); } void NpcAI::ENTITY_DEEP_GAPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEEP_GAPER 00560570"); } void NpcAI::ENTITY_FLY_TRAP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_TRAP 00560ca0"); } void NpcAI::ENTITY_FLY_orbit_parent(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_orbit_parent 00561580"); } @@ -11120,7 +11077,6 @@ Entity * spawn_gfuel_explosion() { generated_stub("spawn_gfuel_explosion 006b945 uint32_t _NpcHelper::spider_load_graphics(uint8_t *param_1) { generated_stub("_NpcHelper::spider_load_graphics 006baa70"); } 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"); } uint8_t is_local_player_owned(void *self) { generated_stub("is_local_player_owned 006d8e10"); } uint32_t FUN_006da6f0() { generated_stub("FUN_006da6f0 006da6f0"); } void FUN_006da710(char param_1) { generated_stub("FUN_006da710 006da710"); } @@ -11223,12 +11179,9 @@ uint32_t FUN_00710f70(int param_1) { generated_stub("FUN_00710f70 00710f70"); } void FUN_00711530(int param_1) { generated_stub("FUN_00711530 00711530"); } uint32_t FUN_00711740() { generated_stub("FUN_00711740 00711740"); } void FUN_007135d0(uint32_t param_1, uint8_t param_2, int *param_3) { generated_stub("FUN_007135d0 007135d0"); } -void spawn_poop_rewards(uint32_t param_1, int param_2, int param_3, char param_4, uint32_t param_5, int param_6) { generated_stub("spawn_poop_rewards 00716db0"); } -void FUN_00718d20(float *param_1) { generated_stub("FUN_00718d20 00718d20"); } void FUN_00718ed0(uint32_t param_1) { generated_stub("FUN_00718ed0 00718ed0"); } uint32_t FUN_00718ee0() { generated_stub("FUN_00718ee0 00718ee0"); } void FUN_0071df70(uint8_t param_1) { generated_stub("FUN_0071df70 0071df70"); } -int FUN_0071df80() { generated_stub("FUN_0071df80 0071df80"); } 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"); } @@ -11362,7 +11315,6 @@ void input_state_reset(void *self) { generated_stub("input_state_reset 00754980" void FUN_00757980(uint32_t *param_1) { generated_stub("FUN_00757980 00757980"); } void FUN_00757a10() { generated_stub("FUN_00757a10 00757a10"); } uint32_t FUN_00758590() { generated_stub("FUN_00758590 00758590"); } -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"); } @@ -11673,129 +11625,50 @@ void FUN_0085e1d0(char param_1) { generated_stub("FUN_0085e1d0 0085e1d0"); } void FUN_0085e2a0(uint32_t *param_1) { generated_stub("FUN_0085e2a0 0085e2a0"); } void FUN_0085e340(uint32_t param_1) { generated_stub("FUN_0085e340 0085e340"); } void FUN_0085e3b0(uint32_t param_1) { generated_stub("FUN_0085e3b0 0085e3b0"); } -void lua_searcher_resources_scripts(uint8_t *param_1) { generated_stub("lua_searcher_resources_scripts 0085f0f0"); } -uint32_t FUN_0085fcc0() { generated_stub("FUN_0085fcc0 0085fcc0"); } -uint32_t FUN_0085fec0(uint32_t param_1) { generated_stub("FUN_0085fec0 0085fec0"); } -uint32_t FUN_008601f0(uint32_t param_1) { generated_stub("FUN_008601f0 008601f0"); } -uint32_t FUN_008603d0(uint32_t param_1) { generated_stub("FUN_008603d0 008603d0"); } -void FUN_00860f00(int param_1) { generated_stub("FUN_00860f00 00860f00"); } uint32_t Catch_00860f8b() { generated_stub("Catch_00860f8b 00860f8b"); } -void FUN_00860fe0(int param_1, uint32_t *param_2) { generated_stub("FUN_00860fe0 00860fe0"); } uint32_t Catch_00861076() { generated_stub("Catch_00861076 00861076"); } -void FUN_008615e0(int param_1) { generated_stub("FUN_008615e0 008615e0"); } uint32_t Catch_0086166f() { generated_stub("Catch_0086166f 0086166f"); } -void FUN_008616c0(int param_1) { generated_stub("FUN_008616c0 008616c0"); } uint32_t Catch_0086174f() { generated_stub("Catch_0086174f 0086174f"); } -void FUN_008617a0(int param_1, uint32_t *param_2) { generated_stub("FUN_008617a0 008617a0"); } uint32_t Catch_00861837() { generated_stub("Catch_00861837 00861837"); } -void FUN_00861970(int param_1) { generated_stub("FUN_00861970 00861970"); } uint32_t Catch_008619ff() { generated_stub("Catch_008619ff 008619ff"); } -void FUN_00861a50(uint32_t param_1, uint32_t *param_2) { generated_stub("FUN_00861a50 00861a50"); } uint32_t Catch_00861b88() { generated_stub("Catch_00861b88 00861b88"); } void FUN_00861bda() { generated_stub("FUN_00861bda 00861bda"); } void FUN_00861c23() { generated_stub("FUN_00861c23 00861c23"); } -void FUN_00861ea0(int param_1) { generated_stub("FUN_00861ea0 00861ea0"); } uint32_t Catch_00861f2f() { generated_stub("Catch_00861f2f 00861f2f"); } -void FUN_00861f80(int param_1) { generated_stub("FUN_00861f80 00861f80"); } uint32_t Catch_0086200f() { generated_stub("Catch_0086200f 0086200f"); } -void FUN_00862060(uint32_t param_1, uint32_t *param_2) { generated_stub("FUN_00862060 00862060"); } uint32_t Catch_00862198() { generated_stub("Catch_00862198 00862198"); } void FUN_008621ea() { generated_stub("FUN_008621ea 008621ea"); } void FUN_00862233() { generated_stub("FUN_00862233 00862233"); } -void FUN_008624b0(int param_1) { generated_stub("FUN_008624b0 008624b0"); } uint32_t Catch_0086253f() { generated_stub("Catch_0086253f 0086253f"); } -void FUN_00862590(int param_1) { generated_stub("FUN_00862590 00862590"); } uint32_t Catch_0086261f() { generated_stub("Catch_0086261f 0086261f"); } -void FUN_00862670(int param_1, uint32_t *param_2) { generated_stub("FUN_00862670 00862670"); } uint32_t Catch_00862707() { generated_stub("Catch_00862707 00862707"); } void FUN_00862d0a() { generated_stub("FUN_00862d0a 00862d0a"); } void FUN_00862d53() { generated_stub("FUN_00862d53 00862d53"); } -void FUN_008635a0(int param_1) { generated_stub("FUN_008635a0 008635a0"); } uint32_t Catch_0086362b() { generated_stub("Catch_0086362b 0086362b"); } uint32_t Catch_00863879() { generated_stub("Catch_00863879 00863879"); } -void FUN_00863be0(int param_1) { generated_stub("FUN_00863be0 00863be0"); } uint32_t Catch_00863c6e() { generated_stub("Catch_00863c6e 00863c6e"); } -void FUN_00863cc0(uint32_t param_1, uint32_t param_2, uint32_t param_3) { generated_stub("FUN_00863cc0 00863cc0"); } uint32_t Catch_00863d4e() { generated_stub("Catch_00863d4e 00863d4e"); } -void FUN_00864130(int param_1) { generated_stub("FUN_00864130 00864130"); } uint32_t Catch_008641bb() { generated_stub("Catch_008641bb 008641bb"); } -void FUN_00864210(int param_1, uint32_t *param_2) { generated_stub("FUN_00864210 00864210"); } uint32_t Catch_008642a4() { generated_stub("Catch_008642a4 008642a4"); } uint32_t Catch_00864682() { generated_stub("Catch_00864682 00864682"); } uint8_t FUN_00864d80(uint32_t param_1, uint32_t param_2, uint32_t param_3, float *param_4) { generated_stub("FUN_00864d80 00864d80"); } uint8_t * Catch_00864e6d() { generated_stub("Catch_00864e6d 00864e6d"); } -void FUN_00864fc0(uint32_t param_1) { generated_stub("FUN_00864fc0 00864fc0"); } uint32_t Catch_0086504e() { generated_stub("Catch_0086504e 0086504e"); } -void FUN_008650a0(uint32_t param_1) { generated_stub("FUN_008650a0 008650a0"); } uint32_t Catch_0086512e() { generated_stub("Catch_0086512e 0086512e"); } uint8_t * Catch_008655b7() { generated_stub("Catch_008655b7 008655b7"); } char * FUN_00865660(char *param_1, uint32_t *param_2) { generated_stub("FUN_00865660 00865660"); } void FUN_00865aad() { generated_stub("FUN_00865aad 00865aad"); } void FUN_00865c61() { generated_stub("FUN_00865c61 00865c61"); } -uint32_t FUN_00866220(uint32_t *param_1, uint32_t *param_2) { generated_stub("FUN_00866220 00866220"); } uint32_t Catch_00866364() { generated_stub("Catch_00866364 00866364"); } uint8_t FUN_008663b6() { generated_stub("FUN_008663b6 008663b6"); } void FUN_00866474() { generated_stub("FUN_00866474 00866474"); } uint8_t * Catch_0086675e() { generated_stub("Catch_0086675e 0086675e"); } -bool FUN_008667d0(Entity *param_1) { generated_stub("FUN_008667d0 008667d0"); } uint32_t Catch_008668e0() { generated_stub("Catch_008668e0 008668e0"); } void FUN_0086e4d0() { generated_stub("FUN_0086e4d0 0086e4d0"); } -void Isaac::DebugString() { generated_stub("Isaac::DebugString 0086ef30"); } -int Isaac::GetPlayer(void *L) { generated_stub("Isaac::GetPlayer 0086ef50"); } -int Isaac::GetFrameCount() { generated_stub("Isaac::GetFrameCount 0086f090"); } -Entity * Isaac::Spawn(int type, int variant, int subType, Vector *position, Vector *velocity, Entity *spawner) { generated_stub("Isaac::Spawn 0086f0a0"); } -GridEntity * Isaac::GridSpawn(int type, int variant, Vector *position, uint8_t isForced) { generated_stub("Isaac::GridSpawn 0086f0d0"); } -void Isaac::RenderText(std_string *text, float x, float y, float red, float green, float blue, float alpha) { generated_stub("Isaac::RenderText 0086f1b0"); } -int Isaac::GetTextWidth(std_string *text) { generated_stub("Isaac::GetTextWidth 0086f370"); } -Vector * Isaac::GetRandomPosition(Vector *param_1) { generated_stub("Isaac::GetRandomPosition 0086f3a0"); } -Vector * Isaac::GetFreeNearPosition(Vector *param_1, Vector *param_2, float param_3) { generated_stub("Isaac::GetFreeNearPosition 0086f3d0"); } -void Isaac::Explode(Vector *position, Entity *source, float damage) { generated_stub("Isaac::Explode 0086f400"); } -void Isaac::SetBuiltInCallbackState(int callbackid, uint8_t enabled) { generated_stub("Isaac::SetBuiltInCallbackState 0086f4b0"); } -uint8_t Isaac::GetBuiltInCallbackState(int callbackid) { generated_stub("Isaac::GetBuiltInCallbackState 0086f4f0"); } -int Isaac::GetEntityTypeByName(std_string *name) { generated_stub("Isaac::GetEntityTypeByName 0086f520"); } -int Isaac::GetEntityVariantByName(uint8_t *param_1) { generated_stub("Isaac::GetEntityVariantByName 0086f5b0"); } -int Isaac::GetTrinketIdByName(std_string *name) { generated_stub("Isaac::GetTrinketIdByName 0086f6e0"); } -int Isaac::GetPlayerTypeByName(std_string *name, uint8_t isTainted) { generated_stub("Isaac::GetPlayerTypeByName 0086f760"); } -int Isaac::GetCardIdByName(std_string *name) { generated_stub("Isaac::GetCardIdByName 0086f800"); } -uint32_t Isaac::GetPillEffectByName(uint8_t *param_1) { generated_stub("Isaac::GetPillEffectByName 0086f880"); } -int Isaac::GetChallengeIdByName(std_string *name) { generated_stub("Isaac::GetChallengeIdByName 0086f900"); } -int Isaac::GetCostumeIdByPath(std_string *path) { generated_stub("Isaac::GetCostumeIdByPath 0086f980"); } -int Isaac::GetCurseIdByName(std_string *name) { generated_stub("Isaac::GetCurseIdByName 0086f9f0"); } -int Isaac::GetMusicIdByName(std_string *name) { generated_stub("Isaac::GetMusicIdByName 0086fa50"); } -uint32_t Isaac::GetSoundIdByName(uint8_t *param_1) { generated_stub("Isaac::GetSoundIdByName 0086fab0"); } -void * Isaac::GetRoomEntities(void *unk) { generated_stub("Isaac::GetRoomEntities 0086fb20"); } -int Isaac::GetChallenge() { generated_stub("Isaac::GetChallenge 0086fc30"); } -void Isaac::AddPillEffectToPool(int param_1) { generated_stub("Isaac::AddPillEffectToPool 0086fc40"); } -void Input::IsButtonTriggered(uint32_t param_1, uint32_t param_2) { generated_stub("Input::IsButtonTriggered 0086fc70"); } -void Input::IsButtonPressed(uint32_t param_1, uint32_t param_2) { generated_stub("Input::IsButtonPressed 0086fca0"); } -float Input::GetButtonValue(int button, int controllerIndex) { generated_stub("Input::GetButtonValue 0086fcd0"); } -void Input::IsActionTriggered(uint32_t param_1, uint32_t param_2) { generated_stub("Input::IsActionTriggered 0086fd10"); } -void Input::IsActionPressed(uint32_t param_1, uint32_t param_2) { generated_stub("Input::IsActionPressed 0086fd40"); } -float Input::GetActionValue(int action, int controllerId) { generated_stub("Input::GetActionValue 0086fd70"); } uint8_t Input::IsMouseBtnPressed(int button) { generated_stub("Input::IsMouseBtnPressed 0086fdb0"); } Vector * Input::GetMousePosition(Vector *outPosition, uint8_t isGameCoords) { generated_stub("Input::GetMousePosition 0086fe50"); } -uint32_t Isaac::GetTime() { generated_stub("Isaac::GetTime 0086ffa0"); } -std_string * Isaac::ExecuteCommand(std_string *outResult, std_string *command) { generated_stub("Isaac::ExecuteCommand 00870020"); } -void Isaac::ConsoleOutput(std_string *text) { generated_stub("Isaac::ConsoleOutput 00870130"); } void Isaac::ScreenToWorld(float *param_1, float *param_2) { generated_stub("Isaac::ScreenToWorld 00870160"); } -Vector * Isaac::WorldToScreen(Vector *outScreenPos, Vector *worldPos) { generated_stub("Isaac::WorldToScreen 00870220"); } -Vector * Isaac::WorldToScreenDistance(Vector *outResult, Vector *distance) { generated_stub("Isaac::WorldToScreenDistance 00870390"); } -Vector * Isaac::WorldToRenderPosition(Vector *outPos, Vector *worldPos) { generated_stub("Isaac::WorldToRenderPosition 008703c0"); } -Vector * Isaac::ScreenToWorldDistance(Vector *outResult, Vector *screenDistance) { generated_stub("Isaac::ScreenToWorldDistance 008704c0"); } -uint32_t Isaac::FindInRadius(void *param_1) { generated_stub("Isaac::FindInRadius 008704f0"); } -uint32_t Isaac::FindByType(void *param_1) { generated_stub("Isaac::FindByType 008707b0"); } -uint32_t Isaac::CountEntities(void *param_1) { generated_stub("Isaac::CountEntities 00870b40"); } -int Isaac::CountEnemies() { generated_stub("Isaac::CountEnemies 00870d70"); } -int Isaac::CountBosses() { generated_stub("Isaac::CountBosses 00870da0"); } -long double Isaac::GetScreenWidth() { generated_stub("Isaac::GetScreenWidth 00870dd0"); } -long double Isaac::GetScreenHeight() { generated_stub("Isaac::GetScreenHeight 00870de0"); } -long double Isaac::GetScreenPointScale() { generated_stub("Isaac::GetScreenPointScale 00870df0"); } void FUN_00870f21() { generated_stub("FUN_00870f21 00870f21"); } -void Isaac::RegisterMod(void *param_1, int param_2, void **param_3, int param_4) { generated_stub("Isaac::RegisterMod 00870f40"); } -void Isaac::SaveModData(void *param_1, int param_2, uint32_t *param_3) { generated_stub("Isaac::SaveModData 008711f0"); } -uint32_t * Isaac::LoadModData(uint32_t *param_1, void *param_2, int param_3) { generated_stub("Isaac::LoadModData 00871550"); } -bool Isaac::HasModData(void *param_1, int param_2) { generated_stub("Isaac::HasModData 00871980"); } -void Isaac::RemoveModData(void *param_1, int param_2) { generated_stub("Isaac::RemoveModData 00871c10"); } void FUN_00871eb0() { generated_stub("FUN_00871eb0 00871eb0"); } void FUN_00871f70(int *param_1, uint32_t param_2) { generated_stub("FUN_00871f70 00871f70"); } void FUN_00871fa0(Entity *param_1, float param_2) { generated_stub("FUN_00871fa0 00871fa0"); } @@ -12829,7 +12702,6 @@ uint32_t FUN_008a9180(void *param_1) { generated_stub("FUN_008a9180 008a9180"); uint32_t FUN_008a91f0(void *param_1) { generated_stub("FUN_008a91f0 008a91f0"); } uint32_t FUN_008a9240(void *param_1) { generated_stub("FUN_008a9240 008a9240"); } uint32_t FUN_008a92b0(void *param_1) { generated_stub("FUN_008a92b0 008a92b0"); } -uint32_t FUN_008a9360(void *param_1) { generated_stub("FUN_008a9360 008a9360"); } uint32_t FUN_008a9440(void *param_1) { generated_stub("FUN_008a9440 008a9440"); } uint32_t FUN_008a9520(void *param_1) { generated_stub("FUN_008a9520 008a9520"); } uint32_t FUN_008a95f0(void *param_1) { generated_stub("FUN_008a95f0 008a95f0"); } @@ -13199,17 +13071,13 @@ int FUN_008bb070() { generated_stub("FUN_008bb070 008bb070"); } int FUN_008bb0d0() { generated_stub("FUN_008bb0d0 008bb0d0"); } bool FUN_008bb130() { generated_stub("FUN_008bb130 008bb130"); } uint32_t FUN_008bb1c0(void *param_1) { generated_stub("FUN_008bb1c0 008bb1c0"); } -uint32_t FUN_008bb260(uint32_t param_1) { generated_stub("FUN_008bb260 008bb260"); } uint32_t FUN_008bb2e0(void *param_1) { generated_stub("FUN_008bb2e0 008bb2e0"); } uint32_t FUN_008bb340(void *param_1) { generated_stub("FUN_008bb340 008bb340"); } -uint32_t FUN_008bb3b0(uint32_t param_1) { generated_stub("FUN_008bb3b0 008bb3b0"); } uint32_t FUN_008bb420(void *param_1) { generated_stub("FUN_008bb420 008bb420"); } uint32_t FUN_008bb480(void *param_1) { generated_stub("FUN_008bb480 008bb480"); } uint32_t FUN_008bb4f0(uint32_t param_1) { generated_stub("FUN_008bb4f0 008bb4f0"); } uint32_t FUN_008bb570(uint32_t param_1) { generated_stub("FUN_008bb570 008bb570"); } -uint32_t FUN_008bb5c0(uint32_t param_1) { generated_stub("FUN_008bb5c0 008bb5c0"); } uint32_t FUN_008bb720(uint32_t param_1) { generated_stub("FUN_008bb720 008bb720"); } -uint32_t FUN_008bb770(void *param_1) { generated_stub("FUN_008bb770 008bb770"); } uint32_t FUN_008bb900(void *param_1) { generated_stub("FUN_008bb900 008bb900"); } uint32_t FUN_008bb960(void *param_1) { generated_stub("FUN_008bb960 008bb960"); } uint32_t FUN_008bb9c0(void *param_1) { generated_stub("FUN_008bb9c0 008bb9c0"); } @@ -13218,7 +13086,6 @@ uint32_t FUN_008bba80(void *param_1) { generated_stub("FUN_008bba80 008bba80"); uint32_t FUN_008bbb20(void *param_1) { generated_stub("FUN_008bbb20 008bbb20"); } uint32_t FUN_008bbbc0(void *param_1) { generated_stub("FUN_008bbbc0 008bbbc0"); } uint32_t FUN_008bbc60(void *param_1) { generated_stub("FUN_008bbc60 008bbc60"); } -uint32_t FUN_008bbcf0(uint32_t param_1) { generated_stub("FUN_008bbcf0 008bbcf0"); } uint32_t FUN_008bbd60(uint32_t param_1) { generated_stub("FUN_008bbd60 008bbd60"); } uint32_t FUN_008bbdb0(void *param_1) { generated_stub("FUN_008bbdb0 008bbdb0"); } uint32_t FUN_008bbe10(void *param_1) { generated_stub("FUN_008bbe10 008bbe10"); } @@ -13232,7 +13099,6 @@ uint32_t FUN_008bc130(void *param_1) { generated_stub("FUN_008bc130 008bc130"); uint32_t FUN_008bc1d0(void *param_1) { generated_stub("FUN_008bc1d0 008bc1d0"); } uint32_t FUN_008bc270(void *param_1) { generated_stub("FUN_008bc270 008bc270"); } uint32_t FUN_008bc2d0(void *param_1) { generated_stub("FUN_008bc2d0 008bc2d0"); } -uint32_t FUN_008bc330(uint32_t param_1) { generated_stub("FUN_008bc330 008bc330"); } uint32_t FUN_008bc3c0(void *param_1) { generated_stub("FUN_008bc3c0 008bc3c0"); } uint32_t FUN_008bc420(void *param_1) { generated_stub("FUN_008bc420 008bc420"); } uint32_t FUN_008bc480(void *param_1) { generated_stub("FUN_008bc480 008bc480"); } @@ -13982,7 +13848,6 @@ void level_generator_rooms_shuffle(int param_1, int param_2) { generated_stub("l void Catch_All_009b1d88() { generated_stub("Catch_All_009b1d88 009b1d88"); } int FUN_009b1dc0(int param_1, int param_2, int param_3) { generated_stub("FUN_009b1dc0 009b1dc0"); } int FUN_009b5800() { generated_stub("FUN_009b5800 009b5800"); } -void FUN_009b9150() { generated_stub("FUN_009b9150 009b9150"); } uint32_t FUN_009b9450(int param_1) { generated_stub("FUN_009b9450 009b9450"); } void FUN_009b9f60(Entity *param_1) { generated_stub("FUN_009b9f60 009b9f60"); } void FUN_009b9fc0(int param_1) { generated_stub("FUN_009b9fc0 009b9fc0"); } diff --git a/generated-src/vector.cpp b/generated-src/vector.cpp index db4f319..99bd0b4 100644 --- a/generated-src/vector.cpp +++ b/generated-src/vector.cpp @@ -55,13 +55,6 @@ Vector * Vector::operator_assign(Vector *other) return this; } -// 0085e630 -uint8_t * Vector::__tostring() -{ - sprintf_s(&DAT_00c82878,0x100,GHIDRA_CAST("%g %g")); - return &DAT_00c82878; -} - // 00a0fe90 Vector::Vector(float x, float y) { diff --git a/generated-src/weighted_outcome_picker.cpp b/generated-src/weighted_outcome_picker.cpp deleted file mode 100644 index 8684f14..0000000 --- a/generated-src/weighted_outcome_picker.cpp +++ /dev/null @@ -1,107 +0,0 @@ -#include "classes.h" - -// 0049cbf0 -uint32_t WeightedOutcomePicker::PickOutcome(RNG rng) -{ - int iVar1; - int iVar2; - int iVar3; - int iVar4; - code *pcVar5; - uint32_t uVar6; - uint32_t outcomeCount; - int *weightPtr; - uint32_t uVar7; - int iVar8; - int iVar9; - int partialSum6; - int partialSum7; - int partialSum0; - int partialSum1; - int partialSum2; - int partialSum3; - int outcomes; - - uVar7 = 0; - outcomes = *GHIDRA_CAST(this); - uVar6 = 0; - outcomeCount = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) - outcomes >> 3; - if ((outcomeCount != 0) && (7 < outcomeCount)) { - partialSum0 = 0; - partialSum1 = 0; - partialSum2 = 0; - partialSum3 = 0; - iVar8 = 0; - iVar9 = 0; - partialSum6 = 0; - partialSum7 = 0; - do { - iVar1 = uVar6 * 8; - iVar2 = uVar6 * 8; - iVar3 = uVar6 * 8; - partialSum0 = partialSum0 + *GHIDRA_CAST((outcomes + 4 + uVar6 * 8)); - partialSum1 = partialSum1 + *GHIDRA_CAST((outcomes + 0xc + uVar6 * 8)); - partialSum2 = partialSum2 + *GHIDRA_CAST((outcomes + 0x14 + uVar6 * 8)); - partialSum3 = partialSum3 + *GHIDRA_CAST((outcomes + 0x1c + uVar6 * 8)); - iVar4 = uVar6 * 8; - uVar6 = uVar6 + 8; - iVar8 = iVar8 + *GHIDRA_CAST((outcomes + 0x24 + iVar4)); - iVar9 = iVar9 + *GHIDRA_CAST((outcomes + 0x2c + iVar3)); - partialSum6 = partialSum6 + *GHIDRA_CAST((outcomes + 0x34 + iVar1)); - partialSum7 = partialSum7 + *GHIDRA_CAST((outcomes + 0x3c + iVar2)); - } while (uVar6 < outcomeCount - (outcomeCount & 7)); - uVar7 = iVar8 + partialSum0 + partialSum6 + partialSum2 + - iVar9 + partialSum1 + partialSum7 + partialSum3; - } - iVar8 = 0; - iVar9 = 0; - if (outcomeCount <= uVar6) goto LAB_0049ccec; - if (outcomeCount - uVar6 < 2) { -LAB_0049cce3: - uVar7 = uVar7 + *GHIDRA_CAST((outcomes + 4 + uVar6 * 8)); - } - else { - do { - iVar8 = iVar8 + *GHIDRA_CAST((outcomes + 4 + uVar6 * 8)); - iVar9 = iVar9 + *GHIDRA_CAST((outcomes + 0xc + uVar6 * 8)); - uVar6 = uVar6 + 2; - } while (uVar6 < outcomeCount - 1); - if (uVar6 < outcomeCount) goto LAB_0049cce3; - } - uVar7 = uVar7 + iVar9 + iVar8; -LAB_0049ccec: - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar5 = (code *)swi(3); - uVar6 = (*pcVar5)(); - return uVar6; - } - uVar6 = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift1 & 0x1f) ^ rng._seed; - uVar6 = uVar6 << ((uint8_t)rng._shift2 & 0x1f) ^ uVar6; - if (uVar7 == 0) { - uVar7 = 0; - } - else { - uVar7 = (uVar6 >> ((uint8_t)rng._shift3 & 0x1f) ^ uVar6) % uVar7; - } - iVar8 = 0; - uVar6 = 0; - outcomes = *GHIDRA_CAST(this); - outcomeCount = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) - outcomes >> 3; - if (outcomeCount != 0) { - weightPtr = GHIDRA_CAST((outcomes + 4)); - do { - iVar8 = iVar8 + *weightPtr; - if (GHIDRA_INT(uVar7) < iVar8) { - return *GHIDRA_CAST((outcomes + uVar6 * 8)); - } - uVar6 = uVar6 + 1; - weightPtr = weightPtr + 2; - } while (uVar6 < outcomeCount); - if (0 < iVar8) { - return 0; - } - } - KAGE_LogMessage(0x10,GHIDRA_CAST("No weights were added. At least one outcome needs weight.")); - return 0; -} diff --git a/src/backdrop.cpp b/src/backdrop.cpp index c4d780c..5a53f7c 100644 --- a/src/backdrop.cpp +++ b/src/backdrop.cpp @@ -46,34 +46,6 @@ constexpr float GRID_SIZE = 26; constexpr int WALL_CELLS = 2; constexpr float WALL_SIZE = WALL_CELLS * GRID_SIZE; -// The backdrops (Lua's BackdropType) drawn or decorated their own way. -constexpr uint32_t BACKDROP_BASEMENT = 1; -constexpr uint32_t BACKDROP_BURNING_BASEMENT = 3; -constexpr uint32_t BACKDROP_DANK_DEPTHS = 9; -constexpr uint32_t BACKDROP_CATHEDRAL = 15; -constexpr uint32_t BACKDROP_DARK_ROOM = 16; -constexpr uint32_t BACKDROP_MEGA_SATAN = 18; -constexpr uint32_t BACKDROP_SHOP = 20; -constexpr uint32_t BACKDROP_ERROR_ROOM = 26; -constexpr uint32_t BACKDROP_GREED_SHOP = 28; -constexpr uint32_t BACKDROP_SACRIFICE = 30; -constexpr uint32_t BACKDROP_DOWNPOUR = 31; -constexpr uint32_t BACKDROP_MINES = 32; -constexpr uint32_t BACKDROP_MAUSOLEUM = 33; -constexpr uint32_t BACKDROP_PLANETARIUM = 35; -constexpr uint32_t BACKDROP_CORPSE_ENTRANCE = 39; -constexpr uint32_t BACKDROP_MAUSOLEUM2 = 40; -constexpr uint32_t BACKDROP_MAUSOLEUM3 = 41; -constexpr uint32_t BACKDROP_MAUSOLEUM4 = 42; -constexpr uint32_t BACKDROP_DROSS = 45; -constexpr uint32_t BACKDROP_ASHPIT = 46; -constexpr uint32_t BACKDROP_GEHENNA = 47; -constexpr uint32_t BACKDROP_CLOSET = 52; -constexpr uint32_t BACKDROP_CLOSET_B = 53; -constexpr uint32_t BACKDROP_DOGMA = 54; -constexpr uint32_t BACKDROP_MINES_SHAFT = 58; -constexpr uint32_t BACKDROP_ASHPIT_SHAFT = 59; - constexpr uint32_t FLOOR_SECOND = 1; constexpr uint32_t HOME_CLOSET_FIRST_SUBTYPE = 10; constexpr int BOSS_MOM_MAUSOLEUM = 89; @@ -149,8 +121,6 @@ constexpr int GLYPH_JITTER = 3; constexpr int JACOB_ESAU_SPLIT_CONTROLS = 1; constexpr int ASCENT_START_ROOM = 84; constexpr uint32_t ASCENT_STAGE_LAST = 6; -constexpr uint32_t STAGE_FIRST = 1; -constexpr uint32_t STAGE_CATHEDRAL = 10; // The control icons the start room shows, a row to each of the controls picture's nulls: moving, shooting, then the // bomb, item, card, drop and card buttons, and shooting again. @@ -836,7 +806,7 @@ static bool is_controls_room() if (game.stage - 1 < ASCENT_STAGE_LAST && (game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH)) startRoom = ASCENT_START_ROOM; - return game.stage == STAGE_FIRST && game.stageType != STAGETYPE_REPENTANCE && + return game.stage == STAGE_BASEMENT_I && game.stageType != STAGETYPE_REPENTANCE && game.stageType != STAGETYPE_REPENTANCE_B && startRoom == game.currentRoomIdx; } @@ -1308,7 +1278,7 @@ static void l_corner_render(Backdrop& backdrop, const WallSheet& sheet, int shap // end, and a top piece) mirrored to each place. static void cathedral_pieces_render(Backdrop& backdrop, int shape, const LRoomTileDesc& tiles) { - if (g_game->stage != STAGE_CATHEDRAL || g_game->stageType != STAGETYPE_WOTL) return; + if (g_game->stage != STAGE_SHEOL || g_game->stageType != STAGETYPE_WOTL) return; SourceQuad side = source_cells(0, WALL_CELLS, WALL_CELLS, 1); SourceQuad sideEnd = source_cells(0, WALL_CELLS, WALL_CELLS, WALL_CELLS, FLIP_Y); diff --git a/src/backdrop.h b/src/backdrop.h index 0ebdfac..d3ef303 100644 --- a/src/backdrop.h +++ b/src/backdrop.h @@ -8,8 +8,73 @@ #include #include -// backdrops.xml fills ids 1 to 62. Id 0 is the default the others start from. -constexpr int BACKDROP_COUNT = 63; +// A room's look (Lua's BackdropType). backdrops.xml fills ids 1 to 62, and id 0 is the default the others start from. +enum BackdropType : int +{ + BACKDROP_BASEMENT = 1, + BACKDROP_CELLAR, + BACKDROP_BURNING_BASEMENT, + BACKDROP_CAVES, + BACKDROP_CATACOMBS, + BACKDROP_FLOODED_CAVES, + BACKDROP_DEPTHS, + BACKDROP_NECROPOLIS, + BACKDROP_DANK_DEPTHS, + BACKDROP_WOMB, + BACKDROP_UTERO, + BACKDROP_SCARRED_WOMB, + BACKDROP_BLUE_WOMB, + BACKDROP_SHEOL, + BACKDROP_CATHEDRAL, + BACKDROP_DARK_ROOM, + BACKDROP_CHEST, + BACKDROP_MEGA_SATAN, + BACKDROP_LIBRARY, + BACKDROP_SHOP, + BACKDROP_ISAAC, + BACKDROP_BARREN, + BACKDROP_SECRET, + BACKDROP_DICE, + BACKDROP_ARCADE, + BACKDROP_ERROR_ROOM, + BACKDROP_BLUE_WOMB_PASS, + BACKDROP_GREED_SHOP, + BACKDROP_DUNGEON, + BACKDROP_SACRIFICE, + BACKDROP_DOWNPOUR, + BACKDROP_MINES, + BACKDROP_MAUSOLEUM, + BACKDROP_CORPSE, + BACKDROP_PLANETARIUM, + BACKDROP_DOWNPOUR_ENTRANCE, + BACKDROP_MINES_ENTRANCE, + BACKDROP_MAUSOLEUM_ENTRANCE, + BACKDROP_CORPSE_ENTRANCE, + BACKDROP_MAUSOLEUM2, + BACKDROP_MAUSOLEUM3, + BACKDROP_MAUSOLEUM4, + BACKDROP_CORPSE2, + BACKDROP_CORPSE3, + BACKDROP_DROSS, + BACKDROP_ASHPIT, + BACKDROP_GEHENNA, + BACKDROP_MORTIS, + BACKDROP_ISAACS_BEDROOM, + BACKDROP_HALLWAY, + BACKDROP_MOMS_BEDROOM, + BACKDROP_CLOSET, + BACKDROP_CLOSET_B, + BACKDROP_DOGMA, + BACKDROP_DUNGEON_GIDEON, + BACKDROP_DUNGEON_ROTGUT, + BACKDROP_DUNGEON_BEAST, + BACKDROP_MINES_SHAFT, + BACKDROP_ASHPIT_SHAFT, + BACKDROP_DARK_CLOSET, + BACKDROP_DEATHMATCH, + BACKDROP_LIL_PORTAL, + BACKDROP_COUNT +}; // How a piece of a backdrop sheet is mirrored as it is drawn, by bit. enum Flip diff --git a/src/beast_arena.cpp b/src/beast_arena.cpp index 7c35bc5..85ad859 100644 --- a/src/beast_arena.cpp +++ b/src/beast_arena.cpp @@ -3,7 +3,6 @@ #include "log.h" #include "room.h" -constexpr int STAGE_ID_HOME = 35; constexpr int BACKGROUND_LAYER_COUNT = 15; constexpr int BACKGROUND_GLOW_LAYER = 8; constexpr int BACKGROUND_ADDITIVE_LAYER = 13; diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index e56a54d..c1e0b68 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -6,6 +6,7 @@ #include "entity_save_state.h" #include "entity_tear.h" #include "game.h" +#include "grid_entity_lock.h" #include "log.h" #include "npc_ai.h" #include "room.h" @@ -43,8 +44,9 @@ constexpr float PLAYER_DAMAGE_STRONG = 85; constexpr float DEATHMATCH_DAMAGE_SCALE = 0.2f; constexpr float IMMOVABLE_MASS = 1000; constexpr int HIT_COUNTDOWN = 30; +constexpr int LOCK_BLAST_DAMAGE = 4; +constexpr float LOCK_BLAST_FRAME = 20; constexpr float TEAR_EFFECT_DAMAGE = 3.5f; -constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; // The grid an explosion breaks: rays cast every so far around its reach, stepping so far, and a line walked in steps. constexpr float RAY_DENSITY = 8; @@ -163,8 +165,12 @@ static void explosion_entity_hurt(Explosion& explosion, Entity& entity, const Te static bool lock_blast(GridEntity& lock) { if (lock.state == 0 && g_game->playerManager.AnyoneHasTrinket(TRINKET_BROKEN_PADLOCK)) - reconstruction_missing("GridEntity_Lock::break_open 00711bb0: a lock Broken Padlock opens for no player"); - return lock.Hurt(4, EntityRef()); + { + static_cast(lock).break_open(nullptr); + if (lock.sprite.animState.animData) lock.sprite.animState.SetFrameFloat(LOCK_BLAST_FRAME); + return true; + } + return lock.Hurt(LOCK_BLAST_DAMAGE, EntityRef()); } // The cells an explosion reaches: its own, and every grid entity along rays cast around it, stopping at metal blocks. diff --git a/src/boss_ai.h b/src/boss_ai.h index e769629..66f1e54 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -49,7 +49,37 @@ inline bool room_is_clear() return g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; } +// Whether a segment follows its parent's trail, or only adds to its own. +enum SegmentMode +{ + SEGMENT_RECORD, + SEGMENT_FOLLOW +}; + +void segment_follow(Entity_NPC& npc, SegmentMode mode, float distance, float maxSpeed); +void segment_death_animation_play(Entity_NPC& npc); +void boss_appear_events(Entity_NPC& npc); + +// A fart (Game::Fart's arguments): where, how far it reaches, what let it, its cloud's size, subtype and tint. +struct Fart +{ + Vector position{}; + Entity* source = nullptr; + ColorMod color = COLOR_DEFAULT; + float radius = 0; + float scale = 1; + int subType = 0; +}; + +void game_fart(const Fart& fart); +bool players_is_falling(); + +void boss_baby_plum_update(Entity_NPC& npc); +void boss_dingle_update(Entity_NPC& npc); +void boss_duke_update(Entity_NPC& npc); void boss_gemini_update(Entity_NPC& npc); +void boss_larry_jr_update(Entity_NPC& npc); +void boss_little_horn_update(Entity_NPC& npc); void boss_monstro_update(Entity_NPC& npc); // Gemini's baby, the variant its twin is tied to. diff --git a/src/boss_baby_plum.cpp b/src/boss_baby_plum.cpp new file mode 100644 index 0000000..3d8b741 --- /dev/null +++ b/src/boss_baby_plum.cpp @@ -0,0 +1,322 @@ +#include "boss_ai.h" +#include "entity_projectile.h" +#include "sfx_manager.h" +#include + +// Baby Plum's attacks, by state: the tear sweep, the stomp and the bouncing tear spray, and leaving. +constexpr int PLUM_SWEEP = NPC_STATE_ATTACK; +constexpr int PLUM_STOMP = NPC_STATE_ATTACK2; +constexpr int PLUM_SPRAY = NPC_STATE_ATTACK3; +constexpr int PLUM_LEAVE = NPC_STATE_SPECIAL; + +// What projectileCooldown means between the attacks' steps: not started, and finished (or leaving). +constexpr int STEP_WAITING = -1; +constexpr int STEP_DONE = -2; + +constexpr int BABY_PLUM_BOSS_ID = 84; +constexpr int CALM_FRAMES = 900; + +constexpr float PLUM_FRICTION = 0.8f; +constexpr float STOMP_FRICTION = 0.7f; +constexpr float STOMP_LANDED_FRICTION = 0.5f; +constexpr float SPRAY_END_FRICTION = 0.9f; +constexpr float SPRAY_FRICTION = 0.98f; +constexpr float CIRCLE_RADIUS = 80; +constexpr float CIRCLE_TURN = 2; +constexpr float CIRCLE_SPEED = 0.6f; +constexpr int PLUM_IDLE_WAIT = 30; +constexpr uint32_t PLUM_ATTACK_ODDS = 30; +constexpr uint32_t ATTACKS = 3; + +constexpr float SHOT_FALL_ACCEL = -0.099f; +constexpr float SWEEP_DRIFT = 4; +constexpr float SWEEP_DAMPING = 0.93f; +constexpr int SWEEP_ARC = 360; +constexpr int SWEEP_STEP = 30; +constexpr float SWEEP_BASE_ANGLE = 90; +constexpr float SWEEP_SHOT_SPEED = 7; + +constexpr int STOMP_SHAKE = 5; +constexpr float STOMP_CREEP_SIZE = 1.5f; +constexpr int STOMP_CREEP_TIMEOUT = 90; +constexpr float STOMP_RING_SPEED = 5; +constexpr int STOMP_RING_SHOTS = 14; +constexpr float STOMP_CROSS_SPEED = 10; + +constexpr float SPRAY_SHOT_SPEED = -5; +constexpr float SPRAY_SHOT_HEIGHT = -10; +constexpr float SPRAY_SHOT_SPEED_SPREAD = 0.2f; +constexpr float SPRAY_SHOT_SPEED_MIN = 0.9f; +constexpr float SPRAY_SHOT_TURN = 60; +constexpr float SPRAY_SHOT_TURN_MIN = -30; +constexpr float SPRAY_SHOT_SCALE_STEP = 3; +constexpr float SPRAY_MOUTH = 12; +constexpr float SPRAY_MOUTH_HEIGHT = 4; +constexpr float SPRAY_PUSH = 0.4f; +constexpr float BOUNCE_NORMAL = 0.2f; +constexpr int SPRAY_FRAMES = 110; +constexpr float SPLASH_TURN = 360; +constexpr float SPLASH_SIZE = 0.8f; +constexpr float SPLASH_SIZE_SPREAD = 0.3f; +constexpr float SPLASH_HEIGHT = -33; +constexpr float SPLASH_DEPTH = 10; +constexpr ColorMod SPLASH_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.54901963f, 0.043137256f, 0.058823533f}}; + +constexpr float LEAVE_SPEED = 0.75f; +constexpr float LEAVE_FRICTION = 0.98f; +constexpr float ROOM_MIDDLE = 0.5f; + +// A random fraction scaled into a range starting at a minimum. +static float random_between(float minimum, float spread) +{ + return random_unit() * spread + minimum; +} + +// Idling, it circles its target on the grid. A boss room's Baby Plum left alone for 900 frames leaves, and after +// a short wait it now and then picks one of its three attacks. +static void plum_idle(Entity_NPC& npc) +{ + npc.friction *= PLUM_FRICTION; + npc.sprite.Play("Idle"); + Vector prey = npc.GetPlayerTarget()->pos; + float angle = (float)(g_game->frameCount - npc.spawnFrame) * CIRCLE_TURN * DEGREES_TO_RADIANS; + Vector orbit = vector_make(std::cos(angle) * CIRCLE_RADIUS + prey.x, std::sin(angle) * CIRCLE_RADIUS + prey.y); + npc.pathfinder.FindGridPath(orbit, CIRCLE_SPEED, 0, DIRECT_PATH_FAR); + + int calmSince = g_game->room->unknown73f0; + if (calmSince > 0 && g_game->frameCount - calmSince > CALM_FRAMES) + { + npc.state = PLUM_LEAVE; + npc.targetPosition = {}; + npc.projectileCooldown = STEP_WAITING; + npc.stateFrame = 0; + return; + } + + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame <= PLUM_IDLE_WAIT || Random() % PLUM_ATTACK_ODDS != 0) return; + constexpr int ATTACK_STATES[ATTACKS] = {PLUM_SWEEP, PLUM_STOMP, PLUM_SPRAY}; + npc.state = ATTACK_STATES[Random() % ATTACKS]; + npc.projectileCooldown = STEP_WAITING; +} + +// The sweep: on Shoot it lunges at its target, then each tick fires a shot sweeping round from below it, a twelfth +// of a turn apart, while the lunge dies down. +static void plum_sweep(Entity_NPC& npc) +{ + npc.friction *= PLUM_FRICTION; + npc.sprite.Play("Attack1"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.targetPosition = vector_scale(aim, SWEEP_DRIFT); + npc.projectileCooldown = 0; + npc.sprite.isFlipX = aim.x * SWEEP_DRIFT < 0; + } + if (npc.sprite.IsEventTriggered("Sound")) npc.sprite.isFlipX = false; + if (!npc.sprite.IsPlaying()) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + return; + } + if (npc.projectileCooldown < 0) return; + + if (npc_ticks_get(npc) > 0) + { + if (npc.projectileCooldown <= SWEEP_ARC) + { + ProjectileParams params; + params.fallingAccelModifier += SHOT_FALL_ACCEL; + float turn = (float)npc.projectileCooldown; + float angle = (npc.sprite.isFlipX ? turn + SWEEP_BASE_ANGLE : SWEEP_BASE_ANGLE - turn) * DEGREES_TO_RADIANS; + Vector shot = vector_make(std::cos(angle) * SWEEP_SHOT_SPEED, std::sin(angle) * SWEEP_SHOT_SPEED); + npc.FireProjectiles(npc.pos, shot, PROJECTILES_SINGLE, params); + } + npc.projectileCooldown += SWEEP_STEP; + } + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, npc.speedMultiplier)); + float damping = SWEEP_DAMPING; + if (npc.speedMultiplier != 1) + damping = SWEEP_DAMPING / ((npc.speedMultiplier + SWEEP_DAMPING) - npc.speedMultiplier * SWEEP_DAMPING); + npc.targetPosition = vector_scale(npc.targetPosition, damping); +} + +// The stomp: on Shoot the screen shakes, red creep spreads and shots burst out in a ring of fourteen and a cross of +// eight. It stays off pits until Sound. +static void plum_stomp(Entity_NPC& npc) +{ + npc.friction *= STOMP_FRICTION; + npc.sprite.Play("Attack2"); + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + if (npc.sprite.IsEventTriggered("Shoot")) + { + game_shake_screen(STOMP_SHAKE); + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, 1); + npc.projectileCooldown = 0; + auto* creep = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, + .seed = Random()})); + creep->sprite.scale = vector_make(STOMP_CREEP_SIZE, STOMP_CREEP_SIZE); + creep->timeout = STOMP_CREEP_TIMEOUT; + creep->lifespan = STOMP_CREEP_TIMEOUT; + + ProjectileParams params; + params.fallingAccelModifier += SHOT_FALL_ACCEL; + npc.FireProjectiles(npc.pos, vector_make(STOMP_RING_SPEED, STOMP_RING_SHOTS), PROJECTILES_RING, params); + npc.FireProjectiles(npc.pos, vector_make(STOMP_CROSS_SPEED, 0), PROJECTILES_EIGHT, params); + } + if (npc.sprite.IsEventTriggered("Sound")) npc.projectileCooldown = STEP_WAITING; + else if (npc.projectileCooldown >= 0) + { + if (room_grid_collision_at(npc.pos) == 0) npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.friction *= STOMP_LANDED_FRICTION; + } + if (npc.sprite.IsPlaying()) return; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; +} + +// One step of the spray: a shot backward from its mouth, sized and turned at random, and a red splash where it +// leaves, drawn in front while it heads up. +static void spray_shot(Entity_NPC& npc) +{ + npc_sound_play(SOUND_BOSS2_BUBBLES, 1, 2, 1); + ProjectileParams params; + params.fallingAccelModifier += SHOT_FALL_ACCEL; + params.heightModifier = SPRAY_SHOT_HEIGHT; + params.scale = ((float)((Random() & 3) + 4) - SPRAY_SHOT_SCALE_STEP) / SPRAY_SHOT_SCALE_STEP; + Vector shot = vector_scale(npc.targetPosition, SPRAY_SHOT_SPEED); + shot = vector_scale(shot, random_between(SPRAY_SHOT_SPEED_MIN, SPRAY_SHOT_SPEED_SPREAD)); + float turn = random_between(SPRAY_SHOT_TURN_MIN, SPRAY_SHOT_TURN) * DEGREES_TO_RADIANS; + float cosine = std::cos(turn); + float sine = std::sin(turn); + shot = vector_make(shot.x * cosine - shot.y * sine, shot.x * sine + shot.y * cosine); + Vector mouth = vector_make(npc.pos.x - npc.targetPosition.x * SPRAY_MOUTH, npc.pos.y - SPRAY_MOUTH_HEIGHT); + npc.FireProjectiles(mouth, shot, PROJECTILES_SINGLE, params); + + Entity* splash = g_game->Spawn( + {.position = mouth, .type = ENTITY_EFFECT, .variant = EFFECT_TEAR_POOF_SMALL, .seed = Random()}); + splash->sprite.rotation = random_unit() * SPLASH_TURN; + float size = random_between(SPLASH_SIZE, SPLASH_SIZE_SPREAD); + splash->sprite.scale = vector_make(size, size); + splash->sprite.color = SPLASH_COLOR; + splash->posOffset = vector_make(0, SPLASH_HEIGHT); + if (npc.targetPosition.y < 0) splash->renderDepthOffset = SPLASH_DEPTH; +} + +// The spray: on Shoot it takes off up and to a random side, then flies about the room spraying shots behind it every +// other tick, bouncing off walls, until it heads up again after 110 ticks and lands. +static void plum_spray(Entity_NPC& npc) +{ + if (npc.projectileCooldown == STEP_WAITING) + { + npc.friction *= PLUM_FRICTION; + npc.sprite.Play("Attack3"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + float side = (Random() & 1) == 0 ? 1.0f : -1.0f; + npc.targetPosition = vector_make(side, -1); + npc.sprite.isFlipX = side < 0; + npc.targetPosition = vector_normalized(npc.targetPosition); + npc.projectileCooldown = 0; + } + } + else if (npc.projectileCooldown == STEP_DONE) + { + npc.friction *= SPRAY_END_FRICTION; + npc.sprite.Play("Attack3End"); + if (!npc.sprite.IsPlaying()) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + } + } + if (npc.projectileCooldown < 0) return; + + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Attack3Loop"); + npc.friction = SPRAY_FRICTION; + for (int ticks = npc_ticks_get(npc); ticks > 0; ticks--) + if (++npc.projectileCooldown % 2 == 0) spray_shot(npc); + + if (npc.isCollidesWithGrid) + { + Vector& heading = npc.targetPosition; + Vector normal = npc.gridCollisionNormal; + if ((heading.x > 0 && normal.x > BOUNCE_NORMAL) || (heading.x < 0 && normal.x < -BOUNCE_NORMAL)) + heading.x = -heading.x; + if ((heading.y > 0 && normal.y > BOUNCE_NORMAL) || (heading.y < 0 && normal.y < -BOUNCE_NORMAL)) + heading.y = -heading.y; + float speed = vector_length(npc.velocity); + if (speed > 0) npc.velocity = vector_scale(npc.velocity, vector_length(npc.gridCollisionVelocity) / speed); + } + npc.sprite.Play(npc.targetPosition.y > 0 ? "Attack3BackLoop" : "Attack3Loop"); + npc.sprite.isFlipX = npc.targetPosition.x < 0; + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, SPRAY_PUSH * npc.speedMultiplier)); + if (npc.projectileCooldown <= SPRAY_FRAMES || npc.targetPosition.y >= 0) return; + npc.sprite.isFlipX = false; + npc.projectileCooldown = STEP_DONE; +} + +// Leaving: untouchable, on Shoot it flies off toward the farther side of the room, and once gone it counts as beaten. +static void plum_leave(Entity_NPC& npc) +{ + npc.sprite.Play("Leave"); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + if (npc.projectileCooldown == STEP_DONE) + { + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, LEAVE_SPEED * npc.speedMultiplier)); + npc.friction *= LEAVE_FRICTION; + } + else + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + Room& room = *g_game->room; + npc.projectileCooldown = STEP_DONE; + float middle = (room.bottomRightPos.x - room.topLeftPos.x) * ROOM_MIDDLE + room.topLeftPos.x; + bool isRight = npc.pos.x >= middle; + npc.targetPosition = vector_make(isRight ? 1.0f : -1.0f, 0); + npc.sprite.isFlipX = !isRight; + } + npc.friction *= PLUM_FRICTION; + } + if (npc.sprite.IsPlaying()) return; + g_game->room->unknown73f0 = -1; + npc.Remove(); + g_game->room->TriggerBossDeath(npc); +} + +// 0043f0c0 NpcAI::ENTITY_BABY_PLUM: Baby Plum circles its target and sweeps, stomps or sprays tears. In its boss +// room Room::unknown73f0 holds the frame it was last hurt, and left unhurt for 900 frames it flies away. +void boss_baby_plum_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_IDLE; + if (room.roomType == ROOM_BOSS && room.bossId == BABY_PLUM_BOSS_ID) room.unknown73f0 = g_game->frameCount; + break; + case NPC_STATE_IDLE: + plum_idle(npc); + if (npc.state == PLUM_LEAVE) return; + break; + case PLUM_SWEEP: + plum_sweep(npc); + break; + case PLUM_STOMP: + plum_stomp(npc); + break; + case PLUM_SPRAY: + plum_spray(npc); + break; + case PLUM_LEAVE: + plum_leave(npc); + break; + } + if (room.unknown73f0 > 0 && npc.pendingDamage > 0) room.unknown73f0 = g_game->frameCount; +} diff --git a/src/boss_death.cpp b/src/boss_death.cpp index f8b2e75..a451050 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -73,7 +73,6 @@ 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}; diff --git a/src/boss_dingle.cpp b/src/boss_dingle.cpp new file mode 100644 index 0000000..d6722ed --- /dev/null +++ b/src/boss_dingle.cpp @@ -0,0 +1,391 @@ +#include "boss_ai.h" +#include "entity_projectile.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// Dingle and Dangle (variant 1), and the subtypes that change what they summon and shoot. +constexpr int DANGLE = 1; +constexpr int DINGLE_POOPER = 1; +constexpr int DINGLE_SPIDERS = 2; +constexpr int CORNY_DIP = 2; +constexpr int RED_POOP = 1; + +// Dingle's states beyond the shared ones. +constexpr int DINGLE_WHISTLE = NPC_STATE_ATTACK2; +constexpr int DINGLE_DANCE = NPC_STATE_ATTACK3; +constexpr int DINGLE_BEFORE_SLIDE = NPC_STATE_ATTACK4; +constexpr int DINGLE_TIRED = NPC_STATE_SPECIAL; + +constexpr ColorMod DINGLE_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; +constexpr ColorMod DANGLE_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; + +constexpr int DINGLE_IDLE_WAIT = 15; +constexpr int DANGLE_IDLE_WAIT = 30; +constexpr uint32_t ACT_ODDS = 10; +constexpr uint32_t DANGLE_ACT_ODDS = 20; +constexpr uint32_t HURT_ACT_ODDS = 5; +constexpr uint32_t DANGLE_HURT_ACT_ODDS = 10; +constexpr uint32_t WHISTLE_ODDS = 3; +constexpr uint64_t STUNNED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +constexpr float SLIDE_KICK = 10; +constexpr float SPIDERS_SLIDE_KICK = 15; +constexpr float SLIDE_PUSH = 1; +constexpr float SPIDERS_SLIDE_PUSH = 1.5f; +constexpr float DINGLE_SLIDE_FRICTION = 0.98f; +constexpr float SLIDE_REST_FRICTION = 0.9f; +constexpr float STILL_FRICTION = 0.7f; +constexpr int SLIDE_SOUND_DELAY = 30; +constexpr uint32_t SLIDE_DROP_ODDS = 5; +constexpr int SLIDE_REST = 12; +constexpr int SLIDES = 2; +constexpr int DANGLE_SLIDES = 1; +constexpr int POOPER_SLIDES = 3; +constexpr float SLIDE_FART_REACH = 20; +constexpr float SLIDE_FART_SCALE = 0.5f; +constexpr float SLIDE_FART_INTERVAL = 2; +constexpr float SLIDE_CREEP_SCALE = 0.75f; +constexpr float SLIDE_CREEP_SCALE_SPREAD = 0.25f; + +constexpr float WALL_SPLAT_REACH = 200; +constexpr float WALL_SPLAT_MARGIN = -24; +constexpr float WALL_SPLAT_SIZE = 1; +constexpr float WALL_SPLAT_SIZE_SPREAD = 2; +constexpr float WALL_SPLAT_TURN = 90; +constexpr int DINGLE_SPLAT_FRAMES = 2; +constexpr int TRAIL_SPLAT_FRAMES = 5; +constexpr float DINGLE_SPLAT_SIZE = 0.2f; +constexpr float DINGLE_SPLAT_SIZE_SPREAD = 0.5f; + +constexpr float DINGLE_SHOT_SPEED = 10; +constexpr float SPRAY_FALLING_ACCEL = 0.001f; +constexpr float SPRAY_FALLING_SPEED = -1; +constexpr int SUMMON_ENEMY_LIMIT = 5; +constexpr int POOP_LIMIT = 6; +constexpr int DIP_LIMIT = 3; +constexpr float SUMMON_REACH = 60; +constexpr float SUMMON_SCATTER = 10; +constexpr float DANGLE_DIP_AHEAD = 30; +constexpr float DANGLE_DIP_KICK = 15; +constexpr float MUSIC_VOLUME = 0.6f; +constexpr int MUSIC_DELAY = 60; +constexpr int WHISTLE_DELAY = 60; +constexpr uint32_t TIRED_WAIT = 60; +constexpr uint32_t TIRED_WAIT_SPREAD = 30; + +// Whether a cell may take a new poop: off the grid, empty, or under a decoration or web, and not in a crawlspace. +static bool poop_cell_is_free(int cell) +{ + Room& room = *g_game->room; + GridEntity* standing = (uint32_t)cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + bool isClear = !standing || standing->type == GRID_DECORATION || standing->type == GRID_SPIDERWEB; + return isClear && room.roomType != ROOM_DUNGEON; +} + +// A blood splat under it, tinted brown, scaled 0.2 to 0.7. +static Entity_Effect* dingle_splat(Entity_NPC& npc, const ColorMod& color) +{ + Entity_Effect* splat = npc.MakeSplat(random_unit() * DINGLE_SPLAT_SIZE_SPREAD + DINGLE_SPLAT_SIZE); + splat->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + return splat; +} + +// Idling, until it whistles for help, dances, or slides at its target, sooner when hurt. A calm Delirium form idles. +static void dingle_idle(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + + bool isDangle = npc.variant == DANGLE; + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame <= (isDangle ? DANGLE_IDLE_WAIT : DINGLE_IDLE_WAIT)) return; + if (Random() % (isDangle ? DANGLE_ACT_ODDS : ACT_ODDS) != 0) + { + if (npc.pendingDamage <= 0) return; + if (Random() % (isDangle ? DANGLE_HURT_ACT_ODDS : HURT_ACT_ODDS) != 0) return; + } + + if (Random() % WHISTLE_ODDS == 0) npc.state = DINGLE_WHISTLE; + else if ((Random() & 1) == 0 && !npc.HasEntityFlags(STUNNED)) npc.state = DINGLE_BEFORE_SLIDE; + else npc.state = DINGLE_DANCE; +} + +// The slide's kick toward its target: Dingle may leave a poop and Dangle a corn mine where it starts. +static void slide_kick(Entity_NPC& npc) +{ + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + float kick = npc.subtype == DINGLE_SPIDERS ? SPIDERS_SLIDE_KICK : SLIDE_KICK; + npc.velocity = vector_add(npc.velocity, vector_scale(aim, kick)); + npc.PlaySound(SOUND_FART_GURG, 1, SLIDE_SOUND_DELAY, false, 1); + if (npc.i1 != 0 || Random() % SLIDE_DROP_ODDS != 0) return; + + if (npc.variant == 0) + { + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.pos); + if (poop_cell_is_free(cell)) room.SpawnGridEntity(cell, GRID_POOP, 0, npc.dropRNG.Next(), 0); + } + else if (npc.variant == DANGLE) + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_CORN_MINE, .seed = Random()}); + npc.PlaySound(SOUND_FART, 1, 2, false, 1); +} + +// Dangle's slide trail: a fart every other tick and a creep puddle, green when poisoned, white when slowed. +static void dangle_trail(Entity_NPC& npc) +{ + if (npc.GetIntervalTicks(SLIDE_FART_INTERVAL, 0) != 0) + game_fart({.position = npc.pos, .source = &npc, .radius = npc.size + SLIDE_FART_REACH, .scale = SLIDE_FART_SCALE}); + + int creep = npc.HasEntityFlags(FLAG_POISON) ? EFFECT_CREEP_GREEN : EFFECT_CREEP_SLIPPERY_BROWN; + if (npc.HasEntityFlags(FLAG_SLOW)) creep = EFFECT_CREEP_WHITE; + Entity* puddle = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = creep, .seed = Random()}); + float size = random_unit() * SLIDE_CREEP_SCALE_SPREAD + SLIDE_CREEP_SCALE; + puddle->sprite.scale = vector_make(size, size); + puddle->Update(); +} + +// Hitting a wall: it picks a new random spot and splashes a splat on the wall behind the hit, turned to face out. +static void slide_wall_hit(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.targetPosition = room.GetRandomPosition(0); + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + + float margin = random_unit() * WALL_SPLAT_MARGIN; + Vector behind = vector_add(npc.pos, vector_scale(npc.gridCollisionNormal, WALL_SPLAT_REACH)); + Vector spot = room.GetClampedPositionImpl(behind, margin, margin, margin, margin); + GridEntity* wall = room_grid_entity_at(spot); + if (!wall || (wall->type != GRID_WALL && wall->type != GRID_DOOR)) return; + + Entity_Effect* splat = npc.MakeSplat(random_unit() * WALL_SPLAT_SIZE_SPREAD + WALL_SPLAT_SIZE); + splat->pos = spot; + splat->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->AddEntityFlags(FLAG_RENDER_WALL); + splat->sprite.rotation = vector_angle(vector_cardinal(npc.gridCollisionNormal)) + WALL_SPLAT_TURN; + splat->Update(); +} + +// The slide: a short rest between slides, then a kick at its target on Slide and a push along while it lasts. Each +// slide ends at its animation's end or when stunned, up to its slides in a row before it tires. +static void dingle_slide(Entity_NPC& npc) +{ + if (npc.stateFrame != 0) + { + npc.friction *= SLIDE_REST_FRICTION; + npc.stateFrame = std::max(npc.stateFrame - npc_ticks_get(npc), 0); + if (npc.stateFrame == 0) npc.sprite.Play("Slide", PLAY_FORCED); + return; + } + + npc.sprite.Play("Slide"); + if (npc.sprite.IsEventTriggered("Slide")) slide_kick(npc); + npc.friction *= DINGLE_SLIDE_FRICTION; + if (npc.sprite.WasEventTriggered("Slide")) + { + Vector push = vector_resized(npc.velocity, npc.subtype == DINGLE_SPIDERS ? SPIDERS_SLIDE_PUSH : SLIDE_PUSH); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(push, npc.speedMultiplier / npc.friction)); + if (npc.variant == DANGLE) dangle_trail(npc); + } + npc.sprite.isFlipX = npc.velocity.x > 0; + if (npc.IsFrame(DINGLE_SPLAT_FRAMES, (int)npc.index)) dingle_splat(npc, DINGLE_SPLAT_COLOR); + + if (!npc.sprite.IsPlaying() || npc.HasEntityFlags(STUNNED)) + { + int slides = npc.variant == DANGLE ? DANGLE_SLIDES : SLIDES; + if (npc.subtype == DINGLE_POOPER) slides = POOPER_SLIDES; + else if (npc.subtype == DINGLE_SPIDERS) slides = 0; + if (npc.i1 < slides) + { + npc.stateFrame = (int)(Random() & 3) + SLIDE_REST; + npc.i1++; + } + else + { + npc.state = DINGLE_TIRED; + npc.stateFrame = 0; + npc.i1 = 0; + } + } + if (npc.isCollidesWithGrid) slide_wall_hit(npc); +} + +// The spit on Shoot: three shots at its target (puke, or blood for the pooper, corn for Dangle) or, for the spider +// Dingle, a ring of eight. It faces its target once it spat, and idles when done. +static void dingle_shoot(Entity_NPC& npc) +{ + npc.sprite.Play("Spit"); + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.sprite.IsEventTriggered("Shoot")) + { + ProjectileParams params; + params.variant = npc.variant == DANGLE ? PROJECTILE_CORN : npc.subtype == DINGLE_POOPER ? PROJECTILE_NORMAL + : PROJECTILE_PUKE; + if (npc.subtype == DINGLE_SPIDERS) + { + params.fallingAccelModifier = SPRAY_FALLING_ACCEL; + params.fallingSpeedModifier = SPRAY_FALLING_SPEED; + npc.FireProjectiles(npc.pos, vector_make(DINGLE_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); + } + else + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(toTarget), DINGLE_SHOT_SPEED), PROJECTILES_THREE, + params); + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + } + if (npc.sprite.WasEventTriggered("Shoot")) npc.sprite.isFlipX = toTarget.x > 0; + if (npc.sprite.IsPlaying()) return; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; +} + +// A spot near it a summon takes: a free pickup spot within reach, scattered a little. +static Vector summon_spot(Entity_NPC& npc) +{ + Vector free = room_free_pickup_position_find({.position = npc.pos, .step = SUMMON_REACH}); + Vector scatter = random_direction(); + float spread = random_unit(); + return vector_add(vector_scale(vector_scale(scatter, spread), SUMMON_SCATTER), free); +} + +// Dangle's corny dip, flung out ahead toward its target and already moving. +static void dangle_dip_spawn(Entity_NPC& npc) +{ + Vector aim = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + uint32_t seed = Random(); + Vector scatter = random_direction(); + float spread = random_unit() * SUMMON_SCATTER; + Vector spot = vector_add(vector_add(vector_scale(scatter, spread), vector_scale(aim, DANGLE_DIP_AHEAD)), npc.pos); + auto* dip = static_cast(g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_DIP, .variant = CORNY_DIP, .seed = seed})); + if (dip->friction != 0) + dip->velocity = vector_add(dip->velocity, vector_scale(aim, DANGLE_DIP_KICK * dip->speedMultiplier / dip->friction)); + dip->ClearEntityFlags(FLAG_APPEAR); + dip->Update(); + dip->state = NPC_STATE_MOVE; +} + +// A spider near it, for the spider Dingle's whistle. +static void spider_spawn(Entity_NPC& npc) +{ + uint32_t seed = Random(); + Vector spot = summon_spot(npc); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_SPIDER, .seed = seed}); +} + +// The whistle's summons on Spawn: one or two dips (three at most in all for a Delirium form), a red poop for the +// pooper (six at most), or one or two spiders for the spider Dingle. Only while the room has few enemies, except that +// the check lets everything but the pooper through. False when nothing was summoned for that. +static bool whistle_summon(Entity_NPC& npc) +{ + Room& room = *g_game->room; + bool isFewEnemies = room.GetAliveEnemiesCount() < SUMMON_ENEMY_LIMIT; + if (!((isFewEnemies && npc.subtype != DINGLE_POOPER) || npc.i2 < POOP_LIMIT)) return false; + + if (npc.subtype == 0) + { + int count = (int)(Random() & 1) + 1; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + count = std::min(count, DIP_LIMIT - npc.CountRelatedEntities(ENTITY_DIP, 0, nullptr)); + for (int i = 0; i < count; i++) + { + if (npc.variant == DANGLE) + { + dangle_dip_spawn(npc); + continue; + } + uint32_t seed = Random(); + Vector spot = summon_spot(npc); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_DIP, .seed = seed})->Update(); + } + } + else if (npc.subtype == DINGLE_POOPER) + { + int cell = room.GetGridIndex(room_free_pickup_position_find({.position = npc.pos, .step = SUMMON_REACH})); + if (poop_cell_is_free(cell)) + { + room.SpawnGridEntity(cell, GRID_POOP, RED_POOP, npc.dropRNG.Next(), 0); + npc.i2++; + } + } + else if (npc.subtype == DINGLE_SPIDERS) + { + spider_spawn(npc); + if ((Random() & 1) == 0) spider_spawn(npc); + } + return true; +} + +// Dingle (and Dangle, variant 1) idles, whistles up dips (or poop or spiders by subtype), dances, and slides at its +// target in bursts before it tires. Each whistle or dance ends in a spit. +static void dingle_act(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_IDLE: + return dingle_idle(npc); + case NPC_STATE_MOVE: + return dingle_slide(npc); + case NPC_STATE_ATTACK: + return dingle_shoot(npc); + case DINGLE_WHISTLE: + npc.sprite.Play("Whistle"); + npc.PlaySound(npc.variant == DANGLE ? SOUND_DANGLE_WHISTLE : SOUND_WHISTLE, 1, WHISTLE_DELAY, false, 1); + if (npc.sprite.IsEventTriggered("Spawn") && whistle_summon(npc)) + npc.PlaySound(SOUND_MEAT_JUMPS, MUSIC_VOLUME, 2, false, 1); + break; + case DINGLE_DANCE: + npc.sprite.Play("Dance"); + npc.PlaySound(SOUND_MEAT_JUMPS, MUSIC_VOLUME, MUSIC_DELAY, false, 1); + break; + case DINGLE_BEFORE_SLIDE: + npc.sprite.Play("BeforeSlide"); + npc.PlaySound(SOUND_MEAT_JUMPS, MUSIC_VOLUME, MUSIC_DELAY, false, 1); + if (npc.sprite.IsPlaying()) return; + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + return; + case DINGLE_TIRED: + { + npc.sprite.Play("Tired"); + uint32_t wait = Random() % TIRED_WAIT_SPREAD + TIRED_WAIT; + if (npc.variant == DANGLE) wait /= 2; + if (npc.stateFrame++ <= (int)wait) return; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + return; + } + default: + return; + } + if (npc.sprite.IsPlaying()) return; + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; +} + +// 004855b0 NpcAI::ENTITY_DINGLE: Dingle and Dangle. The pooper (subtype 1) shrugs off poop damage. Every fifth frame +// it leaves a splat, and it slows down hard unless sliding. +void boss_dingle_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.splatColor = npc.variant == DANGLE ? DANGLE_SPLAT_COLOR : DINGLE_SPLAT_COLOR; + npc.i1 = 0; + npc.i2 = 0; + return; + } + + npc.sprite.isFlipX = false; + if (npc.subtype == DINGLE_POOPER) + for (DamageEvent& hit : npc.damageEvents) + if (hit.damageFlags & DAMAGE_POOP) hit.damage = 0; + dingle_act(npc); + + bool isTrailFrame = (g_game->frameCount + (int)npc.index) % TRAIL_SPLAT_FRAMES == 0; + if (!npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && isTrailFrame) + dingle_splat(npc, npc.splatColor); + if (npc.state != NPC_STATE_MOVE) npc.friction *= STILL_FRICTION; +} diff --git a/src/boss_duke.cpp b/src/boss_duke.cpp new file mode 100644 index 0000000..38e92f5 --- /dev/null +++ b/src/boss_duke.cpp @@ -0,0 +1,382 @@ +#include "boss_ai.h" +#include "entity_projectile.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// The Duke of Flies (variant 0) and the Husk (variant 1), and their subtypes. +constexpr int HUSK = 1; +constexpr int DUKE_MOTERS = 1; +constexpr int DUKE_SUCKERS = 2; +constexpr int HUSK_BOOM_FLY = 1; +constexpr int HUSK_RED_BOOM_FLY = 2; +constexpr int RED_BOOM_FLY = 1; + +// The Duke's attacks, by state: the fly burst (blowing its flies away), the fly cough and the big fly. +constexpr int DUKE_BURST = NPC_STATE_ATTACK; +constexpr int DUKE_COUGH = NPC_STATE_SUMMON; +constexpr int DUKE_BIG_FLY = NPC_STATE_SUMMON2; + +constexpr float CEILING_MARGIN = 40; +constexpr float DUKE_SPEED = 0.4f; +constexpr float HUSK_SPEED = 0.8f; +constexpr float RED_HUSK_SPEED = 1.1f; +constexpr float BOOM_HUSK_SPEED = 0.5f; +constexpr float DRIFT_DOWN_THRESHOLD = 0.1f; +constexpr float DUKE_FRICTION = 0.8f; +constexpr float SUCKER_DUKE_FRICTION = 0.9f; +constexpr float DUKE_FLEE_RANGE = 180; +constexpr float DUKE_FLEE_STRENGTH = 0.02f; +constexpr float DUKE_FLEE_MAX = 1; + +constexpr uint32_t COUGH_ODDS = 40; +constexpr uint32_t BIG_FLY_ODDS = 70; +constexpr uint32_t DUKE_BURST_ODDS = 45; +constexpr uint32_t LONE_BURST_ODDS = 70; +constexpr uint32_t RED_HUSK_BURST_ODDS = 20; +constexpr int COUGH_LIMIT = 9; +constexpr int BIG_FLY_LIMIT = 10; +constexpr int BURST_FLIES = 5; +constexpr int BURST_OTHERS = 4; +constexpr int ATTACK_FRAMES = 39; + +constexpr int BURST_FRAME = 17; +constexpr float DUKE_BURST_PUSH = 18; +constexpr float TINY_FLY_PUSH = 3; +constexpr float NEAR_SQUARED = 0.01f; +constexpr float HUSK_RING_HEIGHT = 40; +constexpr float HUSK_RING_SPEED = 8; +constexpr float MOTER_RING_SPEED = 7; +constexpr int DUKE_RING_SHOTS = 8; + +constexpr int COUGH_FRAME = 20; +constexpr float WING_TURN = 90; +constexpr float WING_HEIGHT = -40; +constexpr ColorMod WING_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float MOUTH_DROP = 20; +constexpr float FLY_GAP = 10; +constexpr int COUGHED_FLIES = 3; +constexpr int DELIRIUM_FLY_LIMIT = 6; +constexpr int DELIRIUM_BOOM_FLY_LIMIT = 3; +constexpr float MIDPOINT = 0.5f; +constexpr float SPIDER_TARGET_REACH = 70; +constexpr float SPIDER_HEIGHT = -30; +constexpr int TINY_FLY_LIMIT = 25; +constexpr uint32_t TINY_FLIES = 5; +constexpr float TINY_FLY_SCATTER = 40; + +constexpr int BIG_FLY_FRAME = 18; +constexpr int BIG_FLY_LIMIT_ALIVE = 5; +constexpr float DUKE_BIG_FLY_SCALE = 1.25f; +constexpr float BIG_FLY_HEALTH = 1.8f; +constexpr int HUSK_SHOTS = 10; + +constexpr float DEATH_TINY_FLY_SCATTER = 50; +constexpr uint32_t DEATH_TINY_FLIES = 10; +constexpr uint32_t DEATH_TINY_FLIES_MIN = 5; +constexpr int DEATH_FLIES = 6; +constexpr uint32_t HUSK_DEATH_FLIES = 3; +constexpr int HUSK_DEATH_FLIES_MIN = 4; +constexpr float DEATH_FLY_SCATTER = 0.8f; + +// A spot scattered about a center, the angle rolled first. +static Vector scatter_spot(const Vector& center, float reach) +{ + Vector direction = random_direction(); + float distance = random_unit() * reach; + return vector_add(vector_scale(direction, distance), center); +} + +// Pushes an entity straight away from the Duke by a speed, unless it sits on it. +static void push_away(Entity_NPC& npc, Entity& entity, float speed) +{ + Vector away = vector_sub(entity.pos, npc.pos); + float distanceSquared = vector_length_squared(away); + if (distanceSquared <= NEAR_SQUARED) return; + float distance = std::sqrt(distanceSquared); + Vector push = vector_scale(away, speed / distance); + if (entity.friction != 0) + entity.velocity = vector_add(entity.velocity, vector_scale(push, entity.speedMultiplier / entity.friction)); +} + +// A minion that starts at once and dies on touch. +static void minion_ready(Entity& minion) +{ + minion.ClearEntityFlags(FLAG_APPEAR); + minion.isKillOnTouch = true; +} + +// It floats diagonally, bouncing off the walls below the ceiling margin, and keeps away from its target while feared +// or shrunk. Confused (and not charmed), it wanders. +static void duke_float(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.pos = room.GetClampedPositionImpl(npc.pos, CEILING_MARGIN, 0, 0, 0); + if (npc.pos.x == room.bottomRightPos.x) npc.velocity.x = -1; + if (npc.pos.x == room.topLeftPos.x) npc.velocity.x = 1; + if (npc.pos.y == room.bottomRightPos.y) npc.velocity.y = -1; + if (npc.pos.y == room.topLeftPos.y + CEILING_MARGIN) npc.velocity.y = 1; + + float speed = DUKE_SPEED; + if (npc.variant == HUSK) + speed = npc.subtype == HUSK_RED_BOOM_FLY ? RED_HUSK_SPEED : npc.subtype == HUSK_BOOM_FLY ? BOOM_HUSK_SPEED + : HUSK_SPEED; + bool isSuckerDuke = npc.variant == 0 && npc.subtype == DUKE_SUCKERS; + if (npc.HasEntityFlags(FLAG_CONFUSION) && !npc.HasEntityFlags(FLAG_CHARM)) + { + npc.friction *= DUKE_FRICTION; + if (isSuckerDuke) npc.friction *= SUCKER_DUKE_FRICTION; + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + Vector drift = vector_make(npc.velocity.x > 0 ? 1 : -1, npc.velocity.y < DRIFT_DOWN_THRESHOLD ? -1 : 1); + npc.friction *= DUKE_FRICTION; + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(drift, speed * npc.speedMultiplier / npc.friction)); + if (isSuckerDuke) npc.friction *= SUCKER_DUKE_FRICTION; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + float strength = std::clamp((DUKE_FLEE_RANGE - distance) * DUKE_FLEE_STRENGTH, 0.0f, DUKE_FLEE_MAX); + if (distance > 0) away = vector_scale(away, strength / distance); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(away, npc.speedMultiplier / npc.friction)); +} + +// While floating it may cough up flies, spit a big fly, or burst its flies away, by how many flies it keeps +// (groupSize) and how crowded the room is. The red Husk never coughs. A calm Delirium form only floats. +static void duke_choose(Entity_NPC& npc, int groupSize, int enemies) +{ + bool isRedHusk = npc.variant == HUSK && npc.subtype == HUSK_RED_BOOM_FLY; + bool isMoterDuke = npc.variant == 0 && npc.subtype == DUKE_MOTERS; + std::string_view attack; + if (!(npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear())) + { + if (Random() % COUGH_ODDS == 0 && groupSize + enemies < COUGH_LIMIT && !isRedHusk) + { + npc.state = DUKE_COUGH; + attack = "Attack01"; + } + else if (Random() % BIG_FLY_ODDS == 0 && enemies - groupSize < BIG_FLY_LIMIT && !isRedHusk) + { + npc.state = DUKE_BIG_FLY; + attack = "Attack02"; + } + else + { + bool isBurst = Random() % DUKE_BURST_ODDS == 0 && groupSize >= BURST_FLIES && enemies - groupSize <= BURST_OTHERS && + !isMoterDuke; + if (!isBurst) + { + bool isLoneRoll = Random() % LONE_BURST_ODDS == 0; + if (isLoneRoll) isBurst = npc.variant == HUSK || isMoterDuke; + else isBurst = isRedHusk && Random() % RED_HUSK_BURST_ODDS == 0; + } + if (isBurst) + { + npc.state = DUKE_BURST; + attack = "Attack03"; + } + } + } + + if (attack.empty()) npc.sprite.Play("Walk"); + else if (npc.sprite.SetAnimation(attack, SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + npc.stateFrame = 0; +} + +// The burst: its flies leave its group and are blown away with the tiny flies about, and the Husk and the Moter +// Duke shoot a ring of eight. +static void duke_burst(Entity_NPC& npc, const std::vector& group) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + for (Entity_NPC* fly : group) + { + fly->parent = nullptr; + fly->groupIdx = -1; + push_away(npc, *fly, DUKE_BURST_PUSH); + } + for (Entity* tinyFly : entity_query(ENTITY_EFFECT, EFFECT_TINY_FLY)) push_away(npc, *tinyFly, TINY_FLY_PUSH); + + ProjectileParams params; + if (npc.variant == HUSK) + npc.FireProjectiles(vector_make(npc.pos.x, npc.pos.y - HUSK_RING_HEIGHT), + vector_make(HUSK_RING_SPEED, DUKE_RING_SHOTS), PROJECTILES_RING, params); + else if (npc.subtype == DUKE_MOTERS) + npc.FireProjectiles(npc.pos, vector_make(MOTER_RING_SPEED, DUKE_RING_SHOTS), PROJECTILES_RING, params); +} + +// An attack fly coughed up into its group, at a spot below its mouth. +static void fly_cough(Entity_NPC& npc, const Vector& spot, std::vector& coughed) +{ + coughed.push_back(g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_ATTACKFLY, .seed = Random()})); +} + +// The cough: two wing gusts, then three attack flies that join its group (the Husk throws a spider for the third), +// a boom fly for the boom Husk instead, and a few tiny flies while the room has few of them. +static void duke_cough(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_2, 1, 2, false, 1); + for (int i = 0; i < 2; i++) + { + auto* gust = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()})); + gust->rotation = i == 0 ? WING_TURN : -WING_TURN; + gust->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + gust->SetColor(WING_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + gust->posOffset = vector_make(0, WING_HEIGHT); + gust->Update(); + } + + Vector mouth = vector_make(npc.pos.x, npc.pos.y + MOUTH_DROP); + if (npc.variant == HUSK && npc.subtype == HUSK_BOOM_FLY) + { + bool isRoom = !npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || + npc.CountRelatedEntities(ENTITY_BOOMFLY, 0, nullptr) < DELIRIUM_BOOM_FLY_LIMIT; + if (isRoom) g_game->Spawn({.position = mouth, .spawner = &npc, .type = ENTITY_BOOMFLY, .seed = Random()}); + } + else + { + int count = COUGHED_FLIES; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + count = DELIRIUM_FLY_LIMIT - npc.CountRelatedEntities(ENTITY_ATTACKFLY, 0, nullptr); + std::vector coughed; + if (count > 0) fly_cough(npc, mouth, coughed); + mouth.x += FLY_GAP; + if (count > 1) fly_cough(npc, mouth, coughed); + mouth.x -= 2 * FLY_GAP; + if (npc.variant == 0 && count > 2) fly_cough(npc, mouth, coughed); + else if (npc.variant == HUSK && count > 2) + { + Vector between = vector_add(vector_scale(npc.pos, MIDPOINT), vector_scale(npc.GetPlayerTarget()->pos, MIDPOINT)); + Vector landing = room_free_pickup_position_find({.position = between, .step = SPIDER_TARGET_REACH}); + Entity_NPC::ThrowSpider(npc.pos, &npc, landing, false, SPIDER_HEIGHT); + } + for (Entity* fly : coughed) + { + static_cast(fly)->groupIdx = (int)npc.index; + fly->parent = &npc; + minion_ready(*fly); + } + } + + if (entity_query(ENTITY_EFFECT, EFFECT_TINY_FLY).size() >= TINY_FLY_LIMIT) return; + Vector center = vector_make(npc.pos.x, npc.pos.y + MOUTH_DROP); + for (uint32_t count = Random() % TINY_FLIES + 1; count > 0; count--) + { + uint32_t seed = Random(); + Vector heading = random_direction(); + Vector spot = scatter_spot(center, TINY_FLY_SCATTER); + Entity* tinyFly = g_game->Spawn({.position = spot, .velocity = heading, .spawner = &npc, .type = ENTITY_EFFECT, + .variant = EFFECT_TINY_FLY, .seed = seed}); + tinyFly->parent = &npc; + tinyFly->ClearEntityFlags(FLAG_APPEAR); + tinyFly->Update(); + } +} + +// The big fly: the Duke spits one big attack fly (a Moter or Sucker by subtype) while fewer than five of its kind +// are its own, the Husk a spray of ten shots at its target. +static void duke_big_fly(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_1, 1, 2, false, 1); + if (npc.variant == HUSK) + { + ProjectileParams params; + npc.FireBossProjectiles(HUSK_SHOTS, npc.GetPlayerTarget()->pos, 0, params); + return; + } + if (npc.variant != 0) return; + + int kind = npc.subtype == DUKE_MOTERS ? ENTITY_MOTER : npc.subtype == DUKE_SUCKERS ? ENTITY_SUCKER : ENTITY_ATTACKFLY; + if (npc.CountRelatedEntities(kind, 0, nullptr) >= BIG_FLY_LIMIT_ALIVE) return; + auto* fly = static_cast(g_game->Spawn({.position = vector_make(npc.pos.x, npc.pos.y + MOUTH_DROP), + .spawner = &npc, + .type = kind, + .seed = Random()})); + minion_ready(*fly); + if (npc.subtype != 0) return; + fly->scale *= DUKE_BIG_FLY_SCALE; + float size = fly->scale * fly->shrinkStatus1; + fly->sprite.scale = vector_make(size, size); + fly->maxHitPoints *= BIG_FLY_HEALTH; + fly->health *= BIG_FLY_HEALTH; +} + +// A fly of the death burst, about it, a plain or attack fly as its own seed's generator rolls. +static void death_fly_spawn(Entity_NPC& npc, RNG& rng, int kind, int variant) +{ + Vector direction = random_direction(); + float distance = random_unit() * DEATH_FLY_SCATTER * npc.size; + Vector spot = vector_add(vector_scale(direction, distance), npc.pos); + uint32_t seed = Random(); + if (kind == ENTITY_NULL) kind = rng.Next() & 1 ? ENTITY_FLY : ENTITY_ATTACKFLY; + g_game->Spawn({.position = spot, .spawner = &npc, .type = kind, .variant = variant, .seed = seed}) + ->ClearEntityFlags(FLAG_APPEAR); +} + +// Its death: five to fourteen tiny flies, then six flies, or for the Husk four to six and one or two pooters (boom +// flies for the boom Husks, red for the red one). +static void duke_death(Entity_NPC& npc) +{ + uint32_t tinyFlies = 0; + do + { + uint32_t seed = Random(); + Vector spot = scatter_spot(npc.pos, DEATH_TINY_FLY_SCATTER); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_TINY_FLY, .seed = seed}); + tinyFlies++; + } while (tinyFlies < Random() % DEATH_TINY_FLIES + DEATH_TINY_FLIES_MIN); + + RNG rng = {npc.initSeed, 5, 9, 7}; + if (npc.variant != HUSK) + { + for (int i = 0; i < DEATH_FLIES; i++) death_fly_spawn(npc, rng, ENTITY_NULL, 0); + return; + } + + for (int count = (int)(rng.Next() % HUSK_DEATH_FLIES) + HUSK_DEATH_FLIES_MIN; count > 0; count--) + death_fly_spawn(npc, rng, ENTITY_NULL, 0); + int kind = npc.subtype == HUSK_BOOM_FLY || npc.subtype == HUSK_RED_BOOM_FLY ? ENTITY_BOOMFLY : ENTITY_POOTER; + int variant = npc.subtype == HUSK_RED_BOOM_FLY ? RED_BOOM_FLY : 0; + for (int count = (int)(rng.Next() & 1) + 1; count > 0; count--) death_fly_spawn(npc, rng, kind, variant); +} + +// 0046e290 NpcAI::ENTITY_DUKE: the Duke of Flies and the Husk float about the room, coughing up flies that circle +// them, spitting big flies and blowing their flies away. They burst into flies when they die. +void boss_duke_update(Entity_NPC& npc) +{ + duke_float(npc); + std::vector group = Entity_NPC::QueryNPCsGroup((int)npc.index); + int groupSize = (int)group.size(); + int enemies = g_game->room->GetAliveEnemiesCount(); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + break; + case NPC_STATE_MOVE: + duke_choose(npc, groupSize, enemies); + break; + case DUKE_BURST: + if (npc.stateFrame == BURST_FRAME) duke_burst(npc, group); + break; + case DUKE_COUGH: + if (npc.stateFrame == COUGH_FRAME) duke_cough(npc); + break; + case DUKE_BIG_FLY: + if (npc.stateFrame == BIG_FLY_FRAME) duke_big_fly(npc); + break; + } + if (++npc.stateFrame > ATTACK_FRAMES) npc.state = NPC_STATE_MOVE; + if (npc.isDead) duke_death(npc); +} diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp index ec62bda..38ef380 100644 --- a/src/boss_gemini.cpp +++ b/src/boss_gemini.cpp @@ -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_WORM_SPIT = 318; constexpr int SOUND_STEVEN_DEATH_BIG = 961; constexpr int SOUND_STEVEN_DEATH_SMALL = 962; constexpr int SOUND_STEVEN_RAGE = 963; diff --git a/src/boss_larry_jr.cpp b/src/boss_larry_jr.cpp new file mode 100644 index 0000000..4bbc677 --- /dev/null +++ b/src/boss_larry_jr.cpp @@ -0,0 +1,469 @@ +#include "boss_ai.h" +#include "entity_player.h" +#include "entity_config.h" +#include "entity_pickup.h" +#include "grid_entity.h" +#include "room_descriptor.h" +#include "sfx_manager.h" +#include +#include + +// Larry Jr.'s kinds, by variant (Tuff Twins have their own AI), and its subtypes. +constexpr int LARRY_HOLLOW = 1; +constexpr int LARRY_TUFF_TWINS = 2; +constexpr int LARRY_TUFF_TWINS_ALT = 3; +constexpr int LARRY_SPITTING = 1; +constexpr int LARRY_SHARED_HEALTH = 2; +constexpr int HOLLOW_LEAVES_CHARGER = 1; +constexpr int HOLLOW_LEAVES_BOOM_FLY = 2; +constexpr int HOLLOW_LEAVES_COIN = 3; + +constexpr float HEAD_HEAL = 25; +constexpr float JOIN_DISTANCE = 42; +constexpr float SHARED_HEALTH_SLACK = 1; +constexpr float SHARED_HEALTH_SHARE = 0.5f; +constexpr float BODY_TILT = 15; +constexpr int LARRY_SPLAT_FRAMES = 10; +constexpr float LARRY_SPLAT_SIZE = 0.3f; +constexpr float LARRY_SPLAT_SIZE_SPREAD = 0.4f; +constexpr float SHARED_HEALTH_FRICTION = 0.96f; + +constexpr int POOP_ODDS = 100; +constexpr int HURT_POOP_ODDS = 20; +constexpr float POOP_DROP_PAUSE = 30; +constexpr int ROAR_ODDS = 120; +constexpr int ROAR_DELAY = 120; + +constexpr int COOLDOWN_STILL = 31; +constexpr float LARRY_WANDER_SPEED = 2; +constexpr int GRUB_CHARGE_WAIT = 51; +constexpr float GRUB_AIM_LEAD = 16; +constexpr float GRUB_AIM_BAND = 20; +constexpr float GRUB_CHARGE_FRICTION = 0.9f; +constexpr float GRUB_CHARGE_SPEED = 3.7f; +constexpr int GRUB_SPAWNS_MIN = 2; +constexpr std::array GRUB_SPAWN_KINDS = {ENTITY_CHARGER, ENTITY_SPITTY, ENTITY_MAGGOT}; +constexpr int DAMAGE_COUNTDOWN_SHARED = 30; + +constexpr float HOLLOW_STILL_SPEED_SQUARED = 0.16000001f; +constexpr float HOLLOW_NUDGE = 0.1f; +constexpr float HOLLOW_FRICTION = 0.85f; +constexpr float HOLLOW_CONFUSED_FRICTION = 0.95f; +constexpr float HOLLOW_LEFT = 1; +constexpr float HOLLOW_TOP = 20; +constexpr float HOLLOW_RIGHT = 1; +constexpr float HOLLOW_BOTTOM = 10; +constexpr float MEGA_SATAN_ROOM_TOP = 320; +constexpr int MEGA_SATAN_BOSS_ID = 55; +constexpr int HOLLOW_TURN_ODDS = 10; +constexpr float HOLLOW_GAIT_LONG = 3; +constexpr float HOLLOW_GAIT_WIDE_SHORT = 1.6f; +constexpr float HOLLOW_GAIT_TALL_SHORT = 1.8f; +constexpr float LARRY_FLEE_RANGE = 160; +constexpr float LARRY_FLEE_STRENGTH = 0.03f; +constexpr float LARRY_FLEE_MAX = 2; + +constexpr int SPIT_ODDS = 3; +constexpr int SPIT_COOLDOWN = 40; +constexpr int SPIT_COOLDOWN_SPREAD = 20; +constexpr float SPIT_SPEED = 7.5f; +constexpr float SPIT_FALLING_ACCEL = 0.3f; +constexpr float SPIT_FALLING_SPEED = -5; +constexpr float CRUSH_REACH = 40; + +constexpr float SEGMENT_GAP = 24; +constexpr float HOLLOW_SEGMENT_GAP = 18; +constexpr float SHARED_HEALTH_GAP = 12; +constexpr float SEGMENT_SPEED = 20; +constexpr float CHARGING_SEGMENT_SPEED = 40; +constexpr float SEGMENT_FRICTION = 0.8f; + +// The walk animations, by direction (left, up, right, down). +using DirectionAnims = std::array; +constexpr DirectionAnims HEAD_ANIMS = {"WalkHeadHori", "WalkHeadUp", "WalkHeadHori", "WalkHeadDown"}; +constexpr DirectionAnims BODY_ANIMS = {"WalkBodyHori", "WalkBodyUp", "WalkBodyHori", "WalkBodyDown"}; +constexpr DirectionAnims TAIL_ANIMS = {"WalkBodyHori", "Butt", "WalkBodyHori", "WalkBodyDown"}; +constexpr DirectionAnims GRUB_CHARGE_ANIMS = {"AttackHeadHori", "AttackHeadUp", "AttackHeadHori", "AttackHeadDown"}; +constexpr DirectionAnims BUTTLICKER_ANIMS = {"WalkHori", "WalkUp", "WalkHori", "WalkDown"}; + +// The death cries alternate between two sounds across every Larry Jr. and Hollow. +static int g_larryDeathCount = 0; +static int g_hollowDeathCount = 0; + +// The flags that keep a Grub from charging: confused, feared or shrunk. +constexpr uint64_t GRUB_STUNNED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// The segment's chain head, when it is an NPC. +static Entity_NPC* chain_head(Entity_NPC& npc) +{ + Entity* head = npc.GetLastParent(); + return head && Entity::is_enemy_type(head->type) ? static_cast(head) : nullptr; +} + +// Plays a direction's animation, mirrored when it faces left. +static void direction_play(Entity_NPC& npc, const DirectionAnims& anims, int direction) +{ + npc.sprite.Play(anims[direction]); + npc.sprite.isFlipX = direction == DIRECTION_LEFT; +} + +// A dead Grub's segments all die and up to 2 to 5 of their free spots, shuffled, grow a Charger, Spitty or Maggot. +static void grub_death(Entity_NPC& npc) +{ + std::vector spots = {npc.pos}; + npc.i2 = 1; + for (Entity_NPC* link = npc.ChildNPC(); link; link = link->ChildNPC()) + { + spots.push_back(link->pos); + link->i2 = 1; + link->Kill(EntityRef()); + } + for (Entity_NPC* link = npc.ParentNPC(); link; link = link->ParentNPC()) + { + spots.push_back(link->pos); + link->i2 = 1; + link->Kill(EntityRef()); + } + + for (int i = (int)spots.size() - 1; i > 0; i--) std::swap(spots[i], spots[Random() % (uint32_t)(i + 1)]); + + uint32_t count = (Random() & 3) + GRUB_SPAWNS_MIN; + for (uint32_t i = 0; i < spots.size() && i < count; i++) + { + if (room_grid_collision_at(spots[i]) != 0) continue; + int kind = GRUB_SPAWN_KINDS[Random() % GRUB_SPAWN_KINDS.size()]; + g_game->Spawn({.position = spots[i], .spawner = &npc, .type = kind, .seed = Random()}); + } + npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); +} + +// A dead segment: a Larry Jr. head heals the segment behind it, a Grub breaks apart, the last segments cry out and a +// Hollow segment may leave a Charger, Boom Fly or coin by its subtype. +static void larry_death(Entity_NPC& npc) +{ + if (npc.type == ENTITY_LARRYJR) + { + Entity_NPC* next = npc.ChildNPC(); + if (!npc.parent && next && next->health > 0 && npc.subtype != LARRY_SHARED_HEALTH) + next->health = std::min(next->health + HEAD_HEAL, next->maxHitPoints); + } + else if (npc.type == ENTITY_GRUB && npc.i2 == 0) grub_death(npc); + if (npc.type != ENTITY_LARRYJR) return; + + if (npc.variant == 0 && !npc.parent) + npc.PlaySound(++g_larryDeathCount & 1 ? SOUND_LARRY_JR_DEATH_2 : SOUND_LARRY_JR_DEATH_1, 1, 2, false, 1); + if (npc.variant != LARRY_HOLLOW) return; + + EntitySpawn left = {.position = npc.pos, .spawner = &npc}; + if (npc.subtype == HOLLOW_LEAVES_CHARGER && room_grid_collision_at(npc.pos) == 0) left.type = ENTITY_CHARGER; + else if (npc.subtype == HOLLOW_LEAVES_BOOM_FLY) left.type = ENTITY_BOOMFLY; + else if (npc.subtype == HOLLOW_LEAVES_COIN) left = {.position = npc.pos, .spawner = &npc, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN}; + if (left.type != ENTITY_NULL) + { + left.seed = Random(); + g_game->Spawn(left); + } + if (!npc.parent) + npc.PlaySound(++g_hollowDeathCount & 1 ? SOUND_HOLLOW_DEATH_2 : SOUND_HOLLOW_DEATH_1, 1, 2, false, 1); +} + +// The first frame: a segment without a parent joins the nearest free tail of its kind within reach, a head names its +// group, and a Grub segment pools its neighbours' health into its own. +static void larry_init(Entity_NPC& npc) +{ + npc.i1 = 0; + npc.i2 = 0; + npc.stateFrame = 0; + if (npc.type != ENTITY_LARRYJR || npc.variant != LARRY_HOLLOW) npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.entityCollisionClass = ENTCOLL_ALL; + + std::vector kin = entity_query(npc.type, -1); + if (!npc.parent && !npc.unknownF54) + for (auto it = kin.rbegin(); it != kin.rend(); ++it) + { + auto* other = static_cast(*it); + if (other == &npc || other->parent == &npc || other->child) continue; + if (vector_length(vector_sub(other->pos, npc.pos)) >= JOIN_DISTANCE) continue; + + Entity* link = other; + while (link && link != &npc) + { + link = link->parent; + if (link == other) break; + } + if (link != &npc) npc.parent = other; + } + + if (!npc.parent) + { + npc.sprite.Play(npc.type == ENTITY_BUTTLICKER ? "WalkDown" : "WalkHeadDown"); + for (Entity_NPC* link = npc.ChildNPC(); link; link = link->ChildNPC()) link->groupIdx = (int)npc.index; + npc.groupIdx = (int)npc.index; + } + else + { + npc.parent->child = &npc; + npc.sprite.Play(npc.type == ENTITY_BUTTLICKER ? "WalkHori" : "WalkBodyHori"); + if (npc.type == ENTITY_GRUB) + { + float pooled = std::max(npc.child ? npc.child->health : 0.0f, npc.parent->health); + npc.health = npc.config->baseHP + pooled; + npc.maxHitPoints = npc.health; + for (Entity* link = npc.parent; link; link = link->parent) link->health = link->maxHitPoints = npc.health; + for (Entity* link = npc.child; link; link = link->child) link->health = link->maxHitPoints = npc.health; + } + } + npc.vectorDeque1.push_front(npc.pos); + npc.vectorDeque2.push_front(npc.velocity); + npc.state = NPC_STATE_MOVE; +} + +// A Larry Jr. tail now and then (more often when hurt) drops a poop where it crawls, outside challenge rooms and +// calm Delirium forms, and pauses its next one. +static void tail_poop(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (room.roomType == ROOM_CHALLENGE) return; + bool isDropped = Random() % POOP_ODDS == 0; + if (!isDropped && npc.pendingDamage > 0) isDropped = Random() % HURT_POOP_ODDS == 0; + if (!isDropped) return; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + + int cell = room.GetGridIndex(npc.pos); + GridEntity* standing = (uint32_t)cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (standing && standing->type != GRID_POOP && standing->type != GRID_DECORATION && standing->type != GRID_SPIDERWEB) + return; + + npc.PlaySound(SOUND_POOP_DROP, 1, 2, false, 1); + room.SpawnGridEntity(cell, GRID_POOP, 0, npc.dropRNG.Next(), 0); + GridEntity* poop = (uint32_t)cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (!poop || poop->type != GRID_POOP) return; + poop->varData = 1; + npc.v1.x = POOP_DROP_PAUSE; +} + +// A body segment: shares health with its parent (subtype 2), tilts (Hollow) and faces toward it, and a tail may poop. +static void body_update(Entity_NPC& npc) +{ + Entity_NPC& parent = *npc.ParentNPC(); + if (npc.type == ENTITY_LARRYJR && npc.subtype == LARRY_SHARED_HEALTH && + std::abs(npc.health - parent.health) > SHARED_HEALTH_SLACK) + { + float share = (parent.health - npc.health) * SHARED_HEALTH_SHARE; + npc.health += share; + parent.health -= share; + } + if (parent.vectorDeque1.size() <= 1) return; + + Vector toParent = vector_sub(parent.pos, npc.pos); + if (npc.variant == LARRY_HOLLOW && !vector_is_zero(toParent)) + { + LayerState* layer = npc.sprite.GetLayer(0); + layer->rotation = (toParent.x < 0) == (toParent.y < 0) ? BODY_TILT : -BODY_TILT; + if (npc.sprite.isFlipX) layer->rotation = -layer->rotation; + } + + int direction = vector_to_direction(toParent); + const DirectionAnims& anims = npc.type == ENTITY_BUTTLICKER ? BUTTLICKER_ANIMS + : !npc.child && npc.type != ENTITY_GRUB ? TAIL_ANIMS + : BODY_ANIMS; + direction_play(npc, anims, direction); + + if (npc.v1.x > 0) npc.v1.x = std::max(npc.v1.x - npc.speedMultiplier, 0.0f); + if (npc.type == ENTITY_LARRYJR && !npc.child && npc.subtype != LARRY_SHARED_HEALTH) tail_poop(npc); +} + +// A Grub head waits, then charges along a row or column when its target (led a little) lines up in plain sight. +static void grub_aim(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(GRUB_STUNNED)) return; + if (npc.stateFrame < GRUB_CHARGE_WAIT) + { + npc.stateFrame += npc_ticks_get(npc); + return; + } + + Vector preyPos = npc.GetPlayerTarget()->pos; + Vector preyVelocity = npc.GetPlayerTarget()->velocity; + Vector lead = vector_scale(vector_scale(preyVelocity, random_unit()), GRUB_AIM_LEAD); + Vector aim = vector_sub(vector_add(lead, preyPos), npc.pos); + if (std::abs(aim.y) >= GRUB_AIM_BAND && std::abs(aim.x) >= GRUB_AIM_BAND) return; + if (!room_check_line(npc.pos, vector_add(npc.pos, aim), LINE_MODE_GROUND, 0)) return; + + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.targetPosition = vector_cardinal(aim); + npc.stateFrame = 0; + npc.i1 = 1; + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; +} + +// A charging Grub runs straight on until it hits a wall or is stunned. +static void grub_charge(Entity_NPC& npc) +{ + if (npc.isCollidesWithGrid || npc.HasEntityFlags(GRUB_STUNNED)) + { + npc.i1 = 0; + npc.targetPosition = {}; + return; + } + npc.friction *= GRUB_CHARGE_FRICTION; + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, + GRUB_CHARGE_SPEED * npc.speedMultiplier / npc.friction)); +} + +// A Hollow head bounces about the room in a long or tall gait, turning off the walls, and keeps away from its +// target while feared or shrunk. Confused, it wanders. +static void hollow_move(Entity_NPC& npc) +{ + if (vector_length_squared(npc.velocity) < HOLLOW_STILL_SPEED_SQUARED && npc.friction != 0) + npc.velocity = vector_add(npc.velocity, + vector_scale(random_direction(), HOLLOW_NUDGE * npc.speedMultiplier / npc.friction)); + + Vector sign = vector_make(npc.velocity.x > 0 ? 1 : -1, npc.velocity.y > 0 ? 1 : -1); + bool isTilted = std::abs(npc.velocity.x) >= std::abs(npc.velocity.y) && npc.velocity.y > 0; + npc.sprite.GetLayer(0)->rotation = isTilted ? BODY_TILT : 0; + npc.friction *= HOLLOW_FRICTION; + + Room& room = *g_game->room; + float left = room.topLeftPos.x + HOLLOW_LEFT; + float top = room.bossId == MEGA_SATAN_BOSS_ID ? MEGA_SATAN_ROOM_TOP : room.topLeftPos.y + HOLLOW_TOP; + float right = room.bottomRightPos.x - HOLLOW_RIGHT; + float bottom = room.bottomRightPos.y - HOLLOW_BOTTOM; + Vector unclamped = npc.pos; + npc.pos = vector_make(std::min(std::max(npc.pos.x, left), right), std::min(std::max(npc.pos.y, top), bottom)); + bool isClamped = npc.pos.x != unclamped.x || npc.pos.y != unclamped.y; + if (isClamped) + { + if ((npc.pos.x == left && npc.velocity.x < 0) || (npc.pos.x == right && npc.velocity.x > 0)) + npc.velocity.x = -npc.velocity.x; + if ((npc.pos.y == top && npc.velocity.y < 0) || (npc.pos.y == bottom && npc.velocity.y > 0)) + npc.velocity.y = -npc.velocity.y; + sign = vector_make(npc.velocity.x > 0 ? 1 : -1, npc.velocity.y > 0 ? 1 : -1); + } + + if (vector_is_zero(npc.v1) || (isClamped && Random() % HOLLOW_TURN_ODDS == 0)) + npc.v1 = Random() & 1 ? vector_make(HOLLOW_GAIT_TALL_SHORT, HOLLOW_GAIT_LONG) + : vector_make(HOLLOW_GAIT_LONG, HOLLOW_GAIT_WIDE_SHORT); + + if (npc.HasEntityFlags(FLAG_CONFUSION)) + { + npc.friction = HOLLOW_CONFUSED_FRICTION; + for (int i = 0; i < 3; i++) npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + return; + } + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(vector_make(sign.x * npc.v1.x, sign.y * npc.v1.y), + npc.speedMultiplier / npc.friction)); + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float strength = std::clamp((LARRY_FLEE_RANGE - vector_length(away)) * LARRY_FLEE_STRENGTH, 0.0f, LARRY_FLEE_MAX); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, + vector_scale(vector_resized(away, strength), npc.speedMultiplier / npc.friction)); +} + +// A spitting Larry Jr. (subtype 1) now and then shoots along its way: one shot, three for the Hollow. +static void larry_spit(Entity_NPC& npc) +{ + if (Random() % SPIT_ODDS != 0) return; + if (npc.projectileCooldown > 0) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return; + } + + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + npc.projectileCooldown = (int)(Random() % SPIT_COOLDOWN_SPREAD) + SPIT_COOLDOWN; + ProjectileParams params; + params.fallingAccelModifier = SPIT_FALLING_ACCEL; + if (npc.variant == 0) params.fallingSpeedModifier = SPIT_FALLING_SPEED; + Vector shot = vector_scale(vector_normalized(npc.velocity), SPIT_SPEED); + npc.FireProjectiles(npc.pos, shot, npc.variant == 0 ? PROJECTILES_SINGLE : PROJECTILES_THREE, params); +} + +// A head: roars, keeps a Grub's segments at the lowest health among them, wanders (Larry Jr., a Grub between +// charges, Buttlicker) or bounces (Hollow), spits, faces its way, dies without a body, and crushes what lies ahead. +static void head_update(Entity_NPC& npc) +{ + if (npc.type == ENTITY_LARRYJR && npc.child && Random() % ROAR_ODDS != 0) + npc.PlaySound(npc.variant == 0 ? SOUND_LARRY_JR_ROAR : SOUND_HOLLOW_ROAR, 1, ROAR_DELAY, false, 1); + else if (npc.type == ENTITY_BUTTLICKER && Random() % ROAR_ODDS != 0) + npc.PlaySound(SOUND_BUTTLICKER_GROWL, 1, ROAR_DELAY, false, 1); + + if (npc.type == ENTITY_GRUB) + { + float lowest = npc.health - npc.pendingDamage; + for (Entity_NPC* link = npc.ChildNPC(); link; link = link->ChildNPC()) + lowest = std::min(lowest, link->health - link->pendingDamage); + for (Entity_NPC* link = &npc; link; link = link->ChildNPC()) + if (lowest < link->health - link->pendingDamage) + link->TakeDamage(link->health - lowest, 0, EntityRef(&npc), DAMAGE_COUNTDOWN_SHARED); + } + + if (npc.projectileCooldown >= COOLDOWN_STILL) npc.projectileCooldown -= npc_ticks_get(npc); + else + { + if (npc.type == ENTITY_GRUB && npc.i1 != 0) grub_charge(npc); + else if (npc.variant == 0 || npc.type == ENTITY_GRUB) + { + npc.pathfinder.MoveRandomlyAxisAligned(LARRY_WANDER_SPEED, STATUS_OBEYED); + if (npc.type == ENTITY_GRUB) grub_aim(npc); + } + else hollow_move(npc); + if (npc.type == ENTITY_LARRYJR && npc.subtype == LARRY_SPITTING) larry_spit(npc); + } + + int direction = npc.get_velocity_direction(); + if (npc.type == ENTITY_BUTTLICKER) direction_play(npc, BUTTLICKER_ANIMS, direction); + else direction_play(npc, npc.type == ENTITY_GRUB && npc.i1 != 0 ? GRUB_CHARGE_ANIMS : HEAD_ANIMS, direction); + + Entity* next = npc.child; + if (npc.type == ENTITY_LARRYJR && (!next || next->isDead)) + { + npc.Kill(EntityRef()); + std::vector group = Entity_NPC::QueryNPCsGroup(npc.groupIdx); + bool isAllDead = std::all_of(group.begin(), group.end(), [](Entity_NPC* member) { return member->isDead; }); + if (isAllDead && !group.empty() && group.front() == &npc) npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); + } + + Room& room = *g_game->room; + Vector ahead = vector_add(npc.pos, vector_scale(vector_normalized(npc.velocity), CRUSH_REACH)); + EntityRef source(&npc); + uint32_t cell = (uint32_t)room.GetGridIndex(ahead); + if (cell < ROOM_GRID_CELLS && room.gridEntities[cell]) room.gridEntities[cell]->Hurt(1, source); +} + +// 0046a0f0 NpcAI::ENTITY_LARRYJR: Larry Jr. and the Hollow (type 19), Buttlicker (89) and Grub (239), heads that +// crawl about trailed by body segments, which die one by one. A head without a body dies too. Tuff Twins and a +// segment a player controls are not reconstructed yet. +void boss_larry_jr_update(Entity_NPC& npc) +{ + if (npc.type == ENTITY_LARRYJR && (npc.variant == LARRY_TUFF_TWINS || npc.variant == LARRY_TUFF_TWINS_ALT)) + return NpcAI::ENTITY_TUFF_TWINS(&npc); + Entity_NPC* head = chain_head(npc); + if (npc.controllerID != -1 || (head && head->controllerID != -1)) + reconstruction_missing("NpcAI::ENTITY_LARRYJR 0046a0f0: a segment a player controls"); + + if (npc.isDead) return larry_death(npc); + if (npc.state == NPC_STATE_INIT) return larry_init(npc); + if (npc.state != NPC_STATE_MOVE) return; + + if (npc.type == ENTITY_LARRYJR) + { + if (npc.subtype == LARRY_SHARED_HEALTH) npc.friction *= SHARED_HEALTH_FRICTION; + if (npc.IsFrame(LARRY_SPLAT_FRAMES, (int)npc.index)) npc.MakeSplat(random_unit() * LARRY_SPLAT_SIZE_SPREAD + LARRY_SPLAT_SIZE); + } + if (npc.parent) body_update(npc); + else head_update(npc); + + float gap = npc.variant == LARRY_HOLLOW ? HOLLOW_SEGMENT_GAP : SEGMENT_GAP; + if (npc.subtype == LARRY_SHARED_HEALTH && npc.type == ENTITY_LARRYJR) gap += SHARED_HEALTH_GAP; + else if (npc.type == ENTITY_BUTTLICKER) gap = HOLLOW_SEGMENT_GAP; + bool isCharging = head && head->type == ENTITY_GRUB && head->i1 != 0; + segment_follow(npc, SEGMENT_FOLLOW, gap, isCharging ? CHARGING_SEGMENT_SPEED : SEGMENT_SPEED); + npc.friction *= SEGMENT_FRICTION; +} diff --git a/src/boss_little_horn.cpp b/src/boss_little_horn.cpp new file mode 100644 index 0000000..ea34633 --- /dev/null +++ b/src/boss_little_horn.cpp @@ -0,0 +1,503 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// Little Horn (variant 0) and the dark ball it spits (variant 1), and their subtypes: the hot one throws burning +// hot bombs and rolling balls, the third neither drops bombs on its dives nor summons pits. +constexpr int HORN_BALL = 1; +constexpr int HORN_HOT = 1; +constexpr int HORN_THIRD = 2; +constexpr int BALL_HOMING = 0; +constexpr int BALL_ROLLING = 1; +constexpr int PIT_FLUNG = 2; + +// Little Horn's states beyond the shared ones. +constexpr int HORN_SHOOT = NPC_STATE_ATTACK; +constexpr int HORN_BOMB = NPC_STATE_ATTACK2; +constexpr int HORN_MEGA_BOMB = NPC_STATE_ATTACK3; +constexpr int HORN_DIVE = NPC_STATE_JUMP; +constexpr int HORN_DIVES = NPC_STATE_SPECIAL; +constexpr int HORN_PIT = NPC_STATE_SUMMON; +constexpr int HORN_PITS = NPC_STATE_SUMMON2; + +constexpr int PITFALL_DONE = 3; +constexpr float OWN_BLAST_SHARE = 0.25f; +constexpr float HORN_FRICTION = 0.8f; +constexpr float SPRITE_HEIGHT = -20; + +constexpr int WANDER_FRAMES = 50; +constexpr float HORN_WANDER_SPEED = 1.2f; +constexpr float PLAYER_SHY = 190; +constexpr float BOMB_SHY = 130; +constexpr float SHY_PUSH = 0.03f; +constexpr float NEAR = 120; +constexpr float INNER_MARGIN = 100; +constexpr float EDGE_PULL = 0.03f; +constexpr float MAX_STEP = 0.8f; +constexpr int CHECK_FRAMES = 15; +constexpr uint32_t DIVE_ODDS = 15; +constexpr uint32_t HORN_ATTACK_ODDS = 25; +constexpr float HURT_SHARE = 0.3f; +constexpr int MULTI_DIVE_ODDS = 20; +constexpr int HURT_MULTI_DIVE_ODDS = 50; +constexpr uint32_t MULTI_DIVES = 3; +constexpr uint32_t MULTI_DIVES_MIN = 3; +constexpr uint32_t LONE_SHOOT_ODDS = 60; +constexpr uint32_t SHOOT_ODDS = 20; +constexpr uint32_t PIT_ODDS = 50; +constexpr uint32_t LONE_PIT_ODDS = 10; +constexpr uint32_t BOMB_ODDS = 75; +constexpr int BALL_LIMIT = 3; +constexpr int THIRD_BALL_LIMIT = 2; +constexpr float PIT_REACH = 140; + +constexpr float HOT_BALL_AHEAD = 5; +constexpr float HOT_BALL_SPEED = 15; +constexpr float HOT_BALL_FRAME = 8; +constexpr float BALL_DROP = 4; +constexpr float SHOOT_KICK = 3.5f; +constexpr float SOUND_PITCH = 0.9f; +constexpr float SOUND_PITCH_SPREAD = 0.2f; +constexpr float BOMB_REACH = 40; +constexpr float DEATH_BOMB_DROP = 5; +constexpr float DEATH_BOMB_SPEED = 3; +constexpr uint32_t DROPPED_BOMB_SEED = 1; + +constexpr int RELOCATE_TRIES = 30; +constexpr float RELOCATE_MIN = 160; +constexpr int DIVE_REST = 75; + +constexpr uint32_t PIT_WIDE_ODDS = 10; +constexpr uint32_t PIT_FEW_ODDS = 50; +constexpr int PITS_WIDE = 5; +constexpr int PITS_FEW = 3; +constexpr int PIT_FRAMES = 240; +constexpr float PIT_SPEED = 8.75f; +constexpr float HORN_FULL_TURN = 360; + +constexpr float BALL_PULL = 0.5f; +constexpr float BALL_DAMPING = 1.1764705f; +constexpr float BALL_MASS = 8; +constexpr float BALL_SHY = 100; +constexpr float BALL_SHY_BALLS = 0.003f; +constexpr float BALL_SHY_BOMBS = 0.01f; +constexpr float BALL_ROLL_SPEED = 10; +constexpr int BALL_TRAILS = 3; +constexpr float TRAIL_BACK = -0.5f; +constexpr float TRAIL_SCATTER = 0.4f; +constexpr ColorMod BALL_SPLAT_COLOR = {{0, 0, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Whether its own or a friend's movement pulls it straight at its target: charmed, confused, feared or shrunk. +constexpr uint64_t DRAWN_TO_TARGET = FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// 009be990 Whether any player is falling into a pit. +bool players_is_falling() +{ + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->pitfallState != 0 && player->pitfallState != PITFALL_DONE) return true; + return false; +} + +// A random sound pitch, 0.9 to 1.1. +static float pitch_roll() +{ + return random_unit() * SOUND_PITCH_SPREAD + SOUND_PITCH; +} + +// A bomb it drops or throws, burning for the hot Little Horn. +static Entity_Bomb* bomb_spawn(Entity_NPC& npc, const EntitySpawn& spawn) +{ + auto* bomb = static_cast(g_game->Spawn(spawn)); + if (npc.subtype != HORN_HOT) return bomb; + bomb->tearFlags = TearFlags().set(TEAR_BURN); + bomb->isLoadCostumes = true; + bomb->SetCollisionDamage(1); + return bomb; +} + +// Pushes a wander spot away from something within a reach, harder the closer. Whether it stood near the Horn. +static bool shy_push(Entity_NPC& npc, Vector& spot, const Vector& from, float reach) +{ + if (vector_length(vector_sub(from, spot)) < reach) + { + Vector away = vector_sub(spot, from); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, (reach - distance) * SHY_PUSH / distance); + spot = vector_add(spot, away); + } + return vector_length(vector_sub(from, npc.pos)) < NEAR; +} + +// Idle drifting: a short random heading every 50 frames, kept off the players and bombs and toward the room's middle, +// or straight at its target while charmed, confused, feared or shrunk. Whether a player or bomb is near. +static bool horn_wander(Entity_NPC& npc) +{ + if (vector_is_zero(npc.v1) || npc.stateFrame > WANDER_FRAMES) npc.stateFrame = 0; + if (npc.stateFrame == 0) + { + Vector heading = vector_scale(random_direction(), HORN_WANDER_SPEED); + npc.v1 = vector_scale(heading, random_unit()); + } + npc.stateFrame++; + + bool isNear = false; + Vector spot = vector_add(npc.pos, npc.v1); + if (!npc.HasEntityFlags(FLAG_FRIENDLY)) + for (Entity_Player* player : g_game->playerManager.playerList) + isNear = shy_push(npc, spot, player->pos, PLAYER_SHY) || isNear; + for (Entity* bomb : entity_query(ENTITY_BOMB, -1)) isNear = shy_push(npc, spot, bomb->pos, BOMB_SHY) || isNear; + + Room& room = *g_game->room; + Vector inside = room.GetClampedPositionImpl(spot, npc.size, npc.size, npc.size, npc.size); + Vector edge = vector_sub(room.GetClampedPositionImpl(npc.pos, INNER_MARGIN, INNER_MARGIN, INNER_MARGIN, + INNER_MARGIN), + npc.pos); + if (edge.x != 0 && edge.y != 0) + edge = std::abs(edge.x) <= std::abs(edge.y) ? vector_make(edge.x + edge.x, 0) : vector_make(0, edge.y + edge.y); + Vector goal = vector_add(vector_scale(edge, EDGE_PULL), inside); + if (npc.HasEntityFlags(DRAWN_TO_TARGET)) goal = npc.CalcTargetPosition(0); + + Vector step = vector_sub(goal, npc.pos); + float length = vector_length(step); + if (length > MAX_STEP && length > 0) step = vector_scale(step, MAX_STEP / length); + if (npc.friction != 0) npc.velocity = vector_add(npc.velocity, vector_scale(step, npc.speedMultiplier / npc.friction)); + return isNear; +} + +// The attack roll every 15th frame: spit a ball (more likely with few balls about), summon pits near or around its +// target, or drop a bomb or mega bomb on it. +static void horn_attack_roll(Entity_NPC& npc) +{ + size_t balls = entity_query(ENTITY_LITTLE_HORN, HORN_BALL).size(); + size_t pits = entity_query(ENTITY_PITFALL, -1).size(); + bool isShoot = false; + if (balls == 0) isShoot = Random() % 100 < LONE_SHOOT_ODDS; + if (!isShoot && balls < BALL_LIMIT) isShoot = Random() % 100 < SHOOT_ODDS; + if (!isShoot) isShoot = npc.subtype == HORN_THIRD && balls < THIRD_BALL_LIMIT; + if (isShoot) + { + npc.state = HORN_SHOOT; + npc.stateFrame = 0; + return; + } + + bool isPit = false; + if (pits == 0) isPit = Random() % 100 < PIT_ODDS; + else if (pits == 1) isPit = Random() % 100 < LONE_PIT_ODDS; + isPit = isPit && !players_is_falling() && npc.subtype != HORN_THIRD && npc.subtype != HORN_HOT && + !npc.HasEntityFlags(FLAG_DELIRIUM_FORM); + if (isPit) + { + float distance = vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.state = distance >= PIT_REACH ? HORN_PITS : HORN_PIT; + npc.stateFrame = 0; + return; + } + + if (npc.subtype == HORN_THIRD) return; + bool isBomb = Random() % 100 < BOMB_ODDS || npc.subtype == HORN_HOT; + npc.state = isBomb ? HORN_BOMB : HORN_MEGA_BOMB; + npc.stateFrame = 0; + npc.UpdateDirtColor(true); +} + +// Idling over its hole: it drifts, dives away when a player or bomb comes near (or now and then), more than once +// when the roll says so (more often when hurt), and every 15th frame may attack. +static void horn_idle(Entity_NPC& npc) +{ + npc.sprite.GetLayer("Hole")->isVisible = true; + npc.sprite.Play("Idle"); + bool isNear = horn_wander(npc); + + int multiOdds = npc.maxHitPoints * HURT_SHARE > npc.health ? HURT_MULTI_DIVE_ODDS : MULTI_DIVE_ODDS; + bool isDive = isNear || (npc.IsFrame(CHECK_FRAMES, (int)npc.index) && Random() % 100 < DIVE_ODDS); + if (isDive && npc.i1 <= 0) + { + npc.state = HORN_DIVE; + npc.stateFrame = 0; + npc.i2 = 1; + if ((int)(Random() % 100) < multiOdds) + { + npc.i2 = (int)(Random() % MULTI_DIVES + MULTI_DIVES_MIN); + npc.state = HORN_DIVES; + } + npc.UpdateDirtColor(true); + } + + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + if (npc.IsFrame(CHECK_FRAMES, (int)npc.index) && Random() % 100 < HORN_ATTACK_ODDS) horn_attack_roll(npc); +} + +// The spit on Shoot: the hot Little Horn throws a burning bomb at its target, the others drop a dark ball and +// recoil up. +static void horn_shoot(Entity_NPC& npc) +{ + npc.sprite.Play("Shoot"); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + npc_sound_play(SOUND_LITTLE_HORN_COUGH, 1, 2, pitch_roll()); + if (npc.subtype == HORN_HOT) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + uint32_t seed = Random(); + Entity_Bomb* bomb = bomb_spawn(npc, {.position = vector_add(vector_scale(aim, HOT_BALL_AHEAD), npc.pos), + .velocity = vector_scale(aim, HOT_BALL_SPEED), + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = BOMB_HOT, + .seed = seed}); + bomb->sprite.animState.SetFrameFloat(HOT_BALL_FRAME); + return; + } + + auto* ball = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_LITTLE_HORN, .variant = HORN_BALL, .seed = Random()})); + ball->velocity = vector_make(0, BALL_DROP); + ball->SetBossColorIdx(npc.bosscoloridx, 0); + ball->ClearEntityFlags(FLAG_APPEAR); + if (npc.friction != 0) npc.velocity.y -= SHOOT_KICK * npc.speedMultiplier / npc.friction; +} + +// The bomb drops: on Bomb a troll bomb (a mega troll bomb, hot for the hot Little Horn) lands near its target. A +// Little Horn dying before it dropped one lets it fall where it is. +static void horn_bomb(Entity_NPC& npc) +{ + npc.sprite.Play(npc.state == HORN_MEGA_BOMB ? "MegaBomb" : "Bomb"); + int variant = npc.subtype == HORN_HOT ? BOMB_HOT : npc.state == HORN_MEGA_BOMB ? BOMB_SUPERTROLL : BOMB_TROLL; + if (npc.sprite.IsEventTriggered("BombDrop")) npc_sound_play(SOUND_LITTLE_HORN_BOMB_DROP, 1, 2, 1); + if (npc.sprite.IsEventTriggered("Bomb")) + { + npc_sound_play(SOUND_LITTLE_HORN_GRUNT_2, 1, 2, pitch_roll()); + Vector spot = room_free_pickup_position_find({.position = npc.CalcTargetPosition(0), .step = BOMB_REACH}); + bomb_spawn(npc, {.position = spot, .spawner = &npc, .subType = 1, .type = ENTITY_BOMB, .variant = variant, + .seed = DROPPED_BOMB_SEED}); + } + if (!npc.isDead || npc.sprite.WasEventTriggered("Bomb")) return; + uint32_t seed = Random(); + bomb_spawn(npc, {.position = vector_make(npc.pos.x, npc.pos.y + DEATH_BOMB_DROP), + .velocity = vector_make(0, DEATH_BOMB_SPEED), + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = variant, + .seed = seed}); +} + +// Comes up somewhere else: a free random spot away from the players and at least 160 from where it went down, +// within 30 tries. +static void horn_relocate(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector origin = npc.pos; + bool isTooNear = true; + for (int tries = RELOCATE_TRIES; tries > 0 && isTooNear; tries--) + { + isTooNear = false; + npc.pos = room_free_pickup_position_find({.position = room.GetRandomPosition(0)}); + for (Entity_Player* player : g_game->playerManager.playerList) + if (vector_length(vector_sub(player->pos, npc.pos)) < NEAR) isTooNear = true; + if (vector_length(vector_sub(origin, npc.pos)) < RELOCATE_MIN) isTooNear = true; + } + npc.UpdateDirtColor(true); +} + +// The dive: it sinks (a multiple dive leaving a bomb behind), moves and comes back up, as often as i2 says, then +// rests from diving for 75 frames. +static void horn_dive(Entity_NPC& npc) +{ + if (npc.stateFrame == 0) + { + npc.sprite.Play("Teleport"); + if (npc.sprite.IsEventTriggered("Dive")) npc_sound_play(SOUND_LITTLE_HORN_DIVE, 1, 2, 1); + if (npc.sprite.WasEventTriggered("CollisionOff")) npc.entityCollisionClass = ENTCOLL_NONE; + if (!npc.sprite.IsPlaying()) + { + if (npc.state == HORN_DIVES && npc.subtype != HORN_THIRD) + { + uint32_t seed = Random(); + bomb_spawn(npc, {.position = npc.pos, .spawner = &npc, .subType = 1, .type = ENTITY_BOMB, + .variant = npc.subtype == HORN_HOT ? BOMB_HOT : BOMB_TROLL, .seed = seed}); + } + npc.stateFrame = 1; + npc.velocity = {}; + float pitch = pitch_roll(); + npc_sound_play(npc.i2 == 1 ? SOUND_LITTLE_HORN_GRUNT_2 : SOUND_LITTLE_HORN_GRUNT_1, 1, 2, pitch); + horn_relocate(npc); + } + } + if (npc.stateFrame != 1) return; + + npc.sprite.Play("Return"); + if (npc.sprite.WasEventTriggered("CollisionOn")) npc.entityCollisionClass = ENTCOLL_ALL; + if (npc.sprite.IsPlaying()) return; + npc.stateFrame = 0; + if (--npc.i2 >= 1) return; + npc.state = NPC_STATE_IDLE; + npc.i1 = DIVE_REST; +} + +// The pit summon on Summon: one pit under it, or three or five flung out around it toward its target. +static void horn_pits(Entity_NPC& npc) +{ + npc.sprite.Play("Summon"); + if (!npc.sprite.IsEventTriggered("Summon")) return; + + bool isRing = npc.state == HORN_PITS; + int count = 1; + if (isRing) + { + uint32_t roll = Random() % 100; + count = roll < PIT_WIDE_ODDS ? PITS_WIDE : roll < PIT_FEW_ODDS ? PITS_FEW : 1; + } + float pitch = pitch_roll(); + npc_sound_play(SOUND_LITTLE_HORN_GRUNT_1, 1, 2, pitch); + float aim = vector_angle(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + for (int i = 0; i < count; i++) + { + auto* pit = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_PITFALL, + .variant = isRing ? PIT_FLUNG : 0, + .seed = Random()})); + if (!pit) continue; + pit->stateFrame = PIT_FRAMES; + if (isRing) + { + Vector heading = vector_from_angle((float)i / (float)count * HORN_FULL_TURN + aim); + pit->ClearEntityFlags(FLAG_APPEAR); + pit->velocity = vector_resized(heading, PIT_SPEED); + } + pit->Update(); + } +} + +// Little Horn proper: shrugs off three quarters of its own bombs' blasts, then idles, attacks or dives. +static void horn_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("HoleOpen")) npc_sound_play(SOUND_LITTLE_HORN_HOLE_OPEN, 1, 2, 1); + if (npc.sprite.IsEventTriggered("HoleExit")) npc_sound_play(SOUND_LITTLE_HORN_HOLE_EXIT, 1, 2, 1); + if (npc.pendingDamage > 0 && (npc.pendingDamageFlags & DAMAGE_EXPLOSION)) + { + npc.pendingDamage = 0; + for (DamageEvent& hit : npc.damageEvents) + { + if (hit.source.spawnerType == npc.type) hit.damage *= OWN_BLAST_SHARE; + npc.pendingDamage += hit.damage; + } + } + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.i1 = 0; + return; + } + if (npc.i1 > 0) npc.i1--; + npc.friction *= HORN_FRICTION; + + switch (npc.state) + { + case NPC_STATE_IDLE: + horn_idle(npc); + break; + case HORN_DIVE: + case HORN_DIVES: + horn_dive(npc); + break; + case HORN_SHOOT: + case HORN_BOMB: + case HORN_MEGA_BOMB: + case HORN_PIT: + case HORN_PITS: + if (npc.state == HORN_SHOOT) horn_shoot(npc); + else if (npc.state == HORN_PIT || npc.state == HORN_PITS) horn_pits(npc); + else horn_bomb(npc); + if (npc.sprite.IsPlaying()) break; + npc.stateFrame = 0; + npc.state = NPC_STATE_IDLE; + break; + } + if (npc.isDead) npc_sound_play(SOUND_LITTLE_HORN_DEATH, 1, 2, 1); +} + +// The homing ball closes on its target and keeps off the other balls and bombs, the rolling one keeps its speed. +// Both leave a trail of three dark clouds a frame, recolored like their Little Horn. +static void ball_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.splatColor = BALL_SPLAT_COLOR; + npc.sprite.offset = vector_make(0, SPRITE_HEIGHT); + npc.state = NPC_STATE_IDLE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.sprite.Play("Idle"); + return; + } + npc.stateFrame++; + + if (npc.subtype == BALL_HOMING) + { + npc.friction *= HORN_FRICTION; + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + float damping = BALL_DAMPING; + if (npc.speedMultiplier != 1) + damping = BALL_DAMPING / ((npc.speedMultiplier + BALL_DAMPING) - npc.speedMultiplier * BALL_DAMPING); + npc.velocity = vector_scale(npc.velocity, damping); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(vector_normalized(toward), + BALL_PULL * npc.scale * npc.speedMultiplier / npc.friction)); + npc.mass = BALL_MASS; + + auto keepOff = [&npc](Entity* other, float strength) + { + if (other == &npc || vector_length(vector_sub(other->pos, npc.pos)) >= BALL_SHY) return; + Vector away = vector_sub(npc.pos, other->pos); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, (BALL_SHY - distance) / distance); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(away, strength * npc.speedMultiplier / npc.friction)); + }; + for (Entity* other : entity_query(ENTITY_LITTLE_HORN, HORN_BALL)) keepOff(other, BALL_SHY_BALLS); + for (Entity* bomb : entity_query(ENTITY_BOMB, -1)) keepOff(bomb, BALL_SHY_BOMBS); + } + else if (npc.subtype == BALL_ROLLING) + { + npc.friction = 1; + npc.mass = BALL_MASS; + npc.velocity = vector_scale(vector_normalized(npc.velocity), BALL_ROLL_SPEED); + } + + for (int i = 0; i < BALL_TRAILS; i++) + { + Entity* trail = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_DARK_BALL_SMOKE_PARTICLE, + .seed = Random()}); + if (!trail) continue; + if (npc.bosscoloridx >= 0) + { + trail->sprite.ReplaceSpritesheet(0, npc.sprite.GetLayer(0)->spriteSheetPath); + trail->sprite.LoadGraphics(); + } + trail->velocity = vector_scale(npc.velocity, TRAIL_BACK); + Vector scatter = random_direction(); + float spread = random_unit(); + float speed = vector_length(npc.velocity); + if (trail->friction != 0) + trail->velocity = vector_add(trail->velocity, + vector_scale(scatter, spread * speed * TRAIL_SCATTER * trail->speedMultiplier / + trail->friction)); + trail->sprite.offset = vector_make(0, SPRITE_HEIGHT); + trail->sprite.scale = vector_make(npc.scale, npc.scale); + } +} + +// 00490680 NpcAI::ENTITY_LITTLE_HORN: Little Horn hides in its hole and pops up to spit dark balls, summon pits and +// drop troll bombs, diving away from anyone close. Its balls chase or roll. +void boss_little_horn_update(Entity_NPC& npc) +{ + if (npc.variant == HORN_BALL) return ball_update(npc); + if (npc.variant == 0) horn_update(npc); +} diff --git a/src/boss_monstro.cpp b/src/boss_monstro.cpp index 77a9692..ab979bb 100644 --- a/src/boss_monstro.cpp +++ b/src/boss_monstro.cpp @@ -2,6 +2,7 @@ #include "entity_effect.h" #include "grid_entity_trap_door.h" #include "room_descriptor.h" +#include "sfx_manager.h" constexpr int ENTITY_MONSTRO = 20; constexpr int MONSTRO_TWINS = 1; @@ -20,25 +21,24 @@ enum MonstroAttack // 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 MONSTRO_FRICTION = 0.9f; +constexpr float MONSTRO_LANDED_FRICTION = 0.8f; +constexpr float MONSTRO_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 SPIT_CLOUD_SCALE = 0.7f; 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 float MONSTRO_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}}; @@ -108,7 +108,7 @@ static void monstro_idle(Entity_NPC& npc) { case MONSTRO_HOP: npc.state = NPC_STATE_MOVE; - npc.PlaySound(SOUND_MONSTER_ROAR_0, HOP_VOLUME, 2, false, 1); + npc.PlaySound(SOUND_BOSS_LITE_ROAR, HOP_VOLUME, 2, false, 1); return anim_restart(npc.sprite, "Walk"); case MONSTRO_SPIT: npc.state = NPC_STATE_ATTACK; @@ -117,7 +117,7 @@ static void monstro_idle(Entity_NPC& npc) return; case MONSTRO_JUMP: npc.state = NPC_STATE_JUMP; - npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.PlaySound(SOUND_BOSS_LITE_ROAR, 1, 2, false, 1); return anim_restart(npc.sprite, "JumpUp"); } } @@ -129,7 +129,7 @@ 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; + npc.friction *= MONSTRO_LANDED_FRICTION; return; } @@ -162,21 +162,21 @@ static void monstro_hop(Entity_NPC& npc, const Vector& target) 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; + vector_scale(toward, MONSTRO_HOP_PULL / distance * npc.speedMultiplier / npc.friction)); + npc.friction *= MONSTRO_FRICTION; npc.sprite.isFlipX = npc.velocity.x > 0; return; } if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) { - npc.friction *= LANDED_FRICTION; + npc.friction *= MONSTRO_LANDED_FRICTION; return; } npc.targetPosition = {}; if (Random() & 1) { - npc.PlaySound(SOUND_MONSTER_ROAR_0, REHOP_VOLUME, 2, false, 1); + npc.PlaySound(SOUND_BOSS_LITE_ROAR, REHOP_VOLUME, 2, false, 1); return anim_restart(npc.sprite, "Walk"); } npc.sprite.playbackSpeed = 1; @@ -213,7 +213,7 @@ static void monstro_stomp(Entity_NPC& npc, Vector target) } bool isLanded = npc.sprite.WasEventTriggered("Land"); - if (vector_is_zero(npc.targetPosition) || isLanded) npc.friction *= LANDED_FRICTION; + if (vector_is_zero(npc.targetPosition) || isLanded) npc.friction *= MONSTRO_LANDED_FRICTION; else { npc.entityCollisionClass = ENTCOLL_NONE; @@ -232,7 +232,7 @@ static void monstro_stomp(Entity_NPC& npc, Vector target) if (npc.sprite.IsEventTriggered("Land")) { npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); - shockwave_make(npc.pos, SHOCKWAVE_AMPLITUDE, SHOCKWAVE_SPEED, SHOCKWAVE_FRAMES); + shockwave_make(npc.pos, SHOCKWAVE_AMPLITUDE, MONSTRO_SHOCKWAVE_SPEED, SHOCKWAVE_FRAMES); npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, 1); } if (npc.sprite.IsEventTriggered("Shoot")) npc.FireBossProjectiles(STOMP_SHOTS, {}, 0, ProjectileParams()); @@ -252,10 +252,10 @@ static void monstro_spit(Entity_NPC& npc) { if (npc.sprite.IsEventTriggered("Shoot")) { - npc.PlaySound(SOUND_BOSS_SPIT, 1, 2, false, 1); + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 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); + Entity_Effect* cloud = npc.MakeBloodCloud(npc.pos, SPIT_CLOUD_COLOR, SPIT_CLOUD_SCALE); cloud->posOffset = vector_make(0, SPIT_CLOUD_HEIGHT); } if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; @@ -271,7 +271,7 @@ 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; + npc.friction *= MONSTRO_FRICTION; Vector target = npc.CalcTargetPosition(0); switch (npc.state) diff --git a/src/boss_pool.cpp b/src/boss_pool.cpp index d7eb7e6..42f25ba 100644 --- a/src/boss_pool.cpp +++ b/src/boss_pool.cpp @@ -57,11 +57,7 @@ constexpr int STAGE_CHAPTER_1 = 1; constexpr int STAGE_CHAPTER_2 = 3; constexpr int STAGE_CHAPTER_2_END = 4; constexpr int STAGE_CHAPTER_3 = 5; -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_VOID = 12; constexpr int CHALLENGE_APRILS_FOOL = 32; constexpr int CHALLENGE_ULTRA_HARD = 34; @@ -137,9 +133,9 @@ static int chapter_end_boss(int levelStage, int stageType) switch (levelStage) { - case STAGE_MOM: + case STAGE_DEPTHS_II: return isAltPath ? BOSS_MOM_MAUSOLEUM : BOSS_MOM; - case STAGE_MOMS_HEART: + case STAGE_WOMB_II: if (isAltPath) return BOSS_MOTHER; return g_manager->persistentGameData.Unlocked(ACHIEVEMENT_IT_LIVES) ? BOSS_IT_LIVES : BOSS_MOMS_HEART; case STAGE_SHEOL: diff --git a/src/entity.cpp b/src/entity.cpp index 272a292..41330d4 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -509,12 +509,6 @@ uint32_t Entity::GetHitListIndex() return GetStatusEffectTarget()->index; } -// 006ac7e0 -int Entity::CountRelatedEntities(int, int, std::vector*) -{ - reconstruction_missing("Entity::CountRelatedEntities 006ac7e0"); -} - // 006ac530 Whether it is an enemy, or a player in a versus match. bool Entity::IsEnemy() { @@ -1367,18 +1361,6 @@ Entity_Effect* Entity::MakeGroundPoofAtSelf(const ColorMod&, float) reconstruction_missing("Entity::MakeGroundPoofAtSelf 006b66a0"); } -// 006b66c0 -Entity_Effect* Entity::MakeBloodPoof(const Vector&, const ColorMod&, float) -{ - reconstruction_missing("Entity::MakeBloodPoof 006b66c0"); -} - -// 006b6810 -Entity_Effect* Entity::MakeBloodPoofAtPos(const ColorMod&, float) -{ - reconstruction_missing("Entity::MakeBloodPoofAtPos 006b6810"); -} - // 006b6c20 void Entity::GetNullCapsule(Capsule&, std::string_view) { diff --git a/src/entity.h b/src/entity.h index 1b5ecdd..323c101 100644 --- a/src/entity.h +++ b/src/entity.h @@ -30,12 +30,16 @@ enum EntityType : int ENTITY_SHOPKEEPER = 17, ENTITY_ATTACKFLY = 18, ENTITY_LARRYJR = 19, + ENTITY_MAGGOT = 21, ENTITY_HIVE = 22, ENTITY_CHARGER = 23, + ENTITY_GLOBIN = 24, ENTITY_BOOMFLY = 25, ENTITY_CHUB = 28, ENTITY_HOPPER = 29, ENTITY_BOIL = 30, + ENTITY_SPITTY = 31, + ENTITY_BRAIN = 32, ENTITY_FIREPLACE = 33, ENTITY_LEAPER = 34, ENTITY_MRMAW = 35, @@ -54,12 +58,14 @@ enum EntityType : int ENTITY_FAMINE = 63, ENTITY_MOMS_HEART = 78, ENTITY_GEMINI = 79, + ENTITY_MOTER = 80, ENTITY_SATAN = 84, ENTITY_SPIDER = 85, ENTITY_BUTTLICKER = 89, ENTITY_HEART = 92, ENTITY_MASK = 93, ENTITY_BIG_SPIDER = 94, + ENTITY_ETERNALFLY = 96, ENTITY_MASK_OF_INFAMY = 97, ENTITY_HEART_OF_INFAMY = 98, ENTITY_GURDY_JR = 99, @@ -74,17 +80,32 @@ enum EntityType : int ENTITY_WALL_HUGGER = 218, ENTITY_SQUIRT = 220, ENTITY_RING_OF_FLIES = 222, + ENTITY_SKINNY = 226, + ENTITY_BONY = 227, + ENTITY_GURGLING = 237, ENTITY_GRUB = 239, + ENTITY_CONJOINED_SPITTY = 243, ENTITY_ROUND_WORM = 244, ENTITY_POOP = 245, + ENTITY_NIGHT_CRAWLER = 255, + ENTITY_DART_FLY = 256, ENTITY_GATE = 263, ENTITY_URIEL = 271, ENTITY_GABRIEL = 272, ENTITY_MEGA_SATAN = 274, + ENTITY_ROUNDY = 276, + ENTITY_BLACK_BONY = 277, + ENTITY_BLACK_GLOBIN = 278, + ENTITY_BLACK_GLOBIN_HEAD = 279, + ENTITY_BLACK_GLOBIN_BODY = 280, + ENTITY_ULCER = 289, ENTITY_PITFALL = 291, ENTITY_MOVABLE_TNT = 292, + ENTITY_CORN_MINE = 295, ENTITY_HUSH_FLY = 296, + ENTITY_POISON_MIND = 301, ENTITY_STONEY = 302, + ENTITY_STAIN = 401, ENTITY_LITTLE_HORN = 404, ENTITY_ULTRA_GREED = 406, ENTITY_HUSH = 407, @@ -96,6 +117,8 @@ enum EntityType : int ENTITY_SMALL_LEECH = 810, ENTITY_ROCK_SPIDER = 818, ENTITY_FLY_BOMB = 819, + ENTITY_SMALL_MAGGOT = 853, + ENTITY_PUSTULE = 861, ENTITY_DARK_ESAU = 866, ENTITY_ORBIT_SPAWNER = 873, ENTITY_GRUDGE = 877, @@ -107,10 +130,13 @@ enum EntityType : int ENTITY_GIDEON = 907, ENTITY_BABY_PLUM = 908, ENTITY_SCOURGE = 909, + ENTITY_CHIMERA = 910, ENTITY_ROTGUT = 911, ENTITY_MOTHER = 912, + ENTITY_MIN_MIN = 913, ENTITY_SINGE = 915, ENTITY_BUMBINO = 916, + ENTITY_COLOSTOMIA = 917, ENTITY_TURDLET = 918, ENTITY_RAGLICH = 919, ENTITY_DOGMA = 950, @@ -199,18 +225,26 @@ enum DamageFlag : uint64_t DAMAGE_FIRE = 1ull << 1, DAMAGE_EXPLOSION = 1ull << 2, DAMAGE_ACID = 1ull << 4, + DAMAGE_RED_HEARTS = 1ull << 5, DAMAGE_COUNTDOWN = 1ull << 6, DAMAGE_SPIKES = 1ull << 7, DAMAGE_POOP = 1ull << 9, + DAMAGE_DEVIL = 1ull << 10, + DAMAGE_TNT = 1ull << 12, DAMAGE_INVINCIBLE = 1ull << 13, DAMAGE_SPAWN_FLY = 1ull << 14, DAMAGE_POISON_BURN = 1ull << 15, + DAMAGE_CURSED_DOOR = 1ull << 16, + DAMAGE_CHEST = 1ull << 20, + DAMAGE_BOOGER = 1ull << 22, DAMAGE_SPAWN_BLACK_HEART = 1ull << 23, DAMAGE_SPAWN_RED_HEART = 1ull << 26, DAMAGE_SPAWN_COIN = 1ull << 27, + DAMAGE_NO_PENALTIES = 1ull << 28, DAMAGE_IGNORE_ARMOR = 1ull << 30, DAMAGE_SPAWN_CARD = 1ull << 31, - DAMAGE_SPAWN_RUNE = 1ull << 32 + DAMAGE_SPAWN_RUNE = 1ull << 32, + DAMAGE_THROUGH_COOLDOWN = 1ull << 35 }; // Lua's EntityGridCollisionClass: what of the room's grid an entity collides with. @@ -278,6 +312,8 @@ using TearFlags = std::bitset<128>; // The drop RNG an entity holds before Init seeds it. constexpr RNG DROP_RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; +// The shifts of a drop RNG restored from a save, its seed taken from the save. +constexpr RNG DROP_RNG_SAVED = {0, 4, 3, 17}; struct Entity; struct lua_State; diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index e9691f1..9cc30a6 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -11,6 +11,7 @@ #include "lua_engine.h" #include "manager.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include "sfx_manager.h" #include @@ -28,6 +29,10 @@ constexpr float DAMAGE_GIGA = 300; constexpr int COLLISION_COOLDOWN = 4; constexpr float ROCKET_HEIGHT = -14; +// A troll bomb returned out of the floor (subtype 1), its hole layer tinted in the floor's color. +constexpr int BOMB_RETURNED = 1; +constexpr std::string_view RETURN_HOLE_LAYER = "Hole"; + // The fall: gravity, Hydrobounce's, the heights the grid collision changes at, and a bounce's loss and limit. constexpr float FALL_GRAVITY = 0.8f; constexpr float FALL_GRAVITY_BOUNCY = 2.5f; @@ -89,7 +94,6 @@ constexpr int TRINKET_BLASTING_CAP = 73; constexpr int PICKUP_BOMB = 40; constexpr int PICKUP_BOMBCHEST = 51; constexpr int POOF01_EFFECT = 15; -constexpr int ENTITY_COLOSTOMIA = 917; constexpr int VISAGE_MASK_VARIANT = 10; // Pushes and slowdowns of a bomb that collides with something low. @@ -136,7 +140,8 @@ bool Entity_Bomb::IsRocket() } // 006a2050 Starts the bomb: its fuse (longer and random for troll and hot bombs, the brimstone and giga bombs' own), -// its damage, its sprite and first animation, and a rocket's flight height. +// its damage, its sprite and first animation (a returned troll bomb's hole in the floor's color), and a rocket's flight +// height. void Entity_Bomb::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { Entity::Init(entityType, entityVariant, entitySubType, seed); @@ -176,11 +181,15 @@ void Entity_Bomb::Init(int entityType, int entityVariant, int entitySubType, uin isLoadCostumes = false; if (variant == BOMB_DECOY) sprite.Play("Idle"); - else if (isTroll || variant == BOMB_GIGA) + else if ((isTroll || variant == BOMB_GIGA) && subtype == BOMB_RETURNED) { - if (subtype == 1) reconstruction_missing("Entity_Bomb::Init 006a2050: a returned bomb in the floor's color"); - sprite.Play("Appear", PLAY_FORCED); + sprite.Play("BombReturn", PLAY_FORCED); + KColor floor = room_floor_color_get(*g_game->room, pos, size); + ColorMod hole = {{floor._red * 2, floor._green * 2, floor._blue * 2, 1}, {}, {}}; + for (LayerState& layer : sprite.layerStates) + if (layer.layerData && layer.layerData->name == RETURN_HOLE_LAYER) layer.color = hole; } + else if (isTroll || variant == BOMB_GIGA) sprite.Play("Appear", PLAY_FORCED); else sprite.Play("Pulse", PLAY_FORCED); rocketAngle = 0; @@ -190,7 +199,7 @@ void Entity_Bomb::Init(int entityType, int entityVariant, int entitySubType, uin AddEntityFlags(FLAG_NO_KNOCKBACK); posOffset.y = ROCKET_HEIGHT; } - lua_callback_check(MC_POST_BOMB_INIT, "LuaEngine::PostBombInit 00861ea0"); + lua_engine_get().PostBombInit(this); } // Falls back to the floor, colliding with less of the grid the higher it flies, and lands with a sound. Hydrobounce @@ -441,7 +450,7 @@ void Entity_Bomb::late_update() } if (isHasCostumes) for (ANM2& costume : bombCostumesSprites) costume.Update(); - lua_callback_check(MC_POST_BOMB_UPDATE, "LuaEngine::PostBombUpdate 00861f80"); + lua_engine_get().PostBombUpdate(this); } // 006a5a60 Draws the bomb at its place: with costumes, the back costume, the bomb, then the others, each following the @@ -458,7 +467,7 @@ void Entity_Bomb::Render(const Vector& offset) if (!frame) { sprite.Render(draw); - lua_callback_check(MC_POST_BOMB_RENDER, "LuaEngine::PostBombRender 00862060"); + lua_engine_get().PostBombRender(this, offset); return; } @@ -485,7 +494,7 @@ void Entity_Bomb::Render(const Vector& offset) } if (i == 0) sprite.Render(draw); } - lua_callback_check(MC_POST_BOMB_RENDER, "LuaEngine::PostBombRender 00862060"); + lua_engine_get().PostBombRender(this, offset); } // Whether a rocket flies past what it meets: anything but enemies, or a friendly enemy. diff --git a/src/entity_bomb.h b/src/entity_bomb.h index f8dbdc6..38caba3 100644 --- a/src/entity_bomb.h +++ b/src/entity_bomb.h @@ -52,6 +52,9 @@ struct Explosion bool isLineCheck = true; }; +// The damage of the blast Black Powder sets off when its player puts out a fire. +constexpr float BLACK_POWDER_DAMAGE = 20; + // Construction and destruction (006a1e80, 006a1f30) are the defaults. // Field accessors (004316a0, 005cd560, 0060cdc0) are the public fields. // A bomb (Lua's EntityBomb): its fuse, the explosion it deals, the tear effects it carries, its fall and bounce, and diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 81a47bf..5fdebcc 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -8,6 +8,7 @@ #include "log.h" #include "manager.h" #include "room.h" +#include "room_grid.h" #include #include #include @@ -168,8 +169,7 @@ static void crush_bridge(Room& room, Entity& crusher, GridEntity& rock) int beyond = room.GetGridIndex( vector_make(center.x + directionX * GRID_CELL_SIZE, center.y + directionY * GRID_CELL_SIZE)); - GridEntity* pit = room.GetGridEntity(beyond); - if (pit && pit->type == GRID_PIT) reconstruction_missing("Room::TryMakeBridge 0081e6e0"); + room_bridge_make(room.GetGridEntity(beyond), &rock); } // 007aa7c0 Whether the player has a transformation: three items of its set, out of the cursed mist and alive. @@ -573,7 +573,14 @@ void Entity::CollideWithGrid(GridCollisionMode mode) bool isCancelled = normal.y * normal.y + normal.x * normal.x < NORMAL_EPSILON; if (type == ENTITY_TEAR && isCancelled) normal = tear_cell_normal(*this, room, normal); else if (IsEnemy() && gridClass == GRIDCOLL_GROUND && isCancelled) - reconstruction_missing("Room::FindFreeTilePosition 0081e520"); + { + Vector tile = room_free_tile_position_find(pos, GRID_CELL_SIZE); + float marginX = HALF_CELL - size * sizeMulti.x; + float marginY = HALF_CELL - size * sizeMulti.y; + pos.x = tile.x - pos.x <= 0 ? tile.x + marginX : tile.x - marginX; + pos.y = tile.y - pos.y > 0 ? tile.y - marginY : tile.y + marginY; + return; + } normal = vector_normalized(normal); if (!isSimulated) gridCollisionNormal = normal; diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 03dee9d..03a6709 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -2,6 +2,7 @@ #include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" +#include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_laser.h" #include "entity_list.h" @@ -70,17 +71,24 @@ constexpr int BLUE_FLY_MAX = 30; constexpr int MAGGY_SWING_READY = 3; // Lua's DamageFlag bits beyond entity.h's. -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_TOOTH_PARTICLE = 35; -constexpr int EFFECT_POOP_PARTICLE = 58; constexpr int EFFECT_BISHOP_SHIELD = 160; constexpr int EFFECT_CHAIN_GIB = 163; constexpr int ROCK_PARTICLE_SUBTYPE = 0x10001; +// An iced enemy shatters into 3 to 6 shards at 3 to 5, a frozen one into its gibs and up to 2 more as rocks at 5, both +// in a cold white and with a pitch of 0.9 to 1.1. +constexpr ColorMod SHATTER_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 0.5f}, {0.3f, 0.5f, 0.8f}}; +constexpr float SHATTER_PITCH_MIN = 0.9f; +constexpr float SHATTER_PITCH_RANGE = 0.2f; +constexpr float ICE_SHARD_SPEED_MIN = 3; +constexpr uint32_t ICE_SHARD_EXTRA_MASK = 3; +constexpr int ICE_SHARD_COUNT_MIN = 3; +constexpr uint32_t FROZEN_SHARD_EXTRA = 3; +constexpr float FROZEN_SHARD_SPEED = 5; + // The sounds the combat code plays (Lua's SoundEffect). constexpr int SOUND_DEATH_BURST_BONE = 27; constexpr int SOUND_DEATH_BURST_SMALL = 30; @@ -334,7 +342,7 @@ bool Entity::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& sou if (HasEntityFlags(FLAG_WEAKNESS)) damage += damage; if (maxHitPoints <= 0) return false; - lua_callback_check(MC_ENTITY_TAKE_DMG, "Entity::TakeDamage 006ace60: MC_ENTITY_TAKE_DMG"); + if (!lua_engine_get().EntityTakeDamage(this, damage, damageFlags, source, countdown)) return false; damageEvents.push_back({.source = source, .damage = damage, .damageFlags = damageFlags}); pendingDamageFlags |= damageFlags; pendingDamage += damage; @@ -354,7 +362,7 @@ void Entity::Kill(const EntityRef& source) { bool isPowderable = variant == FIREPLACE_NORMAL || variant == FIREPLACE_RED || variant == FIREPLACE_MOVEABLE; if (static_cast(killer)->HasCollectible(COLLECTIBLE_BLACK_POWDER) && isPowderable) - reconstruction_missing("Entity::Kill 006ac920: Black Powder's fireplace blast (BombExplosionEffects)"); + explosion_effects({.position = pos, .source = killer, .damage = BLACK_POWDER_DAMAGE}); } if (!IsBoss() && type != ENTITY_FAMILIAR) BloodExplode(); lua_engine_get().PostEntityKill(this); @@ -424,15 +432,30 @@ static void burst_drops_spawn(Entity& entity, int gibsAmount) } } -// 006b45c0 Bursts it: an iced enemy shatters, anything else plays its burst sound and throws its config's gibs, a big -// burst (extra gore, or a huge config) shaking the screen, pushed away from the first hit and with blood drops. It -// leaves a blood splat unless it is a bomb, a pickup or splashes no blood. +// 006b45c0 Bursts it: an iced or frozen enemy only shatters into shards, anything else plays its burst sound and +// throws its config's gibs, a big burst (extra gore, or a huge config) shaking the screen, pushed away from the first +// hit and with blood drops. It leaves a blood splat unless it is a bomb, a pickup or splashes no blood. void Entity::BloodExplode() { if (HasEntityFlags(FLAG_ICE) && !IsBoss() && !config->isBoss) - reconstruction_missing("Entity::BloodExplode 006b45c0: an iced enemy shattering (Game::SpawnParticles)"); + { + npc_sound_play(SOUND_FREEZE, 1, 2, random_unit() * SHATTER_PITCH_RANGE + SHATTER_PITCH_MIN); + float speed = random_unit(); + speed = speed + speed + ICE_SHARD_SPEED_MIN; + int count = (int)(Random() & ICE_SHARD_EXTRA_MASK) + ICE_SHARD_COUNT_MIN; + game_particles_spawn({.color = SHATTER_COLOR, .position = pos, .speed = speed, .count = count, + .variant = EFFECT_TOOTH_PARTICLE}); + return; + } if (HasEntityFlags(FLAG_ICE_FROZEN)) - reconstruction_missing("Entity::BloodExplode 006b45c0: a frozen enemy shattering (Game::SpawnParticles)"); + { + npc_sound_play(SOUND_FREEZE_SHATTER, 1, 2, random_unit() * SHATTER_PITCH_RANGE + SHATTER_PITCH_MIN); + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, 1); + int count = config->gibsAmount + (int)(Random() % FROZEN_SHARD_EXTRA); + game_particles_spawn({.color = SHATTER_COLOR, .position = pos, .speed = FROZEN_SHARD_SPEED, .count = count, + .variant = EFFECT_ROCK_PARTICLE}); + return; + } burst_sound_play(*this); if (type == ENTITY_SUCKER && variant == SUCKER_BULB) diff --git a/src/entity_effect.h b/src/entity_effect.h index 0f430cb..dcfa93a 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -37,14 +37,20 @@ enum EffectVariant : int EFFECT_CREEP_BLACK = 26, EFFECT_WOOD_PARTICLE = 27, EFFECT_TINY_FLY = 33, + EFFECT_FART = 34, + EFFECT_TOOTH_PARTICLE = 35, EFFECT_SPIDER_EXPLOSION = 38, EFFECT_HEAVEN_LIGHT_DOOR = 39, EFFECT_WATER_DROPLET = 41, + EFFECT_POOP_EXPLOSION = 43, EFFECT_PLAYER_CREEP_RED = 46, EFFECT_HEART = 49, + EFFECT_HOT_BOMB_FIRE = 51, EFFECT_PLAYER_CREEP_GREEN = 53, EFFECT_CREEP_BROWN = 56, + EFFECT_POOP_PARTICLE = 58, EFFECT_DUST_CLOUD = 59, + EFFECT_SHOCKWAVE = 61, EFFECT_WORM = 63, EFFECT_BEETLE = 64, EFFECT_WISP = 65, @@ -55,14 +61,21 @@ enum EffectVariant : int EFFECT_TEAR_POOF_SMALL = 79, EFFECT_TEAR_POOF_VERYSMALL = 80, EFFECT_FALLING_EMBER = 87, + EFFECT_DARK_BALL_SMOKE_PARTICLE = 88, EFFECT_PENTAGRAM_BLACKPOWDER = 93, + EFFECT_CREEP_SLIPPERY_BROWN = 94, EFFECT_WATER_SPLASH = 99, + EFFECT_HALLOWED_GROUND = 112, EFFECT_BRIMSTONE_BALL = 113, EFFECT_BROKEN_SHOVEL_SHADOW = 115, + EFFECT_SMALL_ROCKET = 118, EFFECT_SPAWNER = 120, EFFECT_LIGHT = 121, + EFFECT_TAR_BUBBLE = 124, + EFFECT_GRID_ENTITY_PROJECTILE_HELPER = 136, EFFECT_BACKDROP_DECORATION = 140, EFFECT_SMOKE_CLOUD = 141, + EFFECT_FIRE_JET = 147, EFFECT_DOOR_OUTLINE = 154, EFFECT_TALL_LADDER = 156, EFFECT_TADPOLE = 158, diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp index 9990b43..076449e 100644 --- a/src/entity_effect_ambient.cpp +++ b/src/entity_effect_ambient.cpp @@ -35,7 +35,6 @@ enum AmbientVariant : int EFFECT_PLAYER_CREEP_LEMON_PARTY = 78, EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90, EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, - EFFECT_CREEP_SLIPPERY_BROWN = 94, EFFECT_CREEP_STATIC = 169, EFFECT_PLAYER_CREEP_YELLOW = 204 }; @@ -56,8 +55,6 @@ template EffectUpdateEnd finishing(Entity_Effec return EFFECT_UPDATE_FINISH; } -constexpr int STAGE_ID_CATHEDRAL = 15; -constexpr int BACKDROP_DROSS = 45; constexpr int ROOM_BARREN_TYPE = 19; constexpr int SOUND_DROPLET_SPLASH = 397; constexpr int SOUND_SPAWNER_SUMMON = 265; @@ -140,10 +137,6 @@ constexpr int WISP_ORANGE_STAGE = 32; // The water droplets that fall from the ceiling and splash or stain where they land. constexpr int DROPLET_KINDS = 3; -constexpr int STAGE_DEPTHS_2 = 6; -constexpr int STAGE_DEPTHS = 5; -constexpr int STAGE_WOMB = 7; -constexpr int STAGE_TYPE_AFTERBIRTH = 2; constexpr float DROPLET_HEIGHT = -10; constexpr float DROPLET_LANDED_HEIGHT = 10; constexpr float DROPLET_GRAVITY = 1; @@ -671,9 +664,9 @@ static void water_droplet_init(Entity_Effect& drop) { int stage = (int)g_game->stage; - if ((stage == STAGE_DEPTHS || stage == STAGE_DEPTHS_2) && (int)g_game->stageType == STAGE_TYPE_AFTERBIRTH) + if ((stage == STAGE_DEPTHS_I || stage == STAGE_DEPTHS_II) && (int)g_game->stageType == STAGETYPE_AFTERBIRTH) drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_DankDroplets.png"); - else if (stage >= STAGE_WOMB) drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_BloodDroplets.png"); + else if (stage >= STAGE_WOMB_I) drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_BloodDroplets.png"); drop.state = (int)(Random() % DROPLET_KINDS); if (drop.state == 0) @@ -1001,7 +994,6 @@ constexpr int CREEP_RENDER_Z = 2000; constexpr int CREEP_FRAMES = 125; constexpr int LASTING_CREEP_FRAMES = 290; constexpr int GREEN_CREEP_FRAMES = 25; -constexpr int BACKDROP_WOMB = 10; constexpr unsigned int CREEP_STATIC_RENDER_FLAG = 0x20; constexpr float LEMON_MISHAP_PLAYER_SCALE = 1.3f; constexpr float CREEP_RADIUS_PER_SCALE = 20; diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index e6e636c..879799d 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -223,7 +223,6 @@ constexpr float CRATER_SMALL_GROWTH = 2; constexpr uint32_t CRATER_FRAME_SHIFT = 35; constexpr float CRATER_ALPHA_MIN = 0.8f; constexpr float CRATER_ALPHA_RANGE = 0.2f; -constexpr int BACKDROP_DARK_ROOM = 16; constexpr float CRATER_DARK_TINT = 0.5f; constexpr int CRATER_TEMPORARY = 1; constexpr int CRATER_TEMPORARY_FRAMES = 150; @@ -264,7 +263,6 @@ constexpr const char* GROUND_BREAK_MINES_LAVA = "gfx/Effects/Effect_062_GroundBr constexpr const char* GROUND_BREAK_MAUSOLEUM = "gfx/Effects/Effect_062_GroundBreakMausoleum.png"; constexpr const char* GROUND_BREAK_CORPSE = "gfx/Effects/Effect_062_GroundBreakCorpse.png"; constexpr const char* GROUND_BREAK_CORPSE2 = "gfx/Effects/Effect_062_GroundBreakCorpse2.png"; -constexpr int BACKDROP_MINES = 32; constexpr std::array GROUND_BREAKS = {{ {GROUND_BREAK_CAVES, 4, false}, {GROUND_BREAK_CAVES, 5, false}, {GROUND_BREAK_DEPTHS, 7, false}, {GROUND_BREAK_DEPTHS, 8, false}, {GROUND_BREAK_DEPTHS, 9, false}, {GROUND_BREAK_WOMB, 10, true}, diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index d317a65..665f90a 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -13,6 +13,7 @@ #include "entity_text.h" #include "game.h" #include "grid_entity.h" +#include "grid_entity_poop.h" #include "lua_engine.h" #include "manager.h" #include "platform.h" @@ -28,7 +29,6 @@ constexpr int SPAWN_STATUS_FRAMES = 90; // The entity types, variants and boss ids spawning and layouts single out. constexpr int ENTITY_HORF = 12; -constexpr int ENTITY_GLOBIN = 24; constexpr int ENTITY_MAW = 26; constexpr int ENTITY_HOST = 27; constexpr int ENTITY_STONEHEAD = 42; @@ -37,7 +37,6 @@ constexpr int ENTITY_MEMBRAIN = 57; constexpr int ENTITY_PARA_BITE = 58; constexpr int ENTITY_EYE = 60; constexpr int ENTITY_WALKINGBOIL = 88; -constexpr int ENTITY_SKINNY = 226; constexpr int ENTITY_NERVE_ENDING = 231; constexpr int ENTITY_HUSH_GAPER = 297; constexpr int ENTITY_GREED_GAPER = 299; @@ -51,7 +50,6 @@ constexpr int BOSS_SATAN = 24; 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 SLOT_MACHINE = 1; constexpr int SLOT_BEGGAR = 4; @@ -124,19 +122,6 @@ enum EntryType : int }; // The poop variants a layout's poop can turn into (Lua's PoopVariant). -enum PoopVariant : int -{ - POOP_NORMAL, - POOP_RED, - POOP_CORN, - POOP_GOLDEN, - POOP_RAINBOW, - POOP_BLACK, - POOP_HOLY, - POOP_GIGA, - POOP_CHARMING = 11 -}; - // The achievements a layout entry waits for. enum EntryAchievement : int { @@ -189,8 +174,6 @@ constexpr float ELLIPSE_SPREAD_X = 1.25f; constexpr float ELLIPSE_SPREAD_Y = 0.3f; constexpr float ELLIPSE_MINES_SPREAD_X = 1.8f; constexpr float ELLIPSE_MINES_SPREAD_Y = 0.5f; -constexpr int STAGE_ID_MINES = 29; -constexpr int STAGE_ID_ASHPIT = 30; constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float FULL_TURN = 360; @@ -222,13 +205,7 @@ constexpr uint32_t ROOM_CONFIG_FLAG_NO_ALT_ROCKS = 1 << 1; constexpr uint32_t ROOM_CONFIG_FLAG_AFTERBIRTH_HAZARDS = 1 << 3; // The stages layouts tell apart (after Curse of the Labyrinth's and Greed's shifts). -constexpr int STAGE_GREED_LAST = 5; -constexpr int STAGE_GREED_SHOP = 10; 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_VOID_ENTRY = 12; constexpr int STAGE_LABYRINTH_SHIFT = 1; constexpr uint32_t CURSE_LABYRINTH = 1 << 1; constexpr int SPECIAL_DAILY_GOLDEN_FATTY = 7; @@ -485,8 +462,8 @@ static int stage_effective() uint32_t curses = (Seeds::GetForcedCurses() | game.debugCurses | game.curses) & ~Seeds::GetPreventedCurses(); int stage = (int)game.stage + (curses & CURSE_LABYRINTH ? STAGE_LABYRINTH_SHIFT : 0); if (game.difficulty != DIFFICULTY_GREED && game.difficulty != DIFFICULTY_GREEDIER) return stage; - if (stage < STAGE_GREED_LAST) return stage * 2 - 1; - return stage == STAGE_GREED_LAST ? STAGE_GREED_SHOP : 0; + if (stage < STAGE_GREED_SHEOL) return stage * 2 - 1; + return stage == STAGE_GREED_SHEOL ? STAGE_SHEOL : 0; } // A layout pickup or slot that waits for an achievement: matched by type, variant and subtype (-1 for any), and the @@ -603,11 +580,11 @@ static void trapdoor_transform(Room& room, RoomEntry& entry, int stage, RNG& rng { ChallengeParam& params = game.GetChallengeParams(); bool isVoidOpen = - params.endStage == STAGE_VOID_ENTRY || (!isInChallenge && unlocked(ACHIEVEMENT_DARK_ROOM_END)); - int endStage = isVoidOpen ? STAGE_VOID_ENTRY : STAGE_DARK_ROOM; + params.endStage == STAGE_VOID || (!isInChallenge && unlocked(ACHIEVEMENT_DARK_ROOM_END)); + int endStage = isVoidOpen ? STAGE_VOID : STAGE_DARK_ROOM; if (params.isPathTypeSet && params.endStage != 0) endStage = params.endStage; bool isHome = params.isPathTypeSet && params.pathType == PATH_TYPE_HOME; - if (!isHome && endStage >= STAGE_VOID_ENTRY) + if (!isHome && endStage >= STAGE_VOID) { entry.variant = TRAPDOOR_VARIANT_VOID; return; @@ -616,7 +593,7 @@ static void trapdoor_transform(Room& room, RoomEntry& entry, int stage, RNG& rng if (room.roomType == ROOM_ERROR && !game.IsNextStageAvailable()) return stairs(); bool isHeavenward = room.roomType == ROOM_ANGEL; - if (!isHeavenward && room.roomType == ROOM_ERROR && (stage == STAGE_WOMB_2 || stage == STAGE_BLUE_WOMB)) + if (!isHeavenward && room.roomType == ROOM_ERROR && (stage == STAGE_WOMB_II || stage == STAGE_BLUE_WOMB)) isHeavenward = (rng.RandomInt(2) == 0 && isCathedralAllowed) || isCathedralForced; if (!isHeavenward) isHeavenward = @@ -870,10 +847,10 @@ static int poop_variant_roll(Room& room, int variant, RNG& rng) { if (variant == POOP_NORMAL) { - if (rng.RandomInt(CORN_ODDS) == 0) variant = POOP_CORN; + if (rng.RandomInt(CORN_ODDS) == 0) variant = POOP_CORNY; else if (rng.RandomInt(CHARMING_ODDS) == 0 && unlocked(ACHIEVEMENT_POOP_CHARMING)) variant = POOP_CHARMING; } - if (variant == POOP_CORN) + if (variant == POOP_CORNY) { uint32_t roll = rng.RandomInt(CORN_ODDS); if (roll == 1 || roll == 2) variant = POOP_GOLDEN; @@ -944,8 +921,8 @@ constexpr std::array GRID_ENTRIES = {{ // The poop entries' variants, from ENTRY_POOP_RED on (-1 for the gaps). constexpr std::array POOP_ENTRY_VARIANTS = {POOP_RED, -1, -1, -1, - POOP_RAINBOW, POOP_CORN, POOP_GOLDEN, POOP_BLACK, - POOP_HOLY, POOP_GIGA, POOP_NORMAL, POOP_CHARMING}; + POOP_RAINBOW, POOP_CORNY, POOP_GOLDEN, POOP_BLACK, + POOP_WHITE, POOP_GIGA_TOP_LEFT, POOP_NORMAL, POOP_CHARMING}; // Places a layout's grid entity on a free cell: rocks and poops rolled, pits counted, the crawlspace's ladder spawned, // the trapdoor's destination kept in its data. diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index 32a0a0d..e00c2d3 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -1,11 +1,14 @@ #include "entity_familiar.h" #include "boss_ai.h" #include "entity_effect.h" +#include "entity_list.h" #include "entity_player.h" #include "game_state_player.h" #include "log.h" +#include "lua_engine.h" #include "manager.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include "room_grid.h" #include "sfx_manager.h" @@ -136,10 +139,17 @@ 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. +// The Lost Soul's state while it is dead and once its body is gone, and a wisp that never blocks. constexpr int LOST_SOUL_DEAD = 2; +constexpr int LOST_SOUL_GONE = 4; constexpr int WISP_UNBLOCKING = 702; +// The body Blood Puppy's state grows (1 small, 2 big), restored with its health. +constexpr int BLOOD_PUPPY_BIG = 2; + +// The layers UpdateDirtColor tints in the floor's color. +constexpr std::string_view FLOOR_TINTED_LAYERS[] = {"dirt", "Hole"}; + // EntityList::QuerySublist for familiars: the ones of a variant (any for -1) the room updates and queries see. std::vector familiar_query(int queryVariant) { @@ -309,6 +319,7 @@ void Entity_Familiar::Init(int initType, int initVariant, int initSubtype, uint3 entityCollisionClass = ENTCOLL_ENEMIES; entityGridCollisionClass = GRIDCOLL_GROUND; } + lua_engine_get().FamiliarInit(this); if (isFollower || variant == TWISTED_BABY) AddToFollowers(); else if (isDelayed) AddToDelayed(); @@ -521,6 +532,7 @@ void Entity_Familiar::update_tail() orbitAngleOffset = angle_wrap(orbitAngleOffset - orbitSpeed * UNICORN_ORBIT_STEP); } + lua_engine_get().FamiliarUpdate(this); int interval = hit_list_interval(); if (interval > 0 && IsFrame(interval, index) && !familiar_listed(KEEP_HIT_LIST_VARIANTS, variant)) hitList.clear(); @@ -603,6 +615,7 @@ void Entity_Familiar::Render(const Vector& offset) ColorMod saved = sprite.color; Entity::Render(offset); + lua_engine_get().PostFamiliarRender(this, offset); render_charge_indicator(renderPosition); sprite.color = saved; } @@ -824,3 +837,93 @@ void Entity_Familiar::store_backup(FamiliarData* backup) backup->isNotCountedAsFollower = isNotCountedAsFollower; backup->isSubtype55555 = isSubtype55555; } + +// 00630560 Takes back what store_backup kept: drop seed, counters, formation spot and health, then what the variant +// keeps. Tinytoma stays shed, the Lost Soul stays gone, a wisp rejoins its orbit, Blood Puppy's body comes back with its +// health and the Star of Bethlehem regains its speed. +void Entity_Familiar::RestoreState(const FamiliarData& saved) +{ + dropRNG = DROP_RNG_SAVED; + dropRNG._seed = saved.dropSeed; + flags &= ~FLAG_APPEAR; + coins = saved.coins; + hearts = saved.hearts; + keys = saved.keys; + state = saved.state; + roomClearCount = saved.roomClearCount; + formationTargetOffset = saved.formationTargetOffset; + formationOffset = saved.formationTargetOffset; + health = saved.health; + isNotCountedAsFollower = saved.isNotCountedAsFollower; + isSubtype55555 = saved.isSubtype55555; + if (isSubtype55555) SetColor(PERMANENT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + + if (variant == TINYTOMA && state > 0) + { + // A sprite without layers would crash the original. It skips the shell. + if (LayerState* shell = sprite.GetLayer(0)) shell->size = {}; + entityCollisionClass = ENTCOLL_NONE; + shadowSize = 0; + RemoveFromOrbit(); + } + if (variant == LOST_SOUL && state == LOST_SOUL_GONE) + { + isVisible = false; + sprite.Play("Death"); + sprite.SetLastFrame(); + } + else if (variant == LOST_SOUL && coins > 0) sprite.PlayOverlay("Mantle"); + if (variant == WISP || variant == ITEM_WISP) + { + if (saved.roomClearCount < 0) RemoveFromOrbit(); + else AddToOrbit(saved.roomClearCount); + } + if (variant == BLOOD_PUPPY) blood_puppy_restore(saved.health); + if (variant == STAR_OF_BETHLEHEM) + { + health = config->baseHP; + orbitSpeed = saved.health; + } + if (variant == ABYSS_LOCUST) reconstruction_missing("Entity_Familiar::RestoreState 00630560 (a locust)"); + Update(); +} + +// Part of 00630560: Blood Puppy drops its body and grows the one its state says, with the saved health, unless it +// died. Its health stays 0 until then. +void Entity_Familiar::blood_puppy_restore(float bodyHealth) +{ + health = 0; + if (bodyHealth <= 0 || state < 1) return; + + if (linkedEntity) + { + linkedEntity->Remove(); + linkedEntity = nullptr; + } + if (state > BLOOD_PUPPY_BIG) return; + + Entity* body = g_game->Spawn({.position = pos, .spawner = player, .type = ENTITY_BLOOD_PUPPY, + .variant = state - 1, .seed = Random()}); + body->parent = this; + body->Update(); + body->sprite.isFlipX = sprite.isFlipX; + body->flags |= FLAG_AMBUSH; + body->health = bodyHealth; + g_game->room->entityList.AddPersistentEntity(body); + linkedEntity = body; +} + +// 0064ca30 Tints its dirt and hole layers in the floor color under it (Room::GetFloorColorAt doubled), at once. +void Entity_Familiar::UpdateDirtColor() +{ + KColor 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; + for (LayerState& layer : sprite.layerStates) + { + std::string_view name = layer.layerData ? std::string_view(layer.layerData->name) : ""; + if (std::ranges::find(FLOOR_TINTED_LAYERS, name) != std::end(FLOOR_TINTED_LAYERS)) layer.color = color_lerp(layer.color, dirtColor, 1); + } +} diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 4c18e24..b5615a4 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -179,6 +179,7 @@ struct Entity_Familiar : Entity LIL_DUMPY = 212, KNIFE_PIECE_1 = 213, KNIFE_PIECE_2 = 214, + TINYTOMA = 216, BOT_FLY = 218, PASCHAL_CANDLE = 221, KNIFE_FULL = 223, @@ -357,6 +358,7 @@ struct Entity_Familiar : Entity void update_weapon(bool isInterpolated); void ai_lil_gurdy(); void store_backup(FamiliarData* backup); + void RestoreState(const FamiliarData& saved); void MoveDelayed(int numFrames); void MoveDiagonally(float speed); void move_to_parent_offset(); @@ -393,12 +395,13 @@ struct Entity_Familiar : Entity void render_abyss_locust_sprite(ANM2*, float*); void siren_charm(Entity* siren, Entity_Player* player); void RemoveFromPlayer(); - void UpdateDirtColor(uint8_t immediate); + void UpdateDirtColor(); void update_star_of_bethlehem_speed(bool isForce); void ai_blood_clot(bool isPostMove); static uint8_t multidimensional_baby_copy_knife(Entity_Knife* knife, Entity* unused); private: + void blood_puppy_restore(float bodyHealth); bool collision_block(Entity& collider, bool isIgnored); bool collision_contact(Entity& collider, float damageMultiplier, float damage); bool solid_check(Entity& collider, bool isIgnored); diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index e85a4dd..c658eea 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -1,4 +1,5 @@ #include "entity_npc.h" +#include "boss_ai.h" #include "boss_death.h" #include "entity_config.h" #include "entity_effect.h" @@ -18,12 +19,15 @@ #include "room.h" #include "room_config.h" #include "room_descriptor.h" +#include "room_grid.h" #include "sfx_manager.h" #include #include #include -constexpr int ENTITY_ETERNAL_FLY = 96; +// The frames of a controlled NPC's charge bar, empty to full. +constexpr int CHARGE_BAR_FRAMES = 100; + constexpr int ENTITY_FEAR_IMMUNE = 205; constexpr int ENTITY_NO_DECOY_TYPE = 213; constexpr int ENTITY_MOMS_HEART_PLAYER_PICK = 53; @@ -88,7 +92,6 @@ struct LineCorner constexpr std::array LINE_CORNERS = {{{-5, -5}, {-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 float SHIELD_SECOND = 30; constexpr float SHIELD_BASE = 0.09f; constexpr float SHIELD_FALLOFF = 0.18f; @@ -102,7 +105,6 @@ constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; // The burst effects a dead NPC leaves besides blood (Lua's EffectVariant). enum DeathBurst : int { - EFFECT_POOP_EXPLOSION = 43, EFFECT_BURST_810 = 130, EFFECT_BURST_853 = 131, EFFECT_BURST_818 = 145 @@ -150,7 +152,6 @@ constexpr int TRINKET_ICE_CUBE_ID = 188; constexpr int TRINKET_DEVILS_CROWN_ID = 185; constexpr int NULLITEM_DAMOCLES_WEAKNESS = 64; -constexpr int STAGE_VOID = 12; constexpr int CHALLENGE_ULTRA_HARD = 34; constexpr int CHALLENGE_BEANS = 30; constexpr int CHALLENGE_SLOW = 22; @@ -421,7 +422,7 @@ uint32_t room_grid_collision_at(const Vector& position) static int line_cell_collision(Room& room, int column, int row) { RoomConfig_Room* config = room.descriptor ? room.descriptor->data : nullptr; - if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_BEAST_DUNGEON) return COLLISION_NONE; + if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_ID_HOME) return COLLISION_NONE; if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return COLLISION_WALL; int gridIndex = row * room.gridWidth + column; @@ -1398,7 +1399,7 @@ void Entity_NPC::appear_update() if (isChampion && championColorIdx < CHAMPION_COUNT) poof->SetColor(champion_sprite_color_get(championColorIdx), -1, COLOR_PRIORITY_DEFAULT, false, true); - int sound = isDeathSoundAlt ? SOUND_SUMMON_POOF : SOUND_SUMMONSOUND; + int sound = isDeathSoundAlt ? SOUND_SUMMON_WAVE : SOUND_SUMMON_POOF; g_manager->sfxManager.Stop(sound); PlaySound(sound, 1, 2, false, 1); if (type == APPEAR_SOUND_TYPE_A || type == APPEAR_SOUND_TYPE_B || (type == ENTITY_BIG_HORN && variant == 0)) @@ -1425,7 +1426,7 @@ void Entity_NPC::appear_update() } if (std::ranges::find(APPEAR_EVENT_TYPES, type) != APPEAR_EVENT_TYPES.end()) - reconstruction_missing("Entity_NPC::Update 006c4b30: a Repentance boss's appear events"); + boss_appear_events(*this); if (state == NPC_STATE_APPEAR) friction *= APPEAR_FRICTION; appearFrames++; } @@ -1441,7 +1442,7 @@ void Entity_NPC::appear_init() } npc_ai_update(*this); if (championColorIdx == CHAMPION_FLY_PROTECTED || championColorIdx == CHAMPION_RAINBOW) - spawn_at(ENTITY_ETERNAL_FLY, 0, 0, pos, this)->parent = this; + spawn_at(ENTITY_ETERNALFLY, 0, 0, pos, this)->parent = this; if (HasEntityFlags(FLAG_APPEAR)) { isVisible = false; @@ -1504,7 +1505,7 @@ void Entity_NPC::death_animation_start() return; } if (type == ENTITY_CHUB || type == ENTITY_LARRYJR || type == ENTITY_PIN || type == ENTITY_TURDLET) - reconstruction_missing("Entity_NPC::Update 006c4b30: a segmented boss's death animations"); + return segment_death_animation_play(*this); if (type >= DEATH_NO_BURST_FIRST && type <= DEATH_NO_BURST_LAST) return; BloodExplode(); trigger_kill_item_effects(); @@ -2572,8 +2573,11 @@ void Entity_NPC::trigger_kill_item_effects() if (!HasEntityFlags(FLAG_NO_REWARD)) { if (HasEntityFlags(FLAG_SPAWN_BLACK_HP) && dropRNG.Next() % BLACK_HEART_CHANCE == 0) - reconstruction_missing( - "Entity_NPC::trigger_kill_item_effects 006d5400: the black heart (Room::FindFreeTilePosition)"); + g_game->Spawn({.position = room_free_tile_position_find(pos, 0), + .subType = HEART_BLACK, + .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, + .seed = Random()}); Entity_Player* jarOwner = g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES_ID, dropRNG.Next(), nullptr); if (jarOwner && (HasEntityFlags(FLAG_ADD_JAR_FLY | FLAG_FREEZE) || HasEntityFlags(FLAG_ICE_FROZEN))) @@ -2826,12 +2830,6 @@ void Entity_NPC::CreateGoldParticles(uint32_t) reconstruction_missing("Entity_NPC::CreateGoldParticles 0059e4c0"); } -// 006b6830 -Entity_Effect* Entity_NPC::MakeBloodCloud(const Vector&, const ColorMod&) -{ - reconstruction_missing("Entity_NPC::MakeBloodCloud 006b6830"); -} - // 006be760 void Entity_NPC::KillUnique() { @@ -2850,24 +2848,12 @@ void Entity_NPC::update_frozen() reconstruction_missing("Entity_NPC::update_frozen 006ca930"); } -// 006ccdd0 -void Entity_NPC::FireBossProjectiles(int, const Vector&, float, const ProjectileParams&) -{ - reconstruction_missing("Entity_NPC::FireBossProjectiles 006ccdd0"); -} - // 006d0c60 void* Entity_NPC::QueryNPCsType(void*, int, int) { reconstruction_missing("Entity_NPC::QueryNPCsType 006d0c60"); } -// 006d0dd0 -EntityList* Entity_NPC::QueryNPCsGroup(EntityList*, int) -{ - reconstruction_missing("Entity_NPC::QueryNPCsGroup 006d0dd0"); -} - // 006d1580 void* Entity_NPC::fireplace_get_loot(void*, bool) { @@ -2886,16 +2872,17 @@ void Entity_NPC::TransferControl(Entity_NPC*) reconstruction_missing("Entity_NPC::TransferControl 006d88b0"); } -// 006d8b20 -void Entity_NPC::SpawnControlTarget(int, float) +// 006d8b20 The aim target a controlled NPC steers. Without a controller and none shown yet, there is nothing to do. +void Entity_NPC::SpawnControlTarget(int inputMode, float) { + if (!aimTargetEffect && controllerID == -1 && inputMode <= 1) return; reconstruction_missing("Entity_NPC::SpawnControlTarget 006d8b20"); } -// 006d8d30 +// 006d8d30 Where its aim target stands, or its own position without one. Vector Entity_NPC::GetAimTargetPosition() { - reconstruction_missing("Entity_NPC::GetAimTargetPosition 006d8d30"); + return aimTargetEffect ? aimTargetEffect->pos : pos; } // 006d8d80 @@ -2904,10 +2891,29 @@ bool Entity_NPC::is_controller_input_idle() reconstruction_missing("Entity_NPC::is_controller_input_idle 006d8d80"); } -// 006d8e40 -void Entity_NPC::UpdateChargeBar(float, float, float, bool) +// 006d8e40 A controlled NPC's charge bar at value between start and end, hidden when full if asked. +void Entity_NPC::UpdateChargeBar(float start, float end, float value, bool isHideWhenFull) { - reconstruction_missing("Entity_NPC::UpdateChargeBar 006d8e40"); + if (controllerID == -1 && !chargeBarSprite.isLoaded) return; + if (controllerID != -1) + { + if (!chargeBarSprite.isLoaded) chargeBarSprite.Load("gfx/chargebar.anm2", GRAPHICS_LOAD); + chargeBarSprite.GetLayer(2)->isVisible = false; + if (start == end) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + + int frame = (int)(std::clamp((value - start) / (end - start), 0.0f, 1.0f) * CHARGE_BAR_FRAMES); + if (!isHideWhenFull || frame < CHARGE_BAR_FRAMES) + { + if (chargeBarSprite.SetAnimation("Charging", SWITCH_KEEP_FRAME) && chargeBarSprite.animState.animData) + { + chargeBarSprite.animState.SetFrameFloat((float)frame); + chargeBarSprite.animState.isPlaying = false; + } + chargeBarSprite.color._tint[3] = 1; + return; + } + } + chargeBarSprite.color._tint[3] = 0; } // 006d97e0 diff --git a/src/entity_npc.h b/src/entity_npc.h index b228238..3974cec 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -306,12 +306,12 @@ struct Entity_NPC : Entity void PlaySound(int id, float volume, int frameDelay, bool isLoop, float pitch); void FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, const ProjectileParams& params); - void FireBossProjectiles(int count, const Vector& targetPos, float trajectoryModifier, - const ProjectileParams& params); + Entity_Projectile* FireBossProjectiles(int count, const Vector& targetPos, float trajectoryModifier, + const ProjectileParams& params); void projectile_params_apply(Entity_Projectile& projectile, const ProjectileParams& params); void fire_projectile_from_params(Entity_Projectile* projectile); Entity_Effect* MakeSplat(float size); - Entity_Effect* MakeBloodCloud(const Vector& pos, const ColorMod& color); + Entity_Effect* MakeBloodCloud(const Vector& pos, const ColorMod& color, float scale); static Entity_NPC* ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig, float yOffset); @@ -359,7 +359,7 @@ struct Entity_NPC : Entity static int FindTargetPit(const Vector& pos1, const Vector& pos2, uint32_t pitIndex); static Entity_NPC* ThrowStrider(const Vector& pos, Entity* spawner, const Vector& targetPos); static void* QueryNPCsType(void* outList, int type, int variant); - static EntityList* QueryNPCsGroup(EntityList* outList, int groupIdx); + static std::vector QueryNPCsGroup(int groupIdx); static void render_debug(float* position, int unused); }; diff --git a/src/entity_npc_boss.cpp b/src/entity_npc_boss.cpp new file mode 100644 index 0000000..8e81477 --- /dev/null +++ b/src/entity_npc_boss.cpp @@ -0,0 +1,307 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "manager.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +constexpr float BOSS_SHOT_SPEED = 7; +constexpr float BOSS_SHOT_SCATTER = 3.5f; +constexpr float BOSS_SHOT_FALL_ACCEL = 0.32f; +constexpr float BOSS_SHOT_FALL_ACCEL_PER_TRAJECTORY = 0.1f; +constexpr float BOSS_SHOT_FALL_SPEED = 5; +constexpr float BOSS_SHOT_FALL_SPEED_SPREAD = 24; +constexpr float BOSS_SHOT_SCALE = 0.9f; +constexpr float BOSS_SHOT_SCALE_LARGE = 0.4f; +constexpr float BOSS_SHOT_SCALE_SPREAD = 0.05f; +constexpr float WEAKNESS_SHOT_SCALE = 0.8f; +constexpr int SHRINKING_SHOT_DURATION = -150; + +constexpr int BLOOD_POOF_SUBTYPE = 3; +constexpr int BLOOD_POOF_SPRAY_SUBTYPE = 4; +constexpr int BLOOD_CLOUD_SUBTYPE = 5; +constexpr float BLOOD_POOF_SPRAY_HEIGHT = -40; + +constexpr int SEGMENT_HISTORY = 64; +constexpr float SEGMENT_HISTORY_STEP = 3; + +// A POOF02 effect of a subtype at a position, scaled and tinted, with a random flip. +static Entity_Effect* tinted_poof_spawn(Entity* spawner, int subType, const Vector& position, const ColorMod& color, + float scale) +{ + auto* effect = static_cast(g_game->Spawn({.position = position, + .spawner = spawner, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()})); + effect->sprite.scale = vector_make(scale, scale); + effect->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + effect->sprite.isFlipX = (Random() & 1) == 0; + return effect; +} + +// 006b66c0 A blood poof at a position with its spray above, the spray its child. Returns the poof. +Entity_Effect* Entity::MakeBloodPoof(const Vector& position, const ColorMod& poofColor, float scale) +{ + Entity_Effect* poof = tinted_poof_spawn(this, BLOOD_POOF_SUBTYPE, position, poofColor, scale); + poof->Update(); + + Entity_Effect* spray = tinted_poof_spawn(this, BLOOD_POOF_SPRAY_SUBTYPE, position, poofColor, scale); + spray->posOffset = vector_make(0, scale * BLOOD_POOF_SPRAY_HEIGHT); + spray->Update(); + poof->child = spray; + return poof; +} + +// 006b6810 A blood poof where it stands. +Entity_Effect* Entity::MakeBloodPoofAtPos(const ColorMod& poofColor, float scale) +{ + return MakeBloodPoof(pos, poofColor, scale); +} + +// 006b6830 A blood cloud at a position, scaled and tinted, flipped at random both ways. +Entity_Effect* Entity_NPC::MakeBloodCloud(const Vector& position, const ColorMod& color, float cloudScale) +{ + Entity_Effect* cloud = tinted_poof_spawn(this, BLOOD_CLOUD_SUBTYPE, position, color, cloudScale); + cloud->sprite.isFlipY = (Random() & 1) == 0; + cloud->Update(); + return cloud; +} + +// 006ccdd0 Lobs a spray of count shots at a target (anywhere without one), each with a random fall and size, then +// applies params. trajectoryModifier makes them rise and fall harder. Returns the last shot. +Entity_Projectile* Entity_NPC::FireBossProjectiles(int count, const Vector& targetPos, float trajectoryModifier, + const ProjectileParams& params) +{ + float shotScale = HasEntityFlags(FLAG_WEAKNESS) ? WEAKNESS_SHOT_SCALE : 1; + float fallingAccel = trajectoryModifier * BOSS_SHOT_FALL_ACCEL_PER_TRAJECTORY + BOSS_SHOT_FALL_ACCEL; + Entity_Projectile* projectile = nullptr; + + for (int i = 0; i < count; i++) + { + Vector direction = random_direction(); + Vector velocity = vector_scale(direction, BOSS_SHOT_SPEED); + if (!vector_is_zero(targetPos)) + { + Vector aim = vector_normalized(vector_sub(targetPos, pos)); + Vector scatter = vector_scale(vector_scale(direction, random_unit()), BOSS_SHOT_SCATTER); + velocity = vector_add(scatter, vector_scale(aim, BOSS_SHOT_SPEED)); + } + projectile = static_cast(g_game->Spawn({.position = vector_add(pos, params.positionOffset), + .velocity = velocity, + .spawner = this, + .type = ENTITY_PROJECTILE, + .variant = params.variant, + .seed = Random()})); + + projectile->fallingAccel = fallingAccel; + projectile->fallingSpeed = BOSS_SHOT_FALL_SPEED - random_unit() * BOSS_SHOT_FALL_SPEED_SPREAD - trajectoryModifier; + float size = (float)(Random() & 1) * BOSS_SHOT_SCALE_LARGE + BOSS_SHOT_SCALE; + size += random_unit() * BOSS_SHOT_SCALE_SPREAD; + projectile->scale = size * params.scale * shotScale; + projectile->SetCollisionDamage(params.damage < 0 ? 1 : params.damage); + + projectile->projectileFlags |= params.bulletFlags; + projectile->height += params.heightModifier; + projectile->fallingAccel += params.fallingAccelModifier; + projectile->fallingSpeed += params.fallingSpeedModifier; + projectile->velocity = vector_scale(projectile->velocity, params.velocityMulti); + projectile->SetColor(params.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + projectile->acceleration = params.acceleration; + projectile->targetPosition = params.targetPosition; + projectile->changeFlags = params.changeFlags; + projectile->changeVelocity = params.changeVelocity; + projectile->changeTimeout = params.changeTimeout; + projectile->motionHook = params.motionHook; + if (HasEntityFlags(FLAG_SHRINK) && params.variant == PROJECTILE_MEAT) + projectile->AddShrink(EntityRef(this), SHRINKING_SHOT_DURATION, false); + + fire_projectile_from_params(projectile); + projectile->parent = this; + projectile->spawnerType = type; + } + return projectile; +} + +// 006d7df0 Places a segment a distance behind its parent along the parent's trail (steered there at most maxSpeed a +// frame, or set there without one), then adds its own position to its trail, the newest first, 64 kept. +void segment_follow(Entity_NPC& npc, SegmentMode mode, float distance, float maxSpeed) +{ + Entity_NPC* parent = mode == SEGMENT_FOLLOW && npc.parent ? npc.ParentNPC() : nullptr; + if (parent) + { + Vector spot = parent->pos; + float walked = 0; + bool isPlaced = false; + for (const Vector& point : parent->vectorDeque1) + { + Vector step = vector_sub(point, spot); + float length = vector_length(step); + if (walked + length > distance) + { + spot = vector_add(spot, vector_scale(vector_normalized(step), distance - walked)); + isPlaced = true; + break; + } + walked += length; + spot = point; + } + + bool isTrailed = !parent->vectorDeque1.empty(); + if (isPlaced || (isTrailed && vector_length(vector_sub(npc.pos, spot)) > distance)) + { + if (maxSpeed <= 0) + { + npc.pos = spot; + npc.velocity = {}; + } + else + { + Vector toward = vector_sub(spot, npc.pos); + float length = vector_length(toward); + if (length > maxSpeed && length > 0) toward = vector_scale(toward, maxSpeed / length); + npc.velocity = vector_scale(toward, 1 / npc.friction); + } + } + } + + std::deque& trail = npc.vectorDeque1; + if (!trail.empty() && vector_length(vector_sub(npc.pos, trail.front())) <= SEGMENT_HISTORY_STEP) return; + trail.push_front(npc.pos); + if (trail.size() > SEGMENT_HISTORY) trail.resize(SEGMENT_HISTORY); +} + +// 006d0dd0 The NPCs of a group, in update order. +std::vector Entity_NPC::QueryNPCsGroup(int groupIdx) +{ + std::vector group; + for (Entity* entity : g_game->room->entityList.updateEL) + if (Entity::is_enemy_type(entity->type) && static_cast(entity)->groupIdx == groupIdx) + group.push_back(static_cast(entity)); + return group; +} + +constexpr int FART_POISON_FRAMES = 200; +constexpr float FART_DAMAGE = 5; +constexpr int FART_DAMAGE_COUNTDOWN = 30; +constexpr int FART_CONFUSION_FRAMES = 90; +constexpr float BIG_FART_SCALE = 1.8f; +constexpr float BIG_FART_ECHO_VOLUME = 1.2f; +constexpr int BIG_FART_ECHO_DELAY = 20; +constexpr float BIG_FART_ECHO_PITCH = 0.5f; +constexpr int BIG_FART_SHAKE = 3; + +// 00703be0 Game::Fart: poisons and hurts what is vulnerable within a radius (not the source, nor a player it descends +// from) and leaves a tinted fart cloud. Gigante Bean doubles it, a big one booms and shakes the screen, and a player's +// fart shoots its candle. +void game_fart(const Fart& fart) +{ + float radius = fart.radius; + float scale = fart.scale; + int multiplier = 0; + Entity* ancestor = fart.source ? fart.source->GetPlayerAncestor() : nullptr; + auto* player = static_cast(ancestor); + if (player && player->HasTrinket(TRINKET_GIGANTE_BEAN)) + { + radius += radius; + scale += scale; + multiplier = player->GetTrinketMultiplier(TRINKET_GIGANTE_BEAN); + } + + for (Entity* entity : entity_query_radius(fart.position, radius, QUERY_ALL)) + { + if (entity == fart.source || entity->entityGridCollisionClass == GRIDCOLL_BULLET || entity->mass == 0) continue; + if (!entity->IsVulnerableEnemy(nullptr)) continue; + if (entity->type == ENTITY_PLAYER && fart.source && fart.source->IsDescendantOf(entity)) continue; + + entity->AddPoison(EntityRef(fart.source), FART_POISON_FRAMES, 0, false); + entity->TakeDamage(FART_DAMAGE, 0, EntityRef(fart.source), FART_DAMAGE_COUNTDOWN); + if (multiplier > 1) reconstruction_missing("Game::Fart 00703be0: Gigante Bean's knockback (Entity::AddKnockback)"); + if (multiplier > 2) entity->AddConfusion(EntityRef(fart.source), FART_CONFUSION_FRAMES, false); + } + + Entity* cloud = g_game->Spawn({.position = fart.position, + .spawner = fart.source, + .subType = fart.subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_FART, + .seed = Random()}); + cloud->SetColor(fart.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + cloud->sprite.scale = vector_make(scale, scale); + if (scale > BIG_FART_SCALE) + { + SFXManager& sfx = g_manager->sfxManager; + sfx.Stop(SOUND_FART); + sfx.Play(SOUND_FART, {.frameDelay = 0}); + sfx.Play(SOUND_FART, + {.volume = BIG_FART_ECHO_VOLUME, .frameDelay = BIG_FART_ECHO_DELAY, .pitch = BIG_FART_ECHO_PITCH}); + game_shake_screen(BIG_FART_SHAKE); + } + if (fart.source && fart.source->type == ENTITY_PLAYER) static_cast(fart.source)->ShootCandle({}); +} + +// 006ac7e0 Counts the entities of a type and variant that descend from it, collecting them when asked. +int Entity::CountRelatedEntities(int relatedType, int relatedVariant, std::vector* related) +{ + int count = 0; + for (Entity* entity : entity_query(relatedType, relatedVariant)) + { + if (!entity->IsDescendantOf(this)) continue; + count++; + if (related) related->push_back(entity); + } + return count; +} + +constexpr int CHUB_DEATH_SOUND_FRAME = 3; + +// Part of 006c4b30: the first frame of a segmented boss part's death, which has no Death animation: Chub's by the part +// it is, Larry Jr.'s and Turdlet's head or body, Pin's head or body (its tail just goes). +void segment_death_animation_play(Entity_NPC& npc) +{ + constexpr std::array CHUB_PARTS = {"DeathHead", "DeathBody01", "DeathBody02"}; + switch (npc.type) + { + case ENTITY_CHUB: + if (npc.i1 >= 0 && npc.i1 < (int)CHUB_PARTS.size()) npc.sprite.Play(CHUB_PARTS[npc.i1]); + if (npc.sprite.GetFrame() == CHUB_DEATH_SOUND_FRAME) npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + return; + case ENTITY_PIN: + if (!npc.parent) npc.sprite.Play("DeathHead"); + else if (!npc.child) npc.Remove(); + else npc.sprite.Play("DeathBody01"); + return; + default: + npc.sprite.Play(npc.parent ? "DeathBody01" : "DeathHead"); + return; + } +} + +constexpr int MOTHER_SECOND_PHASE = 20; + +// Part of 006c4b30: the sounds and effects some Repentance bosses' Appear animations trigger: Little Horn's hole, +// Min-Min's shot. Mother's particles and Colostomia's landing are not reconstructed yet. +void boss_appear_events(Entity_NPC& npc) +{ + switch (npc.type) + { + case ENTITY_LITTLE_HORN: + if (npc.sprite.IsEventTriggered("HoleOpen")) npc_sound_play(SOUND_LITTLE_HORN_HOLE_OPEN, 1, 2, 1); + if (npc.sprite.IsEventTriggered("HoleExit")) npc_sound_play(SOUND_LITTLE_HORN_HOLE_EXIT, 1, 2, 1); + return; + case ENTITY_MIN_MIN: + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_FLAME_BURST, 1, 2, false, 1); + return; + case ENTITY_MOTHER: + if (npc.variant == MOTHER_SECOND_PHASE && npc.sprite.IsEventTriggered("Shoot")) + reconstruction_missing("Entity_NPC::Update 006c4b30: Mother's appear particles (Game::SpawnParticles)"); + return; + case ENTITY_COLOSTOMIA: + if (npc.sprite.IsEventTriggered("Land")) + reconstruction_missing("Entity_NPC::Update 006c4b30: Colostomia's appear landing (spawn_rock_particles)"); + return; + } +} diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 4448126..b6e6c7b 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -65,7 +65,6 @@ constexpr int COLLECTIBLE_SACK_HEAD = 424; constexpr int COLLECTIBLE_GUPPYS_EYE = 665; constexpr int COLLECTIBLE_THE_POLAROID = 327; constexpr int COLLECTIBLE_THE_NEGATIVE = 328; -constexpr int STAGE_VOID = 12; constexpr float OPTIONS_POOF_DROP = 10; constexpr int OPTIONS_ITEM_TIMEOUT = 4; constexpr int TRINKET_BROKEN_MAGNET = 6; @@ -73,11 +72,8 @@ constexpr int TRINKET_BLACK_LIPSTICK = 17; constexpr int TRINKET_BIBLE_TRACT = 18; 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_SUPER_MAGNET = 68; -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; @@ -108,7 +104,6 @@ constexpr int ACHIEVEMENT_WOODEN_CHEST = 609; constexpr int ACHIEVEMENT_HAUNTED_CHEST = 611; constexpr int ACHIEVEMENT_GOLDEN_PENNY = 613; constexpr int ACHIEVEMENT_GOLDEN_BATTERY = 615; -constexpr int STAGE_HOME = 35; // The other entities and effects pickups spawn, meet and are saved with. constexpr int ENTITY_POLTY = 816; @@ -140,7 +135,6 @@ constexpr int SOUND_FETUS_JUMP = 38; constexpr int SOUND_KEYPICKUP_GAUNTLET = 58; constexpr int SOUND_KEY_DROP0 = 59; constexpr int SOUND_MEAT_FEET_SLOW0 = 68; -constexpr int SOUND_BOSS2_BUBBLES = 185; constexpr int SOUND_DIMEDROP = 198; constexpr int SOUND_DIMEPICKUP = 199; constexpr int SOUND_LUCKYPICKUP = 200; @@ -150,7 +144,6 @@ constexpr int SOUND_NICKELDROP = 231; constexpr int SOUND_NICKELPICKUP = 232; constexpr int SOUND_PENNYDROP = 233; constexpr int SOUND_PENNYPICKUP = 234; -constexpr int SOUND_SCAMPER = 249; constexpr int SOUND_SUPERHOLY = 266; constexpr int SOUND_PING_PONG = 458; constexpr int SOUND_BONE_HEART = 461; @@ -251,7 +244,7 @@ constexpr int BED_RENDER_Z = -3000; constexpr int SACK_HEAD_ODDS = 5; constexpr int SACK_HEAD_COIN_ODDS = 10; constexpr int JAR_HEARTS_MAX = 8; -constexpr int ROOM_DUNGEON_BEAST_STAGE = STAGE_HOME; +constexpr int ROOM_DUNGEON_BEAST_STAGE = STAGE_ID_HOME; constexpr int ETERNAL_CHEST_CLOSE_WAIT = 30; constexpr float HAUNTED_CHEST_RANGE = 100; constexpr float MIMIC_CHEST_RANGE = 50; @@ -866,7 +859,7 @@ void Entity_Pickup::appear_start() if (!sprite.isLoaded) return log_printf(LOG_INFO, "[warn] No sprite for Pickup variant %d\n", variant); - bool isEntering = room.isFirstVisit ? !room.isInitialized && g_game->GetStageID() == STAGE_HOME + bool isEntering = room.isFirstVisit ? !room.isInitialized && g_game->GetStageID() == STAGE_ID_HOME : room.GetFrameCount() < 1; if (isEntering) { @@ -1206,8 +1199,9 @@ 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. -// 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. +// A priced pickup is bought with the player's coins or health, and chests open (entity_pickup_chest.cpp). Sacks, +// 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])) @@ -1286,6 +1280,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) int paidPrice = price; if (price != 0 && (player->IsHoldingItem() || !CanPickupShopItem(*player))) return true; + bool isChestOpened = false; bool isPickedUp = false; int collectedSubtype = subtype; switch (variant) @@ -1313,25 +1308,47 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_PILL: isPickedUp = pocket_item_collect(*this, *player); break; + case PICKUP_CHEST: + case PICKUP_SPIKEDCHEST: + case PICKUP_ETERNALCHEST: + case PICKUP_MIMICCHEST: + case PICKUP_OLDCHEST: + case PICKUP_WOODENCHEST: + case PICKUP_LOCKEDCHEST: + case PICKUP_REDCHEST: + case PICKUP_MOMSCHEST: + isChestOpened = chest_touch(*player); + break; + case PICKUP_MEGACHEST: + mega_chest_touch(*player); + break; + case PICKUP_BOMBCHEST: + case PICKUP_HAUNTEDCHEST: + break; default: - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: chests, sacks and trinkets"); + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: sacks and trinkets"); } + Room& room = *g_game->room; + if (isPickedUp || isChestOpened) + { + RemoveOtherOptions(); + bool isDevilDeal = room.roomType == ROOM_DEVIL || + (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE) || + (room.roomType == ROOM_BOSS && (g_game->levelStateFlags & 0x20000)); + if (isDevilDeal && (state == 1 || spawnGridIndex >= 0)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a devil deal"); + } if (!isPickedUp) { + if (isChestOpened && (room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH)) + g_game->ambush.StartChallenge(); if (variant != PICKUP_COLLECTIBLE && CanReroll() && isCollidesWithGrid) velocity = vector_make(gridCollisionNormal.y * BUMP_SLIDE + velocity.x, -gridCollisionNormal.x * BUMP_SLIDE + velocity.y); - return g_game->room->roomType == ROOM_DUNGEON || price != 0; + return room.roomType == ROOM_DUNGEON || price != 0; } - RemoveOtherOptions(); - Room& room = *g_game->room; - bool isDevilDeal = room.roomType == ROOM_DEVIL || - (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE) || - (room.roomType == ROOM_BOSS && (g_game->levelStateFlags & 0x20000)); - 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(); if (paidPrice != 0) purchase_finish(*player, paidPrice); @@ -1823,12 +1840,6 @@ void Entity_Pickup::AppearFast() reconstruction_missing("Entity_Pickup::AppearFast 006e3020"); } -// 006e6e40 -bool Entity_Pickup::TryOpenChest(Entity_Player*) -{ - reconstruction_missing("Entity_Pickup::TryOpenChest 006e6e40"); -} - // 006ee3f0 bool Entity_Pickup::CanJeraDuplicate() { diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 5894d57..43b54d7 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -2,6 +2,7 @@ #include "entity.h" #include "anm2.h" +#include "loot_list.h" #include #include @@ -163,6 +164,7 @@ struct Entity_Pickup : Entity void update_price_sprite(int newPrice); void AppearFast(); bool TryOpenChest(Entity_Player* player); + LootList GetChestLoot(PoolDraw draw, Entity_Player* player); void PlayDropSound(); void PlayPickupSound(); int GetCoinValue(); @@ -192,6 +194,12 @@ private: bool bomb_collect(Entity_Player& player); void collect_finish(Entity_Player* player); + // The chests' parts of HandleCollision and TryOpenChest (entity_pickup_chest.cpp). + bool chest_touch(Entity_Player& player); + void mega_chest_touch(Entity_Player& player); + bool chest_lock_pay(Entity_Player& player); + void chest_loot_spawn(const LootList& loot, Entity_Player& player, int chestVariant); + // 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(); diff --git a/src/entity_pickup_chest.cpp b/src/entity_pickup_chest.cpp new file mode 100644 index 0000000..61dfe6e --- /dev/null +++ b/src/entity_pickup_chest.cpp @@ -0,0 +1,574 @@ +#include "entity_pickup.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "game.h" +#include "item_pool.h" +#include "log.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "sfx_manager.h" +#include +#include +#include + +// The shift index of the RNG every outcome draw seeds (5, 9, 7), and the one a loot's spot angle comes from. +constexpr int OUTCOME_SHIFT_INDEX = 35; +constexpr int LOOT_ANGLE_SHIFT_INDEX = 18; +constexpr int LOOT_DROP_SHIFT_INDEX = 12; +constexpr float LOOT_ANGLE_SCALE = 3.14f; + +// The chests a player opens by touch, a key for the locked ones, and their pedestals for the items they give. +constexpr std::array LOCKED_CHESTS = {PICKUP_LOCKEDCHEST, PICKUP_ETERNALCHEST, PICKUP_OLDCHEST}; +constexpr std::array GOLDEN_CHESTS = {PICKUP_LOCKEDCHEST, PICKUP_BOMBCHEST, PICKUP_ETERNALCHEST, + PICKUP_MEGACHEST}; +constexpr std::array UNWRITTEN_LOOT = {PICKUP_REDCHEST, PICKUP_MOMSCHEST, PICKUP_OLDCHEST, PICKUP_GRAB_BAG}; +constexpr int EVENT_LOCKED_CHESTS_OPENED = 198; +constexpr float CHEST_VANISH_VOLUME = 0.7f; +constexpr float SPIKED_CHEST_DAMAGE = 1; +constexpr int SPIKED_CHEST_DAMAGE_COOLDOWN = 30; +constexpr int CHEST_WAIT = 20; +constexpr int ETERNAL_CHEST_RECLOSE = 60; +constexpr float CHEST_PUSH_RADIUS = 40; +constexpr float CHEST_PUSH_STRENGTH = 0.4f; +constexpr float ENEMY_LOOT_DISTANCE = 20; +constexpr float CHEST_POOF_HEIGHT = -10; +constexpr float CHEST_POOF_SCALE = 0.8f; +constexpr float CHEST_POOF_ALPHA = 0.3f; +constexpr float CHEST_POOF_DEPTH = 4; +constexpr float MEGA_CHEST_SPEED_BASE = 0.4f; +constexpr float MEGA_CHEST_SPEED_STEP = 0.05f; +constexpr int PICKUP_COUNT_MIN = 2; +constexpr int PICKUP_COUNT_ROLL = 4; +constexpr int GOLDEN_PICKUP_COUNT_ROLL = 7; +constexpr int CHEST_COINS_ROLL = 3; +constexpr int MEGA_CHEST_DRAWS = 5; +constexpr size_t WOODEN_CHEST_TRINKETS = 2; +constexpr int CHEST_TRINKET_ODDS = 100; +constexpr int LUCKY_TOE_ODDS = 3; + +// The pickups a chest's own draw gives (the outcome ids of GetChestLoot's first draw). +enum ChestOutcome +{ + CHEST_OUTCOME_TRINKET, + CHEST_OUTCOME_CHEST, + CHEST_OUTCOME_LOCKED_CHEST, + CHEST_OUTCOME_PICKUPS, + CHEST_OUTCOME_PILL, + CHEST_OUTCOME_CARD, + CHEST_OUTCOME_ITEM, + CHEST_OUTCOME_GILDED_PICKUPS +}; + +// The pickups a chest's pickups draw gives (the outcome ids of its second draw). Gilded Key adds the rarer ones. +enum ChestPickup +{ + CHEST_PICKUP_COINS, + CHEST_PICKUP_HEART, + CHEST_PICKUP_KEY, + CHEST_PICKUP_BOMB, + CHEST_PICKUP_PILL, + CHEST_PICKUP_CARD, + CHEST_PICKUP_RUNE, + CHEST_PICKUP_TRINKET, + CHEST_PICKUP_BATTERY +}; + +// What a wooden chest gives: an item, cards or pills. +enum WoodenChestOutcome +{ + WOODEN_OUTCOME_ITEM, + WOODEN_OUTCOME_CARDS, + WOODEN_OUTCOME_PILLS +}; + +// A trinket that may add a pickup to a chest: the pickup, and the shift index of the RNG it draws from. +struct ChestTrinket +{ + int trinket = 0; + int variant = 0; + int shiftIndex = 0; +}; + +// The bonus trinkets in the order they roll, then the order their pickups take precedence in. +constexpr std::array CHEST_TRINKETS = {{{TRINKET_ACE_OF_SPADES, PICKUP_TAROTCARD, 2}, + {TRINKET_SAFETY_CAP, PICKUP_PILL, 3}, + {TRINKET_CHILDS_HEART, PICKUP_HEART, 5}, + {TRINKET_MATCH_STICK, PICKUP_BOMB, 4}, + {TRINKET_RUSTED_KEY, PICKUP_KEY, 6}}}; +constexpr std::array CHEST_TRINKET_PRECEDENCE = {0, 1, 3, 2, 4}; + +// The odds out of a hundred that one, two or three copies of a bonus trinket add their pickup. +constexpr std::array CHEST_TRINKET_CHANCES = {33, 66, 100}; + +// The pedestal an item from each chest stands on, with its pay to play look, by chest variant. +struct ChestPedestal +{ + int variant = 0; + int pedestal = 0; + int payPedestal = 0; +}; +constexpr std::array CHEST_PEDESTALS = {{{PICKUP_CHEST, 10, 10}, + {PICKUP_BOMBCHEST, 6, 6}, + {PICKUP_SPIKEDCHEST, 7, 7}, + {PICKUP_ETERNALCHEST, 8, 17}, + {PICKUP_MIMICCHEST, 7, 7}, + {PICKUP_OLDCHEST, 12, 18}, + {PICKUP_WOODENCHEST, 13, 13}, + {PICKUP_MEGACHEST, 14, 19}, + {PICKUP_LOCKEDCHEST, 4, 16}, + {PICKUP_REDCHEST, 5, 5}, + {PICKUP_MOMSCHEST, 11, 11}}}; + +// The draws GetChestLoot makes: the chest's RNG (or a copy that leaves it be), how items leave their pool, and the +// bonus trinkets' RNGs and whether each added its pickup. +struct ChestDraw +{ + std::array trinketRngs{}; + std::array isTrinketProc{}; + LootList loot; + RNG* rng = nullptr; + uint32_t poolFlags = 0; + bool isDaemonsTail = false; +}; + +// Adds weight to an outcome, never below zero, or adds the outcome (inlined in the original). +void WeightedOutcomePicker::AddOutcomeWeight(int id, int weight) +{ + for (Outcome& outcome : outcomes) + if (outcome.id == id) + { + outcome.weight = std::max(0, outcome.weight + weight); + return; + } + outcomes.push_back({id, weight}); +} + +// 0049cbf0 Draws an outcome: a roll below the total weight lands in one outcome's share, the first with no weight. +int WeightedOutcomePicker::PickOutcome(RNG rng) +{ + uint32_t total = 0; + int sum = 0; + + for (Outcome& outcome : outcomes) total += outcome.weight; + uint32_t roll = rng.Next(); + roll = total ? roll % total : 0; + for (Outcome& outcome : outcomes) + if ((int)roll < (sum += outcome.weight)) return outcome.id; + if (sum <= 0) log_printf(LOG_ASSERT, "No weights were added. At least one outcome needs weight."); + return 0; +} + +// Draws an outcome from a picker, seeded by the next draw of an RNG. +static int outcome_draw(WeightedOutcomePicker& picker, RNG& rng) +{ + RNG draw; + draw.SetSeed(rng.Next(), OUTCOME_SHIFT_INDEX); + return picker.PickOutcome(draw); +} + +// Adds a pickup to the loot, seeded by the next draw. +static void loot_add(ChestDraw& draw, int variant, int subType = 0) +{ + uint32_t seed = draw.rng->Next(); + draw.loot.entries.push_back({.subType = subType, .type = ENTITY_PICKUP, .variant = variant, .seed = seed}); +} + +// Adds an item from a pool to the loot: its seed first, then the pool's draw. +static void loot_item_add(ChestDraw& draw, int pool) +{ + uint32_t seed = draw.rng->Next(); + int item = g_game->itemPool.GetCollectible((ItemPoolType)pool, draw.rng->Next(), draw.poolFlags, 0, 0); + draw.loot.entries.push_back({.subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = seed}); +} + +// Rolls each bonus trinket for the first player holding it (a Lazarus twin's own copy counts for globally shared +// ones): one in five passes Child's Heart under Daemon's Tail, then one, two or three copies add their pickup a +// third, two thirds or every time. +static void chest_trinkets_roll(ChestDraw& draw) +{ + PlayerManager& players = g_game->playerManager; + for (size_t index = 0; index < CHEST_TRINKETS.size(); index++) + { + int trinket = CHEST_TRINKETS[index].trinket; + ItemConfig_Item* config = g_manager->itemConfig.GetTrinket(trinket); + bool isShared = config && config->HasTags(TAG_LAZ_SHARED_GLOBAL); + auto isHolder = [&](Entity_Player* player) + { + return player->variant == PLAYER_VARIANT_PLAYER && + (player->HasTrinket(trinket) || + (isShared && player->backupPlayer && player->backupPlayer->HasTrinket(trinket))); + }; + if (std::ranges::none_of(players.playerList, isHolder)) continue; + + if (trinket == TRINKET_CHILDS_HEART && draw.isDaemonsTail && draw.rng->Next() % DAEMONS_TAIL_ODDS != 0) + continue; + int copies = std::clamp(players.GetTrinketMultiplier(trinket), 1, (int)CHEST_TRINKET_CHANCES.size()); + draw.isTrinketProc[index] = (int)(draw.rng->Next() % CHEST_TRINKET_ODDS) < CHEST_TRINKET_CHANCES[copies - 1]; + } +} + +// Adds the pickup of the bonus trinket that takes precedence, from its own RNG. Wooden chests only know the first +// two. +static void chest_trinket_pickup_add(ChestDraw& draw, size_t precedenceCount) +{ + for (size_t rank = 0; rank < precedenceCount; rank++) + { + int index = CHEST_TRINKET_PRECEDENCE[rank]; + if (!draw.isTrinketProc[index]) continue; + uint32_t seed = draw.trinketRngs[index].Next(); + draw.loot.entries.push_back({.type = ENTITY_PICKUP, .variant = CHEST_TRINKETS[index].variant, .seed = seed}); + return; + } +} + +// A chest's count of pickups grown by Lucky Toe two times in three and doubled by Mom's Key. +static int chest_pickup_count_grow(ChestDraw& draw, int count) +{ + PlayerManager& players = g_game->playerManager; + if (draw.rng->RandomInt(LUCKY_TOE_ODDS) != 0 && players.AnyoneHasTrinket(TRINKET_LUCKY_TOE)) count++; + if (players.FirstCollectibleOwner(COLLECTIBLE_MOMS_KEY, LAZARUS_SHARE_CHECK)) count *= 2; + return count; +} + +// The pickups a chest's pickups outcome gives: coins (one to three), hearts, keys and bombs, or with Gilded Key also +// pills, cards, runes, trinkets and batteries. +static void chest_pickups_add(ChestDraw& draw, int count, bool isGilded) +{ + WeightedOutcomePicker picker; + int heartWeight = draw.isDaemonsTail ? 4 : 20; + if (isGilded) + picker.outcomes = {{CHEST_PICKUP_COINS, 25}, {CHEST_PICKUP_HEART, heartWeight}, {CHEST_PICKUP_KEY, 10}, + {CHEST_PICKUP_BOMB, 20}, {CHEST_PICKUP_PILL, 5}, {CHEST_PICKUP_CARD, 5}, + {CHEST_PICKUP_RUNE, 5}, {CHEST_PICKUP_TRINKET, 5}, {CHEST_PICKUP_BATTERY, 5}}; + else + picker.outcomes = {{CHEST_PICKUP_COINS, 35}, {CHEST_PICKUP_HEART, heartWeight}, {CHEST_PICKUP_KEY, 15}, + {CHEST_PICKUP_BOMB, 30}}; + + constexpr std::array PICKUP_VARIANTS = {PICKUP_COIN, PICKUP_HEART, PICKUP_KEY, + PICKUP_BOMB, PICKUP_PILL, PICKUP_TAROTCARD, + PICKUP_TAROTCARD, PICKUP_TRINKET, PICKUP_LIL_BATTERY}; + for (; count > 0; count--) + { + int outcome = outcome_draw(picker, *draw.rng); + if (outcome == CHEST_PICKUP_COINS) + { + for (int coins = draw.rng->RandomInt(CHEST_COINS_ROLL) + 1; coins > 0; coins--) loot_add(draw, PICKUP_COIN); + continue; + } + if (outcome != CHEST_PICKUP_RUNE) + { + loot_add(draw, PICKUP_VARIANTS[outcome]); + continue; + } + uint32_t seed = draw.rng->Next(); + uint32_t cardSeed = draw.rng->Next(); + int card = ItemPool::GetCardEx((int)cardSeed, 0, 1, 0, true); + RNG cardRng; + cardRng.SetSeed(cardSeed, OUTCOME_SHIFT_INDEX); + card = lua_engine_get().GetCard({.rng = &cardRng, .card = card, .isOnlyRunes = true, .isRunes = true}); + draw.loot.entries.push_back( + {.subType = card, .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD, .seed = seed}); + } +} + +// An ordinary or golden chest's loot: one draw (five for a Mega Chest) among a trinket, a chest, a locked chest, a +// pill or a card, an item from the golden chest pool and the pickups (two to four, or two to six from golden chests), +// Gilded Key turning a golden chest's pickups richer. A Mega Chest gives two treasure items half the time. +static void chest_loot_draw(ChestDraw& draw, int variant) +{ + bool isMega = variant == PICKUP_MEGACHEST; + bool isGolden = std::ranges::count(GOLDEN_CHESTS, variant) > 0; + if (isMega && draw.rng->RandomInt(2) == 0) + { + loot_item_add(draw, POOL_TREASURE); + loot_item_add(draw, POOL_TREASURE); + return; + } + + WeightedOutcomePicker picker; + if (isGolden && g_game->playerManager.AnyoneHasTrinket(TRINKET_GILDED_KEY)) + { + picker.AddOutcomeWeight(CHEST_OUTCOME_GILDED_PICKUPS, 80); + if (!isMega) picker.AddOutcomeWeight(CHEST_OUTCOME_ITEM, 20); + } + else + { + picker.AddOutcomeWeight(CHEST_OUTCOME_TRINKET, 10); + if (!isMega) picker.AddOutcomeWeight(CHEST_OUTCOME_CHEST, 1); + if (!isMega) picker.AddOutcomeWeight(CHEST_OUTCOME_LOCKED_CHEST, 1); + picker.AddOutcomeWeight(isGolden ? CHEST_OUTCOME_CARD : CHEST_OUTCOME_PILL, 10); + if (isGolden && !isMega) picker.AddOutcomeWeight(CHEST_OUTCOME_ITEM, 20); + picker.AddOutcomeWeight(CHEST_OUTCOME_PICKUPS, isGolden ? 58 : 78); + } + + for (int draws = isMega ? MEGA_CHEST_DRAWS : 1; draws > 0; draws--) + { + int outcome = outcome_draw(picker, *draw.rng); + switch (outcome) + { + case CHEST_OUTCOME_TRINKET: + loot_add(draw, PICKUP_TRINKET); + break; + case CHEST_OUTCOME_CHEST: + loot_add(draw, PICKUP_CHEST); + break; + case CHEST_OUTCOME_LOCKED_CHEST: + loot_add(draw, PICKUP_LOCKEDCHEST); + break; + case CHEST_OUTCOME_PILL: + loot_add(draw, PICKUP_PILL); + break; + case CHEST_OUTCOME_CARD: + loot_add(draw, PICKUP_TAROTCARD); + break; + case CHEST_OUTCOME_ITEM: + loot_item_add(draw, POOL_GOLDEN_CHEST); + break; + default: + { + int roll = isGolden ? GOLDEN_PICKUP_COUNT_ROLL : PICKUP_COUNT_ROLL; + int count = std::max(PICKUP_COUNT_MIN, (int)draw.rng->RandomInt(roll)); + chest_trinket_pickup_add(draw, CHEST_TRINKET_PRECEDENCE.size()); + chest_pickups_add(draw, chest_pickup_count_grow(draw, count), outcome == CHEST_OUTCOME_GILDED_PICKUPS); + } + } + } +} + +// A wooden chest's loot: an item from the wooden chest pool, or two or three cards or pills. A first draw only +// decides whether Lucky Toe may add one, and Ace of Spades or Safety Cap add their pickup. +static void wooden_chest_loot_draw(ChestDraw& draw) +{ + WeightedOutcomePicker picker; + picker.outcomes = {{WOODEN_OUTCOME_ITEM, 2}, {WOODEN_OUTCOME_CARDS, 10}, {WOODEN_OUTCOME_PILLS, 10}}; + int first = outcome_draw(picker, *draw.rng); + int count = (draw.rng->Next() & 1) + PICKUP_COUNT_MIN; + if (first != WOODEN_OUTCOME_ITEM && draw.rng->Next() % LUCKY_TOE_ODDS != 0 && + g_game->playerManager.AnyoneHasTrinket(TRINKET_LUCKY_TOE)) + count++; + chest_trinket_pickup_add(draw, WOODEN_CHEST_TRINKETS); + if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_MOMS_KEY, LAZARUS_SHARE_CHECK)) count *= 2; + + int outcome = outcome_draw(picker, *draw.rng); + if (outcome == WOODEN_OUTCOME_ITEM) return loot_item_add(draw, POOL_WOODEN_CHEST); + for (; count > 0; count--) loot_add(draw, outcome == WOODEN_OUTCOME_CARDS ? PICKUP_TAROTCARD : PICKUP_PILL); +} + +// 006dae40 What the chest gives, drawn from its RNG, or from a copy with POOL_DRAW_PEEK, which also leaves the items +// in their pools. An eternal chest gives nothing a quarter of the time (and stays). Ace of Spades, Safety Cap, +// Match Stick, Child's Heart and Rusted Key may add their pickups, and in the Chest every chest gives a treasure item. +// Red, old and Mom's chests, sacks and Poker Chip stop the game until reached. +LootList Entity_Pickup::GetChestLoot(PoolDraw draw, Entity_Player* player) +{ + ChestDraw chest; + RNG peek = dropRNG; + chest.rng = draw == POOL_DRAW_TAKE ? &dropRNG : &peek; + chest.poolFlags = draw == POOL_DRAW_TAKE ? 0 : POOL_FLAG_NO_DECREASE; + chest.isDaemonsTail = g_game->playerManager.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL); + for (size_t index = 0; index < CHEST_TRINKETS.size(); index++) + chest.trinketRngs[index].SetSeed(dropRNG._seed, CHEST_TRINKETS[index].shiftIndex); + + Game& game = *g_game; + if (variant == PICKUP_ETERNALCHEST && game.stage != STAGE_DARK_ROOM && subtype < 2 && (chest.rng->Next() & 3) == 0) + return chest.loot; + chest_trinkets_roll(chest); + + bool isDeathmatch = game.deathmatchManager.is_active(); + bool isChestFloor = !game.IsGreedMode() && game.stage == STAGE_DARK_ROOM && !isDeathmatch; + bool isPokerChip = isDeathmatch ? player && player->HasTrinket(TRINKET_POKER_CHIP) + : game.playerManager.AnyoneHasTrinket(TRINKET_POKER_CHIP); + if (isPokerChip) reconstruction_missing("Entity_Pickup::GetChestLoot 006dae40 (Poker Chip)"); + if (std::ranges::count(UNWRITTEN_LOOT, variant) > 0) + reconstruction_missing("Entity_Pickup::GetChestLoot 006dae40 (red, old and Mom's chests and sacks)"); + + if (variant == PICKUP_WOODENCHEST) wooden_chest_loot_draw(chest); + else if (!isChestFloor) chest_loot_draw(chest, variant); + else + { + loot_item_add(chest, POOL_TREASURE); + if (variant == PICKUP_MEGACHEST) loot_item_add(chest, POOL_TREASURE); + } + return chest.loot; +} + +// The poof a chest opens in, small and faint over its lid. +static void chest_poof_spawn(Entity_Pickup& chest) +{ + Entity* poof = g_game->Spawn( + {.position = chest.pos, .subType = 2, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->posOffset = vector_make(chest.sprite.scale.x * 0, chest.sprite.scale.x * CHEST_POOF_HEIGHT); + poof->sprite.scale = vector_make(chest.sprite.scale.x * CHEST_POOF_SCALE, chest.sprite.scale.y * CHEST_POOF_SCALE); + poof->sprite.color = {{1, 1, 1, CHEST_POOF_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; + poof->renderDepthOffset = CHEST_POOF_DEPTH; +} + +// The deathmatch's chests vanish once open, in a poof. +static void chest_vanish(Entity_Pickup& chest) +{ + g_game->Spawn({.position = chest.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + int sound = SOUND_SUMMONSOUND; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = CHEST_VANISH_VOLUME}); + chest.Remove(); +} + +// 006e6e40 Opens the chest for a player (the nearest when none): it plays Open with its sounds and a faint poof, +// gives its loot and stays open. An eternal chest that gives nothing closes again. An item turns the chest into its +// pedestal, and a pickup or enemy coming out pushes a close player away. Whether a closed chest opened. +bool Entity_Pickup::TryOpenChest(Entity_Player* player) +{ + if (!player) player = game_nearest_player(pos); + if (subtype == 0) return false; + + sprite.Play("Open", PLAY_FORCED); + sound_play(SOUND_CHEST_OPEN); + if (std::ranges::count(LOCKED_CHESTS, variant) > 0) + { + sound_play(SOUND_UNLOCK); + g_manager->persistentGameData.IncreaseEventCounter(EVENT_LOCKED_CHESTS_OPENED, 1); + } + chest_poof_spawn(*this); + + int chestVariant = variant; + LootList loot = GetChestLoot(POOL_DRAW_TAKE, player); + subtype = 0; + Game& game = *g_game; + if (chestVariant == PICKUP_ETERNALCHEST && loot.entries.empty()) + { + chestReCloseTimer = 0; + game.room->isPickupVisionInvalid = true; + if (game.deathmatchManager.is_active()) chest_vanish(*this); + return true; + } + + chest_loot_spawn(loot, *player, chestVariant); + if (variant == PICKUP_ETERNALCHEST) chestReCloseTimer = ETERNAL_CHEST_RECLOSE; + if (game.deathmatchManager.is_active() && IsChest(variant) && variant != PICKUP_ETERNALCHEST) chest_vanish(*this); + game.room->isPickupVisionInvalid = true; + return true; +} + +// Spawns what a chest gives: the first item turns the chest into its pedestal (a pay to play look for those) and +// more stand beside it, pickups and enemies fly out from a spot beside the chest (a Mega Chest's slower at first), +// enemies placed towards the player, and chests come out smaller. Red chests' spiders, flies and teleports stop the +// game until reached. +void Entity_Pickup::chest_loot_spawn(const LootList& loot, Entity_Player& player, int chestVariant) +{ + RNG dropRng; + dropRng.SetSeed(dropRNG._seed, LOOT_DROP_SHIFT_INDEX); + bool isPushing = false; + int spawned = 0; + + for (const LootEntry& entry : loot.entries) + { + if (entry.type == ENTITY_PICKUP && entry.variant == PICKUP_COLLECTIBLE) + { + Entity_Pickup* item = this; + if (variant == PICKUP_COLLECTIBLE) + item = static_cast(g_game->Spawn({.position = pos, .subType = entry.subType, + .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, + .seed = entry.seed})); + else Morph(ENTITY_PICKUP, PICKUP_COLLECTIBLE, entry.subType, false, false, false); + if (item->variant == PICKUP_COLLECTIBLE) + { + item->targetPosition = pos; + for (const ChestPedestal& pedestal : CHEST_PEDESTALS) + if (pedestal.variant == chestVariant) + item->SetAlternatePedestal(isPayToPlay ? pedestal.payPedestal : pedestal.pedestal); + } + isPushing = true; + continue; + } + if (entry.type != ENTITY_PICKUP) + reconstruction_missing("Entity_Pickup::TryOpenChest 006e6e40 (a red chest's spiders, flies or teleport)"); + + float speed = variant == PICKUP_MEGACHEST + ? std::min(1.0f, (float)spawned * MEGA_CHEST_SPEED_STEP + MEGA_CHEST_SPEED_BASE) + : 1; + Vector velocity = GetRandomPickupVelocity(pos, &dropRng, 0); + RNG angleRng; + angleRng.SetSeed(dropRng.Next(), LOOT_ANGLE_SHIFT_INDEX); + float angle = angleRng.RandomFloat() * LOOT_ANGLE_SCALE * 2; + Entity* out = g_game->Spawn({.position = vector_make(std::cos(angle) + pos.x, std::sin(angle) + pos.y), + .velocity = vector_make(velocity.x * speed, velocity.y * speed), + .subType = entry.subType, + .type = entry.type, + .variant = entry.variant, + .seed = entry.seed}); + if (out->type == ENTITY_PICKUP && variant == PICKUP_MEGACHEST) + static_cast(out)->dropDelay = spawned / 2; + out->Update(); + spawned++; + if (Entity::is_enemy_type(out->type)) + { + Vector toward = vector_sub(pos, player.pos); + float length = std::sqrt(toward.x * toward.x + toward.y * toward.y); + float step = length > 0 ? ENEMY_LOOT_DISTANCE / length : 1; + out->pos = vector_make(pos.x + toward.x * step, pos.y + toward.y * step); + isPushing = true; + } + else if (out->type == ENTITY_PICKUP && IsChest(out->variant)) + out->sprite.scale = vector_make(sprite.scale.x * CHEST_POOF_SCALE, sprite.scale.y * CHEST_POOF_SCALE); + } + if (!isPushing) return; + + Vector away = vector_sub(pos, player.pos); + float distance = std::sqrt(away.x * away.x + away.y * away.y); + if (distance * distance < CHEST_PUSH_RADIUS * CHEST_PUSH_RADIUS) + { + if (distance > 0) away = vector_make(away.x / distance, away.y / distance); + float push = (CHEST_PUSH_RADIUS - distance) * CHEST_PUSH_STRENGTH; + player.velocity = + vector_make((player.velocity.x - push * away.x) * 0.5f, (player.velocity.y - push * away.y) * 0.5f); + } + wait = CHEST_WAIT; +} + +// The chest part of 006e8ae0: a locked, eternal or old chest takes a key (a coin to pay to play) unless the player +// holds Paper Clip, or two Strange Keys in the Blue Womb, then the chest opens. A spiked chest hurts a player still +// touching it. Whether the touch counts as opening, which every unlocked touch does. +bool Entity_Pickup::chest_touch(Entity_Player& player) +{ + bool isLocked = !player.HasTrinket(TRINKET_PAPER_CLIP) && std::ranges::count(LOCKED_CHESTS, variant) > 0; + if (isLocked && subtype == 0) return false; + bool isStrangeKeyed = g_game->stage == STAGE_BLUE_WOMB && player.GetTrinketMultiplier(TRINKET_STRANGE_KEY) >= 2; + if (isLocked && !isStrangeKeyed && !chest_lock_pay(player)) return false; + + int chestVariant = variant; + if (!TryOpenChest(&player) || chestVariant != PICKUP_SPIKEDCHEST) return true; + Vector apart = vector_sub(pos, player.pos); + if (std::sqrt(apart.x * apart.x + apart.y * apart.y) <= size + player.size) + player.TakeDamage(SPIKED_CHEST_DAMAGE, DAMAGE_CHEST | DAMAGE_NO_PENALTIES, EntityRef(this), + SPIKED_CHEST_DAMAGE_COOLDOWN); + return true; +} + +// Pays a chest's lock: a key, or a coin for a pay to play chest. Whether it was paid. +bool Entity_Pickup::chest_lock_pay(Entity_Player& player) +{ + if (!isPayToPlay) return player.TryUseKey(); + if (player.numCoins <= 0) return false; + player.AddCoins(-1); + return true; +} + +// The Mega Chest part of 006e8ae0: a closed Mega Chest not already animating takes a key (or a coin) and plays its +// unlock towards the player, opening when the animation ends. +void Entity_Pickup::mega_chest_touch(Entity_Player& player) +{ + bool isAnimating = sprite.animState.animData && sprite.animState.isPlaying; + if (subtype == 0 || isAnimating || !chest_lock_pay(player)) return; + + target = &player; + if (isPayToPlay) + { + sound_play(SOUND_COIN_INSERT); + sprite.Play("UseCoin", PLAY_FORCED); + return; + } + sound_play(SOUND_UNLOCK); + sprite.Play(player.hasGoldenKey ? "UseGoldenKey" : "UseKey", PLAY_FORCED); +} diff --git a/src/entity_pickup_shop.cpp b/src/entity_pickup_shop.cpp index 78e67e1..574812a 100644 --- a/src/entity_pickup_shop.cpp +++ b/src/entity_pickup_shop.cpp @@ -19,7 +19,6 @@ 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; @@ -321,12 +320,12 @@ void Entity_Pickup::TriggerShopPurchase(Entity_Player& player, int spentMoney) 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. + Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_COINS_SPENT, &player, spentMoney); } else { bool isOthersTaken = deal_health_pay(player, spentMoney); - player.set_last_damage(DAMAGE_DEVIL_DEAL, EntityRef()); + player.set_last_damage(DAMAGE_DEVIL, EntityRef()); if (isOthersTaken) other_deals_take(); if (player.CanPickupItem() && !player.IsHoldingItem()) player.try_trigger_astral_projection(); } diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 33992fc..5e1e252 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -66,8 +66,6 @@ constexpr int DAILY_CHRISTMAS = 19; constexpr int EMPTY_HEART_RED_HEARTS = 3; constexpr int EVENT_BONUS_ITEMS = 114; constexpr int GIANTBOOK_EMPTY_HEART = 41; -constexpr int GIANTBOOK_ETERNAL = 6; -constexpr int GIANTBOOK_ETERNAL_BLACK = 46; constexpr int LOCUST_SUBTYPE_START = 25; constexpr int PEE_ALPHA = 180; constexpr int PEE_OFFSET = 244; @@ -77,7 +75,6 @@ constexpr float PICKUP_SPAWN_RADIUS = 40; constexpr int POCKET_ACTIVE_SLOT = 2; constexpr float RANDOM_FLOAT_SCALE = 2.3283064e-10f; constexpr int RED_REDEMPTION_KEY_CHARGES = 20; -constexpr uint32_t STAGE_BLUE_WOMB = 11; constexpr uint8_t WOODEN_CROSS_STACK = 0x10; constexpr std::string_view COSTUMES_DIR = "costumes"; constexpr std::array SKIN_COLOR_SUFFIXES = {"_white", "_black", "_blue", @@ -395,6 +392,7 @@ void Entity_Player::stats_reset() isBrokenRemotePending = false; cursedPennyPending = 0; vampireCharmKills = 0; + jumperCablesKills = 0; isActiveUsed = false; isPlayingExtraAnimation = false; isHurtPending = false; @@ -902,7 +900,7 @@ void Entity_Player::start_position_set() if (game.stage + (isAltStage ? 1 : 0) != 1 || game.IsAscent()) { pos = PlayerManager::get_player_start_position(this, {}); - if (game.challenge == CHALLENGE_BACKASSWARDS && game.stage == STAGE_BLUE_WOMB) + if (game.challenge == CHALLENGE_BACKASSWARDS && game.stage == STAGE_DARK_ROOM) pos.y += BACKASSWARDS_START_OFFSET_Y; uint32_t curses = @@ -962,9 +960,7 @@ void Entity_Player::level_items_apply(bool isForced) if (player && player->eternalHearts > 0) { player->eternalHearts = 0; - bool isBlackSoul = player->GetHealthType() == HEALTH_SOUL && - (player->playerType == PLAYER_BLACKJUDAS || player->playerType == PLAYER_JUDAS_B); - game.itemOverlay.Show(isBlackSoul ? GIANTBOOK_ETERNAL_BLACK : GIANTBOOK_ETERNAL, 1, nullptr); + player->eternal_heart_overlay_show(); player->AddMaxHearts(2, false); player->AddHearts(2, false, false); } diff --git a/src/entity_player.h b/src/entity_player.h index 077ee5f..013fe94 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -234,7 +234,9 @@ enum PlayerItemId : int COLLECTIBLE_WHITE_PONY = 181, COLLECTIBLE_SACRED_HEART = 182, COLLECTIBLE_3_DOLLAR_BILL = 191, + COLLECTIBLE_MOMS_KEY = 199, COLLECTIBLE_MIDAS_TOUCH = 202, + COLLECTIBLE_GNAWED_LEAF = 210, COLLECTIBLE_BALL_OF_BANDAGES = 207, COLLECTIBLE_GUPPYS_COLLAR = 212, COLLECTIBLE_ANEMIC = 214, @@ -244,6 +246,7 @@ enum PlayerItemId : int COLLECTIBLE_MONSTROS_LUNG = 229, COLLECTIBLE_BALL_OF_TAR = 231, COLLECTIBLE_STOP_WATCH = 232, + COLLECTIBLE_E_COLI = 236, COLLECTIBLE_KEY_PIECE_1 = 238, COLLECTIBLE_KEY_PIECE_2 = 239, COLLECTIBLE_INFAMY = 242, @@ -322,6 +325,7 @@ enum PlayerItemId : int COLLECTIBLE_GREEDS_GULLET = 501, COLLECTIBLE_LITTLE_HORN = 503, COLLECTIBLE_BROKEN_MODEM = 514, + COLLECTIBLE_JUMPER_CABLES = 520, COLLECTIBLE_COUPON = 521, COLLECTIBLE_MOVING_BOX = 523, COLLECTIBLE_DEATHS_LIST = 530, @@ -333,7 +337,9 @@ enum PlayerItemId : int COLLECTIBLE_ALMOND_MILK = 561, COLLECTIBLE_DREAM_CATCHER = 566, COLLECTIBLE_PLAYDOUGH_COOKIE = 570, + COLLECTIBLE_SOCKS = 571, COLLECTIBLE_EYE_OF_THE_OCCULT = 572, + COLLECTIBLE_DIRTY_MIND = 576, COLLECTIBLE_RED_KEY = 580, COLLECTIBLE_WAVY_CAP = 582, COLLECTIBLE_BOOK_OF_VIRTUES = 584, @@ -347,6 +353,7 @@ enum PlayerItemId : int COLLECTIBLE_BIRTHRIGHT = 619, COLLECTIBLE_KNIFE_PIECE_1 = 626, COLLECTIBLE_KNIFE_PIECE_2 = 627, + COLLECTIBLE_EVIL_CHARM = 632, COLLECTIBLE_DOGMA = 633, COLLECTIBLE_ERASER = 638, COLLECTIBLE_URN_OF_SOULS = 640, @@ -384,9 +391,12 @@ enum PlayerItemId : int COLLECTIBLE_CAMO_UNDIES = 497, COLLECTIBLE_MARS = 593, COLLECTIBLE_JUPITER = 594, + COLLECTIBLE_ADRENALINE = 493, + COLLECTIBLE_PLUTO = 598, COLLECTIBLE_MEGA_MUSH = 625, COLLECTIBLE_MONTEZUMAS_REVENGE = 680, COLLECTIBLE_ESAU_JR = 703, + COLLECTIBLE_AZAZELS_RAGE = 699, COLLECTIBLE_BERSERK = 704, COLLECTIBLE_STAPLER = 708, COLLECTIBLE_SUPLEX = 709, @@ -398,6 +408,7 @@ enum PlayerItemId : int COLLECTIBLE_DECAP_ATTACK = 729, COLLECTIBLE_STYE = 731, TRINKET_POOL_SHIFT = 2, + TRINKET_PETRIFIED_POOP = 2, TRINKET_ROSARY_BEAD = 7, TRINKET_CALLUS = 14, TRINKET_PAPER_CLIP = 19, @@ -407,10 +418,19 @@ enum PlayerItemId : int TRINKET_MISSING_POSTER = 23, TRINKET_BUTT_PENNY = 24, TRINKET_CHILDS_HEART = 34, + TRINKET_RUSTED_KEY = 36, TRINKET_MATCH_STICK = 41, + TRINKET_LUCKY_TOE = 42, + TRINKET_SAFETY_CAP = 44, + TRINKET_ACE_OF_SPADES = 45, + TRINKET_POKER_CHIP = 76, + TRINKET_MOMS_LOCKET = 87, TRINKET_CURSED_SKULL = 43, TRINKET_MISSING_PAGE = 48, + TRINKET_BURNT_PENNY = 50, + TRINKET_COUNTERFEIT_PENNY = 52, TRINKET_MAGGYS_FAITH = 55, + TRINKET_JUDAS_TONGUE = 56, TRINKET_CAINS_EYE = 59, TRINKET_EVES_BIRD_FOOT = 60, TRINKET_LEFT_HAND = 61, @@ -423,6 +443,7 @@ enum PlayerItemId : int TRINKET_RIB_OF_GREED = 84, TRINKET_LIL_LARVA = 86, TRINKET_NO = 88, + TRINKET_BROWN_CAP = 90, TRINKET_CHILD_LEASH = 89, TRINKET_MECONIUM = 91, TRINKET_USED_DIAPER = 93, @@ -438,6 +459,7 @@ enum PlayerItemId : int TRINKET_WOODEN_CROSS = 121, TRINKET_BUTTER = 122, TRINKET_BABY_BENDER = 127, + TRINKET_GIGANTE_BEAN = 134, TRINKET_BROKEN_PADLOCK = 136, TRINKET_BETHS_FAITH = 142, TRINKET_PERFECTION = 145, @@ -464,7 +486,10 @@ enum PlayerItemId : int NULLITEM_CHRISTMAS = 16, NULLITEM_SPIN_TO_WIN = 50, NULLITEM_INTRUDER = 55, + NULLITEM_TOOTH_AND_NAIL_STATUE = 59, NULLITEM_REVERSE_CHARIOT = 63, + NULLITEM_JUPITER_BODY_ANGEL = 76, + NULLITEM_LILITH_B = 90, NULLITEM_REVERSE_HANGED_MAN = 65, NULLITEM_REVERSE_SUN = 66, NULLITEM_WAVY_CAP_1 = 71, @@ -541,6 +566,14 @@ struct PocketItem PocketItemType type = POCKET_CARD; }; +// The walk the body costumes follow: its animation, whether the player moves, and whether an item is held up. +struct CostumeWalk +{ + std::string_view animation; + bool isLifted = false; + bool isMoving = false; +}; + // The item a player holds over its head, picked up and not yet added. struct QueueItemData { @@ -934,6 +967,7 @@ public: int evilCharmHazardFrames = 0; int hallowedGroundCountdown = 0; int immaculateConceptionState = 0; + int jumperCablesKills = 0; int keepersSackBonus = 0; int maggySwingCooldown = 0; int marsCooldown = 0; @@ -1083,6 +1117,9 @@ public: bool is_character_plain(); bool is_frame_plain(); void costume_heads_update(int blinkFrame); + void costume_layers_update(); + float body_costumes_walk(const CostumeWalk& walk); + void body_costumes_speed_set(float speed); void costume_layers_map(int skinColor); void costume_skin_apply(CostumeSpriteDesc& costume, int skinColor); int AddActiveCharge(int charge, int slot, bool isFlashHud, bool isOvercharge, bool isForce); @@ -1107,6 +1144,11 @@ private: int conception_count(int collectibleId); bool is_granted(int collectibleId); Entity_Player* health_owner(); + Entity_Player* heart_owner(PlayerType halfOwner); + void eternal_heart_overlay_show(); + int golden_holders_count(); + void bone_hearts_add(int amount); + void rotten_hearts_add(int amount); void red_hearts_add(int hearts, bool isUnknown2); int soul_hearts_absorb(int amount); void soul_hearts_add(int amount, bool isUnknown); @@ -1348,7 +1390,7 @@ public: float get_voice_pitch(); void AddJarFlies(int amount); bool IsPosInSpotLight(Vector position); - void AddGoldenHearts(int amount, bool retBool); + void AddGoldenHearts(int amount, bool isSkipBreak); bool CanPickGoldenHearts(); void BreakGoldenHearts(int count); void AddBoneHearts(int amount); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index b76c1fe..0b0ab2e 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -5,6 +5,7 @@ #include "entity_tear.h" #include "game.h" #include "grid_entity_door.h" +#include "grid_entity_poop.h" #include "hud.h" #include "kage_input.h" #include "key_configs.h" @@ -13,7 +14,7 @@ #include "lua_engine.h" #include "manager.h" #include "menu_manager.h" -#include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include "room_special.h" #include @@ -100,14 +101,6 @@ enum BatterySubType : int }; // The kinds of poop The Poop drops (Lua's GridPoopVariant). -enum PoopVariant : int -{ - POOP_NORMAL = 0, - POOP_GOLDEN = 3, - POOP_BLACK = 5, - POOP_WHITE = 6 -}; - constexpr int ACHIEVEMENT_HALO = 27; constexpr int CHALLENGE_APRILS_FOOL = 32; constexpr int ACTIVE_PICKUP_HOLD_FRAMES = 30; @@ -117,6 +110,7 @@ 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 float THE_POOP_FART_RADIUS = 120; constexpr int GOLDEN_RAZOR_PRICE = 5; constexpr int INPUT_HOOK_PRESSED = 0; constexpr int INPUT_HOOK_TRIGGERED = 1; @@ -138,8 +132,6 @@ 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_NO_PENALTIES = 1ull << 28; 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; @@ -813,7 +805,8 @@ static void poop_use(ItemUse& use) variant = POOP_GOLDEN; room.SpawnGridEntity(gridIndex, GRID_POOP, variant, rng.Next(), 0); - reconstruction_missing("Game::ButterBeanFart 00704360 (The Poop's fart)"); + game_butter_bean_fart( + {.position = player.pos, .source = &player, .radius = THE_POOP_FART_RADIUS, .isShowEffect = false}); } sound_play(ACTIVE_SOUND_FART); player.ShootCandle(Vector{}); @@ -1073,7 +1066,9 @@ UseResult Entity_Player::UseActiveItem(const ActiveUse& request) { UseResult result; if (request.item == 0 || request.slot >= ACTIVE_SLOT_COUNT) return result; - lua_callback_check(MC_PRE_USE_ITEM, "Entity_Player::UseActiveItem 005b39d0: LuaEngine::PreUseItem 00863760"); + LuaItemUse preUse = {.player = this, .rng = &GetCollectibleRNG(request.item), .activeSlot = request.slot, + .collectibleType = request.item, .customVarData = request.varData, .useFlags = request.flags}; + if (lua_engine_get().PreUseItem(preUse)) return result; if (variant == PLAYER_VARIANT_PLAYER && !isActiveUsed) for (Entity_Player* each : g_game->playerManager.playerList) diff --git a/src/entity_player_costumes.cpp b/src/entity_player_costumes.cpp new file mode 100644 index 0000000..869c672 --- /dev/null +++ b/src/entity_player_costumes.cpp @@ -0,0 +1,244 @@ +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "room_render.h" +#include +#include +#include + +constexpr float BLEED_OUT_TINT_HEALTH = 150; +constexpr int REVERSE_CHARIOT_FLASH_FRAMES = 90; +constexpr float STATUE_MASS = 1000; +constexpr float HEAD_LIFT_PER_HEAD_SCALE = 2.5f; +constexpr float HEAD_LIFT_PER_SQUASH = 8; +constexpr std::string_view SUB_ANIM_PREFIX = "SubAnim"; + +// How the player's layers draw this frame (the frame's tints and squashes): the head and body tints, the head's +// offset and size from the body costume's HeadTransform null and the head costume's frame, and the squashes the +// effects add. +struct LayerLook +{ + ColorMod bodyColor = COLOR_DEFAULT; + ColorMod headColor = COLOR_DEFAULT; + Vector bodySquash = vector_make(1, 1); + Vector headFrameScale = vector_make(1, 1); + Vector headOffset{}; + Vector headSize = vector_make(1, 1); + Vector headSquash = vector_make(1, 1); + float headLift = 0; + float offsetX = 0; +}; + +// Whether a costume is a null item's. +static bool is_null_costume(const CostumeSpriteDesc& costume, int nullItemId) +{ + return costume.item && costume.item->type == ITEM_NULL && costume.item->id == nullItemId; +} + +// Reads the head's offset and size from the costumes: the HeadTransform null of the body costume and the frame scale +// of the head costume (Pluto's and Inner Child's heads keep their size). Tainted Forgotten's head rides on his height +// and a bleeding out player reddens. The effects that tint or squash the player stop the game until reached. +static void layer_look_read(Entity_Player& player, LayerLook& look) +{ + PlayerCostumeMap& head = player.playerCostumeMap[PLAYER_LAYER_HEAD]; + if (head.index >= 0) + { + CostumeSpriteDesc& costume = player.costumeSpriteDescs[head.index]; + int id = costume.item ? costume.item->id : 0; + AnimationState& state = costume.sprite.animState; + bool isSized = id != COLLECTIBLE_PLUTO && id != COLLECTIBLE_INNER_CHILD; + const AnimationFrame* frame = isSized && state.animData ? state.GetLayerFrame(head.layerId) : nullptr; + if (frame) look.headFrameScale = vector_make(std::fabs(frame->scale.x), std::fabs(frame->scale.y)); + } + + TemporaryEffects& effects = player.temporaryEffects; + TemporaryEffect* chariot = effects.GetNullEffect(NULLITEM_REVERSE_CHARIOT); + bool isAdrenaline = (player.HasCollectible(COLLECTIBLE_ADRENALINE) || + effects.HasCollectibleEffect(COLLECTIBLE_ADRENALINE)) && + player.IsExtraAnimationFinished(); + bool isGolden = player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH) && + ((player.HasCollectible(COLLECTIBLE_GNAWED_LEAF) && player.mass == STATUE_MASS) || + effects.HasNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE)); + bool isEffectLook = isAdrenaline || isGolden || player.HasCollectible(COLLECTIBLE_MARS) || + player.bladderCharge > 0 || player.ibsChargeBar > 0 || player.flashCountdown > 0 || + effects.GetCollectibleEffectNum(COLLECTIBLE_AZAZELS_RAGE) == 4 || + player.maggySwingCooldown > 0 || player.jellyBellyBounceTimer > 0 || + (chariot && chariot->cooldown < REVERSE_CHARIOT_FLASH_FRAMES) || + player.reverseChariotMoveCooldown > 1 || + effects.HasCollectibleEffect(COLLECTIBLE_BERSERK) || g_game->challenge == CHALLENGE_HOT_POTATO || + !player.IsLocalPlayer(); + if (isEffectLook) + reconstruction_missing("Entity_Player::Update 00782af0 (the effects that tint or squash the player)"); + + PlayerCostumeMap& body = player.playerCostumeMap[PLAYER_LAYER_BODY]; + if (body.index >= 0) + if (const NullFrame* transform = player.costumeSpriteDescs[body.index].sprite.GetNullFrame("HeadTransform"); + transform && transform->isVisible) + { + if (player.playerType == PLAYER_LILITH_B) + reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lilith's head over Gello)"); + look.headOffset = transform->pos; + look.headSize = transform->scale; + } + if (player.playerType == PLAYER_THEFORGOTTEN_B) look.headOffset.y += player.forgottenBHeight; + + bool isBleeding = player.HasEntityFlags(FLAG_BLEED_OUT) && player.bleedSource.entity == &player && + player.bleedOutHealth < BLEED_OUT_TINT_HEALTH; + if (!isBleeding) return; + float fade = (float)player.bleedOutHealth / BLEED_OUT_TINT_HEALTH; + ColorMod bleeding = {{1, fade, fade, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + color_multiply(look.headColor, bleeding); + color_multiply(look.bodyColor, bleeding); +} + +// Poses the player's own layers: the body ones tinted and squashed by the body's scale, the head ones tinted, sized by +// the head's scale and lifted to sit on the body. During an extra animation the whole sprite draws plain. +static void player_layers_pose(Entity_Player& player, const LayerLook& look, bool isWhole) +{ + for (int layerId = 0; layerId < COSTUME_LAYER_COUNT; layerId++) + { + LayerState* layer = player.sprite.GetLayer(layerId); + if (!layer) continue; + bool isBody = player.playerCostumeMap[layerId].isBodyLayer; + layer->color = isBody ? look.bodyColor : look.headColor; + if (isWhole) + { + layer->size = isBody ? vector_make(1, 1) : player.headScale; + layer->pos = {}; + continue; + } + + if (isBody) + layer->size = vector_make(player.bodyScale.x * look.bodySquash.x, player.bodyScale.y * look.bodySquash.y); + else + { + layer->size = vector_make(look.headSize.x * player.headScale.x * look.headFrameScale.x * look.headSquash.x, + look.headSize.y * player.headScale.y * look.headFrameScale.y * look.headSquash.y); + layer->pos.y = look.headOffset.y * player.bodyScale.y + + (player.headScale.y - player.bodyScale.y) * HEAD_LIFT_PER_HEAD_SCALE + + look.headLift * HEAD_LIFT_PER_SQUASH; + } + layer->pos.x = look.offsetX; + } +} + +// Copies the overlay's SubAnim frame into a costume's layers: each layer shows the overlay's crop and scale. +static void sub_anim_apply(ANM2& costume) +{ + const AnimationState& overlay = costume.overlayAnimState; + if (!overlay.animData || !overlay.animData->name.starts_with(SUB_ANIM_PREFIX)) return; + + for (int layerId = 0; layerId < (int)costume.layerStates.size(); layerId++) + if (const AnimationFrame* frame = overlay.GetLayerFrame(layerId)) + { + LayerState& layer = costume.layerStates[layerId]; + layer.cropOffset = frame->crop; + layer.size = vector_make(layer.size.x * frame->scale.x, layer.size.y * frame->scale.y); + } +} + +// The costumes' part of 00782af0: poses the player's layers, then lays each worn costume layer over its player layer +// with the same tint, scale, size and position, and steps every worn costume's animation (its SubAnim overlay copied +// into its layers). Co-op babies and ghosts draw plain. +void Entity_Player::costume_layers_update() +{ + if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost) return; + + LayerLook look; + layer_look_read(*this, look); + sprite.bitflags |= ANIM_RENDER_SIZE_WITH_SPRITE; + ItemConfig_Item* megaMush = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MEGA_MUSH); + bool isWhole = isPlayingExtraAnimation && !is_item_costume_visible(*this, megaMush, -1); + player_layers_pose(*this, look, isWhole); + + std::set worn; + for (int layerId = 0; layerId < COSTUME_LAYER_COUNT; layerId++) + { + PlayerCostumeMap& map = playerCostumeMap[layerId]; + if (map.index < 0) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + LayerState* own = sprite.GetLayer(layerId); + + costume.sprite.color = sprite.color; + if (map.isBodyLayer) color_multiply(costume.sprite.color, look.bodyColor); + else if (layerId > PLAYER_LAYER_BODY1) color_multiply(costume.sprite.color, look.headColor); + costume.sprite.scale = sprite.scale; + if (LayerState* layer = costume.sprite.GetLayer(map.layerId); layer && own) + { + layer->size = own->size; + layer->pos = own->pos; + if (layerId == PLAYER_LAYER_GLOW) layer->bitflags |= ANIM_RENDER_UNTINTED; + } + worn.insert(map.index); + if (map.isBodyLayer && is_null_costume(costume, NULLITEM_LILITH_B)) + reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lilith's Gello costume frame)"); + } + if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + + for (int index : worn) + { + ANM2& costume = costumeSpriteDescs[index].sprite; + costume.bitflags |= ANIM_RENDER_SIZE_WITH_SPRITE; + costume.Update(); + sub_anim_apply(costume); + } +} + +// The body costumes' part of 00782af0's walk: each body costume plays the walk the body plays, or stands on its first +// frame (a looping _Idle animation when it has one, Mega Mush's WalkIdle), with its _Overlay animation. While an item +// is lifted they stop, except Tainted Lilith's. Costumes playing an item's own animation keep it. Returns the walk's +// speed factor: Jupiter's angel body doubles it once per layer it covers. +float Entity_Player::body_costumes_walk(const CostumeWalk& walk) +{ + float speed = 1; + if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost) return speed; + + std::string overlay = std::string(walk.animation) + "_Overlay"; + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0 || !map.isBodyLayer) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + ANM2& worn = costume.sprite; + if (is_null_costume(costume, NULLITEM_JUPITER_BODY_ANGEL)) speed *= 2; + bool isStopped = walk.isLifted && !is_null_costume(costume, NULLITEM_LILITH_B); + + if (walk.isMoving) + { + if (isStopped) worn.Stop(); + else if (!costume.isItemAnimPlay) + { + worn.Play(walk.animation); + if (costume.isHasOverlay) worn.PlayOverlay(overlay); + } + continue; + } + + if (costume.isItemAnimPlay) continue; + if (isStopped) + { + worn.Stop(); + continue; + } + if (costume.item && costume.item->type == ITEM_ACTIVE && costume.item->id == COLLECTIBLE_MEGA_MUSH) + { + worn.SetFrame("WalkIdle", 0); + continue; + } + std::string idle = std::string(walk.animation) + "_Idle"; + if (canFly) worn.Play(walk.animation); + else if (worn.GetAnimationData(idle)) worn.Play(idle); + else worn.SetFrame(walk.animation, 0); + if (!costume.isHasOverlay) continue; + if (canFly) worn.PlayOverlay(overlay); + else worn.SetOverlayFrame(overlay, 0); + } + return speed; +} + +// The end of 00782af0's walk: the body costumes animate at the body's speed. +void Entity_Player::body_costumes_speed_set(float speed) +{ + for (PlayerCostumeMap& map : playerCostumeMap) + if (map.index >= 0 && map.isBodyLayer) costumeSpriteDescs[map.index].sprite.playbackSpeed = speed; +} diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index 8c1c169..e5ff349 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -13,12 +13,10 @@ constexpr int COLLECTIBLE_BINKY = 438; constexpr int COLLECTIBLE_CONE_HEAD = 457; constexpr int COLLECTIBLE_DULL_RAZOR = 486; -constexpr int COLLECTIBLE_EVIL_CHARM = 632; constexpr int COLLECTIBLE_HYPERCOAGULATION = 724; constexpr int COLLECTIBLE_JELLY_BELLY = 690; constexpr int COLLECTIBLE_MARBLES = 538; constexpr int COLLECTIBLE_METAL_PLATE = 449; -constexpr int COLLECTIBLE_PLUTO = 598; constexpr int COLLECTIBLE_SCAPULAR = 142; constexpr int COLLECTIBLE_SPIRIT_SHACKLES = 674; constexpr int TRINKET_BLIND_RAGE = 81; @@ -73,13 +71,10 @@ constexpr int SOUND_BOSS_DELAY_RANDOM = 130; constexpr int SOUND_BOSS_DELAY_MIN = 50; 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_FAKE = 1ull << 21; constexpr uint64_t DAMAGE_NO_MODIFIERS = 1ull << 25; -constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; constexpr uint64_t DAMAGE_IGNORED = 1ull << 34; -constexpr uint64_t DAMAGE_THROUGH_COOLDOWN = 1ull << 35; 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; @@ -124,7 +119,6 @@ constexpr int EVIL_CHARM_GRID_VARIANT = 10000; // Teleport. constexpr int INVINCIBLE_EFFECTS[] = {93, 77, 298, 44}; constexpr int COLLECTIBLE_DARK_ARTS = 705; -constexpr int COLLECTIBLE_GNAWED_LEAF = 210; constexpr int NULLITEM_INVINCIBLE_SHIELD = 59; constexpr int BLOOD_DONATION_VARIANT = 2; constexpr int BLOOD_BANK_VARIANT = 5; @@ -406,13 +400,14 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Holy Mantle's shield)"); if (hallowedGroundCountdown > 0 && !(damageFlags & DAMAGE_NO_MODIFIERS)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hallowed Ground)"); - lua_callback_check(MC_ENTITY_TAKE_DMG, "Entity_Player::TakeDamage 007729d0: LuaEngine::EntityTakeDamage 00864560"); - (void)damageCountdown; + if (!lua_engine_get().EntityTakeDamage(this, (float)amount, damageFlags, source, damageCountdown)) return false; if (try_end_astral_projection()) return false; if (playerType == PLAYER_JACOB_B && source.type == ENTITY_DARK_ESAU) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Jacob's ghost form)"); - // The online stats tally (Player_stats_add 00425ac0) is not written yet: only the online stats screen shows it. + Entity* attacker = source.entity ? source.entity->GetPlayerAncestor() : nullptr; + if (attacker) Player_stats_add(game.onlinePlayerStats, ONLINE_STAT_PLAYER_DAMAGE_DEALT, (Entity_Player*)attacker, amount); + Player_stats_add(game.onlinePlayerStats, ONLINE_STAT_DAMAGE_TAKEN, this, amount); lastDamageSource = source; lastDamageFlags = damageFlags; isHurtThisRoom = true; @@ -498,7 +493,12 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR bool isKilled = try_trigger_astral_projection(); lastDamageSource = source; if (isKilled && game.deathmatchManager.is_active()) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a versus kill, trigger_npc_death)"); + for (Entity* killer = source.entity; killer; killer = killer->spawnerEntity.get()) + if (killer->is_player()) + { + static_cast(killer)->trigger_npc_death(this); + break; + } if (isDead) death_count(source, damageFlags); } } @@ -751,7 +751,8 @@ bool Entity_Player::try_trigger_astral_projection() temporaryEffects.GetNullEffectNum(NULLITEM_SPIRIT_SHACKLES_DISABLED) == 0 && temporaryEffects.GetNullEffectNum(NULLITEM_SHACKLES_GHOST) == 0; if (isShackled) reconstruction_missing("Entity_Player::try_trigger_astral_projection 007afc20 (Spirit Shackles)"); - // The online stats tally of deaths to spikes (Player_stats_add 00425ac0) is not written yet. + if (lastDamageSource.type == ENTITY_SLOT || (lastDamageFlags & DAMAGE_DEVIL)) + Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_DEAL_DEATHS, this, 1); lastDamageSource = EntityRef(); } Kill(EntityRef()); diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index f46e6a5..6e85e43 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -3,6 +3,7 @@ #include "game.h" #include "key_configs.h" #include "log.h" +#include "lua_engine.h" #include "manager.h" #include "menu_manager.h" #include "platform.h" @@ -401,22 +402,24 @@ void Entity_Player::walk_animation_update() Vector direction = GetBodyMoveDirection(); bool isPlayer = variant == PLAYER_VARIANT_PLAYER && !isCoopGhost; - if (direction.x != 0 || direction.y != 0) + CostumeWalk walk{.animation = {}, .isLifted = isLifted, .isMoving = direction.x != 0 || direction.y != 0}; + if (walk.isMoving) { bool isVertical = std::fabs(direction.x) <= std::fabs(direction.y); float axis = isVertical ? direction.y : direction.x; - std::string_view animation = isLifted ? (isVertical ? (axis > 0 ? "PickupWalkDown" : "PickupWalkUp") - : (axis > 0 ? "PickupWalkRight" : "PickupWalkLeft")) - : (isVertical ? (axis > 0 ? "WalkDown" : "WalkUp") - : (axis > 0 ? "WalkRight" : "WalkLeft")); - if (isPlayer) sprite.Play(animation); + walk.animation = isLifted ? (isVertical ? (axis > 0 ? "PickupWalkDown" : "PickupWalkUp") + : (axis > 0 ? "PickupWalkRight" : "PickupWalkLeft")) + : (isVertical ? (axis > 0 ? "WalkDown" : "WalkUp") + : (axis > 0 ? "WalkRight" : "WalkLeft")); + if (isPlayer) sprite.Play(walk.animation); } - else if (isPlayer) + else { - std::string_view idle = isLifted ? "PickupWalkDown" : "WalkDown"; - if (!canFly || playerType == PLAYER_THEFORGOTTEN_B) sprite.SetFrame(idle, 0); - else sprite.Play(idle); + walk.animation = isLifted ? "PickupWalkDown" : "WalkDown"; + if (isPlayer && (!canFly || playerType == PLAYER_THEFORGOTTEN_B)) sprite.SetFrame(walk.animation, 0); + else if (isPlayer) sprite.Play(walk.animation); } + float speedFactor = body_costumes_walk(walk); float speed = 1; if (sprite.IsPlaying()) @@ -426,7 +429,8 @@ void Entity_Player::walk_animation_update() if (length > WALK_FAST_SPEED) speed = range_map(length, WALK_FAST_SPEED, WALK_FASTEST_SPEED, 1, 2); if (slipperyTimer > 0) reconstruction_missing("Entity_Player::Update 00782af0 (walking on a slippery floor)"); } - sprite.playbackSpeed = speed; + sprite.playbackSpeed = speed * speedFactor; + body_costumes_speed_set(sprite.playbackSpeed); } // Turns the head the way a vector points. @@ -685,12 +689,9 @@ void Entity_Player::Update() { bodySprite.Update(); heldSprite.Update(); - for (CostumeSpriteDesc& costume : costumeSpriteDescs) costume.sprite.Update(); - for (int layer = PLAYER_LAYER_BODY; layer <= PLAYER_LAYER_BODY1; layer++) - if (playerCostumeMap[layer].index >= 0) - reconstruction_missing("Entity_Player::Update 00782af0 (body costumes following the walk)"); } sprite_scale_update(); + costume_layers_update(); update_body_animations(); update_bomb_input(); ControlActiveItem(ACTIVE_SLOT_PRIMARY); @@ -702,6 +703,7 @@ void Entity_Player::Update() if (controlsCooldown > 0) controlsCooldown--; if (fireBlockCooldown > 0) fireBlockCooldown--; if (itemHoldCooldown > 0) itemHoldCooldown--; + lua_engine_get().PostPlayerUpdate(this); } // 0078ca00 Draws the player at its place, lifted by its flight and its offset: blinking while hurt, the held entity @@ -732,6 +734,7 @@ void Entity_Player::Render(const Vector& offset) if (heldEntity) reconstruction_missing("Entity_Player::Render 0078ca00 (the held entity)"); render_pass(renderOffset, RENDER_PASS_MAIN); + lua_engine_get().PostPlayerRender(this, offset); if (!is_overlay_pass()) return; if (playerHUD) reconstruction_missing("Entity_Player::Render 0078ca00 (the player's HUD bubble)"); diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index 54a350a..dce2298 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -1,7 +1,13 @@ #include "entity_player.h" #include "game.h" +#include "entity_effect.h" +#include "entity_pickup.h" +#include "item_overlay.h" #include "manager.h" +#include "room_grid.h" +#include "sfx_manager.h" #include +#include constexpr int CONSUMABLE_MAX = 99; constexpr int DEEP_POCKETS_COIN_MAX = 999; @@ -16,6 +22,12 @@ constexpr int HEART_LIMIT_ESAU_SOUL = 4; constexpr int MAX_HEARTS_UNLOCK = 14; constexpr int SOUL_HEARTS_UNLOCK = 8; constexpr int BLACK_HEART_BITS = 32; +constexpr int HEALTH_CHARGE_MAX = 99; +constexpr int JAR_HEARTS_LIMIT = 8; +constexpr int CONCEPTION_STAGE = 5; +constexpr int CONCEPTION_STAGE_DEATHMATCH = 20; +constexpr int CONCEPTION_STAGES = 3; +constexpr float CONCEPTION_HEART_STEP = 40; // The game state bit set once the coins reach 99, which the original keeps one below Lua's STATE_MAX_COINS_OBTAINED. constexpr uint64_t GAME_STATE_MAX_COINS_BIT = 1ull << 43; @@ -407,7 +419,7 @@ void Entity_Player::black_hearts_add(int amount) AddSoulHearts(amount, false); if (!g_game->deathmatchManager.is_active() && !isDead && goldenHearts > 0) { - int holders = (std::min(redHearts, maxHearts) + 1) / 2 + (soulHearts + 1) / 2 + boneHearts; + int holders = golden_holders_count(); if (holders < goldenHearts) { BreakGoldenHearts(goldenHearts - holders); @@ -511,7 +523,7 @@ void Entity_Player::ClampGoldenHearts(bool isSkipBreak) { if (g_game->deathmatchManager.is_active() || isDead || goldenHearts <= 0) return; - int holders = (std::min(redHearts, maxHearts) + 1) / 2 + (soulHearts + 1) / 2 + boneHearts; + int holders = golden_holders_count(); if (holders >= goldenHearts) return; if (!isSkipBreak) BreakGoldenHearts(goldenHearts - holders); goldenHearts = holders; @@ -671,6 +683,23 @@ void Entity_Player::AddKeys(int amount) hud_refresh_players(); } +// 00759e20 Spends a key on a lock, none with the golden key. Mom's Locket heals for each key, with a gulp and a heart. +// Whether the lock opens. +bool Entity_Player::TryUseKey() +{ + if (hasGoldenKey) return true; + if (numKeys < 1) return false; + + numKeys--; + hud_refresh_players(); + ConsumableCountChanged(CONSUMABLE_KEYS); + if (!HasTrinket(TRINKET_MOMS_LOCKET)) return true; + AddHearts(GetTrinketMultiplier(TRINKET_MOMS_LOCKET), false, false); + sound_play(playerType == PLAYER_MAGDALENE_B ? SOUND_VAMP_DOUBLE : SOUND_VAMP_GULP); + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}); + return true; +} + // 007597e0 Shares the changed consumables with every player, as the run keeps one purse. Coins unlock their // achievements. The deathmatch keeps each player's own. void Entity_Player::ConsumableCountChanged(int bitflags) @@ -778,3 +807,285 @@ void Entity_Player::blood_charge_changed(int oldBloodCharge) { if (playerType == PLAYER_BETHANY_B) charge_store_changed(effectiveBloodCharge, oldBloodCharge); } + +// The player a heart pickup rule looks at: Tainted Forgotten's soul stands for its twin, and halfOwner (The Forgotten +// or The Soul) for its other half. +Entity_Player* Entity_Player::heart_owner(PlayerType halfOwner) +{ + Entity_Player* owner = this; + while (true) + { + if (owner->playerType == PLAYER_THESOUL_B && owner->twin_get()) owner = owner->twin_get(); + else if (owner->playerType == halfOwner && owner->subPlayer) owner = owner->subPlayer; + else return owner; + } +} + +// 006dacd0 Whether the red hearts fill every container, bone hearts included where the character has them. +bool Entity_Player::HasFullHearts() +{ + return GetEffectiveMaxHearts() <= redHearts; +} + +// 007c3410 Whether red hearts heal the player: Tainted Bethany while her blood charge has room, The Soul for its body, +// never Keeper's coin hearts. +bool Entity_Player::CanPickRedHearts() +{ + Entity_Player& owner = *health_owner(); + if (owner.playerType == PLAYER_THESOUL && owner.subPlayer) return !owner.subPlayer->HasFullHearts(); + if (owner.playerType == PLAYER_BETHANY_B && owner.effectiveBloodCharge < HEALTH_CHARGE_MAX) return true; + return owner.GetHealthType() != HEALTH_COIN && !owner.HasFullHearts(); +} + +// 007c3460 Whether soul hearts fit: an Alabaster Box with charge to fill, Bethany's soul charge, or room under the +// heart limit. The Forgotten takes them for The Soul. In the deathmatch only the hearts' total counts. +bool Entity_Player::CanPickSoulHearts() +{ + if (g_game->deathmatchManager.is_active()) return maxHearts < HEART_LIMIT_DEATHMATCH; + + Entity_Player& owner = *heart_owner(PLAYER_THEFORGOTTEN); + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + if (owner.activeItems[slot].item == COLLECTIBLE_ALABASTER_BOX && + owner.activeItems[slot].charge < owner.GetActiveMaxCharge(slot)) + return true; + if (owner.playerType == PLAYER_BETHANY && owner.effectiveSoulCharge < HEALTH_CHARGE_MAX) return true; + if (owner.playerType == PLAYER_THEFORGOTTEN) return false; + return owner.soulHearts + owner.boneHearts * 2 + owner.maxHearts < owner.GetHeartLimit(false); +} + +// 007c3550 Whether black hearts fit: as soul hearts, or by turning a full soul heart black. +bool Entity_Player::CanPickBlackHearts() +{ + if (g_game->deathmatchManager.is_active()) return maxHearts < HEART_LIMIT_DEATHMATCH; + + Entity_Player& owner = *heart_owner(PLAYER_THEFORGOTTEN); + if (owner.CanPickSoulHearts()) return true; + for (int half = 1; half < owner.soulHearts; half += 2) + if (!(owner.blackHearts & (1 << (half / 2)))) return true; + return false; +} + +// 00758bd0 Shows the eternal heart's giant book: the soul or black heart one for soul characters. +void Entity_Player::eternal_heart_overlay_show() +{ + int overlay = GIANTBOOK_ETERNAL_HEART; + if (GetHealthType() == HEALTH_SOUL) + overlay = playerType == PLAYER_BLACKJUDAS || playerType == PLAYER_JUDAS_B ? GIANTBOOK_ETERNAL_BLACK_HEART + : GIANTBOOK_ETERNAL_SOUL_HEART; + g_game->itemOverlay.Show(overlay, 1, nullptr); +} + +// 00758c20 Adds eternal hearts. Two of them become a heart container, filled, with the giant book. A co-op ghost +// revives instead, and characters without red health take none. The deathmatch adds a container at once. +void Entity_Player::AddEternalHearts(int amount) +{ + if (isCoopGhost) return RevivePlayerGhost(); + HealthType health = GetHealthType(); + if (health == HEALTH_COIN || health == HEALTH_NO_HEALTH) return; + if (g_game->deathmatchManager.is_active()) + { + AddMaxHearts(amount, false); + AddHearts(amount, false, false); + return; + } + + eternalHearts = std::max(0, eternalHearts + amount); + if (eternalHearts < 2) return; + eternal_heart_overlay_show(); + AddMaxHearts(eternalHearts / 2 * 2, false); + AddHearts(eternalHearts / 2 * 2, false, false); + eternalHearts %= 2; +} + +// 00759390 Adds hearts to The Jar, up to its eight. +void Entity_Player::AddJarHearts(int amount) +{ + Entity_Player& owner = *health_owner(); + owner.jarHearts = std::min(owner.jarHearts + amount, JAR_HEARTS_LIMIT); + hud_refresh_players(); +} + +// 007c8050 Counts hearts picked for Immaculate Conception: every fifteenth gives a familiar not yet given and a soul +// heart, and each fifth changes its costume. The deathmatch counts eight per heart up to sixty. +void Entity_Player::AddImmaculateConceptionCounter(int amount) +{ + constexpr std::array CONCEPTION_FAMILIAR_FLAGS = {0x40, 0x80, 0x100, 0x200, 0x400}; + if (!HasCollectible(COLLECTIBLE_IMMACULATE_CONCEPTION)) return; + + bool isDeathmatch = g_game->deathmatchManager.is_active(); + int stageSize = isDeathmatch ? CONCEPTION_STAGE_DEATHMATCH : CONCEPTION_STAGE; + int oldStage = immaculateConceptionState / stageSize; + immaculateConceptionState += isDeathmatch ? amount * 8 : 1; + if (immaculateConceptionState >= stageSize * CONCEPTION_STAGES) + { + uint32_t roll = GetCollectibleRNG(COLLECTIBLE_IMMACULATE_CONCEPTION).Next(); + size_t familiars = CONCEPTION_FAMILIAR_FLAGS.size(); + for (size_t offset = 0; offset < familiars; offset++) + { + uint32_t familiar = CONCEPTION_FAMILIAR_FLAGS[(roll % familiars + offset) % familiars]; + if (conceptionFamiliarFlags & familiar) continue; + sound_play(SOUND_IMMACULATE_CONCEPTION); + conceptionFamiliarFlags |= familiar; + cacheFlags |= CACHE_FAMILIARS; + EvaluateItems(); + break; + } + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({pos, CONCEPTION_HEART_STEP}); + g_game->Spawn({.position = spot, .spawner = this, .subType = HEART_SOUL, .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, .seed = seed}); + immaculateConceptionState = 0; + } + if (oldStage != immaculateConceptionState / stageSize) trigger_immaculate_conception(false); +} + +// 007c9d10 Adds golden hearts, as many as there are hearts to sit on, flashing them on the HUD. The Lost and Keeper +// break one at once. Tainted Forgotten's soul gives them to its twin. +void Entity_Player::AddGoldenHearts(int amount, bool isSkipBreak) +{ + Entity_Player& owner = *health_owner(); + if (&owner != this) isSkipBreak = false; + if (owner.playerType == PLAYER_THELOST || owner.playerType == PLAYER_THELOST_B || + owner.playerType == PLAYER_KEEPER || owner.playerType == PLAYER_KEEPER_B) + return owner.BreakGoldenHearts(1); + if (g_game->deathmatchManager.is_active()) return owner.ClampHeartsToLimit(HEART_GOLDEN, amount * 2); + + int oldGoldenHearts = owner.goldenHearts; + owner.goldenHearts = std::max(0, std::min(oldGoldenHearts + amount, owner.golden_holders_count())); + owner.ClampGoldenHearts(isSkipBreak); + if (oldGoldenHearts >= owner.goldenHearts) return; + for (PlayerHUD& hud : g_game->hud.playerHUD) + if (hud.player == &owner) + { + hud.goldHeartFlashCountdown = HUD_HEART_FLASH_FRAMES; + return; + } +} + +// The hearts a golden heart can sit on: red hearts in containers, soul hearts and bone hearts. +int Entity_Player::golden_holders_count() +{ + return (std::min(redHearts, maxHearts) + 1) / 2 + (soulHearts + 1) / 2 + boneHearts; +} + +// 007c9e30 Whether a golden heart has a heart to sit on. +bool Entity_Player::CanPickGoldenHearts() +{ + if (g_game->deathmatchManager.is_active()) return maxHearts < HEART_LIMIT_DEATHMATCH; + Entity_Player& owner = *health_owner(); + return owner.goldenHearts < owner.golden_holders_count(); +} + +// 007ca840 Adds bone hearts, or breaks them. New ones push soul hearts out past the limit and take the slots after +// the soul hearts. Keeper gets flies, The Soul gives them to its body, characters without health take none. +void Entity_Player::AddBoneHearts(int amount) +{ + Entity_Player* owner = this; + while (true) + { + owner = owner->health_owner(); + HealthType health = owner->GetHealthType(); + if (health == HEALTH_NO_HEALTH) return; + if (health == HEALTH_COIN) + { + if (amount > 0) owner->AddBlueFlies(amount * 4, owner->pos, nullptr); + return; + } + if (owner->playerType != PLAYER_THESOUL) break; + owner = owner->subPlayer; + if (!owner) return; + } + owner->bone_hearts_add(amount); +} + +// Adds bone hearts to a player that keeps them, after AddBoneHearts settled who. +void Entity_Player::bone_hearts_add(int amount) +{ + if (g_game->deathmatchManager.is_active()) + { + ClampHeartsToLimit(HEART_BONE, amount * 2); + UpdateHeartDependentEffects(); + return; + } + if (amount < 0) + { + if (GetHealthType() == HEALTH_BONE) trigger_max_hearts_removed(-amount * 2); + boneHearts = std::max(0, boneHearts + amount); + redHearts = std::min(redHearts, GetEffectiveMaxHearts()); + update_bone_hearts(); + UpdateHeartDependentEffects(); + return; + } + + int pushedSoul = std::min(soulHearts, soulHearts + (boneHearts + amount) * 2 + maxHearts - GetHeartLimit(false)); + if (pushedSoul > 0) AddSoulHearts(-pushedSoul, false); + amount = std::min(amount, GetHeartLimit(false) / 2 - ((maxHearts + 1 + soulHearts + boneHearts * 2) >> 1)); + if (amount < 1) return; + + int firstSlot = (soulHearts + 1) / 2 + boneHearts; + for (int heart = 0; heart < amount; heart++) boneHeartsMask |= 1 << ((firstSlot + heart) & 31); + boneHearts += amount; + UpdateHeartDependentEffects(); +} + +// 007caa00 Whether a bone heart fits under the heart limit. The Soul takes them for its body, never itself. +bool Entity_Player::CanPickBoneHearts() +{ + if (g_game->deathmatchManager.is_active()) return maxHearts < HEART_LIMIT_DEATHMATCH; + Entity_Player& owner = *heart_owner(PLAYER_THESOUL); + if (owner.GetHealthType() == HEALTH_NO_HEALTH || owner.playerType == PLAYER_THESOUL) return false; + return owner.GetHeartLimit(false) / 2 > (owner.maxHearts + owner.boneHearts * 2) >> 1; +} + +// 007d2fc0 Adds rotten hearts: red hearts that rot, two halves each, or takes them away. Tainted Magdalene doubles them +// and Keeper gets flies. The Have a Heart challenge heals nothing unless isUnknown is set. +void Entity_Player::AddRottenHearts(int amount, bool isUnknown) +{ + Entity_Player* owner = this; + while (true) + { + owner = owner->health_owner(); + if (amount > 0 && !isUnknown && g_game->challenge == CHALLENGE_HAVE_A_HEART) return; + if (owner->playerType != PLAYER_THESOUL || !owner->subPlayer) break; + isUnknown = false; + owner = owner->subPlayer; + } + + HealthType health = owner->GetHealthType(); + if (health == HEALTH_SOUL || health == HEALTH_NO_HEALTH) return; + if (health == HEALTH_COIN) + { + if (amount > 0) owner->AddBlueFlies((amount * 3 + 1) / 2, owner->pos, nullptr); + return; + } + if (g_game->deathmatchManager.is_active()) return owner->ClampHeartsToLimit(HEART_ROTTEN, amount); + if (owner->playerType == PLAYER_MAGDALENE_B && !isUnknown && amount > 0) amount *= 2; + owner->rotten_hearts_add(amount); +} + +// Adds rotten hearts to a player that keeps them, after AddRottenHearts settled who and how many. +void Entity_Player::rotten_hearts_add(int amount) +{ + int oldRottenHearts = rottenHearts; + redHearts = std::max(0, std::min(redHearts + amount, maxHearts + boneHearts * 2)); + if (amount > 0) + { + ClearEntityFlags(FLAG_BLEED_OUT); + bleedOutHealth = 0; + } + rottenHearts = oldRottenHearts + (amount > 0 ? (amount + 1) / 2 : (amount - 1) / 2); + UpdateHeartDependentEffects(); + ClampGoldenHearts(false); + update_bone_hearts(); + if (amount > 0 && oldRottenHearts < rottenHearts) hud_heart_flash(); +} + +// 007d3180 Whether a rotten heart heals the player or replaces a red heart. The Soul takes them for its body, never +// Keeper's coin hearts. +bool Entity_Player::CanPickRottenHearts() +{ + if (g_game->deathmatchManager.is_active()) return maxHearts < HEART_LIMIT_DEATHMATCH; + Entity_Player& owner = *heart_owner(PLAYER_THESOUL); + if (owner.GetHealthType() == HEALTH_COIN) return false; + return !owner.HasFullHearts() || owner.rottenHearts * 2 < owner.GetEffectiveMaxHearts(); +} diff --git a/src/entity_player_hold.cpp b/src/entity_player_hold.cpp new file mode 100644 index 0000000..33c12d1 --- /dev/null +++ b/src/entity_player_hold.cpp @@ -0,0 +1,66 @@ +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include + +constexpr float THROW_HEIGHT = 7; +constexpr float THROWN_BOMB_OFFSET_Y = -24; +constexpr float THROWN_ROCKET_OFFSET_Y = -14; +constexpr float THROWN_BOMB_FALL_SPEED = -4; +constexpr float THROWN_ROCKET_SPEED = 15; + +// A held bomb leaving the hands: a rocket aimed along the throw at shoulder height, any other bomb falling from over +// the head. Both fly at the throw's velocity and stop being held and kept across rooms. +static void bomb_throw(Entity_Bomb& bomb, Vector throwVelocity) +{ + bool isRocket = bomb.variant == BOMB_ROCKET || bomb.variant == BOMB_ROCKET_GIGA; + + if (isRocket) bomb.rocketAngle = std::atan2(throwVelocity.y, throwVelocity.x) * RADIANS_TO_DEGREES; + else bomb.fallSpeed = THROWN_BOMB_FALL_SPEED; + bomb.posOffset = vector_make(0, isRocket ? THROWN_ROCKET_OFFSET_Y : THROWN_BOMB_OFFSET_Y); + bomb.velocity = throwVelocity; + bomb.flags &= ~(FLAG_PERSISTENT | FLAG_HELD); + bomb.rocketSpeed = THROWN_ROCKET_SPEED; +} + +// 007d2470 Lets go of the held entity at a velocity, giving back its visibility and collision classes. An entity that +// takes the throw flies off (a thrown player regains control and flies over the grid, a poop farts), a bomb leaves the +// hands, a small rocket vanishes. Returns what was let go. +Entity* Entity_Player::ThrowHeldEntity(Vector throwVelocity) +{ + Entity* held = heldEntity; + + if (!held) return nullptr; + + held->isVisible = isHeldEntityVisible; + held->entityCollisionClass = heldEntityCollisionClass; + held->entityGridCollisionClass = heldEntityGridCollisionClass; + if (held->TryThrow(EntityRef(this), throwVelocity, THROW_HEIGHT)) + { + if (held->type == ENTITY_PLAYER) + { + held->flags |= FLAG_THROWN; + static_cast(held)->isControlsEnabled = true; + held->entityGridCollisionClass = GRIDCOLL_WALLS; + } + if (held->type == ENTITY_POOP) + { + int sound = SOUND_POOP_THROW; + + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + } + held->flags &= ~FLAG_HELD; + } + else if (held->type == ENTITY_BOMB) bomb_throw(*static_cast(held), throwVelocity); + else if (held->type == ENTITY_EFFECT && held->variant == EFFECT_GRID_ENTITY_PROJECTILE_HELPER) + reconstruction_missing("Entity_Player::ThrowHeldEntity 007d2470: a lifted grid entity's tear (Entity_Effect " + "lacks the GridEntityDesc fields 0x430 to 0x43c Room::PickupGridEntity stores)"); + else if (held->type == ENTITY_EFFECT && held->variant == EFFECT_SMALL_ROCKET) held->Remove(); + + heldEntity = nullptr; + return held; +} diff --git a/src/entity_player_kills.cpp b/src/entity_player_kills.cpp index eee7694..cd2a458 100644 --- a/src/entity_player_kills.cpp +++ b/src/entity_player_kills.cpp @@ -11,13 +11,11 @@ #include constexpr int COLLECTIBLE_CHARM_OF_THE_VAMPIRE = 62; -constexpr int COLLECTIBLE_JUMPER_CABLES = 520; constexpr int COLLECTIBLE_BERSERK_KILLS = 704; constexpr int TRINKET_SAMSONS_LOCK = 58; constexpr int TRINKET_BAT_WING_KILLS = 118; constexpr int TRINKET_SIGIL_OF_BAPHOMET = 189; constexpr int NULLITEM_BAT_WING = 40; -constexpr int SOUND_VAMP_DOUBLE = 614; constexpr int SOUND_BOOK_SHADOWS_SIGIL = 1028; // Charm of the Vampire heals every 13 kills, every 8 in a versus match. The heart rises 24 above the player. @@ -26,6 +24,11 @@ constexpr int VAMPIRE_KILLS_VERSUS = 8; constexpr float HEART_EFFECT_RISE = -24; constexpr int VERSUS_LUSTY_BLOOD_EXTRA = 4; +// Jumper Cables charges every active slot once every 15 kills, showing the heart effect's battery. +constexpr int JUMPER_CABLES_KILLS = 15; +constexpr int HEART_EFFECT_HEART = 0; +constexpr int HEART_EFFECT_BATTERY = 1; + // Samson's Lock rolls out of 10000 and Eve's Bird Foot out of 1000, by trinket multiplier, plus luck scaled up. constexpr int SAMSONS_LOCK_ROLL = 10000; constexpr int SAMSONS_LOCK_ODDS = 666; @@ -61,11 +64,11 @@ constexpr int SIGIL_MAX_FRAMES = 150; constexpr int SIGIL_MAX_FRAMES_DOUBLE = 225; constexpr int SIGIL_MAX_FRAMES_TRIPLE = 300; -// The heart that rises above a player healed by a kill. -static void heart_effect_spawn(Entity_Player& player) +// The heart that rises above a player healed by a kill, or the battery of a Jumper Cables charge. +static void heart_effect_spawn(Entity_Player& player, int subType) { - Entity* heart = g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, - .seed = Random()}); + Entity* heart = g_game->Spawn({.position = player.pos, .subType = subType, .type = ENTITY_EFFECT, + .variant = EFFECT_HEART, .seed = Random()}); heart->sprite.offset = vector_make(0, HEART_EFFECT_RISE); heart->renderDepthOffset = 1; } @@ -188,9 +191,12 @@ static void kill_rewards_trigger(Entity_Player& player, Entity& npc, Entity_NPC* luck_trinkets_update(player); player.trigger_vampire_charm_kill(); - if (player.HasCollectible(COLLECTIBLE_JUMPER_CABLES)) - reconstruction_missing("Entity_Player::trigger_npc_death 007a0080: Jumper Cables' kill counter (+0x160c, which " - "Entity_Player has no field for)"); + if (player.HasCollectible(COLLECTIBLE_JUMPER_CABLES) && ++player.jumperCablesKills >= JUMPER_CABLES_KILLS) + { + heart_effect_spawn(player, HEART_EFFECT_BATTERY); + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) player.AddActiveCharge(1, slot, false, false, false); + player.jumperCablesKills -= JUMPER_CABLES_KILLS; + } bat_wing_update(player); if (game.room->isFirstVisit && killedNpc && killedNpc->spawnGridIndex >= 0 && &player == game.GetPlayer(0)) @@ -232,5 +238,5 @@ void Entity_Player::trigger_vampire_charm_kill() sound_play(playerType == PLAYER_MAGDALENE_B ? SOUND_VAMP_DOUBLE : SOUND_VAMP_GULP); AddHearts(1, true, false); vampireCharmKills -= kills; - heart_effect_spawn(*this); + heart_effect_spawn(*this, HEART_EFFECT_HEART); } diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 921cd2b..056e408 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -33,7 +33,6 @@ ColorMod Entity_Player::get_laser_color_copy() { reconstruction_missing("Entity_Player::get_laser_color_copy 00665c20"); } -bool Entity_Player::HasFullHearts() { reconstruction_missing("Entity_Player::HasFullHearts 006dacd0"); } void Entity_Player::set_last_damage(uint64_t, const EntityRef&) { reconstruction_missing("Entity_Player::set_last_damage 006dad80"); @@ -55,9 +54,7 @@ void Entity_Player::trigger_max_hearts_removed(int) { reconstruction_missing("Entity_Player::trigger_max_hearts_removed 00758850"); } -void Entity_Player::AddEternalHearts(int) { reconstruction_missing("Entity_Player::AddEternalHearts 00758c20"); } void Entity_Player::RemoveBlackHeart(int) { reconstruction_missing("Entity_Player::RemoveBlackHeart 007591e0"); } -void Entity_Player::AddJarHearts(int) { reconstruction_missing("Entity_Player::AddJarHearts 00759390"); } void Entity_Player::AddGoldenKey() { reconstruction_missing("Entity_Player::AddGoldenKey 00759620"); } void Entity_Player::RemoveGoldenKey() { reconstruction_missing("Entity_Player::RemoveGoldenKey 00759660"); } void Entity_Player::restore_curse_mist_backup(int*) @@ -71,7 +68,6 @@ Entity* Entity_Player::AddSwarmFlyOrbital(Vector) { reconstruction_missing("Entity_Player::AddSwarmFlyOrbital 00759bf0"); } -bool Entity_Player::TryUseKey() { reconstruction_missing("Entity_Player::TryUseKey 00759e20"); } void Entity_Player::AddNullCostume(int) { reconstruction_missing("Entity_Player::AddNullCostume 0075d800"); } void Entity_Player::AddPlayerFormCostume(int) { @@ -194,9 +190,6 @@ uint32_t Entity_Player::GetGlitchBabySubType() { reconstruction_missing("Entity_Player::GetGlitchBabySubType 007c2e90"); } -bool Entity_Player::CanPickRedHearts() { reconstruction_missing("Entity_Player::CanPickRedHearts 007c3410"); } -bool Entity_Player::CanPickSoulHearts() { reconstruction_missing("Entity_Player::CanPickSoulHearts 007c3460"); } -bool Entity_Player::CanPickBlackHearts() { reconstruction_missing("Entity_Player::CanPickBlackHearts 007c3550"); } void Entity_Player::RemoveSkinCostume() { reconstruction_missing("Entity_Player::RemoveSkinCostume 007c3620"); } void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Player::SetShootingCooldown 007c37f0"); } void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } @@ -208,10 +201,6 @@ void Entity_Player::trigger_immaculate_conception(bool) { reconstruction_missing("Entity_Player::trigger_immaculate_conception 007c7d70"); } -void Entity_Player::AddImmaculateConceptionCounter(int) -{ - reconstruction_missing("Entity_Player::AddImmaculateConceptionCounter 007c8050"); -} void Entity_Player::dash_impact() { reconstruction_missing("Entity_Player::dash_impact 007c8240"); } Entity_Laser* Entity_Player::SpawnMawOfVoid(int) { reconstruction_missing("Entity_Player::SpawnMawOfVoid 007c8dc0"); } void Entity_Player::AddGoldenBomb() { reconstruction_missing("Entity_Player::AddGoldenBomb 007c8f80"); } @@ -230,11 +219,7 @@ void Entity_Player::apply_victory_lap_penalty(uint32_t) } void Entity_Player::AddJarFlies(int) { reconstruction_missing("Entity_Player::AddJarFlies 007c9bb0"); } bool Entity_Player::IsPosInSpotLight(Vector) { reconstruction_missing("Entity_Player::IsPosInSpotLight 007c9c00"); } -void Entity_Player::AddGoldenHearts(int, bool) { reconstruction_missing("Entity_Player::AddGoldenHearts 007c9d10"); } -bool Entity_Player::CanPickGoldenHearts() { reconstruction_missing("Entity_Player::CanPickGoldenHearts 007c9e30"); } void Entity_Player::BreakGoldenHearts(int) { reconstruction_missing("Entity_Player::BreakGoldenHearts 007ca2d0"); } -void Entity_Player::AddBoneHearts(int) { reconstruction_missing("Entity_Player::AddBoneHearts 007ca840"); } -bool Entity_Player::CanPickBoneHearts() { reconstruction_missing("Entity_Player::CanPickBoneHearts 007caa00"); } void Entity_Player::apply_coop_baby_spawn_bonus() { reconstruction_missing("Entity_Player::apply_coop_baby_spawn_bonus 007cb090"); @@ -277,7 +262,6 @@ Entity_Familiar* Entity_Player::AddMinisaac(Vector, bool) } Entity_Player* Entity_Player::InitTwin(int) { reconstruction_missing("Entity_Player::InitTwin 007d2000"); } bool Entity_Player::TryHoldEntity(Entity*) { reconstruction_missing("Entity_Player::TryHoldEntity 007d2170"); } -Entity* Entity_Player::ThrowHeldEntity(Vector) { reconstruction_missing("Entity_Player::ThrowHeldEntity 007d2470"); } void Entity_Player::AddFriendlyDip(int, Vector) { reconstruction_missing("Entity_Player::AddFriendlyDip 007d2a00"); } void Entity_Player::ThrowFriendlyDip(int, Vector, Vector) { @@ -293,8 +277,6 @@ int Entity_Player::GetEffectiveBloodCharge() { reconstruction_missing("Entity_Player::GetEffectiveBloodCharge 007d2dd0"); } -void Entity_Player::AddRottenHearts(int, bool) { reconstruction_missing("Entity_Player::AddRottenHearts 007d2fc0"); } -bool Entity_Player::CanPickRottenHearts() { reconstruction_missing("Entity_Player::CanPickRottenHearts 007d3180"); } void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Player::AddUrnSouls 007d3480"); } void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::AddGigaBombs 007d34f0"); } void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } diff --git a/src/entity_player_pockets.cpp b/src/entity_player_pockets.cpp index 8450ff1..141efb0 100644 --- a/src/entity_player_pockets.cpp +++ b/src/entity_player_pockets.cpp @@ -85,7 +85,6 @@ 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; @@ -431,7 +430,7 @@ void Entity_Player::UseCard(int cardType, uint32_t useFlag) 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"); + lua_engine_get().UseCard(cardType, this, useFlag); } // 00763290 Unlocks the tears ups achievement once ten Tears Up pills and tears up items are taken. diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index e8e524c..1677a6e 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -27,8 +27,6 @@ constexpr int PLAYER_THE_FORGOTTEN_B = 35; constexpr int PLAYER_NO_DOGMA = 40; 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 BETHS_ESSENCE_WISPS = 5; constexpr int BETHS_ESSENCE_CHANCE_DOUBLE = 50; constexpr int BETHS_ESSENCE_CHANCE_TRIPLE = 100; @@ -202,7 +200,7 @@ static void room_items_apply(Entity_Player& player) Entity* parent = player.parent.get(); if (player.variant == PLAYER_VARIANT_COOP_BABY && parent && - game.GetRoomByIdx(game.currentRoomIdx)->listIndex == game.lastBossRoomListIdx && game.stage == STAGE_MOMS_FLOOR) + game.GetRoomByIdx(game.currentRoomIdx)->listIndex == game.lastBossRoomListIdx && game.stage == STAGE_DEPTHS_II) player.pos = parent->pos; for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) if (player.weapons[slot]) player.weapons[slot]->TriggerNewRoom(); diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index 3f3b8ec..6254591 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -410,6 +410,7 @@ void Entity_Projectile::Init(int entityType, int entityVariant, int entitySubTyp velocity = vector_scale(velocity, WEAKNESS_SPEED); } orbitParentVelocity = {}; + lua_engine_get().PostProjectileInit(this); } // 00652df0 Its time scale: the room's, halved for a hostile shot by the Stop Watch, the Broken Watch's slow rooms @@ -480,6 +481,7 @@ void Entity_Projectile::Update() speed_update(); fall_update(); late_update(); + lua_engine_get().PostProjectileUpdate(this); } // The Broken Modem's freeze: a frozen shot vanishes after a while, and waits in place until then. Whether it did. @@ -1393,6 +1395,7 @@ void Entity_Projectile::Render(const Vector& offset) sprite.Render(draw); } if (isRenderedAtGround) posOffset.y += height; + lua_engine_get().PostProjectileRender(this, offset); } // 0065b500 Places its sprite at its height (lifted on a curve near the floor when it rises) and lets it hit diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 41b05eb..4f4ba69 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -20,6 +20,7 @@ constexpr float TEAR_HEIGHT_START = -23; constexpr float TEAR_DAMAGE_DEFAULT = 3.5f; constexpr float TEAR_FALL_SPREAD = 0.2f; constexpr float TEAR_HOMING_FRICTION = 0.85f; +constexpr float DEFLECT_REBOUND = 0.85f; constexpr float TEAR_KNOCKBACK_MULTIPLIER = 1.7f; constexpr float TEAR_RANGE_DEFAULT = 260; constexpr float TEAR_SCALE_MIN = 0.01f; @@ -183,8 +184,6 @@ 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; @@ -431,6 +430,7 @@ void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uin knockbackMultiplier = TEAR_KNOCKBACK_MULTIPLIER; maxHitPoints = 0; tearFlags.reset(); + intervalFlags.reset(); waitFrames = 0; continueVelocity = {}; hitList.clear(); @@ -1251,6 +1251,19 @@ static float shot_alpha_get(Entity_Tear& tear) return (float)g_manager->optionsConfig.onlinePlayerOpacity * 0.09f + 0.1f; } +// 0067a080 Turns it back the way it came for a new owner, as a fart or a familiar knocks it: no flags or interval flags, +// no parent, alive again, bouncing back up if it was falling. +void Entity_Tear::Deflect(Entity* newSpawner, const Vector& newVelocity) +{ + SetTearFlags({}); + intervalFlags.reset(); + velocity = newVelocity; + parent = nullptr; + spawnerEntity = newSpawner; + isDead = false; + if (fallingAccel > 0 && fallingSpeed > 0) fallingSpeed = -fallingSpeed * DEFLECT_REBOUND; +} + // 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*) @@ -1523,8 +1536,8 @@ static void status_effects_apply(Entity& entity, const TearFlags& flags, Entity* 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); + bool isFireJet = source && source->type == ENTITY_EFFECT && source->variant == EFFECT_FIRE_JET; + entity.AddBurn(ref, isFireJet ? BURN_DURATION_LONG : BURN_DURATION, 0, false); } if (flags[TEAR_MIDAS]) entity.AddMidasFreeze(ref, MIDAS_DURATION, false); if (flags[TEAR_BACKSTAB]) diff --git a/src/entity_tear.h b/src/entity_tear.h index 4c07819..3254d4a 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -213,6 +213,7 @@ struct Entity_Tear : Entity ANM2 tearEffectANM2; ANM2 tearHaloANM2; std::vector hitList; + TearFlags intervalFlags; TearFlags tearFlags; EntityPtr attachedEffect; EntityPtr laserShotLaser; @@ -274,6 +275,7 @@ struct Entity_Tear : Entity void SetHeight(float tearHeight); void SetScale(float scale); void SetTearFlags(TearFlags flags); + void Deflect(Entity* newSpawner, const Vector& newVelocity); void apply_death_flag_effects(Entity* target); void ResetSpriteScale(); bool is_not_familiar_spawned(); diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp index cfb897e..a034baa 100644 --- a/src/familiar_missing.cpp +++ b/src/familiar_missing.cpp @@ -375,12 +375,6 @@ 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) { diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index 423a42b..3db8903 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -51,20 +51,11 @@ constexpr int CHAPTER_STAGE_OFFSET = 4; constexpr int STAGE_LAST_IN_CHAPTERS = 8; constexpr int STAGE_ASCENT_LAST = 6; constexpr int STAGE_CHAPTER_TWO = 3; -constexpr int STAGE_WOMB = 7; -constexpr int STAGE_BLUE_WOMB = 9; -constexpr int STAGE_SHEOL = 10; constexpr int GREED_STAGE_SHEOL = 5; constexpr int DELETE_THIS_STAGES = 11; -constexpr int STAGE_TYPE_ALT = 1; -constexpr int STAGE_TYPE_GREEDMODE = 3; -constexpr int STAGE_TYPE_REPENTANCE = 4; constexpr int STAGE_TYPE_COUNT = 5; constexpr uint32_t CURSE_DARKNESS = 1; constexpr uint32_t CHALLENGE_DELETE_THIS = 45; -constexpr int BACKDROP_PLANETARIUM = 35; -constexpr int BACKDROP_MAUSOLEUM_HEART = 39; -constexpr int BACKDROP_DUNGEON_BEAST = 57; constexpr uint32_t EFFECT_SPRITE_TRAIL = 166; // A normal room shows its floor's light rays one time in RAY_ODDS (in RAY_ODDS_CHAPTER_ONE on the first chapter). @@ -385,7 +376,7 @@ static bool is_stage_listed(const FXLayers& fx, std::string_view stages) if (!stage.empty() && stage.back() == 'a') { stage.pop_back(); - stageType = STAGE_TYPE_ALT; + stageType = STAGETYPE_WOTL; } if (fx.is_stage_shown(level_stage_get(std::atoi(stage.c_str())), 1u << stageType)) return true; } @@ -746,10 +737,10 @@ void FXLayers::LoadConfig(std::string_view path, int levelStage, int levelStageT backdropType = room.backdropType; if (level.get_secret_exit_kind() == SECRET_EXIT_MOMS_HEART && g_game->currentRoomIdx == ROOM_SECRET_EXIT_IDX) { - stage = STAGE_WOMB; + stage = STAGE_WOMB_I; stageType = 0; } - else if (level.IsMausoleumHeartStage()) backdropType = BACKDROP_MAUSOLEUM_HEART; + else if (level.IsMausoleumHeartStage()) backdropType = BACKDROP_CORPSE_ENTRANCE; if (g_game->challenge == CHALLENGE_DELETE_THIS) { @@ -757,7 +748,7 @@ void FXLayers::LoadConfig(std::string_view path, int levelStage, int levelStageT rng.SetSeed(g_game->dungeonPlacementSeed, DELETE_THIS_RNG_SHIFT); if ((uint32_t)(stage - 1) < DELETE_THIS_STAGES) stage = rng.Next() % DELETE_THIS_STAGES + 1; stageType = rng.Next() % STAGE_TYPE_COUNT; - if (stageType == STAGE_TYPE_GREEDMODE) stageType = STAGE_TYPE_REPENTANCE; + if (stageType == STAGETYPE_GREEDMODE) stageType = STAGETYPE_REPENTANCE; } clear(); @@ -815,7 +806,7 @@ bool FXLayers::is_stage_shown(int layerStage, uint32_t stageTypeMask) const if (isAscent && layerStage == STAGE_BLUE_WOMB) { - if (stageTypeMask & 1u << STAGE_TYPE_REPENTANCE) return true; + if (stageTypeMask & 1u << STAGETYPE_REPENTANCE) return true; } else if (layerStage == 0) return true; else if (layerStage <= STAGE_LAST_IN_CHAPTERS) isStageMatch = (stage - 1) / 2 == (layerStage - 1) / 2; diff --git a/src/game.cpp b/src/game.cpp index f9573a0..387208d 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -50,7 +50,6 @@ constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr uint32_t FORTUNE_RNG_SHIFT = 35; constexpr float START_FADE_SPEED = 0.04f; constexpr float FADE_IN_ALPHA_INSTANT = 1e-05f; -constexpr int STAGE_ID_DEATH_CERTIFICATE = 35; // How a co-op award is decided, beside its name. struct CoopAwardRule @@ -174,7 +173,7 @@ void Game::LoadConfigXmls() clicker.filter_set(FILTER_NEAREST, FILTER_NEAREST); } - game.onlinePlayerStats._end = game.onlinePlayerStats._begin; + game.onlinePlayerStats.clear(); for (CoopAward& award : game.coopAwards) award.userIds.clear(); game.isOnlineStatsFinalized = false; game.console.reset(); @@ -476,7 +475,7 @@ void Game::Start(int playerType, uint32_t startChallenge, const Seeds& seeds, Di Manager& manager = *g_manager; isStarted = true; - onlinePlayerStats._end = onlinePlayerStats._begin; + onlinePlayerStats.clear(); for (CoopAward& award : coopAwards) award.userIds.clear(); isOnlineStatsFinalized = false; difficulty = startDifficulty; @@ -549,11 +548,6 @@ void pause_screen_reset(PauseScreen& pauseScreen) pauseScreen.genericPrompt.Initialize(PROMPT_SMALL); } -void Game::Exit(bool) -{ - reconstruction_missing("Game::Exit 006fa0c0"); -} - constexpr const char* BLOOM_SHADER = "Bloom"; constexpr const char* COLOR_MOD_SHADER = "ColorMod"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; @@ -890,7 +884,7 @@ int Game::GetStageID() { if (g_game->challenge == CHALLENGE_RED_REDEMPTION) reconstruction_missing("Game::GetStageID 00738470: Level::GetRoomStageType 0074f690 on Game's room list"); - if (currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) return STAGE_ID_DEATH_CERTIFICATE; + if (currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) return STAGE_ID_HOME; return RoomConfig::GetStageID(stage, stageType, ROOM_MODE_CURRENT); } diff --git a/src/game.h b/src/game.h index 3c89435..cde1e17 100644 --- a/src/game.h +++ b/src/game.h @@ -21,6 +21,7 @@ #include "online_stats_screen.h" #include "pause_screen.h" #include "player_manager.h" +#include "player_stats.h" #include "preload_manager.h" #include "procedural_item_manager.h" #include "revive_player_menu.h" @@ -189,7 +190,7 @@ public: DailyChallenge dailyChallenge{}; ProceduralItemManager proceduralItemManager; std::array glowingHourglassStates{}; - std_vector onlinePlayerStats{}; + std::vector onlinePlayerStats; std::array coopAwards; bool isOnlineStatsFinalized = false; std::vector encounteredBosses; @@ -317,6 +318,7 @@ public: void store_game_state(GameState& state); void restore_game_state(GameState& state, GameRestore restore); static void Exit(bool isSaving); + static void SaveBackwardsStage(int stage); void Update(); void interpolate_update(); void recreate_render_targets(); diff --git a/src/game_exit.cpp b/src/game_exit.cpp new file mode 100644 index 0000000..9521a49 --- /dev/null +++ b/src/game_exit.cpp @@ -0,0 +1,147 @@ +#include "entity_list.h" +#include "entity_player.h" +#include "game.h" +#include "game_over.h" +#include "lua_engine.h" +#include "manager.h" +#include "platform.h" +#include "room.h" +#include "room_transition.h" +#include "stage_transition.h" +#include "texture_cache.h" + +constexpr int EXIT_STAGE_TRANSITION_DURATION = 50; + +// The sounds a run leaves playing past its end: the Ascent's Mom and Dad clips and the monsters next door. +constexpr int EXIT_STOPPED_SOUNDS[] = {SOUND_MOM_AND_DAD_1, SOUND_MOM_AND_DAD_2, SOUND_MOM_AND_DAD_3, + SOUND_MOM_AND_DAD_4, SOUND_MONSTERS_NEXT_DOOR}; + +// 009b9150 Deletes the players (out of the room's lists first), the extra players and Esau Jr.'s, forgets the +// transition and dead players, and frees every player color. +void PlayerManager::players_clear() +{ + EntityList& list = g_game->room->entityList; + + stageTransitionPlayer = nullptr; + roomTransitionPlayer = nullptr; + for (Entity_Player* player : playerList) + { + for (EntityList_EL* sublist : {&list.mainEL, &list.updateEL, &list.renderEL, &list.persistentEL, &list.wispEL}) + std::erase(*sublist, player); + player->isValid = false; + list.invalidate_type_cache(player->type, player->variant, player->subtype); + delete player; + } + playerList.clear(); + for (Entity_Player* player : extraPlayers) delete player; + extraPlayers.clear(); + for (Entity_Player*& player : esauJrState) + { + delete player; + player = nullptr; + } + + deadPlayer = nullptr; + isColorAssignEnabled = true; + log_printf(LOG_INFO, "Clearing player color assignments \n"); + for (int color = 0; color < (int)colorControllers.size(); color++) + { + log_printf(LOG_INFO, "Clearing player color assignment for color %d \n", color); + colorControllers[color] = -1; + } +} + +// Ends the run's screens and transitions: the emote wheel, the death screen, the leaderboard, the online stats, the +// stage and room transitions, the item and boss overlays. +static void run_screens_reset(Game& game) +{ + game.emoteMenuState = 0; + game.emoteWheel.selection = 0; + game.emoteWheel.SetEmoteSet(0); + game.emoteWheel.ringRadius = 0; + game.emoteWheel.openProgress = 0; + game.gameOver.state = GAME_OVER_HIDDEN; + game.gameOver.sprite.Reset(); + game.leaderboard.displayState = LEADERBOARD_HIDDEN; + game.onlinePlayerStats.clear(); + game.onlineStatsScreen.isActive = false; + + StageTransition& stage = game.stageTransition; + RoomTransition& room = game.roomTransition; + + stage.state = STAGE_TRANSITION_NONE; + stage.frame = 0; + stage.isSameStage = false; + stage.type = STAGE_TRANSITION_NEXT; + stage.exitPosition = {}; + stage.duration = EXIT_STAGE_TRANSITION_DURATION; + room.frame = 0; + room.progress = 0; + room.mode = TRANSITION_NONE; + room.direction = {}; + room.animation = TRANSITION_WALK; + room.flags = 0; + + game.itemOverlay.sprite.Reset(); + game.itemOverlay.megaMushPlayerSprite.Reset(); + game.itemOverlay.state = ITEM_OVERLAY_INACTIVE; + game.itemOverlay.overlayID = 0; + game.bossOverlay._state = 0; +} + +// 006fa0c0 Leaves a started run for the menus: the mods hear of it, the run's sounds stop, a playing overlay +// finishes, the music's pitch resets, changed progress is backed up and saved, the run is saved or forgotten, then +// the run's screens, flags, room weights, console, floor, players, HUD, preloaded images and pause screen reset. +// The boss overlay's sprite is not modeled. The original also skips saving on a Game+0x2658b flag nothing sets. +void Game::Exit(bool isSaving) +{ + Game& game = *g_game; + Manager& manager = *g_manager; + PersistentGameData& data = manager.persistentGameData; + + if (!game.isStarted) return; + + lua_engine_get().PreGameExit(isSaving); + manager.sfxManager.StopLoopingSounds(); + for (int sound : EXIT_STOPPED_SOUNDS) manager.sfxManager.Stop(sound); + if (game.itemOverlay.state == ITEM_OVERLAY_ACTIVE) game.itemOverlay.Update(OVERLAY_UPDATE_FINISH); + manager.musicManager.ResetPitch(); + if (data.isChangesMade && data.isFileLoaded) + { + data.isChangesMade = false; + data.BackupSaveFile(); + data.Save(); + } + if (isSaving) Manager::save_game_state(); + else game_save_delete(); + + run_screens_reset(game); + game.reset_run_state(); + data.SetReadOnly(false); + game.playerManager.stageTransitionPlayer = nullptr; + game.playerManager.roomTransitionPlayer = nullptr; + game.gameStateFlags = 0; + for (RoomConfig_Stage& stage : game.roomConfig.stages) + for (RoomSet& set : stage.rooms) + if (set.isLoaded) + for (RoomConfig_Room& room : set.configs) room.weight = room.initialWeight; + + game.console.Close(); + game.level_reset(); + game.playerManager.players_clear(); + game.hud.unload_graphics(); + game.hud.reset(); + TextureCache::Purge(); + for (auto& [name, group] : game.preloadManager.groups) + { + if (group.isLoaded) + { + for (PreloadEntry& entry : group.entries) entry.image.reset(); + group.isLoaded = false; + } + TextureCache::Purge(); + } + pause_screen_reset(game.pauseScreen); + game.framesSinceRoomTransition = 0; + game.isStarted = false; +} diff --git a/src/game_over.cpp b/src/game_over.cpp index a944505..ec5d74c 100644 --- a/src/game_over.cpp +++ b/src/game_over.cpp @@ -3,7 +3,7 @@ #include "entity_player.h" #include "game.h" #include "log.h" -#include "lua_callbacks.h" +#include "lua_engine.h" #include "manager.h" #include "mod_manager.h" #include "platform.h" @@ -59,9 +59,6 @@ constexpr int GREED_SHOP_LOCATION = 10; constexpr int PORTRAIT_UNKNOWN = 149; constexpr int PORTRAIT_BOMB = 65; -constexpr uint64_t DAMAGE_DEVIL = 1ull << 10; -constexpr uint64_t DAMAGE_TNT = 1ull << 12; -constexpr uint64_t DAMAGE_CURSED_DOOR = 1ull << 16; constexpr uint64_t DAMAGE_TIMER = 1ull << 17; constexpr uint64_t DAMAGE_IV_BAG = 1ull << 18; @@ -372,7 +369,7 @@ void game_end(GameEnding ending) game.gameOver.Show(); persistent_game_data_set_writable(); - lua_callback_check(MC_POST_GAME_END, "FUN_00864fc0 MC_POST_GAME_END"); + lua_engine_get().PostGameEnd(ending == ENDING_DEATH); } // 009bc120 A player's death that ends the run: the deaths counter, the game over jingle with its music queued, and the diff --git a/src/game_restore.cpp b/src/game_restore.cpp index c354fb5..589402a 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -4,6 +4,7 @@ #include "game_state_player.h" #include "log.h" #include "manager.h" +#include "npc_ai.h" #include "room.h" #include "texture_cache.h" #include @@ -28,10 +29,8 @@ constexpr uint32_t ITEM_POOL_SHIFT = 3; 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 int DIMENSION_ALTERNATE = 1; +constexpr float FAMILIAR_RESTORE_SCATTER = 20; constexpr int MINI_MUSH_STACKS_SECOND = 4; constexpr int MINI_MUSH_STACKS_THIRD = 7; constexpr int NULLITEM_WAVY_CAP_2 = 72; @@ -630,6 +629,7 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) edenShotSpeed = saved.edenShotSpeed; edenLuck = saved.edenLuck; vampireCharmKills = saved.vampireCharmKills; + jumperCablesKills = saved.jumperCablesKills; for (size_t i = 0; i < activeItems.size(); i++) { const ActiveItemDesc& active = saved.activeItems[i]; @@ -681,11 +681,19 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) // the Forgotten's body for the Soul, its charmed enemies, the items whose effect lasts the floor, its bleeding, Greed's // Gullet, the item it held up, its temporary effects (rebuilt from the persistent ones when it saved none), Dark Esau, // the co-op ghost's entrance and a sub player the Soul of the Forgotten no longer needs. Its stats are evaluated again. -// The familiars, charmed enemies, Dark Esau and the co-op ghost wait for their takeovers. +// The charmed enemies, Dark Esau and the co-op ghost wait for their takeovers. void Entity_Player::RestoreGameState_PostLevelInit(GameStatePlayer& saved) { - if (!saved.familiars.empty()) - reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the familiars (00630560)"); + for (const FamiliarData& familiar : saved.familiars) + { + Vector spot = vector_add(pos, vector_scale(random_direction(), FAMILIAR_RESTORE_SCATTER)); + spot = g_game->room->GetClampedPositionImpl(spot, FAMILIAR_RESTORE_SCATTER, FAMILIAR_RESTORE_SCATTER, + FAMILIAR_RESTORE_SCATTER, FAMILIAR_RESTORE_SCATTER); + Entity* spawned = g_game->Spawn({.position = spot, .spawner = this, .subType = familiar.subtype, + .type = ENTITY_FAMILIAR, .variant = familiar.variant, + .seed = familiar.initSeed}); + static_cast(spawned)->RestoreState(familiar); + } if (replacedPlayer) return; if (playerType == PLAYER_THESOUL) spawn_forgotten_body(); diff --git a/src/game_save.cpp b/src/game_save.cpp index 8af0403..3ef06b1 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -336,7 +336,7 @@ static bool is_familiar_saved(Entity_Familiar& familiar, bool isSaveTemporaryFam // babies that belong to the first player, history, stats and counters, items, pockets and their RNGs, costumes, the // Moving Box, the friendly enemies it charmed (up to 10, the first twin only), its familiars and persistent effects. // The fields the curated player does not have yet keep their defaults: the candy heart and soul locket stat ups, the -// soul charge, the last pill color, the kill counter, the crafting pool, the later poop spells and their counters, +// soul charge, the last pill color, the crafting pool, the later poop spells and their counters, // the last collectible frame and the unknown fields. Its Echo Chamber items are saved without their kind, and its // voided passives without their second word. The unlisted restore state is never set, so familiars come from the room. void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTemporaryFamiliars) @@ -442,6 +442,7 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.edenShotSpeed = edenShotSpeed; state.edenLuck = edenLuck; state.vampireCharmKills = vampireCharmKills; + state.jumperCablesKills = jumperCablesKills; state.activeItems = activeItems; state.tonsilCounter = tonsilCounter; state.tonsilCount = tonsilCount; diff --git a/src/game_state.cpp b/src/game_state.cpp index 1d21fd1..e89a8ae 100644 --- a/src/game_state.cpp +++ b/src/game_state.cpp @@ -326,7 +326,7 @@ void StateWriter::player_write(const GameStatePlayer& player) player.edenShotSpeed, player.edenLuck}) write(value); write(player.vampireCharmKills); - write(player.killCounter); + write(player.jumperCablesKills); for (const ActiveItemDesc& active : player.activeItems) for (int value : {active.item, active.unknown, active.charge, active.batteryCharge, active.partialCharge, @@ -1000,7 +1000,7 @@ bool StateReader::player_read(GameStatePlayer& player) player.luckModifier, player.donateLuck, player.potatoPeelerCounter); if (version >= SAVE_VERSION_BANDAGE) player.potatoPeelerBandageCounter = read(); fields_read(player.edenSpeed, player.edenFireDelay, player.edenDamage, player.edenTearRange, player.edenShotSpeed, - player.edenLuck, player.vampireCharmKills, player.killCounter); + player.edenLuck, player.vampireCharmKills, player.jumperCablesKills); for (ActiveItemDesc& active : player.activeItems) { diff --git a/src/game_state_player.h b/src/game_state_player.h index 61005cd..460d2a7 100644 --- a/src/game_state_player.h +++ b/src/game_state_player.h @@ -170,8 +170,8 @@ struct GameStatePlayer int immaculateConceptionState = 0; int jarFlies = 0; int jarHearts = 0; + int jumperCablesKills = 0; int keepersSackBonus = 0; - int killCounter = 0; int lastCollectibleFrame = -1; int lastPillColor = 0; int luckModifier = 0; diff --git a/src/game_transition.cpp b/src/game_transition.cpp index d06bb7c..ad55526 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -17,10 +17,6 @@ constexpr int DEATH_CERTIFICATE_DIMENSION = 2; constexpr int MIRROR_DIMENSION = 1; constexpr int DOOR_SIDES = 4; constexpr int SIDE_ACROSS = 2; -constexpr int STAGE_ID_HOME = 35; -constexpr int STAGE_ID_SPECIAL_ROOMS = 0; -constexpr uint32_t STAGE_CAVES_I = 3; -constexpr uint32_t STAGE_CAVES_II = 4; constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; constexpr int MAZE_MOVE_CHANCE = 10; constexpr int MAZE_SWAP_CHANCE = 5; @@ -28,7 +24,6 @@ constexpr int MAZE_SHAKE_FRAMES = 30; constexpr int SOUND_MAZE = 22; constexpr float SOUND_MAZE_VOLUME = 0.5f; 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 uint64_t GAME_STATE_BOSSPOOL_SWITCHED = 1ull << 4; @@ -102,7 +97,7 @@ void Game::StartRoomTransition(RoomTransitionRequest request) bool isGuarded = type == ROOM_CHALLENGE || type == ROOM_BOSSRUSH; bool isEscape = isGuarded ? !room->IsClear() : type == ROOM_CURSE || type == ROOM_ERROR; - if (isEscape) Player_stats_add(&onlinePlayerStats, ONLINE_STAT_ESCAPES, player, 1); + if (isEscape) Player_stats_add(onlinePlayerStats, ONLINE_STAT_ESCAPES, player, 1); isSaved = true; } } diff --git a/src/game_update.cpp b/src/game_update.cpp index f41925a..3951f88 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -11,9 +11,6 @@ #include #include -constexpr uint32_t STAGE_BLUE_WOMB = 9; -constexpr uint32_t STAGE_HOME = 13; -constexpr int STAGE_ID_SPECIAL_ROOMS = 0; constexpr int BOSS_MEGA_SATAN = 55; constexpr int BOSS_MOTHER = 88; constexpr int SOUND_TRAPDOOR_LOOP = 1008; diff --git a/src/grid_entity.cpp b/src/grid_entity.cpp index 7b95eef..ae87997 100644 --- a/src/grid_entity.cpp +++ b/src/grid_entity.cpp @@ -1,5 +1,10 @@ #include "grid_entity.h" +#include "boss_ai.h" +#include "entity_bomb.h" #include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" #include "game.h" #include "grid_entity_decoration.h" #include "grid_entity_door.h" @@ -20,13 +25,54 @@ #include "grid_entity_web.h" #include "log.h" #include "manager.h" +#include "npc_ai.h" #include "room.h" +#include "room_grid.h" +#include "room_transition.h" +#include "stage_transition.h" +#include "string_table.h" #include "seeds.h" +#include +#include #include +#include // TNT still standing before its output trigger blows it up. constexpr int TNT_STATE_STANDING_LAST = 3; +// How a grid entity hurts: the damage cooldown it leaves, its push, the hiss of a burning victim (louder with more +// health) and the red of a player's footprints off spikes. +constexpr int GRID_HURT_COOLDOWN = 30; +constexpr float GRID_HURT_PUSH = 4; +constexpr float FIRE_HISS_PER_HEALTH = 0.05f; +constexpr float FIRE_HISS_BASE = 0.5f; +constexpr float SPIKES_FOOTPRINT_RED = 0.47058824f; +constexpr int CHUB_CARRION_QUEEN = 2; + +// The Judas' Tongue strength that lowers a spike offer's spikes on the first hit. +constexpr int JUDAS_TONGUE_SURE_PAY = 3; + +// Sacrifice rewards: where they drop, the rolls of a sacrifice-like spike, the blessings, the angel's delay, the last +// stage Redemption is given on, and the run's end stages that allow the ascent. +constexpr float SACRIFICE_DROP_X = 320; +constexpr float SACRIFICE_DROP_Y = 340; +constexpr float SACRIFICE_LIKE_COINS = 0.15f; +constexpr float SACRIFICE_LIKE_BLOOD = 0.48f; +constexpr float SACRIFICE_LIKE_HEARTS = 0.58f; +constexpr float SACRIFICE_LIKE_ITEM = 0.63f; +constexpr float SACRIFICE_LIKE_FORM = 0.65f; +constexpr int SACRIFICE_LIKE_COIN_COUNT = 6; +constexpr int SACRIFICE_LIKE_FORM_STEPS = 3; +constexpr int PLAYER_FORM_EVIL_ANGEL = 8; +constexpr float SACRIFICE_BLESS_SMALL = 0.15f; +constexpr float SACRIFICE_BLESS_LARGE = 0.5f; +constexpr int SACRIFICE_ANGEL_DELAY = 35; +constexpr uint32_t SACRIFICE_REDEMPTION_LAST_STAGE = 6; +constexpr int SACRIFICE_END_STAGE = 12; +constexpr int SACRIFICE_ASCEND_MIN_END = 10; +constexpr uint32_t STAGE_SHEOL_DARK_ROOM = 11; +constexpr int ACHIEVEMENT_SACRIFICE_DARK_ROOM = 320; + // Plays a sound effect, unless the seeds swap it for a fart. void grid_sound_play(int sound, SoundPlay play) { @@ -238,10 +284,273 @@ bool GridEntity::IsDangerousCrushableOrWalkable() return isHazard || (type == GRID_POOP && variant == POOP_RED); } -// 00709fb0 Hurts one entity the way an exploding or breaking grid entity does. -void GridEntity::hurt_func(Entity&, const GridHurt&) +// Whether hurt_func spares an entity: one flying or keeping to the walls (unless the hurt ignores that), the immune +// kinds, spikes against Callus or Socks, and the familiars a grid entity never hurts. +static bool is_spared(Entity& entity, const GridHurt& hurt) { - reconstruction_missing("GridEntity::hurt_func 00709fb0"); + bool isSpikes = hurt.damageFlags & DAMAGE_SPIKES; + if (!hurt.isIgnoreGridCollisionClass && entity.entityGridCollisionClass <= GRIDCOLL_WALLS) return true; + if (isSpikes && entity.HasEntityFlags(FLAG_NO_SPIKE_DAMAGE)) return true; + if (entity.type == ENTITY_DARK_ESAU || entity.type == ENTITY_BLOOD_PUPPY) return true; + + bool isCarrionQueen = entity.type == ENTITY_CHUB && entity.variant == CHUB_CARRION_QUEEN; + if (hurt.damageFlags & DAMAGE_FIRE) + { + if (entity.type == ENTITY_FLAMING_HOPPER || isCarrionQueen) return true; + if (entity.is_player() && entity.ToPlayer()->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL)) return true; + } + bool isPoop = hurt.damageFlags & DAMAGE_POOP; + if (isPoop && isCarrionQueen) return true; + if (isSpikes && entity.is_player() && !hurt.isIgnoreGridCollisionClass) + { + Entity_Player& player = *entity.ToPlayer(); + if (player.HasTrinket(TRINKET_CALLUS) || player.HasCollectible(COLLECTIBLE_SOCKS)) return true; + } + if (!entity.IsFamiliar()) return false; + return (isPoop && entity.variant == Entity_Familiar::DIP) || entity.variant == Entity_Familiar::WISP || + entity.variant == Entity_Familiar::ITEM_WISP || entity.variant == Entity_Familiar::BLOOD_BABY; +} + +// Lowers a spike offer's spikes once they hurt the player (or Isaac's Heart): on the second hit, or one time in two +// on the first unless Judas' Tongue is strong enough. The nearest spike offer stops pricing itself and a collectible +// one takes its paid state. +static void spike_offer_pay(GridEntity& spikes) +{ + spikes.varData++; + RNG payRng = {spikes.spawnSeed, 5, 9, 7}; + bool isFirstHit = spikes.varData < 2; + if (isFirstHit && payRng.RandomInt(2) != 0 && + g_game->playerManager.GetTrinketMultiplier(TRINKET_JUDAS_TONGUE) < JUDAS_TONGUE_SURE_PAY) + return; + + Vector position = spikes.Position(); + Entity_Pickup* nearest = nullptr; + float best = FLT_MAX; + for (Entity* entity : entity_query(ENTITY_PICKUP, PICKUP_COLLECTIBLE)) + { + Entity_Pickup* pickup = dynamic_cast(entity); + if (!pickup || pickup->price != PRICE_SPIKES_OFFER) continue; + Vector offset = vector_sub(pickup->pos, position); + float distance = offset.y * offset.y + offset.x * offset.x; + if (distance >= best) continue; + nearest = pickup; + best = distance; + } + if (nearest) + { + nearest->update_price_sprite(0); + nearest->isAutoUpdatePrice = false; + if (nearest->variant == PICKUP_COLLECTIBLE) nearest->state = 1; + } + static_cast(spikes).unsummon(false); +} + +// Spawns count pickups of a kind on free spots near a position, each seeded from the reward rng. +static void sacrifice_pickups_spawn(RNG& reward, const Vector& near, int variant, int subType, int count) +{ + for (; count > 0; count--) + { + uint32_t seed = reward.Next(); + Vector position = room_free_pickup_position_find({.position = near}); + g_game->Spawn({.position = position, .subType = subType, .type = ENTITY_PICKUP, .variant = variant, .seed = seed}); + } +} + +// Raises the angel room chance with the blessed fortune. +static void sacrifice_bless(float chance) +{ + g_game->angelRoomChance += chance; + std::string text(g_manager->stringTable.translate("#YOU_FEEL_BLESSED")); + g_game->hud.show_fortune_text_impl(text.c_str()); +} + +// A sacrifice-like spike's reward (a layout variant of 100 and up): six pennies, Sanguine Bond's effect for a while, +// two black hearts, a collectible or a Leviathan step, by one roll. +static void sacrifice_like_reward(GridEntity& spikes, RNG& reward, Entity_Player* rewardPlayer) +{ + Vector position = spikes.Position(); + float roll = reward.RandomFloat(); + if (roll < SACRIFICE_LIKE_COINS) + sacrifice_pickups_spawn(reward, position, PICKUP_COIN, COIN_PENNY, SACRIFICE_LIKE_COIN_COUNT); + else if (roll < SACRIFICE_LIKE_BLOOD) + { + if (rewardPlayer) rewardPlayer->temporaryEffects.AddCollectibleEffect(COLLECTIBLE_SANGUINE_BOND, false, 1); + } + else if (roll < SACRIFICE_LIKE_HEARTS) + sacrifice_pickups_spawn(reward, position, PICKUP_HEART, HEART_BLACK, 2); + else if (roll < SACRIFICE_LIKE_ITEM) + sacrifice_pickups_spawn(reward, position, PICKUP_COLLECTIBLE, 0, 1); + else if (roll < SACRIFICE_LIKE_FORM && rewardPlayer) + rewardPlayer->IncrementPlayerFormCounter(PLAYER_FORM_EVIL_ANGEL, SACRIFICE_LIKE_FORM_STEPS); +} + +// The sacrifice room's twelfth and later reward: half the time, unless the run ends before the Dark Room or Cathedral +// or plays Greed, the player is taken up a floor, or from the Dark Room's floor back to its start. +// The game animates the sacrificing player without checking one was found. Here no one is animated then. +static void sacrifice_ascend(RNG& reward, Entity_Player* player) +{ + Game& game = *g_game; + if (reward.RandomInt(2) != 0 || game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER) return; + + ChallengeParam& params = game.GetChallengeParams(); + bool isLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_SACRIFICE_DARK_ROOM] && + (g_manager->state != MANAGER_STATE_GAME || !game.isDebug); + int endStage = SACRIFICE_END_STAGE; + if (params.endStage != SACRIFICE_END_STAGE && (game.challenge != 0 || game.dailyChallenge._id != 0 || isLocked)) + endStage = SACRIFICE_END_STAGE - 1; + if (params.isPathTypeSet) + { + if (params.pathType == PATH_TYPE_CATHEDRAL) return; + if (params.endStage != 0) endStage = params.endStage; + if (params.pathType == PATH_TYPE_HOME) return; + } + if (endStage <= SACRIFICE_ASCEND_MIN_END) return; + + if (game.stage == STAGE_SHEOL_DARK_ROOM && game.stageType == 0) + { + game.leaveDoor = -1; + game.StartRoomTransition({.player = player, .animation = TRANSITION_TELEPORT, .dimension = 0, + .roomIndex = game.startingRoomIdx}); + return; + } + game.stageTransition.start({.type = STAGE_TRANSITION_SHEOL}); + if (player) player->PlayExtraAnimation("TeleportUp"); + grid_sound_play(SOUND_HELL_PORTAL2); +} + +// A sacrifice room's reward for its count of sacrifices so far, each by its own roll. +static void sacrifice_room_reward(int sacrifices, RNG& reward, Entity_Player* player) +{ + Vector center = vector_make(SACRIFICE_DROP_X, SACRIFICE_DROP_Y); + Game& game = *g_game; + switch (sacrifices) + { + case 0: + case 1: + if ((game.levelStateFlags & 1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED) && game.GetPlayer(0)->numBombs < 1) + { + reward.Next(); + sacrifice_pickups_spawn(reward, center, PICKUP_BOMB, BOMB_NORMAL, 1); + } + else if (reward.RandomInt(2) == 0) + sacrifice_pickups_spawn(reward, center, PICKUP_COIN, COIN_PENNY, 1); + break; + case 2: + if (reward.RandomInt(2) == 0) sacrifice_bless(SACRIFICE_BLESS_SMALL); + break; + case 3: + if (reward.RandomInt(2) == 0) sacrifice_pickups_spawn(reward, center, PICKUP_CHEST, 0, 1); + break; + case 4: + if (reward.RandomInt(2) != 0) sacrifice_pickups_spawn(reward, center, PICKUP_COIN, COIN_PENNY, 3); + else sacrifice_bless(SACRIFICE_BLESS_LARGE); + break; + case 5: + if (reward.RandomInt(3) != 0) + { + sacrifice_pickups_spawn(reward, center, PICKUP_CHEST, 0, 1); + break; + } + game.InitializeDevilAngelRoom(true, false); + game.leaveDoor = -1; + game.InitializeDevilAngelRoom(false, false); + game.StartRoomTransition({.player = player, .animation = TRANSITION_TELEPORT, .roomIndex = -1}); + break; + case 6: + { + uint32_t pick = reward.RandomInt(3); + if (pick == 0) + { + uint32_t seed = reward.Next(); + int item = game.itemPool.GetCollectible(POOL_ANGEL, reward.Next(), 0, 0, 0); + Vector position = room_free_pickup_position_find({.position = center}); + game.Spawn({.position = position, .subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + } + else if (pick == 2 && game.devilRoomDeals >= 1 && + game.itemPool.is_collectible_available(COLLECTIBLE_REDEMPTION, UNLOCK_CHECKED) && + game.stage <= SACRIFICE_REDEMPTION_LAST_STAGE) + sacrifice_pickups_spawn(reward, center, PICKUP_COLLECTIBLE, COLLECTIBLE_REDEMPTION, 1); + else sacrifice_pickups_spawn(reward, center, PICKUP_HEART, HEART_SOUL, 1); + break; + } + case 7: + game.room->unknown7230 = SACRIFICE_ANGEL_DELAY; + break; + case 8: + case 10: + { + uint32_t seed = reward.Next(); + Vector position = room_free_pickup_position_find({.position = center}); + int angel = sacrifices == 8 ? ENTITY_URIEL : ENTITY_GABRIEL; + game.Spawn({.position = position, .type = angel, .seed = seed})->Update(); + break; + } + case 9: + if (reward.RandomInt(2) != 0) sacrifice_pickups_spawn(reward, center, PICKUP_COIN, COIN_PENNY, 30); + else sacrifice_pickups_spawn(reward, center, PICKUP_HEART, HEART_SOUL, 7); + break; + default: + sacrifice_ascend(reward, player); + break; + } +} + +// Rewards a player's sacrifice on a sacrifice room's spikes (or a sacrifice-like spike), once per hit until the room +// is done. The reward goes to Tainted Forgotten rather than his soul. +static void sacrifice_reward(GridEntity& spikes, Entity& victim) +{ + bool isSacrificeLike = (uint32_t)spikes.variant >= SPIKES_LAYOUT_VARIANTS; + if (g_game->room->roomType != ROOM_SACRIFICE && !isSacrificeLike) return; + if (g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE) return; + + Entity* spawner = victim.GetLastSpawner(); + Entity_Player* player = spawner && spawner->is_player() ? spawner->ToPlayer() : nullptr; + Entity_Player* rewardPlayer = player; + if (player && player->playerType == PLAYER_THESOUL_B && player->twinPlayer) + rewardPlayer = player->twinPlayer->ToPlayer(); + + RNG reward = {spikes.rng.Next(), 1, 5, 19}; + int sacrifices = spikes.varData++; + if (isSacrificeLike) sacrifice_like_reward(spikes, reward, rewardPlayer); + else sacrifice_room_reward(sacrifices, reward, player); + spikes.variableSeed = spikes.rng._seed; +} + +// 00709fb0 Hurts one entity the way a grid entity does, from it as the source: a player (or Isaac's Heart) takes the +// player damage, halved for a strong Callus on a sacrifice room's spikes, and leaves bloody footprints on spikes. +// What it hurts is pushed away, fire hisses, and spikes pay out a spike offer or a sacrifice. +void GridEntity::hurt_func(Entity& entity, const GridHurt& hurt) +{ + if (is_spared(entity, hurt)) return; + + EntityRef source; + source.type = ENTITY_NULL; + source.variant = type; + float damage = hurt.damage; + bool isPlayerLike = entity.is_player() || (entity.IsFamiliar() && (entity.variant == Entity_Familiar::ISAACS_HEART || + entity.variant == Entity_Familiar::PUNCHING_BAG)); + bool isSpikes = hurt.damageFlags & DAMAGE_SPIKES; + if (isPlayerLike && !g_game->deathmatchManager.is_active()) + { + damage = (float)hurt.playerDamage; + Entity* ancestor = entity.GetPlayerAncestor(); + bool isStrongCallus = ancestor && ancestor->ToPlayer()->GetTrinketMultiplier(TRINKET_CALLUS) > 1; + if (isStrongCallus && g_game->room->roomType == ROOM_SACRIFICE && type == GRID_SPIKES) damage *= 0.5f; + } + if (isPlayerLike && entity.is_player() && isSpikes) + entity.ToPlayer()->SetFootprintColor(kcolor_rgba(SPIKES_FOOTPRINT_RED, 0, 0, 1), true); + if (entity.isInvincible || !entity.TakeDamage(damage, hurt.damageFlags, source, GRID_HURT_COOLDOWN)) return; + + if (hurt.damageFlags & DAMAGE_FIRE) + grid_sound_play(SOUND_FIREDEATH_HISS, {.volume = std::min(entity.health * FIRE_HISS_PER_HEALTH + FIRE_HISS_BASE, 1.0f)}); + Vector push = vector_normalized(vector_sub(entity.pos, Position())); + entity.velocity = vector_add(entity.velocity, vector_scale(push, GRID_HURT_PUSH)); + + bool isSacrificer = entity.is_player() || (entity.IsFamiliar() && entity.variant == Entity_Familiar::ISAACS_HEART); + if (!isSacrificer || !isSpikes) return; + if (type == GRID_SPIKES_ALT) spike_offer_pay(*this); + else if (type == GRID_SPIKES) sacrifice_reward(*this, entity); } // 0070b170 Hurts every colliding entity near the cell, players within their own distance. diff --git a/src/grid_entity_decoration.cpp b/src/grid_entity_decoration.cpp index 9eff794..a5b519c 100644 --- a/src/grid_entity_decoration.cpp +++ b/src/grid_entity_decoration.cpp @@ -8,12 +8,6 @@ #include #include -constexpr int BACKDROP_CAVES = 4; -constexpr int BACKDROP_CATACOMBS = 5; -constexpr int BACKDROP_GREED_SHOP = 20; -constexpr int BACKDROP_DUNGEON_GIDEON = 55; -constexpr int BACKDROP_DUNGEON_ROTGUT = 56; - // The G FUEL seed's props: on the second and later floors, every fifth seed, and always on these stages. constexpr int GFUEL_STAGES[] = {3, 4, 11}; constexpr uint32_t GFUEL_SEED_STEP = 5; @@ -58,7 +52,7 @@ void GridEntity_Decoration::subclass_init() sprite.Play("Ladder3"); return; } - if (isGreed && (variant == DECORATION_LADDER_LOW || backdrop == BACKDROP_GREED_SHOP)) + if (isGreed && (variant == DECORATION_LADDER_LOW || backdrop == BACKDROP_SHOP)) { sprite.Load("gfx/grid/Props_12_Greed.anm2", GRAPHICS_LOAD); sprite.PlayRandom(rng.Next()); diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index f223356..8760292 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -1,5 +1,6 @@ #include "grid_entity_door.h" #include "entity_familiar.h" +#include "entity_npc.h" #include "game.h" #include "log.h" #include "manager.h" @@ -12,13 +13,8 @@ constexpr int DOOR_TARGET_MIRROR = -100; 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_VOID = 12; -constexpr uint32_t STAGE_HOME = 13; constexpr int DIMENSION_MIRROR = 1; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; -constexpr int STAGE_ID_HOME = 35; -constexpr int BACKDROP_DARK_ROOM = 16; // The secret exits get_secret_exit_kind tells apart, by the exit room's subtype, and the boss subtype of Mom's Heart's // exit. @@ -44,7 +40,6 @@ constexpr uint64_t GAME_STATE_HEART_EXIT_OPENED = 1ull << 52; constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; constexpr int FAMILIAR_KEY_FULL = 236; constexpr int FAMILIAR_STATE_KEY_DOOR = 1; -constexpr int ONLINE_STAT_SECRET_DOORS_BOMBED = 19; // How far a door's sprite stands out from the wall, and the angles its sprites turn to by direction. constexpr float DOOR_SPRITE_OFFSET = 15; @@ -58,7 +53,6 @@ constexpr int DOOR_SOUND_DELAY = 10; constexpr int SOUND_DOOR_HEAVY_CLOSE = 35; 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 float GROUNDPOUND_PITCH = 0.33f; @@ -72,8 +66,10 @@ constexpr int DOOR_REOPEN_DELAY = 30; // The cursed door's spikes, as a box around the door's cell by direction: left, top, right and bottom. constexpr float SPIKE_BOXES[4][4] = {{-43, -20, 15, 20}, {-20, -43, 20, 15}, {-15, -20, 43, 20}, {-20, -15, 20, 43}}; -constexpr uint64_t DAMAGE_CURSED_DOOR = 1ull << 16; -constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; + +// How long a door's opening shakes the screen, and the Mausoleum's secret exit's. +constexpr int DOOR_SHAKE_FRAMES = 4; +constexpr int MAUSOLEUM_DOOR_SHAKE_FRAMES = 8; // The Shiny Rock's sparkle: every so many frames, faster with a stronger rock. constexpr int SPARKLE_PERIOD = 300; @@ -943,10 +939,10 @@ void GridEntity_Door::Update() if (sprite.animState.animData) { if (sprite.WasEventTriggered("ScreenshakeStop")) - reconstruction_missing("GridEntity_Door::Update 0070c5c0: Game::ShakeScreen"); + game_shake_screen(0); else if (sprite.WasEventTriggered("ScreenshakeStart")) { - reconstruction_missing("GridEntity_Door::Update 0070c5c0: Game::ShakeScreen"); + game_shake_screen(DOOR_SHAKE_FRAMES); if (sprite.IsEventTriggered("ScreenshakeStart")) grid_sound_play(SOUND_HELLBOSS_GROUNDPOUND, {.pitch = GROUNDPOUND_PITCH}); } @@ -966,7 +962,10 @@ void GridEntity_Door::Update() } } if (sprite.IsEventTriggered("FX")) - reconstruction_missing("GridEntity_Door::Update 0070c5c0: Game::ShakeScreen and SpawnDust"); + { + game_shake_screen(MAUSOLEUM_DOOR_SHAKE_FRAMES); + SpawnDust(); + } } RoomDescriptor* target = g_game->GetRoomByIdx(targetRoomIdx); @@ -1184,6 +1183,6 @@ bool GridEntity_Door::Destroy(bool, const EntityRef& source) if (g_game->GetRoomByIdx(targetRoomIdx)->visitedCount == 0 && source.entity) if (Entity* player = source.entity->GetPlayerAncestor()) - Player_stats_add(&g_game->onlinePlayerStats, ONLINE_STAT_SECRET_DOORS_BOMBED, (Entity_Player*)player, 1); + Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_SECRET_DOORS_BOMBED, (Entity_Player*)player, 1); return isBlownOpen; } diff --git a/src/grid_entity_lock.cpp b/src/grid_entity_lock.cpp index d08fff7..2db04a1 100644 --- a/src/grid_entity_lock.cpp +++ b/src/grid_entity_lock.cpp @@ -1,16 +1,53 @@ #include "grid_entity_lock.h" -#include "log.h" +#include "entity_pickup.h" +#include "game.h" +#include "room.h" -// 00711780 Loads the block, a coin block under Pay To Play. +// The grid path a standing block claims, and how near a player must come to open it. +constexpr int GRID_PATH_LOCK = 4000; +constexpr float UNLOCK_DISTANCE_SQUARED = 961; + +// A broken block's drop: one time in ten, a heart a quarter of the time (Daemon's Tail takes some back), else a penny. +constexpr float LOCK_DROP_CHANCE = 0.1f; +constexpr float LOCK_HEART_CHANCE = 0.25f; + +// 00711780 Loads the block, a coin block under Pay To Play, standing solid or already broken. void GridEntity_Lock::subclass_init() { - reconstruction_missing("GridEntity_Lock::subclass_init 00711780"); + sprite.Load("gfx/grid/grid_locks.anm2", GRAPHICS_LOAD); + isCoinLock = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_PAY_TO_PLAY, LAZARUS_SHARE_CHECK); + if (state != 0) + { + sprite.SetFrame("Broken", 0); + collisionClass = COLLISION_NONE; + return; + } + + sprite.SetFrame(isCoinLock ? "IdleCoin" : "Idle", 0); + collisionClass = COLLISION_WALL; + path_set(GRID_PATH_LOCK); } -// 00711950 Animates the block and unblocks the cell once it breaks. +// 00711950 Frees the cell once the breaking animation breaks, and lets the players near a standing block open it. void GridEntity_Lock::Update() { - reconstruction_missing("GridEntity_Lock::Update 00711950"); + if (sprite.animState.animData && sprite.IsEventTriggered("Break")) + { + collisionClass = COLLISION_NONE; + path_set(0); + } + if (state == 0) + { + Vector position = Position(); + for (size_t i = 0; i < g_game->playerManager.playerList.size(); i++) + { + Entity_Player* player = g_game->playerManager.playerList[i]; + Vector offset = vector_make(player->pos.x - position.x, player->pos.y - position.y); + bool isNear = offset.y * offset.y + offset.x * offset.x < UNLOCK_DISTANCE_SQUARED; + if (player->variant == PLAYER_VARIANT_PLAYER && isNear) try_unlock(*player, false); + } + } + sprite.Update(); } // 00711f30 Draws the sprite on its cell. @@ -25,14 +62,43 @@ WaterClipInfo GridEntity_Lock::GetWaterClipInfo() return {collisionClass != COLLISION_NONE ? WATER_CLIP_SOLID : WATER_CLIP_FLAT, 0}; } -// 00711af0 Breaks the block with a player's key or coins. -void GridEntity_Lock::try_unlock(Entity_Player&, bool) +// 00711af0 Breaks the standing block with a player's key (Paper Clip's strong form needs none) or, under Pay To Play, +// a coin. Forced, it costs nothing. +void GridEntity_Lock::try_unlock(Entity_Player& player, bool isForce) { - reconstruction_missing("GridEntity_Lock::try_unlock 00711af0"); + if (state != 0) return; + + if (!isForce && !isCoinLock && player.GetTrinketMultiplier(TRINKET_PAPER_CLIP) < 2 && !player.TryUseKey()) return; + if (!isForce && isCoinLock) + { + if (player.numCoins < 1) return; + player.AddCoins(-1); + } + grid_sound_play(isCoinLock ? SOUND_COIN_INSERT : SOUND_UNLOCK); + break_open(&player); } -// 00711bb0 Breaks the block open. -void GridEntity_Lock::break_open(Entity_Player&) +// 00711bb0 Breaks the block open (golden with a golden key), and one time in ten drops a heart or a penny. A block +// broken by no one counts the first player with Daemon's Tail. +void GridEntity_Lock::break_open(Entity_Player* player) { - reconstruction_missing("GridEntity_Lock::break_open 00711bb0"); + grid_sound_play(SOUND_METAL_BLOCKBREAK); + if (isCoinLock) sprite.Play("BreakingCoin"); + else sprite.Play(player && player->hasGoldenKey ? "BreakingGolden" : "Breaking"); + state = 1; + + RNG dropRng = {spawnSeed, 1, 5, 16}; + if (dropRng.RandomFloat() >= LOCK_DROP_CHANCE) return; + if (!player) + for (Entity_Player* candidate : g_game->playerManager.playerList) + if (candidate->variant == PLAYER_VARIANT_PLAYER && candidate->HasTrinket(TRINKET_DAEMONS_TAIL)) + { + player = candidate; + break; + } + + bool isHeart = dropRng.RandomFloat() < LOCK_HEART_CHANCE && + (!player || player->GetTrinketRNG(TRINKET_DAEMONS_TAIL).Next() % DAEMONS_TAIL_ODDS == 0); + g_game->Spawn({.position = Position(), .type = ENTITY_PICKUP, .variant = isHeart ? PICKUP_HEART : PICKUP_COIN, + .seed = dropRng.Next()}); } diff --git a/src/grid_entity_lock.h b/src/grid_entity_lock.h index f87b6bf..412804e 100644 --- a/src/grid_entity_lock.h +++ b/src/grid_entity_lock.h @@ -14,5 +14,5 @@ struct GridEntity_Lock : GridEntity void Render(const Vector& offset) override; WaterClipInfo GetWaterClipInfo() override; void try_unlock(Entity_Player& player, bool isForce); - void break_open(Entity_Player& player); + void break_open(Entity_Player* player); }; diff --git a/src/grid_entity_pit.cpp b/src/grid_entity_pit.cpp index d0aca04..84207b5 100644 --- a/src/grid_entity_pit.cpp +++ b/src/grid_entity_pit.cpp @@ -1,38 +1,308 @@ #include "grid_entity_pit.h" +#include "entity_effect.h" +#include "entity_player.h" #include "game.h" #include "grid_entity_rock.h" #include "log.h" #include "room.h" +#include "room_config.h" +#include +#include // The grid path a pit claims, and a spiked bridge's. constexpr int GRID_PATH_PIT = 3000; constexpr int GRID_PATH_SPIKED_BRIDGE = 999; +// A layout pit's variant: its frame in the low byte, the event flag, and the rails above it. +constexpr int PIT_VARIANT_FRAME = 0xff; +constexpr int PIT_VARIANT_EVENT = 0x80; +constexpr int PIT_VARIANT_RAILS = 0xff00; +constexpr int PIT_RAILS_SHIFT = 8; + +// The neighbours a pit's frame counts, by bit. +constexpr int PIT_EDGE_LEFT = 1 << 0; +constexpr int PIT_EDGE_UP = 1 << 1; +constexpr int PIT_EDGE_RIGHT = 1 << 2; +constexpr int PIT_EDGE_DOWN = 1 << 3; + +// An event pit's countdown fills it at this varData, and once filled it holds the done value. +constexpr int PIT_EVENT_COUNTDOWN_END = 10; +constexpr int PIT_EVENT_DONE = 2; + +// The challenge that mixes backdrops, how often a pit picks from its own seed, the death certificate dimension, the +// Flooded Caves' stage id and the water the G Fuel seed curses, and the sprite's offset. +constexpr uint32_t CHALLENGE_MIXED_PITS = 45; +constexpr uint32_t MIXED_PIT_ODDS = 10; +constexpr int DIMENSION_UNCURSED_WATER = 2; +constexpr float VERY_CURSED_WATER = 0.5f; +constexpr float PIT_SPRITE_OFFSET = 2; + +// A spiked bridge's hurt. +constexpr float BRIDGE_SPIKES_DISTANCE = 11; +constexpr float BRIDGE_SPIKES_DAMAGE = 8; +constexpr int BRIDGE_SPIKES_PLAYER_DAMAGE = 2; + +// The pits' life: the mineshaft's dust (one in 40 frames, its tint, spin, life and size), the Mines' embers (one in +// 20 frames over hot lava), and the Dank Depths' tar bubbles (checked every 10 frames, one in 6). +constexpr float PIT_RANDOM_UNIT = 2.3283064e-10f; +constexpr uint32_t MINESHAFT_DUST_ODDS = 40; +constexpr int MINESHAFT_DUST_SUBTYPE = 2; +constexpr float MINESHAFT_DUST_ALPHA_MIN = 0.1f; +constexpr float MINESHAFT_DUST_ALPHA_RANGE = 0.2f; +constexpr float MINESHAFT_DUST_SPIN_MIN = 2; +constexpr float MINESHAFT_DUST_SPIN_RANGE = 10; +constexpr int MINESHAFT_DUST_LIFE_MIN = 20; +constexpr uint32_t MINESHAFT_DUST_LIFE_RANGE = 30; +constexpr float MINESHAFT_DUST_SCALE_MIN = 0.8f; +constexpr float MINESHAFT_DUST_SCALE_RANGE = 0.2f; +constexpr float LAVA_HOT = 0.5f; +constexpr uint32_t LAVA_EMBER_ODDS = 20; +constexpr float LAVA_EMBER_RISE = -1.2800001f; +constexpr float LAVA_EMBER_DRIFT = 0.4f; +constexpr float LAVA_EMBER_SPREAD = 18; +constexpr int TAR_CHECK_FRAMES = 10; +constexpr uint32_t TAR_BUBBLE_ODDS = 6; +constexpr float TAR_SPREAD = 15; + // Lava cooler than this leaves the Mines' lava pits walkable. constexpr float LAVA_COOLED = 0.2f; -// 00713760 Loads the pit's sprite from the backdrop, its edges joined to the pits around it. +// The backdrop a pit's acid comes from under the challenge that mixes backdrops: one time in ten by the pit's own +// seed, else the floor's, among the backdrops with pits. +static int pit_backdrop_get(GridEntity_Pit& pit) +{ + Room& room = *g_game->room; + if (g_game->challenge != CHALLENGE_MIXED_PITS) return room.backdropType; + + RNG pick = {pit.spawnSeed, 2, 15, 25}; + RNG mixed = pick.Next() % MIXED_PIT_ODDS == 0 ? RNG{pit.spawnSeed, 5, 9, 7} + : RNG{g_game->dungeonPlacementSeed, 2, 15, 25}; + BackdropConfig& config = room.backdrop.configs[1 + mixed.Next() % (BACKDROP_COUNT - 1)]; + return config.pit.empty() ? room.backdropType : config.backdropId; +} + +// The G Fuel seed's cursed water in the Flooded Caves. +static bool is_very_cursed_water() +{ + Game& game = *g_game; + int stageType = 0; + if (game.challenge == CHALLENGE_RED_REDEMPTION) stageType = game.GetRoomStageType(game.currentRoomIdx); + else if (game.currentDimensionIdx != DIMENSION_UNCURSED_WATER) stageType = (int)game.stageType; + else return false; + + return RoomConfig::GetStageID((int)game.stage, stageType, ROOM_MODE_CURRENT) == STAGE_ID_FLOODED_CAVES && + game.seedEffects.HasSeedEffect(SEED_G_FUEL) && game.room->waterAmount > VERY_CURSED_WATER; +} + +// 00713760 Loads the pit from the backdrop: dry, or water with its highlights from a random frame (the womb's +// sometimes acid), with the backdrop's rocks as its bridge. An event pit's variant carries its flag and its rails. void GridEntity_Pit::subclass_init() { - reconstruction_missing("GridEntity_Pit::subclass_init 00713760"); + Room& room = *g_game->room; + if (variant & PIT_VARIANT_EVENT) + { + variant &= ~PIT_VARIANT_EVENT; + varData = 1; + } + if (variant & PIT_VARIANT_RAILS) room.railManager.rails[gridIndex] = (uint8_t)(variant >> PIT_RAILS_SHIFT); + hasLadder = false; + int backdrop = pit_backdrop_get(*this); + + BackdropConfig& config = room.backdrop.configs[room.backdropType]; + if (!(room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER)) + { + sprite.Load("gfx/grid/grid_pit.anm2", GRAPHICS_DEFER); + sprite.ReplaceSpritesheet(0, config.pit); + } + else + { + sprite.Load("gfx/grid/grid_pit_water.anm2", GRAPHICS_DEFER); + sprite.PlayOverlay("highlights"); + const AnimationData* highlights = sprite.GetAnimationData("highlights"); + int length = highlights ? highlights->length : 0; + int frame = length == 0 ? 0 : (int)(Random() % (uint32_t)length); + if (sprite.overlayAnimState.animData) sprite.overlayAnimState.SetFrameFloat((float)frame); + + std::string sheet = config.waterPit; + if (backdrop == BACKDROP_WOMB || backdrop == BACKDROP_UTERO) + { + RNG acid = {room.descriptor ? room.descriptor->decorationSeed : 0, 1, 5, 19}; + if (acid.Next() & 1) sheet = "gfx/grid/grid_pit_acid_womb.png"; + } + sprite.ReplaceSpritesheet(0, sheet); + } + if (is_very_cursed_water()) + sprite.ReplaceSpritesheet(0, "gfx/promo/gfuel/grid/grid_pit_floodedcaves_verycursed.png"); + sprite.ReplaceSpritesheet(1, config.rocks); + sprite.LoadGraphics(); + sprite.SetFrame("pit", 0); + sprite.offset = vector_make(PIT_SPRITE_OFFSET, PIT_SPRITE_OFFSET); } -// 00714320 Joins the pit's edges to its neighbours once the room is laid out. +// Whether a pit stands on a tile of the room. +static bool is_pit_at(Room& room, int column, int row) +{ + GridEntity* grid = room.GetGridEntity(room.GetGridIndexByTile(column, row)); + return grid && grid->type == GRID_PIT; +} + +// 00714320 Joins the pit's edges to its neighbours: its own while the room is laid out, else the whole block around +// it, swallowing the walking players standing in it (unless Mega Mush). The room's pits are redrawn. void GridEntity_Pit::PostInit() { - reconstruction_missing("GridEntity_Pit::PostInit 00714320"); + Game& game = *g_game; + Room& room = *game.room; + room.isUnknown11f6 = true; + if (!room.isInitialized || game.frameCount - room.enterFrame < 2) + { + update_sprite_edges(); + return UpdateCollision(); + } + + int column = (int)((uint32_t)gridIndex % (uint32_t)room.gridWidth); + int row = (int)((uint32_t)gridIndex / (uint32_t)room.gridWidth); + for (int dx = -1; dx <= 1; dx++) + for (int dy = -1; dy <= 1; dy++) + if (is_pit_at(room, column + dx, row + dy)) + static_cast(room.GetGridEntity(room.GetGridIndexByTile(column + dx, row + dy))) + ->update_sprite_edges(); + + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->entityGridCollisionClass <= GRIDCOLL_WALLS || player->pitfallState != 0) continue; + if (room.GetGridIndex(player->pos) != gridIndex) continue; + + player->pos = Position(); + if (player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) continue; + player->PlayExtraAnimation("FallIn"); + player->isControlsEnabled = false; + player->entityCollisionClass = ENTCOLL_NONE; + player->pitfallState = 1; + player->pitfallTimer = 0; + } + UpdateCollision(); } -// 00712180 Swallows what falls in, fills into a bridge and animates the lava. +// Shows the bridge layer's frame for the pit's state, only once bridged. +static void bridge_layer_update(GridEntity_Pit& pit) +{ + if (pit.sprite.layerStates.size() < 2) return; + + pit.sprite.SetLayerFrame(1, std::max(pit.state - PIT_STATE_FILLED, 0)); + pit.sprite.GetLayer(1)->isVisible = pit.state > PIT_STATE_BRIDGE_PENDING; +} + +// A pit's floating dust in the escaping mineshaft: red, additive, slowly turning and rising, gone in 20 to 49 frames. +static void mineshaft_dust_spawn(const Vector& position) +{ + float rise = (float)Random() * PIT_RANDOM_UNIT; + Vector velocity = vector_make(0, -1 - (rise + rise)); + uint32_t seed = Random(); + Entity* dust = g_game->Spawn({.position = position, .velocity = velocity, .subType = MINESHAFT_DUST_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed}); + LayerState* layer = dust->sprite.GetLayer(0); + layer->color = {{1, 0, 0, (float)Random() * PIT_RANDOM_UNIT * MINESHAFT_DUST_ALPHA_RANGE + MINESHAFT_DUST_ALPHA_MIN}, {0, 0, 0, 0}, {0, 0, 0}}; + KAGE::Graphics::BlendMode mode; + mode.SetMode(KAGE::Graphics::BLEND_ADDITIVE); + layer->blendMode = {mode.equation, mode.rgbSource, mode.rgbDest, mode.alphaSource, mode.alphaDest}; + + Entity_Effect& effect = static_cast(*dust); + effect.rotation = (float)Random() * PIT_RANDOM_UNIT * MINESHAFT_DUST_SPIN_RANGE + MINESHAFT_DUST_SPIN_MIN; + effect.timeout = (int)(Random() % MINESHAFT_DUST_LIFE_RANGE) + MINESHAFT_DUST_LIFE_MIN; + effect.lifespan = effect.timeout; + float scale = (float)Random() * PIT_RANDOM_UNIT * MINESHAFT_DUST_SCALE_RANGE + MINESHAFT_DUST_SCALE_MIN; + dust->sprite.scale = vector_make(scale, scale); + dust->Update(); +} + +// A lava pit's ember in the Mines, drifting up from somewhere on the cell. +static void lava_ember_spawn(const Vector& position) +{ + float rise = (float)Random() * PIT_RANDOM_UNIT * LAVA_EMBER_RISE; + float drift = ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * LAVA_EMBER_DRIFT; + float x = position.x + ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * LAVA_EMBER_SPREAD; + float y = position.y + ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * LAVA_EMBER_SPREAD; + uint32_t seed = Random(); + g_game->Spawn({.position = vector_make(x, y), .velocity = vector_make(drift, rise), .type = ENTITY_EFFECT, + .variant = EFFECT_EMBER_PARTICLE, .seed = seed}); +} + +// 00712180 Bridges a spiked bridge once its spikes go (plates or the Flat File), shows the bridge, hurts what walks +// a spiked one, fills an event pit when its countdown ends (passing the countdown on), and keeps the backdrop's pit +// life: the escaping mineshaft's dust, the Mines' lava embers and the Dank Depths' tar bubbles. void GridEntity_Pit::Update() { - reconstruction_missing("GridEntity_Pit::Update 00712180"); + Game& game = *g_game; + Room& room = *game.room; + RoomDescriptor* current = game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx); + bool isSpikesGone = (current->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED) || + game.playerManager.AnyoneHasTrinket(TRINKET_FLAT_FILE); + if (state == PIT_STATE_FILLED_SPIKED && isSpikesGone) state = PIT_STATE_FILLED; + sprite.Update(); + bridge_layer_update(*this); + if (state == PIT_STATE_FILLED_SPIKED) + hurt_surroundings({.damageFlags = DAMAGE_SPIKES | DAMAGE_NO_PENALTIES, .damage = BRIDGE_SPIKES_DAMAGE, + .distance = BRIDGE_SPIKES_DISTANCE, .playerDistance = BRIDGE_SPIKES_DISTANCE, + .playerDamage = BRIDGE_SPIKES_PLAYER_DAMAGE}); + + if (varData != 0) + { + if (varData == PIT_EVENT_COUNTDOWN_END) + { + varData = 1; + uint32_t seed = Random(); + game.Spawn({.position = Position(), .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + grid_sound_play(SOUND_ROCK_CRUMBLE); + if (state == PIT_STATE_EMPTY || state == PIT_STATE_BRIDGE_PENDING) + { + state = PIT_STATE_FILLED; + UpdateCollision(); + } + } + else if (varData > PIT_EVENT_COUNTDOWN_END) + varData--; + if (state > PIT_STATE_BRIDGE_PENDING && varData != PIT_EVENT_DONE) + { + varData = PIT_EVENT_DONE; + grid_mark_neighbors_dirty(gridIndex); + } + } + + bool isWater = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER; + if (room.backdropType != BACKDROP_MINES) + { + bool isShaft = room.backdropType == BACKDROP_MINES_SHAFT || room.backdropType == BACKDROP_ASHPIT_SHAFT; + if (isShaft && (game.levelStateFlags & 1u << LEVEL_STATE_MINESHAFT_ESCAPE) && state == PIT_STATE_EMPTY && + Random() % MINESHAFT_DUST_ODDS == 0) + mineshaft_dust_spawn(Position()); + } + else if (isWater && room.lavaIntensity > LAVA_HOT && state == PIT_STATE_EMPTY && Random() % LAVA_EMBER_ODDS == 0) + lava_ember_spawn(Position()); + + if (game.frameCount % TAR_CHECK_FRAMES != 0 || !isWater || room.backdropType != BACKDROP_DANK_DEPTHS || + state != PIT_STATE_EMPTY || Random() % TAR_BUBBLE_ODDS != 0) + return; + Vector position = Position(); + position.x += ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * TAR_SPREAD; + position.y += ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * TAR_SPREAD; + uint32_t seed = Random(); + game.Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_TAR_BUBBLE, .seed = seed}); } -// 00713440 Draws the pit or its bridge. -void GridEntity_Pit::Render(const Vector&) +// 00713440 Draws the pit in the floor's color, its bridge (when shown) drawn over it on its own. +void GridEntity_Pit::Render(const Vector& offset) { - reconstruction_missing("GridEntity_Pit::Render 00713440"); + sprite.color = g_game->room->floorColor; + Vector position = get_render_position(); + SpriteDraw draw = {.position = vector_make(position.x + offset.x, position.y + offset.y)}; + if (sprite.layerStates.size() < 2) return sprite.Render(draw); + + LayerState* bridge = sprite.GetLayer(1); + bool isBridgeVisible = bridge->isVisible; + bridge->isVisible = false; + sprite.Render(draw); + bridge->isVisible = isBridgeVisible; + if (isBridgeVisible) sprite.RenderLayer(1, draw); } // 00714750 Water lies flat over the pit. @@ -41,10 +311,69 @@ WaterClipInfo GridEntity_Pit::GetWaterClipInfo() return {WATER_CLIP_FLAT, 0}; } -// 00713ee0 Picks the pit's frame from the pits around it. +// 00713ee0 Picks the pit's frame from the pits beside it (a lone pit one of two at random), then from the diagonal +// ones where two sides meet, and keeps it in the variant's low byte. The bridge layer follows the state. void GridEntity_Pit::update_sprite_edges() { - reconstruction_missing("GridEntity_Pit::update_sprite_edges 00713ee0"); + Room& room = *g_game->room; + int column = (int)((uint32_t)gridIndex % (uint32_t)room.gridWidth); + int row = (int)((uint32_t)gridIndex / (uint32_t)room.gridWidth); + auto isPit = [&room, column, row](int dx, int dy) { return is_pit_at(room, column + dx, row + dy); }; + + int frame = (isPit(-1, 0) ? PIT_EDGE_LEFT : 0) | (isPit(0, -1) ? PIT_EDGE_UP : 0) | + (isPit(1, 0) ? PIT_EDGE_RIGHT : 0) | (isPit(0, 1) ? PIT_EDGE_DOWN : 0); + if (frame == 0) frame = (int)(Random() & 1) << 4; + + bool isOpenUpLeft = !isPit(-1, -1); + bool isOpenUpRight = !isPit(1, -1); + bool isOpenDownLeft = !isPit(-1, 1); + bool isOpenDownRight = !isPit(1, 1); + switch (frame) + { + case PIT_EDGE_LEFT | PIT_EDGE_UP: + if (isOpenUpLeft) frame += 14; + break; + case PIT_EDGE_UP | PIT_EDGE_RIGHT: + if (isOpenUpRight) frame += 12; + break; + case PIT_EDGE_LEFT | PIT_EDGE_UP | PIT_EDGE_RIGHT: + { + int corners = (isOpenUpRight ? 1 : 0) + (isOpenUpLeft ? 2 : 0); + if (corners != 0) frame = corners + 26; + break; + } + case PIT_EDGE_LEFT | PIT_EDGE_DOWN: + if (isOpenDownLeft) frame += 10; + break; + case PIT_EDGE_LEFT | PIT_EDGE_UP | PIT_EDGE_DOWN: + if (isOpenUpLeft) frame += 15; + break; + case PIT_EDGE_RIGHT | PIT_EDGE_DOWN: + if (isOpenDownRight) frame += 8; + break; + case PIT_EDGE_LEFT | PIT_EDGE_RIGHT | PIT_EDGE_DOWN: + { + int corners = (isOpenDownRight ? 1 : 0) + (isOpenDownLeft ? 2 : 0); + if (corners != 0) frame = corners + 29; + break; + } + case PIT_EDGE_UP | PIT_EDGE_RIGHT | PIT_EDGE_DOWN: + if (isOpenUpRight) frame += 11; + break; + case PIT_EDGE_LEFT | PIT_EDGE_UP | PIT_EDGE_RIGHT | PIT_EDGE_DOWN: + { + int corners = (isOpenUpLeft ? 1 : 0) + (isOpenUpRight ? 2 : 0); + if (corners != 0) frame = corners + 20; + else frame = isOpenDownLeft && isOpenDownRight ? 24 : 15; + break; + } + default: + break; + } + + sprite.SetFrame("pit", frame); + bridge_layer_update(*this); + variant = (variant & ~PIT_VARIANT_FRAME) | frame; } // 00714610 Claims the cell as a pit (climbable with a ladder) until it is bridged. Cooled lava claims nothing. diff --git a/src/grid_entity_poop.cpp b/src/grid_entity_poop.cpp index 5971bf8..d5b5d05 100644 --- a/src/grid_entity_poop.cpp +++ b/src/grid_entity_poop.cpp @@ -1,40 +1,509 @@ #include "grid_entity_poop.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "entity_npc.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_grid.h" +#include "room_special.h" +#include "seeds.h" +#include +#include +#include +#include -// A red poop's state while it grows back, and how many frames that takes. -constexpr int POOP_STATE_REVIVING = 1000; +// How much of its state a hit breaks of a poop, a golden poop (50 to 124), a white poop and a giant poop, the giant +// poop's state per reward, and the stages a state shows. +constexpr int POOP_STATE_STEP = 250; +constexpr int GOLDEN_STATE_STEP_MIN = 50; +constexpr uint32_t GOLDEN_STATE_STEP_RANGE = 75; +constexpr int WHITE_STATE_STEP = 125; +constexpr int GIGA_STATE_STEP = 20; +constexpr int GIGA_ANIM_STEP = 10; +constexpr int POOP_STAGE_LAST_STANDING = 3; +constexpr int POOP_STAGE_BROKEN = 4; +constexpr uint32_t BONUS_HIT_ODDS = 3; + +// The grid path a standing poop claims, how long a red poop takes to grow back, and its burn. +constexpr int GRID_PATH_POOP = 1500; constexpr int RED_POOP_REVIVE_FRAMES = 120; +constexpr float RED_POOP_DISTANCE = 22.5f; +constexpr float RED_POOP_PLAYER_DISTANCE = 18.5f; +constexpr float RED_POOP_DAMAGE = 16; +constexpr float RED_POOP_VERSUS_DAMAGE = 4; +constexpr float RED_POOP_PULSE_SPEED = 0.25f; +constexpr float RED_POOP_PULSE = 0.1f; -// 00715940 Loads the poop for its variant and the seeds. +// How near a player stands to leave footprints, to have spawned inside the poop, or (for an enemy) to sit inside it, +// and how far the white poop's aura reaches and how long it lasts past the player leaving. +constexpr float FOOTPRINT_DISTANCE = 21; +constexpr float UNDER_PLAYER_DISTANCE = 20; +constexpr float UNDER_PLAYER_SPAWN_DISTANCE_SQUARED = 400; +constexpr float ENEMY_INSIDE_RADIUS = 16; +constexpr float HALLOWED_REACH = 70; +constexpr int HALLOWED_FRAMES = 4; +constexpr uint32_t HALLOWED_CACHE = CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_TEARFLAG | CACHE_TEARCOLOR; + +// Where the giant poop's parts sit on its two by two cells, and where each one's center lies from its own cell. +constexpr std::array, 4> GIGA_TILES = {{{0, 0}, {1, 0}, {0, 1}, {1, 1}}}; +constexpr std::array, 4> GIGA_CENTERS = {{{20, 20}, {-20, 20}, {20, -20}, {-20, -20}}}; +constexpr float GIGA_RENDER_OFFSET = 13; +constexpr std::array GIGA_OTHER_PARTS = {POOP_GIGA_TOP_LEFT, POOP_GIGA_TOP_RIGHT, POOP_GIGA_BOTTOM_RIGHT}; + +// The white poop's glow on its spawn layer and its aura's place, the poop enemies' eternal fly state, and the odds of +// Dirty Mind's dip and a reward from a giant poop hit. +constexpr ColorMod WHITE_POOP_COLOR = {{1, 1, 1, 1}, {1.9f, 2, 2, 1}, {0.1f, 0.3f, 0.4f}}; +constexpr float HALLOWED_AURA_RISE = -4; +constexpr int HALLOWED_AURA_Z = 10000; + +// The chances a broken poop drops at all (raised by Butt Penny and Petrified Poop, cut by ReduceSpawnRate), and what +// it drops: one in twenty its Petrified Poop, else a heart a quarter of the time (Daemon's Tail and Butt Penny take +// some back) or a penny. +constexpr float POOP_DROP_CHANCE = 0.1f; +constexpr float GIGA_DROP_CHANCE = 0.25f; +constexpr float LOW_DROP_CHANCE = 0.01f; +constexpr float BUTT_PENNY_BASE = 0.2f; +constexpr float PETRIFIED_BASE = 0.4f; +constexpr float POOP_TRINKET_STEP = 0.1f; +constexpr float HEART_CHANCE = 0.25f; +constexpr uint32_t PETRIFIED_ODDS = 20; +constexpr uint32_t BUTT_PENNY_HEART_ODDS = 3; + +// The golden poop's Counterfeit Penny (one in three) or its five to seven pennies, thrown clear of walls, and +// Meconium's black heart, per hundred by multiplier. +constexpr uint32_t COUNTERFEIT_ODDS = 3; +constexpr int GOLDEN_COINS_MIN = 5; +constexpr uint32_t GOLDEN_COINS_RANGE = 3; +constexpr int COIN_THROW_ATTEMPTS = 10; +constexpr float COIN_THROW_SPEED = 5; +constexpr float COIN_THROW_CHECK = 7; +constexpr uint32_t MECONIUM_ODDS = 5; +constexpr uint32_t MECONIUM_ODDS_DOUBLE = 7; +constexpr uint32_t MECONIUM_ODDS_TRIPLE = 10; +constexpr uint32_t MECONIUM_ROLL = 100; + +// The rainbow poop's giant book and event, the black poop's blast and cloud, Brown Cap's blast per multiplier, the +// Oh Crap form's heal and the broken poop event. +constexpr int GIANTBOOK_RAINBOW_POOP = 29; +constexpr int EVENT_RAINBOW_POOP_DESTROYED = 194; +constexpr int EVENT_POOP_DESTROYED = 5; +constexpr float BLACK_POOP_DAMAGE = 10; +constexpr int BLACK_POOP_DAMAGE_COOLDOWN = 30; +constexpr int BLACK_POOP_CONFUSION = 60; +constexpr ColorMod BLACK_POOP_CLOUD = {{0.01f, 0.01f, 0.01f, 1}, {0, 0, 0, 1}, {0, 0, 0}}; +constexpr float BROWN_CAP_DAMAGE = 100; +constexpr float BROWN_CAP_RADIUS = 50; +constexpr int PLAYER_FORM_POOP = 9; +constexpr int OH_CRAP_FORM_COUNT = 3; + +// The gibs: a third more of them per hit with Extra Blood, how fast they fly, and a rainbow gib's flatter throw. +constexpr int POOP_EXTRA_BLOOD_GIBS = 3; +constexpr float POOP_GIB_SPEED_MIN = 2; +constexpr float POOP_RANDOM_UNIT = 2.3283064e-10f; +constexpr float POOP_HALF_TURN = 3.14f; +constexpr float RAINBOW_GIB_FLATTEN = 0.5f; +constexpr float STONE_BREAK_SPEED = 4; +constexpr int STONE_BREAK_COUNT = 3; +constexpr int STONE_BREAK_SUBTYPE = 0x30001; +constexpr float PLOP_VOLUME = 0.9f; +constexpr float GIGA_PLOP_PITCH = 0.5f; +constexpr float GIGA_SPLAT_SCALE = 2; + +// The gib and splat colors by poop kind, and the rainbow gib's five. +constexpr ColorMod GOLDEN_POOP_COLOR = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.55f, 0.45f, 0}}; +constexpr ColorMod RED_GIB_COLOR = {{1, 1, 1, 1}, {1, 0, 0, 0.9f}, {0, 0, 0}}; +constexpr ColorMod BLACK_POOP_COLOR = {{1, 1, 1, 1}, {0.3f, 0.3f, 0.3f, 1}, {0, 0, 0}}; +constexpr ColorMod POOP_FLAMING_GIB = {{1, 1, 1, 1}, {1, 0.2f, 0, 0.9f}, {0, 0, 0}}; +constexpr ColorMod POOP_STINKY_GIB = {{1, 1, 1, 1}, {0.3f, 1, 0.2f, 0.9f}, {0, 0, 0}}; +constexpr ColorMod RED_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 0, 0, 0.9f}, {0, 0, 0}}; +constexpr ColorMod POOP_FLAMING_SPLAT = {{1, 1, 1, 1}, {1, 0.2f, 0, 1}, {0, 0, 0}}; +constexpr ColorMod POOP_STINKY_SPLAT = {{1, 1, 1, 1}, {0.3f, 1, 0.2f, 1}, {0, 0, 0}}; +constexpr std::array, 5> RAINBOW_GIB_COLORS = { + {{1, 0, 0}, {0, 1, 0}, {0.5f, 0.5f, 1}, {1, 0, 1}, {1, 1, 0}}}; + +// The footprints a poop leaves on the players who walk over it, by kind, and the rainbow poop's six. +constexpr std::array FOOTPRINT_BROWN = {0.15294118f, 0.09803922f, 0.08627451f}; +constexpr std::array FOOTPRINT_RED = {0.5764706f, 0.07058824f, 0.10980392f}; +constexpr std::array FOOTPRINT_GOLDEN = {0.84705883f, 0.5058824f, 0}; +constexpr std::array FOOTPRINT_BLACK = {0.078431375f, 0.078431375f, 0.078431375f}; +constexpr std::array FOOTPRINT_WHITE = {0.44313726f, 0.74509805f, 0.8235294f}; +constexpr std::array, 6> FOOTPRINT_RAINBOW = { + {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}, {1, 0, 1}}}; + +// What a poop's drop roll gave: a pickup variant (none for nothing), its subtype and its seed. +struct PoopDrop +{ + int subType = 0; + int variant = PICKUP_NULL; + uint32_t seed = 0; +}; + +// Whether a poop variant is a part of the giant poop. +static bool is_giga(int variant) +{ + return variant >= POOP_GIGA_TOP_LEFT && variant <= POOP_GIGA_BOTTOM_RIGHT; +} + +// Whether an entity walks on the floor rather than flying over it or keeping to the walls. +static bool is_grounded(Entity& entity) +{ + return entity.entityGridCollisionClass > GRIDCOLL_WALLS; +} + +// The animation of the stage a state shows: State1 to State4 while standing, State5 once broken. +static std::string state_animation_get(int state) +{ + int stage = state == POOP_STATE_BROKEN ? POOP_STAGE_BROKEN : std::clamp(state / POOP_STATE_STEP, 0, + POOP_STAGE_LAST_STANDING); + return "State" + std::to_string(stage + 1); +} + +// The spritesheet of a poop variant: the plain, red and white poops pick one of three from the rng. +static std::string poop_sheet_get(GridEntity_Poop& poop) +{ + switch (poop.variant) + { + case POOP_NORMAL: + return "gfx/grid/grid_poop_" + std::to_string(poop.rng.Next() % 3 + 1) + ".png"; + case POOP_RED: + return "gfx/grid/grid_poop_red_" + std::to_string(poop.rng.Next() % 3 + 1) + ".png"; + case POOP_CORNY: + return "gfx/grid/grid_poop_corn.png"; + case POOP_GOLDEN: + return "gfx/grid/grid_poop_gold.png"; + case POOP_RAINBOW: + return "gfx/grid/grid_poop_rainbow.png"; + case POOP_BLACK: + return "gfx/grid/grid_poop_black.png"; + case POOP_WHITE: + return "gfx/grid/grid_poop_white_" + std::to_string(poop.rng.Next() % 3 + 1) + ".png"; + case POOP_CHARMING: + return "gfx/grid/grid_poop_charming.png"; + default: + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Unknown poop variant: %d"); + return {}; + } +} + +// The pickups a breaking poop may drop, ready in the cache. +static void drops_preload() +{ + EntityConfig& config = g_manager->entityConfig; + for (auto [type, variant] : {std::array{ENTITY_EFFECT, EFFECT_POOP_EXPLOSION}, + {ENTITY_EFFECT, EFFECT_POOP_PARTICLE}, {ENTITY_PICKUP, PICKUP_HEART}, + {ENTITY_PICKUP, PICKUP_COIN}}) + if (EntityConfig_Entity* entity = config.GetEntity(type, variant, 0)) config.PreloadResources(entity); +} + +// 00715940 Loads the poop for its variant from its seed, standing on a player spawned in it until they step off, +// with a corny poop's eternal fly and a white poop's aura. A red poop saved broken comes back whole. +// The game leaves an unknown variant's spritesheet unset. Here it keeps the file's own. void GridEntity_Poop::subclass_init() { - reconstruction_missing("GridEntity_Poop::subclass_init 00715940"); + Room& room = *g_game->room; + varData = 0; + isEnemyInside = false; + isUnderPlayer = false; + if (room.isInitialized) + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector offset = vector_sub(player->pos, Position()); + if (player->variant != PLAYER_VARIANT_PLAYER || !is_grounded(*player)) continue; + if (offset.y * offset.y + offset.x * offset.x >= UNDER_PLAYER_SPAWN_DISTANCE_SQUARED) continue; + isUnderPlayer = true; + break; + } + collisionClass = isUnderPlayer ? COLLISION_NONE : COLLISION_SOLID; + + if (variant == POOP_CORNY && state != POOP_STATE_BROKEN) + { + uint32_t seed = Random(); + Entity* fly = g_game->Spawn({.position = Position(), .type = ENTITY_ETERNALFLY, .seed = seed}); + dynamic_cast(*fly).state = NPC_STATE_INIT; + } + else if (variant == POOP_RED && state == POOP_STATE_BROKEN) + state = 0; + reviveTimer = 0; + path_set(state != POOP_STATE_BROKEN ? GRID_PATH_POOP : 0); + drops_preload(); + + rng = {spawnSeed, 5, 9, 7}; + if (is_giga(variant)) + sprite.Load("gfx/grid/grid_poop_giant.anm2", GRAPHICS_LOAD); + else + { + sprite.Load("gfx/grid/grid_poop.anm2", GRAPHICS_DEFER); + std::string sheet = poop_sheet_get(*this); + if (!sheet.empty()) sprite.ReplaceSpritesheet(0, sheet); + sprite.LoadGraphics(); + } + + std::string anim = state_animation_get(state); + if (!room.isInitialized) + { + const AnimationData* data = sprite.GetAnimationData(anim); + sprite.SetFrame(anim, data ? data->length : 0); + } + else sprite.Play(state < POOP_STATE_STEP ? "Appear" : anim); + sprite.isFlipX = (rng.Next() & 1) == 0; + + if (variant != POOP_WHITE) return; + if (LayerState* layer = sprite.GetLayer("Spawn")) + { + std::copy(std::begin(WHITE_POOP_COLOR._colorize), std::end(WHITE_POOP_COLOR._colorize), layer->color._colorize); + std::copy(std::begin(WHITE_POOP_COLOR._offset), std::end(WHITE_POOP_COLOR._offset), layer->color._offset); + } + if (state == POOP_STATE_BROKEN) return; + + uint32_t seed = Random(); + Entity* aura = + g_game->Spawn({.position = Position(), .type = ENTITY_EFFECT, .variant = EFFECT_HALLOWED_GROUND, .seed = seed}); + if (!room.isInitialized) aura->sprite.Play("Idle"); + aura->posOffset = vector_make(0, HALLOWED_AURA_RISE); + aura->renderZOffset = HALLOWED_AURA_Z; } -// 00718dd0 Joins a giant poop's parts once the room is laid out. +// 00718dd0 Gathers a giant poop's other three parts from its top left one, making the missing ones. A giant poop +// that cannot have all four turns back into plain poops, its state shared. void GridEntity_Poop::PostInit() { - reconstruction_missing("GridEntity_Poop::PostInit 00718dd0"); + if (variant != POOP_GIGA_TOP_LEFT) return; + + std::array parts = {get_giga_part(POOP_GIGA_TOP_RIGHT, true), + get_giga_part(POOP_GIGA_BOTTOM_LEFT, true), + get_giga_part(POOP_GIGA_BOTTOM_RIGHT, true)}; + bool isWhole = parts[0] && parts[1] && parts[2]; + if (!isWhole) + { + variant = POOP_NORMAL; + subclass_init(); + } + for (GridEntity_Poop* part : parts) + { + if (!part) continue; + part->state = state; + if (isWhole) continue; + part->variant = POOP_NORMAL; + part->subclass_init(); + } } -// 00714770 Grows red poop back, animates the poop and its effects. +// Colors the footprints of a player walking over the poop in its own colors, on the foot stepping down. +static void footprint_color(GridEntity_Poop& poop, Entity_Player& player) +{ + std::array color = FOOTPRINT_BROWN; + switch (poop.variant) + { + case POOP_RED: + color = FOOTPRINT_RED; + break; + case POOP_GOLDEN: + color = FOOTPRINT_GOLDEN; + break; + case POOP_RAINBOW: + color = FOOTPRINT_RAINBOW[Random() % FOOTPRINT_RAINBOW.size()]; + break; + case POOP_BLACK: + color = FOOTPRINT_BLACK; + break; + case POOP_WHITE: + color = FOOTPRINT_WHITE; + break; + default: + break; + } + if (!player.is_footstep_triggered(-1) || player.canFly) return; + + ColorMod& footprint = player.is_footstep_triggered(0) ? player.footprintColor2 : player.footprintColor1; + std::copy(color.begin(), color.end(), footprint._offset); +} + +// Lets the players walk over the poop: footprints for those on it, and no collision while one spawned inside it +// or an enemy sits in it still stands there. +static void walkers_update(GridEntity_Poop& poop) +{ + Vector position = poop.Position(); + bool isStillUnder = false; + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER || !is_grounded(*player)) continue; + + float distance = vector_length(vector_sub(position, player->pos)); + if (distance >= FOOTPRINT_DISTANCE) continue; + footprint_color(poop, *player); + if (!poop.isUnderPlayer || distance >= UNDER_PLAYER_DISTANCE) continue; + poop.collisionClass = COLLISION_NONE; + isStillUnder = true; + } + + if (poop.isEnemyInside) + { + bool isInside = false; + for (Entity* entity : entity_query_radius(position, ENEMY_INSIDE_RADIUS, QUERY_ALL)) + { + if (!entity) continue; + bool isWalker = (g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY); + if (!isWalker || !is_grounded(*entity)) continue; + poop.collisionClass = COLLISION_NONE; + isInside = true; + break; + } + poop.isEnemyInside = isInside; + } + if (!isStillUnder) poop.isUnderPlayer = false; +} + +// Keeps the white poop's hallowed ground on the players near it, updating their stats when it starts. +static void hallowed_ground_update(GridEntity_Poop& poop) +{ + Vector position = poop.Position(); + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (vector_length(vector_sub(position, player->pos)) >= player->size + HALLOWED_REACH) continue; + + int previous = player->hallowedGroundCountdown; + player->hallowedGroundCountdown = std::min(previous + HALLOWED_FRAMES, HALLOWED_FRAMES); + if ((previous > 0) == (player->hallowedGroundCountdown > 0)) continue; + player->cacheFlags |= HALLOWED_CACHE; + player->EvaluateItems(); + } +} + +// 00714770 Breaks a giant poop missing a part into a plain one, turns red poop plain once the plates are pressed, +// grows red poop back, burns and pulses while red, walks the players over it and keeps the white poop's aura. void GridEntity_Poop::Update() { - reconstruction_missing("GridEntity_Poop::Update 00714770"); + if (is_giga(variant)) + for (int part = POOP_GIGA_TOP_LEFT; part <= POOP_GIGA_BOTTOM_RIGHT; part++) + { + if (part == variant || get_giga_part(part, false)) continue; + variant = POOP_NORMAL; + subclass_init(); + break; + } + + RoomDescriptor* current = g_game->GetRoomByIdx(g_game->currentRoomIdx, g_game->currentDimensionIdx); + if (variant == POOP_RED && (current->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED)) + { + bool isFlipX = sprite.isFlipX; + reviveTimer = 0; + variant = POOP_NORMAL; + subclass_init(); + std::string anim = state_animation_get(state); + const AnimationData* data = sprite.GetAnimationData(anim); + sprite.SetFrame(anim, data ? data->length : 0); + sprite.isFlipX = isFlipX; + uint32_t seed = Random(); + g_game->Spawn({.position = Position(), .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + } + + if (reviveTimer > 0 && --reviveTimer < 1) + { + sprite.Play("Appear"); + state = 0; + path_set(GRID_PATH_POOP); + } + + collisionClass = state == POOP_STATE_BROKEN ? COLLISION_NONE : COLLISION_SOLID; + if (state != POOP_STATE_BROKEN && variant == POOP_RED) + { + float damage = g_game->deathmatchManager.is_active() ? RED_POOP_VERSUS_DAMAGE : RED_POOP_DAMAGE; + hurt_surroundings({.damageFlags = DAMAGE_POOP, .damage = damage, .distance = RED_POOP_DISTANCE, + .playerDistance = RED_POOP_PLAYER_DISTANCE, .playerDamage = 1, + .isIgnoreGridCollisionClass = true}); + float pulse = std::sin((float)g_game->frameCount * RED_POOP_PULSE_SPEED); + sprite.color = {{1 - pulse * RED_POOP_PULSE, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + } + + if (sprite.animState.animData && !sprite.animState.isPlaying && sprite.GetAnimation() == "Appear") + { + sprite.Play("State1"); + sprite.SetLastFrame(); + } + + walkers_update(*this); + if (variant == POOP_WHITE && state != POOP_STATE_BROKEN) hallowed_ground_update(*this); + sprite.Update(); } -// 007151e0 Draws the poop. -void GridEntity_Poop::Render(const Vector&) +// 007151e0 Draws the poop in the floor's color. Only the giant poop's bottom left part draws, for all four. +void GridEntity_Poop::Render(const Vector& offset) { - reconstruction_missing("GridEntity_Poop::Render 007151e0"); + if (!is_giga(variant)) return GridEntity::Render(offset); + if (variant != POOP_GIGA_BOTTOM_LEFT) return; + + sprite.color = g_game->room->floorColor; + sprite_render(vector_make(offset.x + GIGA_RENDER_OFFSET, offset.y - GIGA_RENDER_OFFSET)); } -// 00715330 Breaks the poop a stage, spawning gibs and, at the last, its drops. -bool GridEntity_Poop::Hurt(int, const EntityRef&) +// 00715330 Breaks the poop a stage or more, the giant poop through its bottom left part, giving the rewards of the +// stages broken, gibs now and then and, once it breaks, its effects and drops. A red poop starts growing back. +// The online co-op stat of a broken poop (Player_stats_add 00425ac0) is left to the online stats. +bool GridEntity_Poop::Hurt(int damage, const EntityRef& source) { - reconstruction_missing("GridEntity_Poop::Hurt 00715330"); + if (is_giga(variant) && variant != POOP_GIGA_BOTTOM_LEFT) + { + GridEntity_Poop* main = get_giga_part(POOP_GIGA_BOTTOM_LEFT, false); + return main && main->Hurt(damage, source); + } + if (state == POOP_STATE_BROKEN) return false; + + int hits = Random() % BONUS_HIT_ODDS == 0 ? damage + 1 : damage; + if (variant == POOP_NORMAL && Random() % BONUS_HIT_ODDS == 0) hits++; + int step = POOP_STATE_STEP; + if (variant == POOP_GOLDEN) step = (int)(Random() % GOLDEN_STATE_STEP_RANGE) + GOLDEN_STATE_STEP_MIN; + else if (variant == POOP_WHITE) step = WHITE_STATE_STEP; + else if (variant == POOP_GIGA_BOTTOM_LEFT) step = GIGA_STATE_STEP; + int stateDamage = step * hits; + if (stateDamage < 1) return false; + + int previousState = state; + Vector center = center_get(); + state = std::min(state + stateDamage, POOP_STATE_BROKEN); + std::string anim = state_animation_get(state); + bool isRestart = variant == POOP_GIGA_BOTTOM_LEFT && sprite.GetAnimation() == anim && + !(sprite.animState.animData && sprite.animState.isPlaying); + if (isRestart) + { + sprite.Play(anim, PLAY_FORCED); + sprite.SetFrame(2.0f); + } + else sprite.Play(anim); + + int stageStep = variant == POOP_GIGA_BOTTOM_LEFT ? GIGA_ANIM_STEP : POOP_STATE_STEP; + bool isLowDropChance = varData == 1; + spawn_rewards({.source = source, .position = center, .seed = spawnSeed, .damage = stateDamage, + .previousState = previousState, .variant = variant, .isLowDropChance = isLowDropChance}); + if (state == POOP_STATE_BROKEN || ((Random() & 1) == 0 && state / stageStep - previousState / stageStep >= 1)) + spawn_hit_gibs(center, variant, state / POOP_STATE_STEP); + + destroySource = source; + if (state == POOP_STATE_BROKEN) + { + path_set(GRID_PATH_FREED); + collisionClass = COLLISION_NONE; + if (variant == POOP_RED) reviveTimer = RED_POOP_REVIVE_FRAMES; + destroy_effects(center, variant); + spawn_drops({.source = destroySource, .position = center, .seed = spawnSeed, .variant = variant, + .isLowDropChance = isLowDropChance}); + } + if (variant != POOP_GIGA_BOTTOM_LEFT) return true; + + for (int partVariant : GIGA_OTHER_PARTS) + { + GridEntity_Poop* part = get_giga_part(partVariant, false); + if (!part) continue; + part->state = state; + if (state == POOP_STATE_BROKEN) part->path_set(GRID_PATH_FREED); + } + return true; } // 007166b0 Water clips around the poop unless it is growing back. @@ -60,26 +529,405 @@ void GridEntity_Poop::RespawnRedPoop() sprite.animState.isPlaying = false; } -// 00716760 Spawns the gibs a poop of a variant throws when hit, at most so many. -void GridEntity_Poop::spawn_hit_gibs(const Vector&, int, int) +// 00718d20 The poop's center: its cell's, or for a giant poop part the middle of all four. +Vector GridEntity_Poop::center_get() { - reconstruction_missing("GridEntity_Poop::spawn_hit_gibs 00716760"); + Vector position = Position(); + if (!is_giga(variant)) return position; + + const std::array& center = GIGA_CENTERS[variant - POOP_GIGA_TOP_LEFT]; + return vector_make(position.x + center[0], position.y + center[1]); } -// 00716b10 Spawns a broken poop's effects: the golden poop's sparkle, the black poop's creep and the rest. -void GridEntity_Poop::destroy_effects() +// 00718ac0 Another part of the giant poop this part belongs to, made when asked and missing. A poop of another kind +// in its cell is removed first, which also queues the new part for removal at the room's next update, as in the game. +GridEntity_Poop* GridEntity_Poop::get_giga_part(int partVariant, bool isCreate) { - reconstruction_missing("GridEntity_Poop::destroy_effects 00716b10"); + if (!is_giga(variant) || !is_giga(partVariant)) return nullptr; + + Room& room = *g_game->room; + const std::array& tile = GIGA_TILES[partVariant - POOP_GIGA_TOP_LEFT]; + const std::array& own = GIGA_TILES[variant - POOP_GIGA_TOP_LEFT]; + int column = (int)((uint32_t)gridIndex % (uint32_t)room.gridWidth) + tile[0] - own[0]; + int row = (int)((uint32_t)gridIndex / (uint32_t)room.gridWidth) + tile[1] - own[1]; + int cell = room.GetGridIndexByTile(column, row); + GridEntity* found = room.GetGridEntity(cell); + bool isPoop = found && found->type == GRID_POOP; + if (isPoop && found->variant == partVariant) return static_cast(found); + if (!isCreate) return nullptr; + + if (isPoop) + { + room.gridPaths[cell] = 0; + room.pendingGridRemovals.insert(cell); + } + if (!room.SpawnGridEntity(cell, GRID_POOP, partVariant, Random(), 0)) return nullptr; + GridEntity* part = room.GetGridEntity(cell); + return part && part->type == GRID_POOP && part->variant == partVariant ? static_cast(part) + : nullptr; } -// 007178c0 Spawns what a broken poop drops. -void GridEntity_Poop::spawn_drops() +// 00716760 Spawns the gibs a poop of a variant throws when hit, one to maxGibs (three times as many with Extra +// Blood), colored by kind. The rainbow poop's fly one by one in its colors. +void GridEntity_Poop::spawn_hit_gibs(const Vector& position, int poopVariant, int maxGibs) { - reconstruction_missing("GridEntity_Poop::spawn_drops 007178c0"); + uint32_t extra = maxGibs < 1 ? 0 : Random() % (uint32_t)maxGibs; + int count = (int)extra + 1; + if (g_game->seedEffects.HasSeedEffect(SEED_EXTRA_BLOOD)) count *= POOP_EXTRA_BLOOD_GIBS; + + if (poopVariant == POOP_RAINBOW) + { + ColorMod color = COLOR_DEFAULT; + for (int i = 0; i < count; i++) + { + const std::array& tone = RAINBOW_GIB_COLORS[Random() % RAINBOW_GIB_COLORS.size()]; + std::copy(tone.begin(), tone.end(), color._colorize); + color._colorize[3] = 1; + + uint32_t seed = Random(); + float angle = (float)Random() * POOP_RANDOM_UNIT * POOP_HALF_TURN; + angle += angle; + float speed = (float)Random() * POOP_RANDOM_UNIT + POOP_GIB_SPEED_MIN; + Vector velocity = vector_make(std::cos(angle) * speed, std::sin(angle) * RAINBOW_GIB_FLATTEN * speed); + Entity* gib = g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_EFFECT, + .variant = EFFECT_POOP_PARTICLE, .seed = seed}); + gib->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + gib->Update(); + } + return; + } + + ColorMod color = COLOR_DEFAULT; + int variant = EFFECT_POOP_PARTICLE; + switch (poopVariant) + { + case POOP_GOLDEN: + color = GOLDEN_POOP_COLOR; + break; + case POOP_RED: + color = RED_GIB_COLOR; + break; + case POOP_BLACK: + color = BLACK_POOP_COLOR; + break; + case POOP_WHITE: + color = WHITE_POOP_COLOR; + break; + case POOP_STONE: + variant = EFFECT_TOOTH_PARTICLE; + break; + case POOP_FLAMING: + color = POOP_FLAMING_GIB; + break; + case POOP_STINKY: + color = POOP_STINKY_GIB; + break; + default: + break; + } + float speed = (float)Random() * POOP_RANDOM_UNIT + POOP_GIB_SPEED_MIN; + game_particles_spawn({.color = color, .position = position, .speed = speed, .count = count, .variant = variant}); } -// 00718ac0 Another part of the giant poop this part belongs to, created when asked and missing. -GridEntity_Poop* GridEntity_Poop::get_giga_part(int, bool) +// 00716b10 Counts a broken poop and spawns its break: a splat colored by kind (twice the size for the giant poop) +// with a plop, or for the stone poop enemy rock bits with a crumble. +void GridEntity_Poop::destroy_effects(const Vector& position, int poopVariant) { - reconstruction_missing("GridEntity_Poop::get_giga_part 00718ac0"); + g_manager->persistentGameData.IncreaseEventCounter(EVENT_POOP_DESTROYED, 1); + if (poopVariant == POOP_STONE) + { + grid_sound_play(SOUND_ROCK_CRUMBLE); + game_particles_spawn({.position = position, .speed = STONE_BREAK_SPEED, .count = STONE_BREAK_COUNT, + .subType = STONE_BREAK_SUBTYPE, .variant = EFFECT_ROCK_PARTICLE}); + return; + } + + grid_sound_play(SOUND_PLOP, {.volume = PLOP_VOLUME, .pitch = is_giga(poopVariant) ? GIGA_PLOP_PITCH : 1}); + uint32_t seed = Random(); + Entity* splat = + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOP_EXPLOSION, .seed = seed}); + ColorMod color = COLOR_DEFAULT; + switch (poopVariant) + { + case POOP_WHITE: + color = WHITE_POOP_COLOR; + break; + case POOP_RED: + color = RED_SPLAT_COLOR; + break; + case POOP_GOLDEN: + color = GOLDEN_POOP_COLOR; + break; + case POOP_BLACK: + color = BLACK_POOP_COLOR; + break; + case POOP_FLAMING: + color = POOP_FLAMING_SPLAT; + break; + case POOP_STINKY: + color = POOP_STINKY_SPLAT; + break; + default: + if (is_giga(poopVariant)) splat->sprite.scale = vector_make(GIGA_SPLAT_SCALE, GIGA_SPLAT_SCALE); + return; + } + splat->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// Raises a drop chance for Butt Penny and Petrified Poop. A poop reduced by ReduceSpawnRate keeps one in a hundred. +static float drop_chance_get(float chance, bool isLowDropChance) +{ + PlayerManager& players = g_game->playerManager; + if (players.FirstTrinketOwner(TRINKET_BUTT_PENNY, nullptr, LAZARUS_SHARE_CHECK)) + chance = std::max(players.GetTrinketMultiplier(TRINKET_BUTT_PENNY) * POOP_TRINKET_STEP + BUTT_PENNY_BASE, chance); + if (players.FirstTrinketOwner(TRINKET_PETRIFIED_POOP, nullptr, LAZARUS_SHARE_CHECK)) + chance = std::max(players.GetTrinketMultiplier(TRINKET_PETRIFIED_POOP) * POOP_TRINKET_STEP + PETRIFIED_BASE, chance); + return isLowDropChance ? LOW_DROP_CHANCE : chance; +} + +// The drop roll of a poop: the owners of Daemon's Tail, Butt Penny and E. Coli drawn from ownerRng, then from rng +// one in twenty the Petrified Poop (while in the pool), else a heart or a penny. E. Coli may still give a heart when +// nothing drops. +static PoopDrop poop_drop_roll(RNG& ownerRng, RNG& rng, float baseChance, bool isLowDropChance) +{ + PlayerManager& players = g_game->playerManager; + RNG* tail = nullptr; + RNG* buttPenny = nullptr; + RNG* eColi = nullptr; + players.RandomTrinketOwner(TRINKET_DAEMONS_TAIL, ownerRng.Next(), &tail); + players.RandomTrinketOwner(TRINKET_BUTT_PENNY, ownerRng.Next(), &buttPenny); + players.RandomCollectibleOwner(COLLECTIBLE_E_COLI, ownerRng.Next(), &eColi); + float chance = drop_chance_get(baseChance, isLowDropChance); + + if (chance <= rng.RandomFloat()) + { + bool isHeart = eColi && eColi->RandomFloat() < chance && (rng.RandomFloat() < LOW_DROP_CHANCE || !isLowDropChance) && + rng.RandomFloat() < HEART_CHANCE && (!tail || tail->Next() % DAEMONS_TAIL_ODDS == 0); + return isHeart ? PoopDrop{.variant = PICKUP_HEART, .seed = rng.Next()} : PoopDrop{}; + } + if (rng.Next() % PETRIFIED_ODDS == 0 && g_game->itemPool.RemoveTrinket(TRINKET_PETRIFIED_POOP)) + return {.subType = TRINKET_PETRIFIED_POOP, .variant = PICKUP_TRINKET, .seed = Random()}; + + bool isHeart = rng.RandomFloat() < HEART_CHANCE && (!tail || tail->Next() % DAEMONS_TAIL_ODDS == 0) && + (!buttPenny || buttPenny->Next() % BUTT_PENNY_HEART_ODDS == 0); + return {.variant = isHeart ? PICKUP_HEART : PICKUP_COIN, .seed = rng.Next()}; +} + +// The player a versus hit belongs to, from its source. +static Entity_Player* source_player_get(const EntityRef& source) +{ + Entity* ancestor = source.entity ? source.entity->GetPlayerAncestor() : nullptr; + return ancestor ? ancestor->ToPlayer() : nullptr; +} + +// 00716db0 Gives the rewards of the stages a hit broke: a giant poop's stage (one in twenty states) may drop a +// pickup, a charming poop's makes a friendly dip, and with Dirty Mind a stage makes a dip half the time (always with +// Petrified Poop, and for the last one). +void GridEntity_Poop::spawn_rewards(const PoopHit& hit) +{ + PlayerManager& players = g_game->playerManager; + Entity_Player* dirtyMind = players.RandomCollectibleOwner(COLLECTIBLE_DIRTY_MIND, hit.seed, nullptr); + bool isGiga = is_giga(hit.variant); + if (!dirtyMind && !isGiga && hit.variant != POOP_CHARMING) return; + + int state = std::min(hit.previousState + hit.damage, POOP_STATE_BROKEN); + int step = isGiga ? GIGA_STATE_STEP : POOP_STATE_STEP; + int previousStage = hit.previousState / step; + int rewards = state / step - previousStage; + RNG rng = {hit.seed, 5, 15, 17}; + for (int i = 0; i < previousStage && rewards > 0; i++) rng.Next(); + + Vector position = hit.position; + Vector still{}; + for (int i = 0; i < rewards; i++) + { + rng.Next(); + if (dirtyMind) + { + bool isLast = i == rewards - 1 && state == POOP_STATE_BROKEN; + RNG dipRng = {rng._seed, 7, 13, 25}; + if (isLast || players.FirstTrinketOwner(TRINKET_PETRIFIED_POOP, nullptr, LAZARUS_SHARE_CHECK) || + (dipRng.Next() & 1) == 0) + spawn_dip_at(hit.variant, &position, dirtyMind, &still); + } + + if (hit.variant == POOP_CHARMING) + { + Entity_Player* player = g_game->deathmatchManager.is_active() ? source_player_get(hit.source) : nullptr; + if (!player) player = player_nearest_find(position); + if (player) spawn_dip_at(POOP_CHARMING, &position, player, &still); + continue; + } + if (!isGiga) continue; + + RNG roll = {rng._seed, 7, 17, 21}; + if ((roll.Next() & 1) != 0) continue; + PoopDrop drop = poop_drop_roll(roll, roll, GIGA_DROP_CHANCE, hit.isLowDropChance); + Entity* pickup = drop.variant == PICKUP_NULL ? nullptr + : g_game->Spawn({.position = position, .subType = drop.subType, + .type = ENTITY_PICKUP, .variant = drop.variant, + .seed = drop.seed}); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, nullptr, 0); + if (!pickup) continue; + pickup->velocity = velocity; + pickup->pos = vector_add(pickup->pos, velocity); + } +} + +// The golden poop's drop: one time in three its Counterfeit Penny while in the pool, else five to seven pennies +// thrown where the way is clear. +static void golden_drops_spawn(const Vector& position, RNG& rng) +{ + if (rng.Next() % COUNTERFEIT_ODDS == 0 && g_game->itemPool.RemoveTrinket(TRINKET_COUNTERFEIT_PENNY)) + { + g_game->Spawn({.position = position, .subType = TRINKET_COUNTERFEIT_PENNY, .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, .seed = rng.Next()}); + return; + } + + for (int coins = (int)(rng.Next() % GOLDEN_COINS_RANGE) + GOLDEN_COINS_MIN; coins > 0; coins--) + { + Vector velocity{}; + for (int attempt = 0; attempt < COIN_THROW_ATTEMPTS; attempt++) + { + float angle = (float)Random() * POOP_RANDOM_UNIT * POOP_HALF_TURN; + angle += angle; + velocity = vector_make(std::cos(angle) * COIN_THROW_SPEED, std::sin(angle) * COIN_THROW_SPEED); + if (room_check_line(position, vector_add(position, vector_scale(velocity, COIN_THROW_CHECK)), LINE_MODE_CELL, + 0)) + break; + } + g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_PICKUP, .variant = PICKUP_COIN, + .seed = rng.Next()}); + } +} + +// The rainbow poop's reward: its giant book and fanfare, and full health for every living player (in versus, only the +// one who broke it). +static void rainbow_heal(const EntityRef& source) +{ + g_game->itemOverlay.Show(GIANTBOOK_RAINBOW_POOP, 0, nullptr); + grid_sound_play(SOUND_HAPPY_RAINBOW); + g_manager->persistentGameData.IncreaseEventCounter(EVENT_RAINBOW_POOP_DESTROYED, 1); + for (Entity_Player* player : g_game->playerManager.playerList) + { + bool isOwn = !g_game->deathmatchManager.is_active() || (source.entity && source.entity->IsDescendantOf(player)); + if (isOwn && !player->isDead) player->SetFullHearts(); + } +} + +// The black poop's blast: every vulnerable enemy (but the breaker in versus) hurt and confused, under a dark cloud. +static void black_poop_blast(const EntityRef& source) +{ + EntityRef blast; + blast.spawnerType = ENTITY_PLAYER; + Entity* breaker = source.entity ? source.entity->GetPlayerAncestor() : nullptr; + EntityList_EL& entities = g_game->room->entityList.updateEL; + for (size_t i = 0; i < entities.size(); i++) + { + Entity* enemy = entities[i]; + if ((g_game->deathmatchManager.is_active() && enemy == breaker) || !enemy->IsVulnerableEnemy(nullptr)) continue; + enemy->TakeDamage(BLACK_POOP_DAMAGE, 0, blast, BLACK_POOP_DAMAGE_COOLDOWN); + enemy->AddConfusion(blast, BLACK_POOP_CONFUSION, false); + } + g_game->room->fxLayers.AddPoopFx(BLACK_POOP_CLOUD); +} + +// Meconium's chance at a black heart from a black poop (by the breaker's in versus). +static void meconium_drop_try(const Vector& position, const EntityRef& source, RNG& rng) +{ + Entity_Player* owner = g_game->playerManager.FirstTrinketOwner(TRINKET_MECONIUM); + if (g_game->deathmatchManager.is_active()) + { + if (!source.entity) return; + owner = source_player_get(source); + } + if (!owner) return; + + int multiplier = owner->GetTrinketMultiplier(TRINKET_MECONIUM); + uint32_t odds = multiplier == 2 ? MECONIUM_ODDS_DOUBLE : multiplier == 3 ? MECONIUM_ODDS_TRIPLE : MECONIUM_ODDS; + if (rng.Next() % MECONIUM_ROLL >= odds) return; + g_game->Spawn({.position = position, .subType = HEART_BLACK, .type = ENTITY_PICKUP, .variant = PICKUP_HEART, + .seed = rng.Next()}); + Random(); +} + +// Whether a player has the Oh Crap form and so heals on broken poop. +static bool is_oh_crap(Entity_Player& player) +{ + return !player.hasCurseMistEffect && !player.isCoopGhost && player.playerForms[PLAYER_FORM_POOP] >= OH_CRAP_FORM_COUNT; +} + +// Lil Larva's blue flies and Brown Cap's blast from a broken poop (the breaker's trinkets in versus). +static void trinket_effects_spawn(const Vector& position, const EntityRef& source) +{ + PlayerManager& players = g_game->playerManager; + bool isLarva = players.AnyoneHasTrinket(TRINKET_LIL_LARVA); + bool isBrownCap = players.AnyoneHasTrinket(TRINKET_BROWN_CAP); + if (g_game->deathmatchManager.is_active()) + { + Entity_Player* breaker = (isLarva || isBrownCap) ? source_player_get(source) : nullptr; + if (!breaker) return; + isLarva = breaker->HasTrinket(TRINKET_LIL_LARVA); + isBrownCap = breaker->HasTrinket(TRINKET_BROWN_CAP); + } + + if (isLarva) + game_nearest_player(position)->AddBlueFlies(players.GetTrinketMultiplier(TRINKET_LIL_LARVA), position, nullptr); + if (!isBrownCap) return; + + uint32_t seed = Random(); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = seed}); + bomb_crater_spawn(position, nullptr, 1); + explosion_damage({.position = position, .damageFlags = DAMAGE_EXPLOSION | DAMAGE_POOP, + .damage = (float)players.GetTrinketMultiplier(TRINKET_BROWN_CAP) * BROWN_CAP_DAMAGE, + .radius = BROWN_CAP_RADIUS, .isLineCheck = false}); +} + +// 007178c0 Spawns what a broken poop drops by kind: plain, corny and white poop roll a pickup, golden poop pays out, +// rainbow poop heals everyone, black poop blasts the room (with Meconium's black heart), then the Oh Crap form heals +// and Lil Larva and Brown Cap go off for all but red poop. +// The swinging player (set only by Entity_Knife::UpdateSwingHits, not curated) never rolls again or makes Book of +// Virtues wisps here. +void GridEntity_Poop::spawn_drops(const PoopHit& hit) +{ + RNG ownerRng = {hit.seed, 2, 7, 7}; + RNG rng = {hit.seed, 1, 5, 16}; + switch (hit.variant) + { + case POOP_NORMAL: + case POOP_CORNY: + case POOP_WHITE: + { + PoopDrop drop = poop_drop_roll(ownerRng, rng, POOP_DROP_CHANCE, hit.isLowDropChance); + if (drop.variant == PICKUP_NULL) break; + g_game->Spawn({.position = hit.position, .subType = drop.subType, .type = ENTITY_PICKUP, + .variant = drop.variant, .seed = drop.seed}); + if (drop.variant != PICKUP_TRINKET) Random(); + break; + } + case POOP_GOLDEN: + golden_drops_spawn(hit.position, rng); + break; + case POOP_RAINBOW: + rainbow_heal(hit.source); + break; + case POOP_BLACK: + black_poop_blast(hit.source); + meconium_drop_try(hit.position, hit.source, rng); + break; + default: + break; + } + + bool isHealing = hit.variant == POOP_NORMAL || hit.variant == POOP_CORNY || hit.variant == POOP_GOLDEN || + hit.variant == POOP_WHITE; + std::vector& list = g_game->playerManager.playerList; + bool isOhCrap = std::any_of(list.begin(), list.end(), [](Entity_Player* player) + { return player->variant == PLAYER_VARIANT_PLAYER && is_oh_crap(*player); }); + if (isHealing && isOhCrap) + for (Entity_Player* player : list) + if (is_oh_crap(*player)) player->AddHearts(1, false, false); + + if (hit.variant != POOP_RED) trinket_effects_spawn(hit.position, hit.source); } diff --git a/src/grid_entity_poop.h b/src/grid_entity_poop.h index 0461298..3d2873d 100644 --- a/src/grid_entity_poop.h +++ b/src/grid_entity_poop.h @@ -3,7 +3,8 @@ #include "grid_entity.h" #include -// The kinds of poop (Lua's PoopGridEntityVariant). +// The kinds of poop (Lua's PoopGridEntityVariant). Stone, flaming and stinky are the poop enemies' own, for their gibs +// and break effects. enum PoopVariant : int { POOP_NORMAL, @@ -17,22 +18,40 @@ enum PoopVariant : int POOP_GIGA_TOP_RIGHT, POOP_GIGA_BOTTOM_LEFT, POOP_GIGA_BOTTOM_RIGHT, - POOP_CHARMING + POOP_CHARMING, + POOP_STONE, + POOP_FLAMING, + POOP_STINKY }; -// Destruction (0070bc60) is the default. ReduceSpawnRate (00456870) sets varData to 1. A poop (Lua's GridEntityPoop): -// it breaks in four hits into gibs and drops. Red poop grows back. +// A poop's state once broken, and a red poop's while it grows back. +constexpr int POOP_STATE_BROKEN = 1000; +constexpr int POOP_STATE_REVIVING = 1000; + +// A hit on a poop as its rewards and drops see it: where it broke, its kind and seed, the state before the hit and +// the damage dealt, and who dealt it. A poop reduced by ReduceSpawnRate rarely drops. The poop enemies leave out +// the swinging player's wisps. +struct PoopHit +{ + EntityRef source{}; + Vector position{}; + uint32_t seed = 0; + int damage = 0; + int previousState = 0; + int variant = POOP_NORMAL; + bool isLowDropChance = false; + bool isNoWisp = false; +}; + +// Destruction (0070bc60) is the default, and Destroy is the base hurt of 4. ReduceSpawnRate (00456870) sets varData +// to 1. A poop (Lua's GridEntityPoop): it breaks in four hits into gibs and drops, red poop grows back, and four +// giant poop parts share one state through the bottom left part. struct GridEntity_Poop : GridEntity { + EntityRef destroySource{}; std::string stateAnimation; - Vector unknown184{}; - Vector unknown18c{}; - Vector unknown194{}; int reviveTimer = 0; - int unknown174 = 0; - int unknown178 = 0; - int unknown17c = 0; - int unknown180 = 0; + bool isEnemyInside = false; bool isUnderPlayer = false; void subclass_init() override; @@ -43,8 +62,10 @@ struct GridEntity_Poop : GridEntity WaterClipInfo GetWaterClipInfo() override; void RespawnRedPoop(); - static void spawn_hit_gibs(const Vector& position, int poopVariant, int maxGibs); - void destroy_effects(); - void spawn_drops(); + Vector center_get(); GridEntity_Poop* get_giga_part(int partVariant, bool isCreate); + static void spawn_hit_gibs(const Vector& position, int poopVariant, int maxGibs); + static void destroy_effects(const Vector& position, int poopVariant); + static void spawn_rewards(const PoopHit& hit); + static void spawn_drops(const PoopHit& hit); }; diff --git a/src/grid_entity_rock.cpp b/src/grid_entity_rock.cpp index a17198b..fadfcc7 100644 --- a/src/grid_entity_rock.cpp +++ b/src/grid_entity_rock.cpp @@ -8,6 +8,8 @@ #include "log.h" #include "manager.h" #include "room.h" +#include "room_config.h" +#include "room_grid.h" #include "seeds.h" #include #include @@ -57,6 +59,16 @@ constexpr float SECRETS_GLOW_FRAMES = 30; constexpr int ROCK_EVENT_COUNTDOWN_END = 10; constexpr int SPIDER_CHECK_FRAMES = 15; constexpr uint32_t SPIDER_ODDS = 100; +constexpr float SPIDER_SIDE = 26; +constexpr float SPIDER_FAR = 1e6f; + +// A spiked rock's spikes: how far it looks, how near a collision point must come (players and familiars nearer), and +// the damage they deal. +constexpr float SPIKED_ROCK_QUERY_RADIUS = 80; +constexpr float SPIKED_ROCK_REACH = 25; +constexpr float SPIKED_ROCK_REACH_SMALL = 21; +constexpr float SPIKED_ROCK_DAMAGE = 16; +constexpr float SPIKED_ROCK_VERSUS_DAMAGE = 4; // 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; @@ -66,6 +78,28 @@ constexpr uint32_t WORM_ODDS = 50; constexpr uint32_t WORM_MAX = 5; constexpr float WORM_DISTANCE = 20; +// The gold rock's pennies, the tinted rock's Small Rock odds, rolls (more for a super secret rock, one more with Lucky +// Toe), the trinkets that pay out from it with their odds per hundred, its soul heart, key and chest chances, and +// Keeper's Kin's spiders. +constexpr int GOLD_COINS_MIN = 2; +constexpr int SMALL_ROCK_ITEM = 90; +constexpr uint32_t SMALL_ROCK_ODDS = 10; +constexpr int TINTED_ROCK_DROPS = 2; +constexpr int SS_ROCK_DROPS = 4; +constexpr uint32_t LUCKY_TOE_ODDS = 3; +constexpr std::array TINTED_TRINKETS = {TRINKET_ACE_OF_SPADES, TRINKET_SAFETY_CAP, TRINKET_CHILDS_HEART, + TRINKET_MATCH_STICK, TRINKET_RUSTED_KEY}; +constexpr uint32_t TRINKET_ODDS = 33; +constexpr uint32_t TRINKET_ODDS_DOUBLE = 66; +constexpr uint32_t TRINKET_ODDS_TRIPLE = 100; +constexpr uint32_t TRINKET_ROLL = 100; +constexpr float TINTED_SOUL_CHANCE = 0.6f; +constexpr float TINTED_KEY_CHANCE = 0.7f; +constexpr float TINTED_CHEST_CHANCE = 0.71f; +constexpr float TINTED_LOCKED_CHEST_CHANCE = 0.9f; +constexpr uint32_t KEEPERS_KIN_SPIDERS = 3; +constexpr int DIMENSION_DEATH_CERTIFICATE_ROCKS = 2; + // Stud Finder's chance of a crawlspace, Lucky Rock's of a coin, the most Lucky Rocks that count, and the countdown an // event rock or pit beside a broken rock starts. constexpr int TRINKET_LUCKY_ROCK = 15; @@ -329,6 +363,51 @@ static void glint_update(GridEntity_Rock& rock) rock.sprite.color = {{1, 1, 1, 1}, {0, 0, 0, 0}, {offset, offset, offset}}; } +// A spiked rock's spikes: every colliding entity with a collision point within reach of the cell (players and +// familiars nearer) takes the rock's hurt, ignoring how it flies. +static void spikes_hurt(GridEntity_Rock& rock) +{ + Vector position = rock.Position(); + float damage = g_game->deathmatchManager.is_active() ? SPIKED_ROCK_VERSUS_DAMAGE : SPIKED_ROCK_DAMAGE; + for (Entity* entity : entity_query_radius(position, SPIKED_ROCK_QUERY_RADIUS, QUERY_ALL)) + { + if (entity->entityCollisionClass == ENTCOLL_NONE) continue; + + bool isSmall = entity->type == ENTITY_PLAYER || entity->type == ENTITY_FAMILIAR; + float reach = isSmall ? SPIKED_ROCK_REACH_SMALL : SPIKED_ROCK_REACH; + for (const Vector& point : entity->collisionPoints) + { + bool isInside = std::abs(entity->pos.x + point.x - position.x) <= reach && + std::abs(entity->pos.y + point.y - position.y) <= reach; + if (!isInside) continue; + rock.hurt_func(*entity, {.damage = damage, .playerDamage = 1, .isIgnoreGridCollisionClass = true}); + break; + } + } +} + +// Keeper's Kin lets a blue spider out of a rock, on the free side of it nearest its owner. +static void rock_spider_release(GridEntity_Rock& rock, Entity_Player& owner) +{ + constexpr std::array, 4> SIDES = { + {{-SPIDER_SIDE, 0}, {SPIDER_SIDE, 0}, {0, -SPIDER_SIDE}, {0, SPIDER_SIDE}}}; + Room& room = *g_game->room; + Vector position = rock.Position(); + Vector spot{}; + float best = SPIDER_FAR; + for (const std::array& side : SIDES) + { + Vector at = vector_make(position.x + side[0], position.y + side[1]); + float dx = owner.pos.x - at.x; + float dy = owner.pos.y - at.y; + float distance = dy * dy + dx * dx; + if (room.GetGridCollision(room.GetGridIndex(at)) != COLLISION_NONE || distance >= best) continue; + best = distance; + spot = at; + } + if (spot.x != 0 || spot.y != 0) owner.AddBlueSpider(spot); +} + // 00718fe0 Glints a tinted, super secret or crawlspace rock, breaks an event rock once its countdown ends, lets // Keeper's Kin's spiders out now and then, blows a primed bomb rock once its fuse runs out, and hurts what touches a // spiked rock until a plate or the Flat File retracts its spikes. @@ -358,10 +437,9 @@ void GridEntity_Rock::Update() varData--; bool isSpiderFrame = g_game->frameCount % SPIDER_CHECK_FRAMES == 0 && Random() % SPIDER_ODDS == 0; - if (isSpiderFrame && room.GetAliveEnemiesCount() >= 1 && - g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_KEEPERS_KIN, Random(), nullptr)) - reconstruction_missing("GridEntity_Rock::Update 00718fe0: Keeper's Kin's " - "spider (Entity_Player::AddBlueSpider)"); + if (isSpiderFrame && room.GetAliveEnemiesCount() >= 1) + if (Entity_Player* owner = g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_KEEPERS_KIN, Random(), nullptr)) + rock_spider_release(*this, *owner); } else if (state == ROCK_STATE_PRIMED && fuseFrames-- <= 0) Destroy(false, EntityRef()); @@ -372,14 +450,14 @@ void GridEntity_Rock::Update() RoomDescriptor* current = g_game->GetRoomByIdx(g_game->currentRoomIdx, g_game->currentDimensionIdx); bool isRetracted = (current->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED) || g_game->playerManager.AnyoneHasTrinket(TRINKET_FLAT_FILE); - if (!isRetracted) - reconstruction_missing("GridEntity_Rock::Update 00718fe0: a spiked rock's spikes " - "(EntityList::QueryRadius, hurt_func)"); - - state = ROCK_STATE_CRACKED; - anim = "spiked_retracted"; - rubbleAnim = "rubble"; - UpdateAnimFrame(); + if (!isRetracted) spikes_hurt(*this); + else + { + state = ROCK_STATE_CRACKED; + anim = "spiked_retracted"; + rubbleAnim = "rubble"; + UpdateAnimFrame(); + } } previousState = state; } @@ -691,18 +769,24 @@ bool GridEntity_Rock::TrySpawnLadder() return true; } -// 0071b410 Spawns what a broken rock of a type drops: Lucky Rock's coins (a third of the time each) for any rock, and -// Keeper's Kin's spiders. Gold, tinted, super secret and alternate rocks' own drops are left to come. -// The knife swing that breaks rocks (Entity_Knife::UpdateSwingHits) is not curated, so no swinging player rolls again -// or makes wisps here. -void GridEntity_Rock::SpawnDrops(const Vector& position, GridEntityType type, int, uint32_t seed, int, Entity* source) +// The gold rock's two to four pennies, thrown at random. +static void gold_coins_spawn(const Vector& position, RNG& dropRng, RNG& velocityRng) { - bool isOwnDrop = type == GRID_ROCK_GOLD || type == GRID_ROCKT || type == GRID_ROCK_SS || type == GRID_ROCK_ALT || - type == GRID_ROCK_ALT2; - if (isOwnDrop) reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: gold, tinted and alternate rocks' drops"); + uint32_t first = dropRng.Next() & 1; + uint32_t second = dropRng.Next() & 1; + for (int coins = (int)(first + second) + GOLD_COINS_MIN; coins > 0; coins--) + { + uint32_t coinSeed = dropRng.Next(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); + g_game->Spawn({.position = position, .velocity = velocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, .seed = coinSeed}) + ->Update(); + } +} - RNG dropRng = {seed, 5, 9, 7}; - RNG velocityRng = {seed, 1, 9, 29}; +// Lucky Rock's coins, a third of the time each (the breaker's own Lucky Rocks in versus). +static void lucky_rock_coins_spawn(const Vector& position, Entity* source, RNG& dropRng, RNG& velocityRng) +{ int luckyRocks = 0; if (!g_game->deathmatchManager.is_active()) luckyRocks = g_game->playerManager.GetTrinketMultiplier(TRINKET_LUCKY_ROCK); for (Entity* ancestor = source; ancestor && g_game->deathmatchManager.is_active(); ancestor = ancestor->spawnerEntity) @@ -717,12 +801,167 @@ void GridEntity_Rock::SpawnDrops(const Vector& position, GridEntityType type, in uint32_t coinSeed = dropRng.Next(); Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); - g_game->Spawn({.position = position, .velocity = velocity, .subType = 1, .type = ENTITY_PICKUP, .variant = PICKUP_COIN, - .seed = coinSeed}) + g_game->Spawn({.position = position, .velocity = velocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, .seed = coinSeed}) ->Update(); } - if (g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_KEEPERS_KIN, seed, nullptr)) - reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: Keeper's Kin's spiders"); +} + +// The pickup a trinket that pays out from tinted rocks gives: Child's Heart a heart, Rusted Key a key, Match Stick a +// bomb, Safety Cap a pill and Ace of Spades a card. +static int trinket_pickup_get(int trinket) +{ + switch (trinket) + { + case TRINKET_RUSTED_KEY: + return PICKUP_KEY; + case TRINKET_MATCH_STICK: + return PICKUP_BOMB; + case TRINKET_SAFETY_CAP: + return PICKUP_PILL; + case TRINKET_ACE_OF_SPADES: + return PICKUP_TAROTCARD; + default: + return PICKUP_HEART; + } +} + +// The first of the tinted rock's trinkets whose owner's roll comes up (a third of the time, two thirds doubled, always +// tripled) pays out its pickup. Daemon's Tail mostly keeps Child's Heart from it. +static void trinket_drop_spawn(const Vector& position, RNG& ownerRng, RNG& velocityRng) +{ + PlayerManager& players = g_game->playerManager; + for (int trinket : TINTED_TRINKETS) + { + Entity_Player* owner = players.RandomTrinketOwner(trinket, ownerRng.Next(), nullptr); + if (!owner || !owner->HasTrinket(trinket)) continue; + bool isTailKept = trinket == TRINKET_CHILDS_HEART && owner->HasTrinket(TRINKET_DAEMONS_TAIL) && + Random() % DAEMONS_TAIL_ODDS != 0; + if (isTailKept) continue; + + int multiplier = players.GetTrinketMultiplier(trinket); + uint32_t odds = multiplier == 2 ? TRINKET_ODDS_DOUBLE : multiplier > 2 ? TRINKET_ODDS_TRIPLE : TRINKET_ODDS; + RNG& trinketRng = owner->GetTrinketRNG(trinket); + if (trinketRng.Next() % TRINKET_ROLL >= odds) continue; + + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 1); + g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_PICKUP, + .variant = trinket_pickup_get(trinket), .seed = trinketRng.Next()}) + ->Update(); + return; + } +} + +// Whether the floor is the Mines or the Ashpit, whose tinted rocks may hold rock spiders. +static bool is_mines_stage() +{ + Game& game = *g_game; + int stageType = 0; + if (game.challenge == CHALLENGE_RED_REDEMPTION) stageType = game.GetRoomStageType(game.currentRoomIdx); + else if (game.currentDimensionIdx != DIMENSION_DEATH_CERTIFICATE_ROCKS) stageType = (int)game.stageType; + else return false; + + int stageId = RoomConfig::GetStageID((int)game.stage, stageType, ROOM_MODE_CURRENT); + return stageId == STAGE_ID_MINES || stageId == STAGE_ID_ASHPIT; +} + +// The tinted and super secret rocks' drops: one time in ten Small Rock while in the pool (and nothing else), else two +// (four for a super secret rock, one more with Lucky Toe two times in three) rolls after the trinkets pay out: soul +// hearts (rock spiders in the Mines, half of them free), keys, bombs, and on the first roll a chest that ends them. +static void tinted_drops_spawn(const Vector& position, GridEntityType type, RNG& dropRng, RNG& velocityRng, + RNG& ownerRng) +{ + if (dropRng.Next() % SMALL_ROCK_ODDS == 0 && + g_game->itemPool.RemoveCollectible(SMALL_ROCK_ITEM, REMOVE_AVAILABLE, REMOVE_APPLY)) + { + g_game->Spawn({.position = position, .subType = SMALL_ROCK_ITEM, .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, .seed = dropRng.Next()}) + ->Update(); + return; + } + + PlayerManager& players = g_game->playerManager; + int drops = type == GRID_ROCK_SS ? SS_ROCK_DROPS : TINTED_ROCK_DROPS; + if (dropRng.Next() % LUCKY_TOE_ODDS != 0 && players.FirstTrinketOwner(TRINKET_LUCKY_TOE, nullptr, LAZARUS_SHARE_CHECK)) + drops++; + trinket_drop_spawn(position, ownerRng, velocityRng); + RNG* tail = nullptr; + players.RandomTrinketOwner(TRINKET_DAEMONS_TAIL, ownerRng.Next(), &tail); + + for (int i = 0; i < drops; i++) + { + float roll = dropRng.RandomFloat(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); + if (roll < TINTED_SOUL_CHANCE && (!tail || tail->Next() % DAEMONS_TAIL_ODDS == 0)) + { + if (is_mines_stage() && (dropRng._seed & 1) == 0) + reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: a tinted rock's rock spider " + "(Entity_NPC::ThrowRockSpider 004f9920)"); + else + g_game->Spawn({.position = position, .velocity = velocity, .subType = HEART_SOUL, .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, .seed = dropRng.Next()}) + ->Update(); + if ((dropRng.Next() & 1) == 0) drops--; + continue; + } + + int variant = PICKUP_BOMB; + if (roll < TINTED_KEY_CHANCE) variant = PICKUP_KEY; + else if (roll < TINTED_CHEST_CHANCE && i == 0) variant = PICKUP_CHEST; + else if (roll < TINTED_LOCKED_CHEST_CHANCE && i == 0) variant = PICKUP_LOCKEDCHEST; + g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_PICKUP, .variant = variant, + .seed = dropRng.Next()}) + ->Update(); + if (variant == PICKUP_CHEST || variant == PICKUP_LOCKEDCHEST) break; + } +} + +// Keeper's Kin's blue spiders from a broken rock: none to three for a random owner (the breaker in versus). +static void keepers_kin_spiders_spawn(const Vector& position, uint32_t seed, Entity* source) +{ + Game& game = *g_game; + Entity_Player* owner = game.playerManager.RandomCollectibleOwner(COLLECTIBLE_KEEPERS_KIN, seed, nullptr); + if (!owner) return; + if (game.deathmatchManager.is_active()) + { + if (!source) return; + owner = nullptr; + for (Entity_Player* player : game.playerManager.playerList) + if (player->HasCollectible(COLLECTIBLE_KEEPERS_KIN) && source->IsDescendantOf(player)) + { + owner = player; + break; + } + if (!owner) return; + } + + RNG spiderRng = {seed, 7, 25, 12}; + uint32_t spiders = spiderRng.Next() % KEEPERS_KIN_SPIDERS; + spiders += spiderRng.Next() & 1; + for (; spiders > 0; spiders--) + { + owner->numBlueSpiders++; + Vector at = position; + Vector still{}; + spawn_blue_spider(&at, owner, &still); + } +} + +// 0071b410 Spawns what a broken rock of a type drops: a gold rock's pennies, Lucky Rock's coins for any rock, a tinted +// or super secret rock's pickups, and Keeper's Kin's spiders. +// The knife swing that breaks rocks (Entity_Knife::UpdateSwingHits) is not curated, so no swinging player rolls again +// or makes wisps here. +void GridEntity_Rock::SpawnDrops(const Vector& position, GridEntityType type, int, uint32_t seed, int, Entity* source) +{ + RNG dropRng = {seed, 5, 9, 7}; + RNG velocityRng = {seed, 1, 9, 29}; + RNG ownerRng = {seed, 2, 7, 7}; + if (type == GRID_ROCK_GOLD) gold_coins_spawn(position, dropRng, velocityRng); + lucky_rock_coins_spawn(position, source, dropRng, velocityRng); + if (type == GRID_ROCKT || type == GRID_ROCK_SS) tinted_drops_spawn(position, type, dropRng, velocityRng, ownerRng); + else if (type == GRID_ROCK_ALT || type == GRID_ROCK_ALT2) + reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: the alternate rocks' drops"); + keepers_kin_spiders_spawn(position, seed, source); } // 0071dee0 Sets the countdown on the event rocks and empty event pits beside a cell, so they break or fill in turn. diff --git a/src/grid_entity_spikes.cpp b/src/grid_entity_spikes.cpp index cf37133..7b9642c 100644 --- a/src/grid_entity_spikes.cpp +++ b/src/grid_entity_spikes.cpp @@ -1,22 +1,153 @@ #include "grid_entity_spikes.h" +#include "entity_effect.h" #include "entity_player.h" #include "game.h" #include "log.h" #include "room.h" +#include +#include +#include -// The items and trinket that keep spikes down, and the variants spikes of the room's own layout have. -constexpr uint32_t SPIKES_LAYOUT_VARIANTS = 100; +// The grid path spikes claim standing and lowered, and the countdowns of timed spikes (per variant step, and between +// switches). +constexpr int GRID_PATH_SPIKES = 999; +constexpr int GRID_PATH_SPIKES_DOWN = 500; +constexpr int SPIKES_TIMEOUT = 30; +constexpr int SPIKES_SWITCH_FRAMES = 60; +constexpr int SPIKES_TIMER_STEP = 12; +constexpr int SPIKES_ANNOUNCE_FRAME = 5; +constexpr uint32_t SPIKES_TIMED_UP = 5; +constexpr uint32_t SPIKES_SHAPES = 4; -// 0071dfc0 Loads the spikes for the backdrop and starts their timer. -void GridEntity_Spikes::subclass_init() +// How spikes hurt: their reach, the damage to enemies and players, and the splat under a sacrifice-like spike. +constexpr float SPIKES_DISTANCE = 11; +constexpr float SPIKES_DAMAGE = 8; +constexpr int SPIKES_PLAYER_DAMAGE = 2; +constexpr float SACRIFICE_SPLAT_SCALE = 1.8f; + +// The backdrops whose spikes are the womb's. +constexpr std::array WOMB_BACKDROPS = {10, 11, 12, 13, 34, 43, 44, 48}; + +// 0071df80 Whether the room's backdrop shows the womb's spikes. +static bool is_womb() { - reconstruction_missing("GridEntity_Spikes::subclass_init 0071dfc0"); + return std::find(WOMB_BACKDROPS.begin(), WOMB_BACKDROPS.end(), g_game->room->backdropType) != WOMB_BACKDROPS.end(); } -// 0071e9b0 Raises and lowers timed spikes, hurting what stands on them while up. +// Shows the last frame of the animation the sprite plays, stopped. +static void sprite_finish(ANM2& sprite) +{ + std::string anim = sprite.GetAnimation(); + sprite.SetFrame(anim, 0); + sprite.SetLastFrame(); +} + +// 0071dfc0 Loads the spikes with the backdrop's sheet and starts them: a layout's spikes pick one of four shapes, +// timed spikes start up or down on their variant's countdown, and a spike offer's spikes rise unless paid for. +// Spikes the plates or the Flat File keep down start lowered. A sacrifice-like spike leaves a splat of blood. +void GridEntity_Spikes::subclass_init() +{ + Room& room = *g_game->room; + collisionClass = COLLISION_NONE; + path_set(GRID_PATH_SPIKES); + sprite.Load("gfx/grid/grid_spikes.anm2", GRAPHICS_DEFER); + std::string sheet = room.backdrop.configs[room.backdropType].spikes; + for (int layer = 0; layer < (int)sprite.layerStates.size(); layer++) + sprite.ReplaceSpritesheet(layer, sheet); + sprite.LoadGraphics(); + + if (type == GRID_SPIKES && (uint32_t)variant % SPIKES_LAYOUT_VARIANTS == 0) + { + RNG shape = {spawnSeed, 5, 9, 7}; + variant += (int)(shape.Next() % SPIKES_SHAPES) + 1; + if (!isInitialized) variableSeed = shape.Next(); + } + int savedState = state; + rng = {variableSeed, 5, 9, 7}; + timeout = SPIKES_TIMEOUT; + state = 0; + + bool isWomb = is_womb(); + if (type == GRID_SPIKES_ONOFF) + { + if ((uint32_t)variant == 0 || (uint32_t)variant > SPIKES_TIMED_UP) + { + sprite.Play(isWomb ? "WombSpikes03" : "Spikes01"); + if (variant != 0) timeout = (variant - (int)SPIKES_TIMED_UP) * SPIKES_TIMER_STEP; + } + else + { + state = 1; + timeout = variant * SPIKES_TIMER_STEP; + sprite.Play(isWomb ? "UnsummonWomb" : "Unsummon"); + sprite.SetLastFrame(); + } + } + else if (type == GRID_SPIKES_ALT) + { + bool isEntering = !room.isInitialized || g_game->frameCount - room.enterFrame < 1; + if (savedState == 1) + { + sprite.Play("UnsummonPayment"); + sprite_finish(sprite); + state = 1; + } + else sprite.Play(isEntering ? "PaymentSpike" : "SummonPayment"); + } + else + { + char anim[32]; + snprintf(anim, sizeof(anim), isWomb ? "WombSpikes%02u" : "Spikes%02u", + (uint32_t)variant % SPIKES_LAYOUT_VARIANTS); + sprite.Play(anim); + } + + if (is_disabled()) unsummon(true); + if (type != GRID_SPIKES || (uint32_t)variant < SPIKES_LAYOUT_VARIANTS) return; + + RNG splatRng = {spawnSeed, 2, 7, 9}; + Entity* splat = + g_game->Spawn({.position = Position(), .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = splatRng.Next()}); + splat->sprite.scale = vector_make(SACRIFICE_SPLAT_SCALE, SACRIFICE_SPLAT_SCALE); + splat->Update(); +} + +// 0071e9b0 Hurts what walks on standing spikes (without penalties in a sacrifice room, on a sacrifice-like or paid +// spike), switches timed spikes every 60 frames with their animation five frames ahead, and lowers kept-down spikes. void GridEntity_Spikes::Update() { - reconstruction_missing("GridEntity_Spikes::Update 0071e9b0"); + if (state != 0) path_set(GRID_PATH_SPIKES_DOWN); + else + { + bool isSacrifice = g_game->room->roomType == ROOM_SACRIFICE; + bool isSacrificeLike = (uint32_t)variant >= SPIKES_LAYOUT_VARIANTS; + bool isPenaltyFree = isSacrifice || isSacrificeLike || type == GRID_SPIKES_ALT; + bool isIgnoreClass = isSacrifice || type == GRID_SPIKES_ALT || (type == GRID_SPIKES && isSacrificeLike); + hurt_surroundings({.damageFlags = DAMAGE_SPIKES | (isPenaltyFree ? DAMAGE_NO_PENALTIES : 0), + .damage = SPIKES_DAMAGE, .distance = SPIKES_DISTANCE, .playerDistance = SPIKES_DISTANCE, + .playerDamage = SPIKES_PLAYER_DAMAGE, .isIgnoreGridCollisionClass = isIgnoreClass}); + path_set(GRID_PATH_SPIKES); + } + + if (is_disabled()) + { + if (state == 0 || (sprite.animState.animData && sprite.animState.isPlaying)) unsummon(false); + } + else if (type == GRID_SPIKES_ONOFF && timeout > 0) + { + if (--timeout < 1) + { + timeout = SPIKES_SWITCH_FRAMES; + state = state == 0 ? 1 : 0; + } + else if (timeout == SPIKES_ANNOUNCE_FRAME) + { + bool isWomb = is_womb(); + if (state != 0) sprite.Play(isWomb ? "SummonWomb" : "Summon"); + else sprite.Play(isWomb ? "UnsummonWomb" : "Unsummon"); + } + } + sprite.Update(); } // 0071e920 Whether the spikes stay down: pressed plates and the Flat File lower them, and a devil room's spikes go with @@ -35,8 +166,12 @@ bool GridEntity_Spikes::is_disabled() g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SANGUINE_BOND, LAZARUS_SHARE_CHECK); } -// 0071eb30 Lowers the spikes, at once or animated. -void GridEntity_Spikes::unsummon(bool) +// 0071eb30 Lowers the spikes for good, animated or (instantly) on their lowered frame. +void GridEntity_Spikes::unsummon(bool isInstant) { - reconstruction_missing("GridEntity_Spikes::unsummon 0071eb30"); + state = 1; + timeout = -1; + if (type == GRID_SPIKES_ALT) sprite.Play("UnsummonPayment"); + else sprite.Play(is_womb() ? "UnsummonWomb" : "Unsummon"); + if (isInstant) sprite_finish(sprite); } diff --git a/src/grid_entity_spikes.h b/src/grid_entity_spikes.h index 7c9c49e..eef736e 100644 --- a/src/grid_entity_spikes.h +++ b/src/grid_entity_spikes.h @@ -2,6 +2,9 @@ #include "grid_entity.h" +// The variants spikes of a room's own layout have: 100 and up are sacrifice-like. +constexpr uint32_t SPIKES_LAYOUT_VARIANTS = 100; + // Destruction (0070bdd0) is the default. // Spikes (Lua's GridEntitySpikes), always out or going in and out on a timer, hurting what walks over them. struct GridEntity_Spikes : GridEntity diff --git a/src/grid_entity_statue.cpp b/src/grid_entity_statue.cpp index efab67d..b42a26f 100644 --- a/src/grid_entity_statue.cpp +++ b/src/grid_entity_statue.cpp @@ -1,10 +1,39 @@ #include "grid_entity_statue.h" -#include "log.h" +#include "entity_effect.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "manager.h" +#include "music_manager.h" +#include "room.h" -// 00838ae0 Spawns the statue effect that draws it. +// The statue kinds and the effects that draw them, and the grid path a standing statue claims. +constexpr int STATUE_DEVIL = 0; +constexpr int STATUE_ANGEL = 1; +constexpr int EFFECT_DEVIL_STATUE = 6; +constexpr int EFFECT_ANGEL_STATUE = 9; + +// The run's flags for each angel once spawned, the achievement that lets angel statues break into them, the +// alternate floors' boss music and the music fade. +constexpr int GAME_STATE_URIEL_SPAWNED = 25; +constexpr int GAME_STATE_GABRIEL_SPAWNED = 26; +constexpr int ACHIEVEMENT_ANGEL_STATUES = 155; +constexpr uint32_t ROOM_DESCRIPTOR_FLAG_BOSS_MUSIC_2 = 1 << 6; +constexpr float ANGEL_MUSIC_FADE = 0.08f; + +// 00838ae0 Spawns the statue effect that draws a standing devil or angel statue, and claims its cell while it stands. void GridEntity_Statue::subclass_init() { - reconstruction_missing("GridEntity_Statue::subclass_init 00838ae0"); + if (state < STATUE_STATE_STANDING) state = STATUE_STATE_STANDING; + bool isKnown = variant == STATUE_DEVIL || variant == STATUE_ANGEL; + if (state == STATUE_STATE_STANDING && isKnown) + { + uint32_t seed = Random(); + int effect = variant == STATUE_DEVIL ? EFFECT_DEVIL_STATUE : EFFECT_ANGEL_STATUE; + statueEffect = g_game->Spawn({.position = Position(), .type = ENTITY_EFFECT, .variant = effect, .seed = seed}); + } + path_set(state == STATUE_STATE_STANDING ? GRID_PATH_SOLID : 0); } // 00838520 Animates the statue, solid while it stands. @@ -17,8 +46,89 @@ void GridEntity_Statue::Update() collisionClass = COLLISION_NONE; } -// 00838560 Breaks the statue into its angel. +// Whether the run lets an angel statue break into its angel: the achievement, or a daily or debug run. +static bool is_angel_unlocked() +{ + Manager& manager = *g_manager; + return manager.persistentGameData.achievements[ACHIEVEMENT_ANGEL_STATUES] || + (manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug)); +} + +// Picks the angel a statue breaks into: the one not met yet, or the one whose key piece is still missing, else a +// coin flip from the statue's rng. +static int angel_pick(RNG& rng) +{ + Game& game = *g_game; + bool isKey1Owned = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_KEY_PIECE_1, LAZARUS_SHARE_CHECK); + bool isKey2Owned = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_KEY_PIECE_2, LAZARUS_SHARE_CHECK); + bool isKey1Pedestal = false; + bool isKey2Pedestal = false; + bool isUrielPresent = false; + bool isGabrielPresent = false; + for (Entity* entity : game.room->entityList.updateEL) + { + if (entity->type == ENTITY_PICKUP && entity->variant == PICKUP_COLLECTIBLE) + { + isKey1Pedestal |= entity->subtype == COLLECTIBLE_KEY_PIECE_1; + isKey2Pedestal |= entity->subtype == COLLECTIBLE_KEY_PIECE_2; + } + isUrielPresent |= entity->type == ENTITY_URIEL; + isGabrielPresent |= entity->type == ENTITY_GABRIEL; + } + + bool isUrielSpawned = game.gameStateFlags & 1ull << GAME_STATE_URIEL_SPAWNED; + bool isGabrielSpawned = game.gameStateFlags & 1ull << GAME_STATE_GABRIEL_SPAWNED; + bool isUrielDue = (!isUrielSpawned && isGabrielSpawned) || (isGabrielPresent && !isUrielPresent) || + (!isKey1Pedestal && !isKey1Owned && isKey2Owned && !isUrielPresent); + bool isGabrielDue = (isUrielSpawned && !isGabrielSpawned) || (isUrielPresent && !isGabrielPresent) || + (!isKey2Pedestal && !isKey2Owned && isKey1Owned && !isGabrielPresent); + return ((rng.Next() & 1) == 0 && !isGabrielDue) || isUrielDue ? ENTITY_URIEL : ENTITY_GABRIEL; +} + +// 00838560 Breaks a standing angel statue into Uriel or Gabriel (once angels are unlocked), with the boss music, the +// doors shut and the room no longer clear. Devil statues do not break. +// The room keeps no records of the NPCs killed in it (Room::record_killed_npc), so a dead angel is not counted. bool GridEntity_Statue::Destroy(bool, const EntityRef&) { - reconstruction_missing("GridEntity_Statue::Destroy 00838560"); + if (state != STATUE_STATE_STANDING || variant != STATUE_ANGEL) return false; + if (!is_angel_unlocked()) return true; + + Game& game = *g_game; + Room& room = *game.room; + RNG rng = {spawnSeed, 5, 9, 7}; + int angelType = angel_pick(rng); + Entity* angel = game.Spawn({.position = Position(), .type = angelType, .seed = rng.Next()}); + game.gameStateFlags |= 1ull << (angelType == ENTITY_URIEL ? GAME_STATE_URIEL_SPAWNED : GAME_STATE_GABRIEL_SPAWNED); + if (angel->CanShutDoors() && angel->type != ENTITY_DARK_ESAU) + { + room.entityList.enemyCount++; + if (angel->IsBoss()) room.entityList.bossCount++; + } + angel->Update(); + + int music = MUSIC_BOSS; + if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) music = MUSIC_BOSS3; + else if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_BOSS_MUSIC_2) music = MUSIC_BOSS2; + g_manager->musicManager.Crossfade(music, ANGEL_MUSIC_FADE); + + if (statueEffect) + { + statueEffect->Remove(); + statueEffect = nullptr; + } + path_set(0); + state = STATUE_STATE_BROKEN; + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + GridEntity_Door* door = room.GetDoor(slot); + if (!door || door->state == DOOR_STATE_CLOSED) continue; + + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + for (int roomType : {door->currentRoomType, door->targetRoomType}) + if (roomType == ROOM_SECRET || roomType == ROOM_SUPERSECRET || roomType == ROOM_ULTRASECRET) + door->openAnimation = "Open"; + } + room.descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; + return true; } diff --git a/src/grid_entity_tnt.cpp b/src/grid_entity_tnt.cpp index 63b0f31..77fe21c 100644 --- a/src/grid_entity_tnt.cpp +++ b/src/grid_entity_tnt.cpp @@ -13,7 +13,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 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 0887257..be4bd1c 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -32,17 +32,11 @@ constexpr std::string_view ANIM_OPENED = "Opened"; constexpr std::string_view ANIM_PLAYER_FALL = "Trapdoor"; // The stages (with a labyrinth counted as the next) whose exits are holes in the floor or the Void's portal. -constexpr int STAGE_WOMB_I = 7; -constexpr int STAGE_BLUE_WOMB = 9; -constexpr int STAGE_DEPTHS_I = 5; -constexpr int STAGE_DEPTHS_II = 6; -constexpr int STAGE_CAVES_I = 3; constexpr int STAGE_LAST_CHAPTER = 10; constexpr int GAME_STATE_BACKWARDS_PATH_INIT = 47; // Mother's boss room in the special rooms. -constexpr int STAGE_ID_SPECIAL_ROOMS = 0; constexpr int BOSS_MOTHER = 88; constexpr int MINES_LAYER_HIDDEN = 1; constexpr int EFFECT_MINES_TRAPDOOR_COVER = 139; diff --git a/src/grid_entity_wall.cpp b/src/grid_entity_wall.cpp index fe30d2b..b8b049e 100644 --- a/src/grid_entity_wall.cpp +++ b/src/grid_entity_wall.cpp @@ -7,9 +7,6 @@ #include "seeds.h" #include -constexpr int BACKDROP_DUNGEON_GIDEON = 55; -constexpr int BACKDROP_DUNGEON_ROTGUT = 56; - // The walls inside an L-shaped room's corner: the columns either side of the middle and the rows above and below it. constexpr int L_COLUMN_LEFT = 13; constexpr int L_COLUMN_RIGHT = 14; diff --git a/src/grid_entity_web.cpp b/src/grid_entity_web.cpp index be5e03d..6d59e1d 100644 --- a/src/grid_entity_web.cpp +++ b/src/grid_entity_web.cpp @@ -1,16 +1,58 @@ #include "grid_entity_web.h" -#include "log.h" +#include "entity_player.h" +#include "game.h" +#include +#include -// 00721540 Loads the web. +// How often a web slows the players in it, how near they must be, and how much and how long it slows them, tinted +// blue. A web turns in quarter turns. +constexpr int WEB_CHECK_FRAMES = 4; +constexpr float WEB_REACH = 21; +constexpr int WEB_SLOW_FRAMES = 4; +constexpr float WEB_SLOW = 0.75f; +constexpr ColorMod WEB_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {0.15686275f, 0.15686275f, 0.15686275f}}; +constexpr uint32_t WEB_TURNS = 3; +constexpr float WEB_TURN_DEGREES = 90; + +// 00721540 Loads the web, burnt on its first bombed frame or swaying from a random frame, flipped and turned at +// random. void GridEntity_Web::subclass_init() { - reconstruction_missing("GridEntity_Web::subclass_init 00721540"); + collisionClass = COLLISION_NONE; + sprite.Load("gfx/grid/grid_web.anm2", GRAPHICS_LOAD); + if (state != WEB_STATE_STANDING) return sprite.SetFrame("Bombed", 0); + + sprite.Play("Swaying"); + const AnimationData* data = sprite.animState.animData; + int length = data ? data->length : 0; + int frame = length == 0 ? 0 : (int)(Random() % (uint32_t)length); + if (sprite.animState.animData) + { + sprite.animState.SetFrameFloat((float)frame); + sprite.animState.isPlaying = false; + } + sprite.isFlipX = (Random() & 1) == 0; + sprite.rotation = (float)(Random() & WEB_TURNS) * WEB_TURN_DEGREES; } -// 00721780 Slows the entities in the web. +// 00721780 Every fourth frame slows the walking players in a standing web (but not with Evil Charm), tinted blue. void GridEntity_Web::Update() { - reconstruction_missing("GridEntity_Web::Update 00721780"); + if (state == WEB_STATE_STANDING && g_game->frameCount % WEB_CHECK_FRAMES == 0) + { + Vector position = Position(); + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->entityGridCollisionClass <= GRIDCOLL_WALLS) continue; + bool isCharmed = player->HasCollectible(COLLECTIBLE_EVIL_CHARM) || + player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_EVIL_CHARM); + if (isCharmed && type == GRID_SPIDERWEB) continue; + + float reach = std::max(std::abs(player->pos.y - position.y), std::abs(player->pos.x - position.x)); + if (reach < WEB_REACH) player->AddSlowing(EntityRef(), WEB_SLOW_FRAMES, WEB_SLOW, WEB_SLOW_COLOR, false); + } + } + sprite.Update(); } // 00721a10 Burns a standing web away, stopped on its first bombed frame. diff --git a/src/hud.cpp b/src/hud.cpp index 55e8edd..64a3dc6 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -77,8 +77,6 @@ constexpr int STB_HOME = 35; constexpr int BOSS_MEGA_SATAN = 55; constexpr int BOSS_GREAT_GIDEON = 83; constexpr int BOSS_MOTHER = 88; -constexpr int BACKDROP_DOGMA = 54; -constexpr int STAGE_ULTRA_GREED = 7; constexpr uint32_t ROOM_FLAG_CLEAR = 1; constexpr int ONLINE_HUD_COMPACT = 1; constexpr int ONLINE_HUD_HIDDEN = 2; diff --git a/src/item_overlay.cpp b/src/item_overlay.cpp index 2c8c1bb..528240e 100644 --- a/src/item_overlay.cpp +++ b/src/item_overlay.cpp @@ -19,8 +19,6 @@ 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; diff --git a/src/item_overlay.h b/src/item_overlay.h index 957fcc6..cf3acd9 100644 --- a/src/item_overlay.h +++ b/src/item_overlay.h @@ -21,9 +21,12 @@ enum OverlayUpdate // The giant book overlays of giantbook.xml (g_game->itemOverlay) that do more than play. enum GiantbookOverlay : int { + GIANTBOOK_ETERNAL_SOUL_HEART = 6, + GIANTBOOK_ETERNAL_HEART = 13, GIANTBOOK_CLICKER = 39, GIANTBOOK_SLEEP_NIGHTMARE = 44, - GIANTBOOK_MEGA_MUSH = 45 + GIANTBOOK_MEGA_MUSH = 45, + GIANTBOOK_ETERNAL_BLACK_HEART = 46 }; // Destruction (009abd80) is the default. diff --git a/src/item_pool.cpp b/src/item_pool.cpp index 5852644..5a0bdd3 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -75,7 +75,6 @@ constexpr uint32_t TRINKET_GOLDEN = 0x8000; constexpr uint32_t STATE_SATANIC_BIBLE_USED = 0x20000; constexpr uint32_t DESCRIPTOR_DEVIL_TREASURE = 0x800; constexpr int BOSS_THE_FALLEN = 23; -constexpr int STAGE_HOME = 35; constexpr int HOME_CHEST_SUBTYPE = 2; constexpr int COLLECTIBLE_ROTTEN_MEAT = 26; @@ -437,7 +436,7 @@ int ItemPool::get_pool_from_room_entities(uint32_t roomSeed, RoomDescriptor& roo roomType = ROOM_BOSS; int pool = GetPoolForRoom(roomType, roomSeed); - bool isHomeChest = data.type == ROOM_DEFAULT && data.stageId == STAGE_HOME && data.subtype == HOME_CHEST_SUBTYPE; + bool isHomeChest = data.type == ROOM_DEFAULT && data.stageId == STAGE_ID_HOME && data.subtype == HOME_CHEST_SUBTYPE; return isHomeChest ? POOL_MOMS_CHEST : pool; } diff --git a/src/level.cpp b/src/level.cpp index 2bc05c3..e3414e2 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -35,40 +35,13 @@ constexpr int ROOM_OFF_MAP_15_IDX = -15; constexpr float OFF_MAP_15_ENTRY_X = 80; constexpr float OFF_MAP_15_ENTRY_Y = 400; -constexpr uint32_t LEVEL_STAGE_BASEMENT_I = 1; -constexpr uint32_t LEVEL_STAGE_CAVES_I = 3; -constexpr uint32_t LEVEL_STAGE_CAVES_II = 4; -constexpr uint32_t LEVEL_STAGE_DEPTHS_I = 5; -constexpr uint32_t LEVEL_STAGE_DEPTHS_II = 6; -constexpr uint32_t LEVEL_STAGE_WOMB_I = 7; -constexpr uint32_t LEVEL_STAGE_WOMB_II = 8; -constexpr uint32_t LEVEL_STAGE_BLUE_WOMB = 9; -constexpr uint32_t LEVEL_STAGE_SHEOL = 10; -constexpr uint32_t LEVEL_STAGE_DARK_ROOM = 11; -constexpr uint32_t LEVEL_STAGE_VOID = 12; -constexpr uint32_t LEVEL_STAGE_HOME = 13; constexpr uint32_t ASCENT_LAST_STAGE = 6; constexpr int VOID_STAGE_ID_LAST = 17; -constexpr int STAGE_ID_SPECIAL_ROOMS = 0; -constexpr int STAGE_ID_DEPTHS = 7; -constexpr int STAGE_ID_NECROPOLIS = 8; -constexpr int STAGE_ID_DANK_DEPTHS = 9; -constexpr int STAGE_ID_DARK_ROOM = 16; -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_MINES = 29; -constexpr int STAGE_ID_CORPSE = 33; -constexpr int STAGE_ID_DOWNPOUR = 27; -constexpr int STAGE_ID_DROSS = 28; -constexpr int STAGE_ID_VOID = 26; constexpr uint32_t CHALLENGE_XXXXXXXXL = 21; // The Ascent's music: the alternate path's stages take the layers past the chapters'. constexpr int ALT_PATH_LAYER_FIRST = 3; -constexpr int STAGE_ID_HOME = 35; constexpr int DIMENSION_MINESHAFT = 2; constexpr int ENEMY_TYPE_LAST = 999; @@ -139,12 +112,14 @@ constexpr int ROOM_INDEX_OTHER_DIMENSION = -100; constexpr int ROOM_INDEX_MIRRORED_START = -101; constexpr int MIRROR_START_GRID_INDEX = 162; constexpr int MIRROR_START_SUBTYPE = 10; -constexpr int BACKDROP_DOWNPOUR_ENTRANCE = 31; -constexpr int BACKDROP_DOWNPOUR_EXIT = 36; -constexpr int BACKDROP_DROSS = 45; constexpr int BOSS_RUSH_PAR_TIME = 36000; constexpr int BOSS_RUSH_PAR_TIME_ALT = 45000; constexpr uint32_t BACKWARDS_STAGE_END = 8; +constexpr size_t BACKWARDS_ROOMS_KEPT = 2; +constexpr uint32_t RANDOM_ROOM_SHIFT_INDEX = 16; +constexpr uint32_t BLACK_MARKET_TELEPORT_ODDS = 50; +constexpr int CHALLENGE_SUBTYPE_BOSS = 1; +constexpr int CHALLENGE_LOW_HEALTH = 2; constexpr int STATE_GREED_SPAWNED = 15; constexpr int STATE_SUPER_GREED_SPAWNED = 16; @@ -257,7 +232,6 @@ constexpr int GREED_SUBTYPE_SUPER = 11; constexpr int GREED_SUBTYPE_DEVIL = 15; constexpr int RED_ROOM_DOOR_TARGET = -2; constexpr int HUD_REFRESH_FRAMES = 2; -constexpr int BACKDROP_CORPSE3 = 44; constexpr int EFFECT_VARIANT_BLOOD_SPLAT = 7; constexpr uint32_t TRANSITION_FLAG_TREASURE_REROLL = 1 << 0; constexpr uint32_t TRANSITION_FLAG_NO_TAKEOVER = 1 << 1; @@ -396,7 +370,7 @@ void Level::Init(bool isResetLilPortalRoom) generationRNG.Next(); // The words at Game+0x188fc..0x1890c this also resets are not modeled yet. - isBossChallenge = stage > 0 && stage <= LEVEL_STAGE_WOMB_II && stage % 2 == 0; + isBossChallenge = stage > 0 && stage <= STAGE_WOMB_II && stage % 2 == 0; enterDoor = DOOR_NONE; leaveDoor = DOOR_NONE; startingRoomIdx = START_GRID_INDEX; @@ -416,12 +390,12 @@ void Level::Init(bool isResetLilPortalRoom) if (is_unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE)) curseOdds = CURSE_ODDS_TERRIBLE[isHard]; if (g_manager->persistentGameData.eventCounters[EVENT_COUNTER_CURSE_ODDS] != 0 || game.dailyChallenge._id != 0) curseOdds = CURSE_ODDS_DAILY[isHard]; - if (stage == LEVEL_STAGE_BASEMENT_I && !is_unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE)) curseOdds = 0; + if (stage == STAGE_BASEMENT_I && !is_unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE)) curseOdds = 0; RNG curseRng{}; curseRng.SetSeed(generationRNG._seed, GENERATION_SHIFT_INDEX); - bool isCurseRolled = stage != LEVEL_STAGE_HOME && !IsAscent() && curseOdds != 0 && + bool isCurseRolled = stage != STAGE_HOME && !IsAscent() && curseOdds != 0 && !game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BLACK_CANDLE, LAZARUS_SHARE_CHECK) && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_NO_CURSES; @@ -479,14 +453,14 @@ void Level::Init(bool isResetLilPortalRoom) ChallengeParam& params = g_manager->GetChallengeParams((int)game.challenge); curses = (curses | params.getCurse) & ~params.curseFilter; - if (game.challenge == CHALLENGE_RED_REDEMPTION || stage % 2 == 0 || stage >= LEVEL_STAGE_WOMB_II || is_greed()) + if (game.challenge == CHALLENGE_RED_REDEMPTION || stage % 2 == 0 || stage >= STAGE_WOMB_II || is_greed()) curses &= ~CURSE_OF_LABYRINTH; } - if (stage == LEVEL_STAGE_BLUE_WOMB || game.victoryLap > 2) curses &= ~CURSE_OF_DARKNESS; + if (stage == STAGE_BLUE_WOMB || game.victoryLap > 2) curses &= ~CURSE_OF_DARKNESS; game.hud.InvalidateCraftingItem(nullptr); game.roomConfig.ClearGeneratedRooms(); - if (stage == LEVEL_STAGE_VOID) + if (stage == STAGE_VOID) { for (int stageId = 1; stageId <= VOID_STAGE_ID_LAST; stageId++) if (stageId != STAGE_ID_BLUE_WOMB) game.roomConfig.ResetRoomWeights(stageId, ROOM_MODE_CURRENT); @@ -501,10 +475,10 @@ void Level::Init(bool isResetLilPortalRoom) game.roomConfig.ResetRoomWeights(STAGE_ID_SPECIAL_ROOMS, ROOM_MODE_CURRENT); generate_greed(); } - else if (stage == LEVEL_STAGE_HOME) generate_home_level(); + else if (stage == STAGE_HOME) generate_home_level(); else if (stage <= ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH)) generate_backwards(); else if (game.challenge == CHALLENGE_RED_REDEMPTION) generate_random_layout(); - else if (stage == LEVEL_STAGE_BLUE_WOMB) generate_home(); + else if (stage == STAGE_BLUE_WOMB) generate_home(); else { game.roomConfig.ResetRoomWeights(STAGE_ID_SPECIAL_ROOMS, ROOM_MODE_CURRENT); @@ -513,7 +487,7 @@ void Level::Init(bool isResetLilPortalRoom) update_all_room_doors(); dungeonPlacementSeed = generationRNG.Next(); - if (!is_greed() && stage == LEVEL_STAGE_VOID && firstBossRoomListIdx >= 0) + if (!is_greed() && stage == STAGE_VOID && firstBossRoomListIdx >= 0) reconstruction_missing("Level::Init 00744940: the Void's Delirium distances (get_rooms_within_two_doors)"); currentRoomIdx = startingRoomIdx; @@ -526,7 +500,7 @@ void Level::Init(bool isResetLilPortalRoom) } log_printf(LOG_INFO, "CURRENT ROOM INDEX %d %08x\n", currentRoomIdx, GetRoomByIdx(currentRoomIdx)->listIndex); - bool isBackasswardsEnd = game.challenge == CHALLENGE_BACKASSWARDS && stage == LEVEL_STAGE_DARK_ROOM; + bool isBackasswardsEnd = game.challenge == CHALLENGE_BACKASSWARDS && stage == STAGE_DARK_ROOM; if (isBackasswardsEnd) { @@ -536,8 +510,8 @@ void Level::Init(bool isResetLilPortalRoom) load_room(); if (isBackasswardsEnd) room->Update(); room->PlayMusic(); - if (game.challenge != CHALLENGE_BACKASSWARDS || stage == LEVEL_STAGE_DARK_ROOM) UpdateVisibility(); - if (stage == LEVEL_STAGE_DARK_ROOM && game.GetChallengeParams().isMegaSatan && + if (game.challenge != CHALLENGE_BACKASSWARDS || stage == STAGE_DARK_ROOM) UpdateVisibility(); + if (stage == STAGE_DARK_ROOM && game.GetChallengeParams().isMegaSatan && game.challenge != CHALLENGE_BACKASSWARDS) for (int keyPiece : {COLLECTIBLE_KEY_PIECE_1, COLLECTIBLE_KEY_PIECE_2}) if (!game.playerManager.FirstCollectibleOwner(keyPiece, LAZARUS_SHARE_CHECK)) @@ -546,7 +520,7 @@ void Level::Init(bool isResetLilPortalRoom) uint32_t voiceStage = effectiveStage + ((GetCurses() & CURSE_OF_LABYRINTH) && effectiveStage % 2 == 0 ? 1 : 0); if (IsAscent() && g_manager->optionsConfig.isAscentVoiceover && voiceStage % 2 == 1 && - voiceStage <= LEVEL_STAGE_WOMB_I) + voiceStage <= STAGE_WOMB_I) reconstruction_missing("Level::Init 00744940: the Ascent's voiceover timer (Entity_Effect::CreateTimer)"); game.playerManager.trigger_level_start(); @@ -611,13 +585,13 @@ void Level::generate_dungeon(RNG& curseRng) else if (GetCurses() & CURSE_OF_THE_LOST) roomCount += ROOM_COUNT_LOST_BONUS; if (game.challenge == CHALLENGE_XXXXXXXXL) roomCount = (int)(generationRNG.Next() % ROOM_COUNT_ROLL) + ROOM_COUNT_XXXXXXXXL; - if (stage == LEVEL_STAGE_VOID) roomCount = (int)(generationRNG.Next() % ROOM_COUNT_ROLL) + ROOM_COUNT_VOID; + if (stage == STAGE_VOID) roomCount = (int)(generationRNG.Next() % ROOM_COUNT_ROLL) + ROOM_COUNT_VOID; if (uint32_t flip = curseRng.Next() & 1; isHard) roomCount += ROOM_COUNT_HARD_BONUS + (int)flip; if (GetCurses() & CURSE_OF_GIANT) roomCount = std::max(ROOM_COUNT_GIANT_MIN, roomCount * GIANT_ROOM_SHARE / GIANT_ROOM_DIVISOR); - int deadEndCount = DEAD_ENDS_BASE + (stage != LEVEL_STAGE_BASEMENT_I) + isLabyrinth + - (stage == LEVEL_STAGE_VOID ? DEAD_ENDS_VOID_BONUS : 0); + int deadEndCount = DEAD_ENDS_BASE + (stage != STAGE_BASEMENT_I) + isLabyrinth + + (stage == STAGE_VOID ? DEAD_ENDS_VOID_BONUS : 0); if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_VOODOO_HEAD, LAZARUS_SHARE_CHECK)) deadEndCount++; if (HasAbandonedMineshaft() || HasMirrorDimension()) deadEndCount++; @@ -626,7 +600,7 @@ void Level::generate_dungeon(RNG& curseRng) int minDifficulty = isHard ? DIFFICULTY_MEDIUM : DIFFICULTY_EASY; int maxDifficulty = isHard ? DIFFICULTY_MAX : DIFFICULTY_HARD_MAX; - if (!isLabyrinth && stage < LEVEL_STAGE_BLUE_WOMB) + if (!isLabyrinth && stage < STAGE_BLUE_WOMB) { bool isEven = stage % 2 == 0; @@ -642,7 +616,7 @@ void Level::generate_dungeon(RNG& curseRng) } } - bool isVoid = stage == LEVEL_STAGE_VOID; + bool isVoid = stage == STAGE_VOID; int stageId = RoomConfig::GetStageID((int)stage, (int)stageType, ROOM_MODE_CURRENT); auto rooms_collect = [&]() { std::vector rooms; @@ -678,7 +652,7 @@ void Level::generate_dungeon(RNG& curseRng) if (config->shape >= 0 && config->shape < ROOMSHAPE_ANY) settings.allowedShapes |= 1u << config->shape; if (GetCurses() & CURSE_OF_GIANT) settings.allowedShapes &= ~(1u << ROOMSHAPE_1x1 | 1u << ROOMSHAPE_IH | 1u << ROOMSHAPE_IV); - settings.isChapter6 = stage == LEVEL_STAGE_DARK_ROOM; + settings.isChapter6 = stage == STAGE_DARK_ROOM; settings.isVoid = isVoid; settings.isXL = isLabyrinth || game.challenge == CHALLENGE_XXXXXXXXL; @@ -845,7 +819,7 @@ uint32_t Level::filter_curses(uint32_t mask) // Greed and Red Redemption. bool Level::CanStageHaveCurseOfLabyrinth(uint32_t levelStage) { - return g_game->challenge != CHALLENGE_RED_REDEMPTION && levelStage % 2 == 1 && levelStage < LEVEL_STAGE_WOMB_II && + return g_game->challenge != CHALLENGE_RED_REDEMPTION && levelStage % 2 == 1 && levelStage < STAGE_WOMB_II && !is_greed(); } @@ -870,15 +844,61 @@ void Level::SetRedHeartDamage() greedWavesClearedWithoutRedHeartDamage = 0; } +// A room the Ascent keeps: its descriptor, with its config named apart. +static SavedRoom backwards_room_save(const RoomDescriptor& desc) +{ + SavedRoom saved{desc, {}}; + + if (desc.data) room_config_ref_save(*desc.data, saved.config, nullptr); + saved.desc.data = nullptr; + return saved; +} + +// 00708050 Keeps a stage's rooms for the Ascent as the floor is left: its stage type, the last boss room first, then +// up to one more boss room and two treasure rooms of the main dimension. A second boss room makes the stage an XL one, +// which clears the next stage's rooms. A stage outside 1 to 7 is only logged, as the original writes past the stages. +void Game::SaveBackwardsStage(int stage) +{ + Game& game = *g_game; + + if (stage < 1 || stage > BACKWARDS_STAGE_COUNT) return log_printf(LOG_ASSERT, "Invalid backwards path stage ID"); + + BackwardsStageDesc& saved = game.backwardsStages[stage - 1]; + + saved.stageType = game.stageType; + saved.bossRooms = {backwards_room_save(game.roomList[game.lastBossRoomListIdx])}; + saved.treasureRooms.clear(); + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& desc = game.roomList[i]; + + if (!desc.data || desc.dimension != 0) continue; + if (desc.data->type == ROOM_BOSS) + { + if (i != game.lastBossRoomListIdx && saved.bossRooms.size() < BACKWARDS_ROOMS_KEPT) + saved.bossRooms.push_back(backwards_room_save(desc)); + } + else if (desc.data->type == ROOM_TREASURE && saved.treasureRooms.size() < BACKWARDS_ROOMS_KEPT) + saved.treasureRooms.push_back(backwards_room_save(desc)); + } + + saved.isXL = saved.bossRooms.size() > 1; + if (saved.isXL && stage < BACKWARDS_STAGE_COUNT) + { + game.backwardsStages[stage].bossRooms.clear(); + game.backwardsStages[stage].treasureRooms.clear(); + } +} + // 007466d0 Moves to a stage and type (clamped to the game's), recording the stage left for the Ascent, the stage for // the nightmare scenes, and Boss Rush's par time (longer on the alternate path's first six stages). void Level::SetStage(int stageId, int alt) { - uint32_t newStage = (uint32_t)std::clamp(stageId, 0, (int)LEVEL_STAGE_HOME); + uint32_t newStage = (uint32_t)std::clamp(stageId, 0, (int)STAGE_HOME); uint32_t newType = (uint32_t)std::clamp(alt, 0, (int)STAGETYPE_REPENTANCE_B); if (stage > 0 && !IsAscent() && stage + (IsAltPath() ? 1 : 0) < BACKWARDS_STAGE_END) - reconstruction_missing("Level::SetStage 007466d0: Game::SaveBackwardsStage 00708050"); + Game::SaveBackwardsStage((int)stage + (IsAltPath() ? 1 : 0)); stage = newStage; stageType = newType; @@ -893,7 +913,7 @@ uint32_t Level::GetStageID() { Room& current = *g_game->room; - if (current.backdropType == BACKDROP_DOWNPOUR_ENTRANCE || current.backdropType == BACKDROP_DOWNPOUR_EXIT) + if (current.backdropType == BACKDROP_DOWNPOUR || current.backdropType == BACKDROP_DOWNPOUR_ENTRANCE) return STAGE_ID_DOWNPOUR; if (current.backdropType == BACKDROP_DROSS) return STAGE_ID_DROSS; @@ -956,33 +976,33 @@ static uint32_t stage_with_labyrinth(Level& level) // 0074ea50 Whether the run is about to start the Ascent: Mausoleum II (or an XL Mausoleum) after its heart was killed. bool Level::IsPreAscent() { - return is_path_stage(*this, true) && stage_with_labyrinth(*this) == LEVEL_STAGE_DEPTHS_II && + return is_path_stage(*this, true) && stage_with_labyrinth(*this) == STAGE_DEPTHS_II && game_flag_get(LEVEL_GAME_STATE_MAUSOLEUM_HEART_KILLED); } // 0074e9b0 Whether the floor is Mausoleum II (or an XL Mausoleum) holding Mother's heart room. bool Level::IsMausoleumHeartStage() { - return is_path_stage(*this, true) && stage_with_labyrinth(*this) == LEVEL_STAGE_DEPTHS_II && + return is_path_stage(*this, true) && stage_with_labyrinth(*this) == STAGE_DEPTHS_II && game_flag_get(LEVEL_GAME_STATE_MAUSOLEUM_HEART_ROOM); } // 0074ef70 Whether the floor has Dross or Downpour II's mirror world (or an XL first one). bool Level::HasMirrorDimension() { - return is_path_stage(*this, true) && is_chapter_second_floor(*this, LEVEL_STAGE_BASEMENT_I); + return is_path_stage(*this, true) && is_chapter_second_floor(*this, STAGE_BASEMENT_I); } // 0074efd0 Whether the floor has the Mines or Ashpit II's abandoned mineshaft (or an XL first one). bool Level::HasAbandonedMineshaft() { - return is_path_stage(*this, true) && is_chapter_second_floor(*this, LEVEL_STAGE_CAVES_I); + return is_path_stage(*this, true) && is_chapter_second_floor(*this, STAGE_CAVES_I); } // 0074f030 Whether the floor has Depths II's strange door (or an XL Depths). bool Level::HasPhotoDoor() { - return is_path_stage(*this, false) && is_chapter_second_floor(*this, LEVEL_STAGE_DEPTHS_I); + return is_path_stage(*this, false) && is_chapter_second_floor(*this, STAGE_DEPTHS_I); } // What placing a floor's special rooms shares between its steps: the layout, the room types the run's challenge leaves @@ -1058,7 +1078,7 @@ static void room_place(Level& level, LevelGenerator_Room* room, RoomConfig_Room* // The trinket of the floor's crown: Wicked Crown on Sheol, Holy Crown on the Cathedral, none elsewhere. static int crown_trinket_get(Level& level) { - if (level.stage != LEVEL_STAGE_SHEOL) return 0; + if (level.stage != STAGE_SHEOL) return 0; if (level.stageType == STAGETYPE_ORIGINAL) return TRINKET_WICKED_CROWN; return level.stageType == STAGETYPE_WOTL ? TRINKET_HOLY_CROWN : 0; } @@ -1087,8 +1107,8 @@ static bool is_deal_floor(Level& level, int wombTrinket) PlayerManager& players = g_game->playerManager; int crown = crown_trinket_get(level); - if (level.stage < LEVEL_STAGE_WOMB_I) return true; - if (level.stage < LEVEL_STAGE_BLUE_WOMB && players.AnyoneHasTrinket(wombTrinket)) return true; + if (level.stage < STAGE_WOMB_I) return true; + if (level.stage < STAGE_BLUE_WOMB && players.AnyoneHasTrinket(wombTrinket)) return true; return crown && players.AnyoneHasTrinket(crown); } @@ -1118,7 +1138,7 @@ static bool boss_rooms_place(SpecialRoomPlacement& placement) Game& game = *g_game; LevelGenerator& generator = placement.generator; - if (game.GetChallengeParams().isMegaSatan && level.stage == LEVEL_STAGE_DARK_ROOM) + if (game.GetChallengeParams().isMegaSatan && level.stage == STAGE_DARK_ROOM) { level.lastBossRoomListIdx = level.GetRoomByIdx(ROOM_MEGA_SATAN_IDX)->listIndex; return true; @@ -1132,7 +1152,7 @@ static bool boss_rooms_place(SpecialRoomPlacement& placement) level.firstBossRoomListIdx = level.nbRooms; boss_room_commit(level, *bossRoom, config); - if (level.stage == LEVEL_STAGE_VOID) + if (level.stage == STAGE_VOID) { int extraCount = (int)level.generationRNG.RandomInt(VOID_EXTRA_BOSS_ROLL) + VOID_EXTRA_BOSSES_MIN; std::vector bossIds(VOID_BOSS_IDS.begin(), VOID_BOSS_IDS.end()); @@ -1203,7 +1223,7 @@ static int shop_subtype_get(Level& level, int& crownMultiplier) uint32_t roll = rng.Next(); auto is_lucky = [&]() { crownMultiplier = crown_multiplier_get(level); - return crownMultiplier >= 2 || ((level.stage == LEVEL_STAGE_WOMB_I || level.stage == LEVEL_STAGE_WOMB_II) && + return crownMultiplier >= 2 || ((level.stage == STAGE_WOMB_I || level.stage == STAGE_WOMB_II) && is_trinket_strong(TRINKET_SILVER_DOLLAR, 2)); }; bool isLucky = false; @@ -1431,7 +1451,7 @@ static void miniboss_room_place(SpecialRoomPlacement& placement) { Level& level = placement.level; RNG& rng = level.generationRNG; - int difficulty = level.stage < LEVEL_STAGE_WOMB_I ? DIFFICULTY_EASY : DIFFICULTY_HARD_MAX; + int difficulty = level.stage < STAGE_WOMB_I ? DIFFICULTY_EASY : DIFFICULTY_HARD_MAX; int sin = miniboss_sin_get(placement); if (sin >= 0) @@ -1497,7 +1517,7 @@ static void arcade_place(SpecialRoomPlacement& placement) (config->type == ROOM_CHEST && player.numKeys >= 2)); if (config && !placement.is_excluded(config->type) && isAffordable && - (isEvenFloor || (isCainBirthright && stage < (int)LEVEL_STAGE_DARK_ROOM))) + (isEvenFloor || (isCainBirthright && stage < (int)STAGE_DARK_ROOM))) room_place(level, room, config, rng._seed); else end_room_return(placement.generator, room); } @@ -1604,7 +1624,7 @@ static bool dark_room_extra_place(SpecialRoomPlacement& placement) { Level& level = placement.level; - if (level.stage != LEVEL_STAGE_DARK_ROOM || level.stageType != STAGETYPE_ORIGINAL) return true; + if (level.stage != STAGE_DARK_ROOM || level.stageType != STAGETYPE_ORIGINAL) return true; uint32_t seed = level.generationRNG.Next(); RoomQuery query = room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_DEFAULT, -1); @@ -1678,7 +1698,7 @@ static bool normal_rooms_place(SpecialRoomPlacement& placement, int minDifficult Level& level = placement.level; RNG& rng = level.generationRNG; std::vector rooms = placement.generator.get_all_rooms(); - bool isDarkRoomFloor = level.stage == LEVEL_STAGE_DARK_ROOM; + bool isDarkRoomFloor = level.stage == STAGE_DARK_ROOM; placed.reserve(rooms.size()); for (LevelGenerator_Room* room : rooms) @@ -1795,7 +1815,7 @@ static void greed_takeover_roll(SpecialRoomPlacement& placement) game.donationModGreed = 0; if (level.generationRNG.RandomFloat() < chance && isAllowed && placement.secretIdx >= 0 && - level.stage > LEVEL_STAGE_CAVES_II) + level.stage > STAGE_CAVES_II) { RNG takeoverRng = {level.generationRNG._seed, 2, 7, 9}; @@ -1803,7 +1823,7 @@ static void greed_takeover_roll(SpecialRoomPlacement& placement) level.roomList[placement.secretIdx].flags |= ROOM_DESCRIPTOR_FLAG_SURPRISE_MINIBOSS; } if (level.generationRNG.RandomFloat() < chance && isAllowed && placement.shopIdx >= 0 && - level.stage > LEVEL_STAGE_CAVES_I) + level.stage > STAGE_CAVES_I) level.roomList[placement.shopIdx].flags |= ROOM_DESCRIPTOR_FLAG_SURPRISE_MINIBOSS; } @@ -1855,8 +1875,8 @@ static void off_map_rooms_init(SpecialRoomPlacement& placement) RNG angelRng = {rng.Next(), 3, 3, 28}; off_map_room_init(level, ROOM_ANGEL_SHOP_IDX, angelRng, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ANGEL, 1)); - if (level.IsAltPath() && (level.stage == LEVEL_STAGE_WOMB_II || - (level.stage == LEVEL_STAGE_WOMB_I && (level.GetCurses() & CURSE_OF_LABYRINTH)))) + if (level.IsAltPath() && (level.stage == STAGE_WOMB_II || + (level.stage == STAGE_WOMB_I && (level.GetCurses() & CURSE_OF_LABYRINTH)))) { rng.Next(); off_map_room_init(level, ROOM_SECRET_EXIT_IDX, rng, room_query(placement.stageId, ROOM_BOSS, BOSS_MOTHER)); @@ -1880,7 +1900,7 @@ bool Level::place_special_rooms(LevelGenerator& generator, int minDifficulty, in placement.secretSeed = generationRNG.Next(); if (!shop_place(placement) || !treasure_rooms_place(placement)) return false; planetarium_place(placement); - if (stage < LEVEL_STAGE_DARK_ROOM) + if (stage < STAGE_DARK_ROOM) { sacrifice_room_place(placement); library_place(placement); @@ -1889,7 +1909,7 @@ bool Level::place_special_rooms(LevelGenerator& generator, int minDifficulty, in challenge_room_place(placement); arcade_place(placement); } - if (stage < LEVEL_STAGE_WOMB_I) bedroom_place(placement); + if (stage < STAGE_WOMB_I) bedroom_place(placement); if (!special_door_rooms_place(placement)) return false; secret_rooms_place(placement); if (!dark_room_extra_place(placement)) return false; @@ -1972,7 +1992,7 @@ std::set Level::get_secret_room_excluded_cells() { std::set cells; - if (stage == LEVEL_STAGE_DARK_ROOM) + if (stage == STAGE_DARK_ROOM) for (int offset : {1, -1, LEVEL_GRID_WIDTH, -LEVEL_GRID_WIDTH}) if (startingRoomIdx + offset >= 0 && startingRoomIdx + offset < LEVEL_GRID_CELLS) cells.insert(startingRoomIdx + offset); @@ -2061,7 +2081,7 @@ bool Level::CanSpawnTrapDoor() Game& game = *g_game; int effectiveStage = (int)stage + ((GetCurses() & CURSE_OF_LABYRINTH) ? 1 : 0); bool isRepentanceStart = IsAltPath() && (effectiveStage == 1 || effectiveStage == 3 || effectiveStage == 5 || - effectiveStage == LEVEL_STAGE_WOMB_I); + effectiveStage == STAGE_WOMB_I); if (HasMirrorDimension() && currentDimensionIdx == 1) return false; if (!isLevelGenerating && room && room->roomType == ROOM_BOSS && @@ -2073,8 +2093,8 @@ bool Level::CanSpawnTrapDoor() return false; if (is_greed()) return IsNextStageAvailable(); if (!IsNextStageAvailable()) return false; - return game.stage < LEVEL_STAGE_WOMB_II || - (game.stage == LEVEL_STAGE_WOMB_II && IsStageWithinEnd(LEVEL_STAGE_SHEOL, false)); + return game.stage < STAGE_WOMB_II || + (game.stage == STAGE_WOMB_II && IsStageWithinEnd(STAGE_SHEOL, false)); } // 0074b710 Whether the run goes on past the floor: not from Home's stage, the pre-Ascent floor, the Dark Room, the Void @@ -2091,13 +2111,13 @@ bool Level::IsNextStageAvailable() if ((isRedRedemption || currentDimensionIdx != DEATH_CERTIFICATE_DIMENSION) && RoomConfig::GetStageID(nextStage, type, ROOM_MODE_CURRENT) == STAGE_ID_BACKWARDS) return false; - if (IsPreAscent() || nextStage >= (int)LEVEL_STAGE_DARK_ROOM || - (is_greed() && nextStage == (int)LEVEL_STAGE_WOMB_I)) + if (IsPreAscent() || nextStage >= (int)STAGE_DARK_ROOM || + (is_greed() && nextStage == (int)STAGE_WOMB_I)) return false; - if ((curses & CURSE_OF_LABYRINTH) && nextStage % 2 == 1 && nextStage <= (int)LEVEL_STAGE_WOMB_I) nextStage++; - if (nextStage == LEVEL_STAGE_WOMB_II && IsAltPath()) return false; - if ((nextStage == LEVEL_STAGE_DEPTHS_II || - (nextStage == LEVEL_STAGE_DEPTHS_I && filter_curses(CURSE_OF_LABYRINTH))) && + if ((curses & CURSE_OF_LABYRINTH) && nextStage % 2 == 1 && nextStage <= (int)STAGE_WOMB_I) nextStage++; + if (nextStage == STAGE_WOMB_II && IsAltPath()) return false; + if ((nextStage == STAGE_DEPTHS_II || + (nextStage == STAGE_DEPTHS_I && filter_curses(CURSE_OF_LABYRINTH))) && params.pathType == PATH_TYPE_HOME && !game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH)) return false; return (game.challenge == 0 && game.dailyChallenge._id == 0) || nextStage < params.endStage; @@ -2111,16 +2131,16 @@ bool Level::IsStageWithinEnd(int levelStage, bool isAltPath) Game& game = *g_game; ChallengeParam& params = game.GetChallengeParams(); bool isChallenge = game.challenge != 0 || game.dailyChallenge._id != 0; - int endStage = params.endStage == LEVEL_STAGE_VOID || (!isChallenge && is_unlocked(ACHIEVEMENT_THE_VOID)) - ? LEVEL_STAGE_VOID - : LEVEL_STAGE_DARK_ROOM; - bool isChapter5 = levelStage == LEVEL_STAGE_SHEOL || levelStage == LEVEL_STAGE_DARK_ROOM; + int endStage = params.endStage == STAGE_VOID || (!isChallenge && is_unlocked(ACHIEVEMENT_THE_VOID)) + ? STAGE_VOID + : STAGE_DARK_ROOM; + bool isChapter5 = levelStage == STAGE_SHEOL || levelStage == STAGE_DARK_ROOM; auto is_shovel = [&]() { return game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BROKEN_SHOVEL_1, LAZARUS_SHARE_CHECK) || game.playerManager.FirstCollectibleOwner(COLLECTIBLE_MOMS_SHOVEL, LAZARUS_SHARE_CHECK); }; - if (is_greed()) return levelStage <= (int)LEVEL_STAGE_WOMB_I; + if (is_greed()) return levelStage <= (int)STAGE_WOMB_I; if (isChapter5 && isAltPath && is_shovel() && (!params.isPathTypeSet || params.pathType != PATH_TYPE_CATHEDRAL)) return false; if (!params.isPathTypeSet) return levelStage <= endStage; @@ -2147,8 +2167,8 @@ float Level::GetPlanetariumChance() }; float chance = PLANETARIUM_CHANCE_MIN; - if (stage > LEVEL_STAGE_SHEOL || (stage > LEVEL_STAGE_DEPTHS_II && !isLens) || - (stage > LEVEL_STAGE_WOMB_II && !isGoldenLens && !isMomsBox)) + if (stage > STAGE_SHEOL || (stage > STAGE_DEPTHS_II && !isLens) || + (stage > STAGE_WOMB_II && !isGoldenLens && !isMomsBox)) return 0; if (game.planetariumsVisited == 0) { @@ -2197,7 +2217,7 @@ static bool is_treasure_reroll(Level& level, RoomDescriptor& desc) { Game& game = *g_game; PlayerManager& players = game.playerManager; - bool isWomb = level.stage == LEVEL_STAGE_WOMB_I || level.stage == LEVEL_STAGE_WOMB_II; + bool isWomb = level.stage == STAGE_WOMB_I || level.stage == STAGE_WOMB_II; bool isStrongCrown = desc.data->type == ROOM_TREASURE && desc.visitedCount == 0 && (crown_multiplier_get(level) >= 2 || (isWomb && is_trinket_strong(TRINKET_BLOODY_CROWN, 2))); @@ -2423,7 +2443,7 @@ void Level::load_room() if (room->roomType == ROOM_ULTRASECRET) ultra_secret_door_open(*this); bool isMineshaftFloor = - stage == LEVEL_STAGE_CAVES_II || (stage == LEVEL_STAGE_CAVES_I && (GetCurses() & CURSE_OF_LABYRINTH)); + stage == STAGE_CAVES_II || (stage == STAGE_CAVES_I && (GetCurses() & CURSE_OF_LABYRINTH)); bool isMineshaftEntrance = desc.data->type == ROOM_DEFAULT && desc.data->subtype == MINESHAFT_ENTRANCE_SUBTYPE && (desc.flags & ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE) && !desc.data->spawns.empty(); @@ -2469,7 +2489,7 @@ void Level::load_room() bool isHomePathBoss = game.GetChallengeParams().pathType == PATH_TYPE_HOME && - (stage == LEVEL_STAGE_DEPTHS_II || (stage == LEVEL_STAGE_DEPTHS_I && (GetCurses() & CURSE_OF_LABYRINTH))); + (stage == STAGE_DEPTHS_II || (stage == STAGE_DEPTHS_I && (GetCurses() & CURSE_OF_LABYRINTH))); if (isHomePathBoss && GetRoomByIdx(currentRoomIdx)->listIndex == lastBossRoomListIdx && (room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR)) @@ -2737,10 +2757,33 @@ void Level::RemoveCompassEffect() g_game->minimap.Refresh(); } -// 00740860 A random room index. -int Level::GetRandomRoomIndex(bool, uint32_t) +// 00740860 A random room by a seed among those of the current dimension and group but the players' own. The error +// room's teleport may also land in the error room (while a next floor exists) or, one seed in 50, the Black Market. +// With no room to pick the original reads past an empty list, so the players stay where they are. +int Level::GetRandomRoomIndex(bool isErrorRoom, uint32_t seed) { - reconstruction_missing("Level::GetRandomRoomIndex 00740860"); + RoomDescriptor& current = *room->descriptor; + std::vector candidates; + RNG rng{}; + + rng.SetSeed(seed, RANDOM_ROOM_SHIFT_INDEX); + if (isErrorRoom && IsNextStageAvailable()) + { + candidates.push_back(ROOM_ERROR_IDX); + if (rng.Next() % BLACK_MARKET_TELEPORT_ODDS == 0) candidates.push_back(ROOM_BLACK_MARKET_IDX); + } + + for (int cell = 0; cell < LEVEL_GRID_CELLS; cell++) + { + int listIndex = currentRoomMap[cell]; + + if (listIndex < 0 || listIndex == current.listIndex) continue; + RoomDescriptor& desc = roomList[listIndex]; + if (desc.dimension == currentDimensionIdx && (desc.group == -1 || desc.group == current.group)) + candidates.push_back(cell); + } + if (candidates.empty()) return currentRoomIdx; + return candidates[rng.Next() % candidates.size()]; } // 00740a60 A room not cleared yet. @@ -2755,24 +2798,6 @@ int Level::QueryRoomTypeIndex(int, bool, RNG&, bool) reconstruction_missing("Level::QueryRoomTypeIndex 007484c0"); } -// 00748d40 The room matching another. -int Level::find_matching_room_idx(int) -{ - reconstruction_missing("Level::find_matching_room_idx 00748d40"); -} - -// 00749270 Swaps two rooms for the Curse of the Maze. -bool Level::maze_swap_rooms(int, int) -{ - reconstruction_missing("Level::maze_swap_rooms 00749270"); -} - -// 007496a0 The rooms within two doors of a cell. -std::set Level::get_rooms_within_two_doors(int) -{ - reconstruction_missing("Level::get_rooms_within_two_doors 007496a0"); -} - // 0074a090 Where the players enter the current room when no door brings them: a crawlspace's ladder (by the // Black Market's or a room's), the secret shop's and the off-map rooms' spots, or back where a crawlspace was entered. // Elsewhere none, the origin. @@ -2862,10 +2887,31 @@ void Level::InitializeGenesisRoom() reconstruction_missing("Level::InitializeGenesisRoom 008e11b0"); } -// 00748760 Whether a challenge room may open. -bool Level::CanOpenChallengeRoom(int) +// 00748760 Whether a challenge room's door opens: once its challenge is done, for a boss challenge while every player +// has a heart or less (or no player is left), for a normal one at full health, and always through a red room. +bool Level::CanOpenChallengeRoom(int roomIdx) { - reconstruction_missing("Level::CanOpenChallengeRoom 00748760"); + RoomDescriptor& desc = *GetRoomByIdx(roomIdx); + PlayerManager& players = g_game->playerManager; + bool isOpen = false; + + if (!desc.data) return false; + if (desc.flags & ROOM_DESCRIPTOR_FLAG_CHALLENGE_DONE) return true; + if (desc.data->subtype == CHALLENGE_SUBTYPE_BOSS) + { + isOpen = true; + for (int i = 0; i < (int)players.playerList.size() && isOpen; i++) + { + Entity_Player& player = *players.GetPlayer(i); + + if (player.variant == PLAYER_VARIANT_PLAYER && player.soulHearts + player.redHearts > CHALLENGE_LOW_HEALTH) + isOpen = false; + } + } + else isOpen = players.check_full_health(HEALTH_CHECK_ALL); + + return isOpen || (room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM) || + (desc.flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM); } // 007481d0 Forces a horseman boss. @@ -2884,17 +2930,17 @@ bool Level::CanSpawnDevilRoom() int labyrinthStage = (int)stage_with_labyrinth(*this); bool isAltStage = stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; - bool isMausoleumTwo = !is_greed() && isAltStage && labyrinthStage == (int)LEVEL_STAGE_WOMB_II; + bool isMausoleumTwo = !is_greed() && isAltStage && labyrinthStage == (int)STAGE_WOMB_II; bool isBackwards = stage - 1 < ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH); if (isMausoleumTwo || IsPreAscent() || isBackwards) return false; int dealStage = labyrinthStage + (isAltStage ? 1 : 0); if (!is_greed()) { - if (dealStage == (int)LEVEL_STAGE_BASEMENT_I && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_DEALS) + if (dealStage == (int)STAGE_BASEMENT_I && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_DEALS) return false; - if (dealStage != (int)LEVEL_STAGE_BASEMENT_I && dealStage > (int)LEVEL_STAGE_WOMB_II) return false; - if (dealStage == (int)LEVEL_STAGE_DEPTHS_II && !is_unlocked(ACHIEVEMENT_THE_WOMB)) return false; + if (dealStage != (int)STAGE_BASEMENT_I && dealStage > (int)STAGE_WOMB_II) return false; + if (dealStage == (int)STAGE_DEPTHS_II && !is_unlocked(ACHIEVEMENT_THE_WOMB)) return false; } return std::popcount(roomList[lastBossRoomListIdx].data->doors & 0xff) > 1; } @@ -2917,18 +2963,6 @@ void Level::raise_mineshaft_rail() reconstruction_missing("Level::raise_mineshaft_rail 0074eaf0"); } -// 0074a2d0 Adds curses. -void Level::AddCurse(uint32_t, bool) -{ - reconstruction_missing("Level::AddCurse 0074a2d0"); -} - -// 00748bc0 Removes curses. -void Level::RemoveCurses(uint32_t) -{ - reconstruction_missing("Level::RemoveCurses 00748bc0"); -} - // The music layer the Ascent turns on for a stage it climbs through: one per chapter, the alternate paths' past them. static int backwards_layer_get(int ascentStage) { @@ -2950,7 +2984,7 @@ bool Level::UpdateBackwardsPathStages() if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME) return false; int floor = (int)game.stage; - bool isAscentFloor = floor >= (int)LEVEL_STAGE_BASEMENT_I && floor <= (int)ASCENT_LAST_STAGE; + bool isAscentFloor = floor >= (int)STAGE_BASEMENT_I && floor <= (int)ASCENT_LAST_STAGE; if (isAscentFloor && (game.gameStateFlags >> LEVEL_GAME_STATE_BACKWARDS_PATH & 1)) { bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; @@ -2963,7 +2997,7 @@ bool Level::UpdateBackwardsPathStages() layers >> layer & 1 ? music.EnableLayer(layer, LAYER_FADE) : music.DisableLayer(layer); return layers != 0; } - if (!isAscentFloor && floor == (int)LEVEL_STAGE_HOME && game.stageType == STAGETYPE_WOTL) return true; + if (!isAscentFloor && floor == (int)STAGE_HOME && game.stageType == STAGETYPE_WOTL) return true; int depth = floor; if (game.IsGreedMode()) depth = floor <= GREED_STAGE_LAST_PAIRED ? floor * 2 - 1 : floor == GREED_STAGE_SHOP ? GREED_DEPTH_SHOP : 0; @@ -2976,7 +3010,7 @@ bool Level::UpdateBackwardsPathStages() break; } - if (floor < (int)LEVEL_STAGE_BLUE_WOMB) + if (floor < (int)STAGE_BLUE_WOMB) { for (Entity* entity : room->entityList.updateEL) { @@ -3075,7 +3109,7 @@ std::string Level::get_stage_display_name(const StageNameQuery& query) bool isNumbered = mode != ROOM_MODE_GREED && game.challenge != CHALLENGE_RED_REDEMPTION; if (isNumbered && (query.curses & CURSE_OF_LABYRINTH)) name += " XL"; - else if (isNumbered && query.numeral == 0 && query.stage >= 1 && query.stage <= (int)LEVEL_STAGE_WOMB_II) + else if (isNumbered && query.numeral == 0 && query.stage >= 1 && query.stage <= (int)STAGE_WOMB_II) name += query.stage & 1 ? " I" : " II"; return query.isScrambled ? string_scramble_seeded(name) : name; } diff --git a/src/level.h b/src/level.h index 8861f62..c7760a0 100644 --- a/src/level.h +++ b/src/level.h @@ -100,10 +100,71 @@ enum StageType : uint32_t STAGETYPE_REPENTANCE_B }; -// Home's night stage type, the Dark Room's stage and the Blue Womb's stage id. +// Home's night stage type. constexpr int STAGE_TYPE_HOME_NIGHT = 1; -constexpr int STAGE_DARK_ROOM = 11; -constexpr int STAGE_ID_BLUE_WOMB = 13; + +// A floor's depth (Lua's LevelStage), from Basement I to Home. Greed mode counts its own floors, its shop the sixth. +enum LevelStage : int +{ + STAGE_BASEMENT_I = 1, + STAGE_BASEMENT_II, + STAGE_CAVES_I, + STAGE_CAVES_II, + STAGE_DEPTHS_I, + STAGE_DEPTHS_II, + STAGE_WOMB_I, + STAGE_WOMB_II, + STAGE_BLUE_WOMB, + STAGE_SHEOL, + STAGE_DARK_ROOM, + STAGE_VOID, + STAGE_HOME, + STAGE_GREED_SHEOL = 5, + STAGE_GREED_SHOP, + STAGE_ULTRA_GREED +}; + +// The room set a floor draws its rooms from (REPENTOGON's StbType), numbered as the files in rooms/ are. +enum StbType : int +{ + STAGE_ID_SPECIAL_ROOMS, + STAGE_ID_BASEMENT, + STAGE_ID_CELLAR, + STAGE_ID_BURNING_BASEMENT, + STAGE_ID_CAVES, + STAGE_ID_CATACOMBS, + STAGE_ID_FLOODED_CAVES, + STAGE_ID_DEPTHS, + STAGE_ID_NECROPOLIS, + STAGE_ID_DANK_DEPTHS, + STAGE_ID_WOMB, + STAGE_ID_UTERO, + STAGE_ID_SCARRED_WOMB, + STAGE_ID_BLUE_WOMB, + STAGE_ID_SHEOL, + STAGE_ID_CATHEDRAL, + STAGE_ID_DARK_ROOM, + STAGE_ID_CHEST, + STAGE_ID_GREED_SPECIAL, + STAGE_ID_GREED_BASEMENT, + STAGE_ID_GREED_CAVES, + STAGE_ID_GREED_DEPTHS, + STAGE_ID_GREED_WOMB, + STAGE_ID_GREED_SHEOL, + STAGE_ID_GREED_SHOP, + STAGE_ID_ULTRA_GREED, + STAGE_ID_VOID, + STAGE_ID_DOWNPOUR, + STAGE_ID_DROSS, + STAGE_ID_MINES, + STAGE_ID_ASHPIT, + STAGE_ID_MAUSOLEUM, + STAGE_ID_GEHENNA, + STAGE_ID_CORPSE, + STAGE_ID_MORTIS, + STAGE_ID_HOME, + STAGE_ID_BACKWARDS +}; // 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). diff --git a/src/level_curses.cpp b/src/level_curses.cpp new file mode 100644 index 0000000..7477b15 --- /dev/null +++ b/src/level_curses.cpp @@ -0,0 +1,185 @@ +#include "entity_pickup.h" +#include "game.h" +#include "hud.h" +#include "level.h" +#include "manager.h" +#include "room.h" +#include +#include + +// The curses that shape the floor as it is laid out, which RemoveCurses leaves on. +constexpr uint32_t FLOOR_SHAPING_CURSES = CURSE_OF_LABYRINTH | CURSE_OF_GIANT; +constexpr int DARKNESS_LIFT_TIMEOUT = 4; + +// The rows and columns a room's doors sit on in a plain rectangle, as the maze's swap finds them: the left and right +// doors on the rows of each half, the top and bottom ones on the columns of each half. +constexpr int MAZE_DOOR_ROW_FIRST = 4; +constexpr int MAZE_DOOR_ROW_SECOND = 11; +constexpr int MAZE_DOOR_COLUMN_FIRST = 7; +constexpr int MAZE_DOOR_COLUMN_SECOND = 20; + +// Adds the run's challenge curses and takes away those it filters out. +static void challenge_curses_apply(Level& level) +{ + if (g_game->challenge == 0) return; + + ChallengeParam& params = g_manager->GetChallengeParams((int)g_game->challenge); + + level.curses = (level.curses | params.getCurse) & ~params.curseFilter; +} + +// 0074a2d0 Adds curses, the first one named on the fortune paper when asked, and keeps the challenge's curses. +void Level::AddCurse(uint32_t addedCurses, bool isShowName) +{ + Game& game = *g_game; + + curses |= addedCurses; + if (isShowName) + { + std::string name; + + for (uint32_t curse = 0; curse < game.roomConfig.curses.size(); curse++) + if (addedCurses & 1u << curse) + { + name = game.roomConfig.GetCurseName(curse + 1); + break; + } + game.hud.show_fortune_line(name.c_str()); + } + challenge_curses_apply(*this); + game.hud.InvalidateCraftingItem(nullptr); +} + +// 00748bc0 Removes curses but the Labyrinth and the Giant, and keeps the challenge's curses. Lifting Darkness flashes +// the room dark for a moment. Lifting Blind uncovers the room's pedestals. +void Level::RemoveCurses(uint32_t removedCurses) +{ + Game& game = *g_game; + uint32_t oldCurses = curses; + + curses &= ~(removedCurses & ~FLOOR_SHAPING_CURSES); + challenge_curses_apply(*this); + + uint32_t liftedCurses = oldCurses & ~curses; + + if (liftedCurses & CURSE_OF_DARKNESS) + { + game.darknessModifier = 1; + game.darknessStrength = 1; + game.darknessTimeout = DARKNESS_LIFT_TIMEOUT; + } + if (liftedCurses & CURSE_OF_BLIND) + { + for (Entity* entity : std::vector(room->entityList.updateEL)) + if (entity->type == ENTITY_PICKUP && entity->variant == PICKUP_COLLECTIBLE) + static_cast(entity)->UpdateSprite(false); + game.hud.InvalidateCraftingItem(nullptr); + } +} + +// 007496a0 The rooms one or two doors from a room, through doors it allows, to a normal or visited room that is not +// cleared. Past such a room any neighbour but the first room counts, as the original tests the first room again. +std::set Level::get_rooms_within_two_doors(int roomIdx) +{ + RoomDescriptor& start = *GetRoomByIdx(roomIdx); + std::set rooms; + + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + if (start.doors[slot] < 0 || !(start.allowedDoors >> slot & 1)) continue; + + RoomDescriptor& neighbor = *GetRoomByIdx(start.doors[slot]); + bool isOpen = neighbor.data->type == ROOM_DEFAULT || neighbor.visitedCount != 0; + + if (!isOpen || (neighbor.flags & ROOM_DESCRIPTOR_FLAG_CLEAR)) continue; + rooms.insert(start.doors[slot]); + for (int farSlot = 0; farSlot < DOOR_SLOT_COUNT; farSlot++) + { + int farIdx = neighbor.doors[farSlot]; + + if (farIdx >= 0 && neighbor.allowedDoors >> farSlot & 1 && farIdx != roomIdx) rooms.insert(farIdx); + } + } + return rooms; +} + +// Whether the maze may swap a room: it has a layout that is not a special normal room, and it is not the start room. +static bool is_maze_room(Level& level, const RoomDescriptor& desc) +{ + if (!desc.data || (desc.data->type == ROOM_DEFAULT && desc.data->subtype != 0)) return false; + return desc.dimension != 0 || desc.gridIndex != level.startingRoomIdx; +} + +// 00748d40 A visited room the maze may swap a visited room with, tried in a random order: the same group, dimension, +// allowed doors, shape and type, red or not alike. -1 when none fits. +int Level::find_matching_room_idx(int roomIdx) +{ + RoomDescriptor& target = *GetRoomByIdx(roomIdx); + std::vector order(nbRooms); + + if (!is_maze_room(*this, target)) return -1; + + std::iota(order.begin(), order.end(), 0); + for (int i = nbRooms - 1; i > 0; i--) std::swap(order[i], order[Random() % (uint32_t)(i + 1)]); + for (int i : order) + { + RoomDescriptor& other = roomList[i]; + bool isRedAlike = !((other.flags ^ target.flags) & ROOM_DESCRIPTOR_FLAG_RED_ROOM); + bool isAlike = other.group == target.group && isRedAlike && other.dimension == target.dimension; + + if (i == target.listIndex || other.visitedCount == 0 || target.visitedCount == 0) continue; + if (!isAlike || !is_maze_room(*this, other) || other.allowedDoors != target.allowedDoors) continue; + + RoomConfig_Room& config = *other.data; + + if (config.shape == target.data->shape && config.type == target.data->type) return other.safeGridIndex; + } + return -1; +} + +// 00749270 Swaps two rooms of the same size for the Curse of the Maze: everything they hold trades places but their +// cells and doors, the doors' saved grid cells included. False when their sizes differ. +// A room off the list fails too, where the original indexes before the list. +bool Level::maze_swap_rooms(int roomIdx, int otherRoomIdx) +{ + int index = GetRoomByIdx(roomIdx)->listIndex; + int otherIndex = GetRoomByIdx(otherRoomIdx)->listIndex; + + if (index < 0 || otherIndex < 0) return false; + + RoomDescriptor& desc = roomList[index]; + RoomDescriptor& other = roomList[otherIndex]; + + if (!desc.data || !other.data) return false; + if (desc.data->width != other.data->width || desc.data->height != other.data->height) return false; + + std::swap(desc, other); + std::swap(desc.doors, other.doors); + std::swap(desc.gridIndex, other.gridIndex); + std::swap(desc.safeGridIndex, other.safeGridIndex); + std::swap(desc.listIndex, other.listIndex); + + int stride = desc.data->width + 2; + int bottomRow = (desc.data->height + 1) * stride; + int rightColumn = desc.data->width + 1; + int cellCount = (desc.data->height + 2) * stride; + const int doorCells[DOOR_SLOT_COUNT] = {MAZE_DOOR_ROW_FIRST * stride, + MAZE_DOOR_COLUMN_FIRST, + MAZE_DOOR_ROW_FIRST * stride + rightColumn, + bottomRow + MAZE_DOOR_COLUMN_FIRST, + MAZE_DOOR_ROW_SECOND * stride, + MAZE_DOOR_COLUMN_SECOND, + MAZE_DOOR_ROW_SECOND * stride + rightColumn, + bottomRow + MAZE_DOOR_COLUMN_SECOND}; + + for (int cell : doorCells) + { + if (cell >= cellCount) continue; + + GridEntityDesc& grid = desc.savedGridEntities[cell]; + GridEntityDesc& otherGrid = other.savedGridEntities[cell]; + + if (grid._type == GRID_DOOR || otherGrid._type == GRID_DOOR) std::swap(grid, otherGrid); + } + return true; +} diff --git a/src/level_stage.cpp b/src/level_stage.cpp index a7d2f16..5f72ed3 100644 --- a/src/level_stage.cpp +++ b/src/level_stage.cpp @@ -6,19 +6,6 @@ #include #include -constexpr int STAGE_BASEMENT_I = 1; -constexpr int STAGE_BASEMENT_II = 2; -constexpr int STAGE_CAVES_I = 3; -constexpr int STAGE_CAVES_II = 4; -constexpr int STAGE_DEPTHS_I = 5; -constexpr int STAGE_DEPTHS_II = 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_VOID = 12; -constexpr int STAGE_HOME = 13; -constexpr int STAGE_GREED_SHOP = 7; constexpr int STAGE_ROLLED_LAST = 9; constexpr int ASCENT_STAGE_LAST = 6; @@ -163,7 +150,7 @@ void Level::SetNextStage() { nextStageType = STAGETYPE_ORIGINAL; if (stage < STAGE_DEPTHS_II) nextStage = stage + 1; - else if (stage <= STAGE_GREED_SHOP) nextStage = STAGE_GREED_SHOP; + else if (stage <= STAGE_ULTRA_GREED) nextStage = STAGE_ULTRA_GREED; else log_printf(LOG_ASSERT, "Wrong Stage (Greed Mode)"); } else diff --git a/src/loot_list.h b/src/loot_list.h new file mode 100644 index 0000000..71bf8e2 --- /dev/null +++ b/src/loot_list.h @@ -0,0 +1,37 @@ +#pragma once + +#include "classes.h" +#include + +// One thing a chest gives (LootList's entries): what to spawn and the seed it spawns from. +struct LootEntry +{ + int subType = 0; + int type = 0; + int variant = 0; + uint32_t seed = 0; +}; + +// Copies and destruction (006c20e0) are the defaults. +// What a chest or sack gives when it opens, in spawn order. +struct LootList +{ + std::vector entries; +}; + +// Destruction is the default. +// A draw among outcomes by weight (WeightedOutcomePicker): each outcome id holds the weight added for it. +struct WeightedOutcomePicker +{ + // An outcome id and its weight. + struct Outcome + { + int id = 0; + int weight = 0; + }; + + std::vector outcomes; + + void AddOutcomeWeight(int id, int weight); + int PickOutcome(RNG rng); +}; diff --git a/src/lua_api.cpp b/src/lua_api.cpp new file mode 100644 index 0000000..64dd944 --- /dev/null +++ b/src/lua_api.cpp @@ -0,0 +1,175 @@ +#include "lua_api.h" +#include "classes.h" + +// Pushes field name of the table at index without metamethods. +static int field_raw_get(lua_State* state, int index, const char* name) +{ + lua_pushstring(state, name); + return lua_rawget(state, index < 0 ? index - 1 : index); +} + +// Sets field name of the table at index to the value on top, popping it, without metamethods. +void lua_table_set(lua_State* state, int table, const char* name) +{ + lua_pushstring(state, name); + lua_insert(state, -2); + lua_rawset(state, table < 0 ? table - 1 : table); +} + +// Sets a key of the begun class's __propget or __propset to the function on top, popping it. +void lua_property_set(lua_State* state, const char* table, const char* name) +{ + field_raw_get(state, -2, table); + lua_insert(state, -2); + lua_table_set(state, -2, name); + lua_pop(state, 1); +} + +// __index of objects, classes and namespaces: a method or field of the metatable, else a property getter, else the +// same in each parent class, else nil. +static int index_get(lua_State* state) +{ + lua_getmetatable(state, 1); + while (true) + { + lua_pushvalue(state, 2); + if (lua_rawget(state, -2) != LUA_TNIL) return 1; + lua_pop(state, 1); + + if (field_raw_get(state, -1, "__propget") == LUA_TTABLE) + { + lua_pushvalue(state, 2); + if (lua_rawget(state, -2) == LUA_TFUNCTION) + { + lua_pushvalue(state, 1); + lua_call(state, 1, 1); + return 1; + } + lua_pop(state, 1); + } + lua_pop(state, 1); + + if (field_raw_get(state, -1, "__parent") == LUA_TNIL) return 1; + lua_remove(state, -2); + } +} + +// __newindex of objects, classes and namespaces: a property setter of the class or a parent. Anything else raises +// an error, so scripts add to namespaces with rawset. +static int index_set(lua_State* state) +{ + lua_getmetatable(state, 1); + while (true) + { + if (field_raw_get(state, -1, "__propset") == LUA_TTABLE) + { + lua_pushvalue(state, 2); + if (lua_rawget(state, -2) == LUA_TFUNCTION) + { + lua_pushvalue(state, 1); + lua_pushvalue(state, 3); + lua_call(state, 2, 0); + return 0; + } + lua_pop(state, 1); + } + lua_pop(state, 1); + + if (field_raw_get(state, -1, "__parent") == LUA_TNIL) + return luaL_error(state, "no writable variable '%s'", lua_tostring(state, 2)); + lua_remove(state, -2); + } +} + +// Pushes an object as a userdata holding its pointer, with its class's metatable, or nil for none. +void lua_object_push(lua_State* state, void* object, LuaClass luaClass) +{ + if (!object) return lua_pushnil(state); + + *(void**)lua_newuserdata(state, sizeof(void*)) = object; + lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(luaClass)); + lua_setmetatable(state, -2); +} + +// The object argument index holds when it is of the class or one derived from it. Raises an argument error if not. +void* lua_object_check(lua_State* state, int index, LuaClass luaClass) +{ + void** block = lua_type(state, index) == LUA_TUSERDATA ? (void**)lua_touserdata(state, index) : nullptr; + lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(luaClass)); + if (!block || !lua_getmetatable(state, index)) lua_pushnil(state); + while (!lua_isnil(state, -1)) + { + if (lua_rawequal(state, -1, -2)) + { + lua_pop(state, 2); + return *block; + } + field_raw_get(state, -1, "__parent"); + lua_remove(state, -2); + } + + field_raw_get(state, -2, "__name"); + const char* expected = lua_pushfstring(state, "%s expected, got %s", lua_tostring(state, -1), + luaL_typename(state, index)); + luaL_argerror(state, index, expected); + return nullptr; +} + +// Gives the table on top the fields every class, static table and namespace has. +static void table_init(lua_State* state, const char* name) +{ + lua_pushcfunction(state, index_get); + lua_table_set(state, -2, "__index"); + lua_pushcfunction(state, index_set); + lua_table_set(state, -2, "__newindex"); + lua_newtable(state); + lua_table_set(state, -2, "__propget"); + lua_newtable(state); + lua_table_set(state, -2, "__propset"); + lua_pushstring(state, name); + lua_table_set(state, -2, "__name"); +} + +// Begins a class as LuaBridge lays one out: a static table that is its own metatable, holding the constructor and +// static functions with __class pointing at the class table, the metatable its objects get. The class table keeps the +// methods and properties, with __parent pointing at the parent class's. Leaves the static and class tables on top. +void lua_class_begin(lua_State* state, const char* name, LuaClass luaClass, LuaClass parent) +{ + lua_newtable(state); + lua_pushvalue(state, -1); + lua_setmetatable(state, -2); + table_init(state, name); + + lua_newtable(state); + table_init(state, name); + if (parent != LUA_CLASS_COUNT) + { + lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(parent)); + lua_table_set(state, -2, "__parent"); + } + lua_pushvalue(state, -1); + lua_table_set(state, -3, "__class"); + lua_pushvalue(state, -1); + lua_rawsetp(state, LUA_REGISTRYINDEX, lua_class_key(luaClass)); +} + +// Begins a namespace: a table that is its own metatable, left on top twice so functions and properties are added to +// it as to a class. +void lua_namespace_begin(lua_State* state, const char* name) +{ + lua_newtable(state); + lua_pushvalue(state, -1); + lua_setmetatable(state, -2); + table_init(state, name); + lua_pushvalue(state, -1); +} + +// Ends the class or namespace begun last, naming it as a global or in the namespace below it. +void lua_class_end(lua_State* state, LuaScope scope) +{ + field_raw_get(state, -1, "__name"); + std::string name = lua_tostring(state, -1); + lua_pop(state, 2); + if (scope == LUA_SCOPE_GLOBAL) lua_setglobal(state, name.c_str()); + else lua_table_set(state, -2, name.c_str()); +} diff --git a/src/lua_api.h b/src/lua_api.h new file mode 100644 index 0000000..aea57de --- /dev/null +++ b/src/lua_api.h @@ -0,0 +1,361 @@ +#pragma once + +#include "lua_engine.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// classes.h declares the original's Lua imports, and its luaL_newstate differs from Lua's only in its return type. +#define luaL_newstate lua_newstate_auxiliary +extern "C" +{ +#include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +} +#undef luaL_newstate + +struct ColorMod; +struct EntityPtr; +struct EntityRef; +struct Entity_Bomb; +struct Entity_Effect; +struct Entity_Familiar; +struct Entity_Knife; +struct Entity_Laser; +struct Entity_NPC; +struct Entity_Pickup; +struct Entity_Player; +struct Entity_Projectile; +struct Entity_Tear; +struct Font; +struct FontSettings; +struct GridEntity; +struct ItemConfig; +struct ItemConfig_Card; +struct ItemConfig_Costume; +struct ItemConfig_Item; +struct ItemConfig_Pill; +struct KColor; +struct ANM2; +struct ProjectileParams; +struct RoomConfig_Room; +struct RoomDescriptor; +struct Seeds; +struct TearParams; +struct TemporaryEffects; +class Game; +class HUD; +class ItemPool; +class Level; +class MusicManager; +class Room; +class SFXManager; + +// Where lua_class_end puts a class: a global, or a field of the namespace begun below it. +enum LuaScope +{ + LUA_SCOPE_GLOBAL, + LUA_SCOPE_NAMESPACE +}; + +// An argument a binding is handed but does not read, such as the table a constructor's __call gets first. +struct LuaIgnored +{ +}; + +// The rooms of a floor as Level:GetRooms hands them out: the room list and how many rooms it has. +struct LuaRoomList +{ + RoomDescriptor* rooms = nullptr; + int count = 0; +}; + +// The Lua class each C++ type is pushed and checked as. TearFlags are Lua's BitSet128 and ColorMod is Lua's Color. +template +constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_COUNT; +template <> +inline constexpr LuaClass LUA_CLASS_OF> = LUA_CLASS_BIT_SET128; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_COLOR; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_BOMB; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_EFFECT; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_FAMILIAR; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_KNIFE; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_LASER; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_NPC; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PICKUP; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PLAYER; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PROJECTILE; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEAR; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY_PTR; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ENTITY_REF; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_FONT; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_FONT_SETTINGS; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_GAME; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_GRID_ENTITY; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_HUD; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ITEM_CONFIG; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ITEM_CONFIG_CARD; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ITEM_CONFIG_COSTUME; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ITEM_CONFIG_ITEM; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ITEM_CONFIG_PILL; +template <> +inline constexpr LuaClass LUA_CLASS_OF>> = LUA_CLASS_ITEM_CONFIG_CARD_LIST; +template <> +inline constexpr LuaClass LUA_CLASS_OF>> = LUA_CLASS_ITEM_CONFIG_ITEM_LIST; +template <> +inline constexpr LuaClass LUA_CLASS_OF>> = LUA_CLASS_ITEM_CONFIG_PILL_LIST; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ITEM_POOL; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_KCOLOR; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_LEVEL; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_MUSIC_MANAGER; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PROJECTILE_PARAMS; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_RNG; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM_CONFIG_ROOM; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM_DESCRIPTOR; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM_LIST; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SEEDS; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SFX_MANAGER; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SPRITE; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEAR_PARAMS; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_TEMPORARY_EFFECTS; +template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_VECTOR; + +// The class and member type of a pointer to a data member, for decltype only. +template +C lua_member_class(T C::*); +template +T lua_member_type(T C::*); + +// Whether a type has a Lua class to push and check it as. +template +constexpr bool IS_LUA_CLASS = LUA_CLASS_OF != LUA_CLASS_COUNT; + +template +constexpr bool IS_LUA_STRING = std::is_same_v || std::is_same_v; + +void lua_object_push(lua_State* state, void* object, LuaClass luaClass); +void* lua_object_check(lua_State* state, int index, LuaClass luaClass); +void lua_class_begin(lua_State* state, const char* name, LuaClass luaClass, LuaClass parent = LUA_CLASS_COUNT); +void lua_namespace_begin(lua_State* state, const char* name); +void lua_class_end(lua_State* state, LuaScope scope = LUA_SCOPE_GLOBAL); +void lua_table_set(lua_State* state, int table, const char* name); +void lua_property_set(lua_State* state, const char* table, const char* name); + +void lua_api_bit_set128_register(lua_State* state); +void lua_api_color_register(lua_State* state); +void lua_api_entity_register(lua_State* state); +void lua_api_entities_register(lua_State* state); +void lua_api_entity_player_register(lua_State* state); +void lua_api_game_register(lua_State* state); +void lua_api_isaac_register(lua_State* state); +void lua_api_item_config_register(lua_State* state); +void lua_api_rng_register(lua_State* state); +void lua_api_room_register(lua_State* state); +void lua_api_sprite_register(lua_State* state); +void lua_api_vector_register(lua_State* state); + +// Pushes a copy Lua owns: a userdata holding the copy's pointer first, as an object's, then the copy. +// Classes whose copies need destroying get a __gc from lua_gc_set. +template +void lua_copy_push(lua_State* state, const T& value) +{ + static_assert(alignof(T) <= alignof(void*)); + void** block = (void**)lua_newuserdata(state, sizeof(void*) + sizeof(T)); + *block = new (block + 1) T(value); + lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(LUA_CLASS_OF)); + lua_setmetatable(state, -2); +} + +// Pushes a value as the API does: numbers, booleans and strings as themselves, objects by pointer (nil for none) and +// class values as copies. +template +void lua_push(lua_State* state, const T& value) +{ + if constexpr (std::is_same_v) lua_pushboolean(state, value); + else if constexpr (std::is_integral_v || std::is_enum_v) lua_pushinteger(state, (lua_Integer)value); + else if constexpr (std::is_floating_point_v) lua_pushnumber(state, value); + else if constexpr (IS_LUA_STRING) lua_pushlstring(state, value.data(), value.size()); + else if constexpr (std::is_same_v) lua_pushstring(state, value); + else if constexpr (std::is_pointer_v) + { + static_assert(IS_LUA_CLASS>>); + lua_object_push(state, (void*)value, LUA_CLASS_OF>>); + } + else + { + static_assert(IS_LUA_CLASS); + lua_copy_push(state, value); + } +} + +// Reads argument index as a T: numbers are checked, booleans are truthiness, objects are checked against their class +// (nil only for a pointer), and a class value is copied unless T is a reference. +template +T lua_get(lua_State* state, int index) +{ + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) return {}; + else if constexpr (std::is_same_v) return lua_toboolean(state, index); + else if constexpr (std::is_integral_v || std::is_enum_v) return (V)luaL_checkinteger(state, index); + else if constexpr (std::is_floating_point_v) return (V)luaL_checknumber(state, index); + else if constexpr (IS_LUA_STRING) + { + size_t length = 0; + const char* text = luaL_checklstring(state, index, &length); + return V(text, length); + } + else if constexpr (std::is_pointer_v) + { + using O = std::remove_cv_t>; + static_assert(IS_LUA_CLASS); + return lua_isnoneornil(state, index) ? nullptr : (V)lua_object_check(state, index, LUA_CLASS_OF); + } + else + { + static_assert(IS_LUA_CLASS); + return *(V*)lua_object_check(state, index, LUA_CLASS_OF); + } +} + +// The C function a binding runs as: reads its arguments from the stack, calls it, and pushes what it returns. +// References to objects are pushed as the objects, not copies. +template +int lua_thunk(lua_State* state) +{ + R (*function)(Args...); + std::memcpy(&function, lua_touserdata(state, lua_upvalueindex(1)), sizeof(function)); + + return [&](std::index_sequence) { + if constexpr (std::is_void_v) + { + function(lua_get(state, I + 1)...); + return 0; + } + else + { + using V = std::remove_cvref_t; + if constexpr (std::is_lvalue_reference_v && std::is_class_v && !IS_LUA_STRING) + lua_push(state, &function(lua_get(state, I + 1)...)); + else lua_push(state, function(lua_get(state, I + 1)...)); + return 1; + } + }(std::index_sequence_for{}); +} + +// Pushes a binding as a closure over its function pointer. +template +void lua_function_push(lua_State* state, R (*function)(Args...)) +{ + std::memcpy(lua_newuserdata(state, sizeof(function)), &function, sizeof(function)); + lua_pushcclosure(state, lua_thunk, 1); +} + +// Adds a method to the class begun last, or a function to the namespace begun last. +template +void lua_method(lua_State* state, const char* name, F function) +{ + lua_function_push(state, +function); + lua_table_set(state, -2, name); +} + +// Adds a function to the static table of the class begun last, such as its __call constructor. +template +void lua_static(lua_State* state, const char* name, F function) +{ + lua_function_push(state, +function); + lua_table_set(state, -3, name); +} + +// Adds a property to the class or namespace begun last, read-only without a setter. +template +void lua_property(lua_State* state, const char* name, G getter) +{ + lua_function_push(state, +getter); + lua_property_set(state, "__propget", name); +} + +template +void lua_property(lua_State* state, const char* name, G getter, S setter) +{ + lua_property(state, name, getter); + lua_function_push(state, +setter); + lua_property_set(state, "__propset", name); +} + +// Adds a property reading and writing a data member, of class C when the member is its base's. +template +void lua_field(lua_State* state, const char* name) +{ + using T = decltype(lua_member_type(Member)); + lua_property( + state, name, [](C& object) -> T { return object.*Member; }, [](C& object, T value) { object.*Member = value; }); +} + +// Adds a read-only property for a data member. +template +void lua_field_get(lua_State* state, const char* name) +{ + using T = decltype(lua_member_type(Member)); + lua_property(state, name, [](C& object) -> T { return object.*Member; }); +} + +// Gives the class begun last a __gc that destroys the copies Lua owns, such as sprites scripts construct. +template +void lua_gc_set(lua_State* state) +{ + lua_pushcfunction(state, [](lua_State* gcState) { + void** block = (void**)lua_touserdata(gcState, 1); + if (block && *block == block + 1) static_cast(*block)->~T(); + return 0; + }); + lua_table_set(state, -2, "__gc"); +} diff --git a/src/lua_api_bit_set128.cpp b/src/lua_api_bit_set128.cpp new file mode 100644 index 0000000..ef0636a --- /dev/null +++ b/src/lua_api_bit_set128.cpp @@ -0,0 +1,56 @@ +#include "classes.h" +#include "lua_api.h" +#include + +using LuaBitSet = std::bitset<128>; + +constexpr int BIT_SET_HALF = 64; +constexpr LuaBitSet BIT_SET_LOW_MASK = LuaBitSet(~0ull); + +// The low or high 64 bits. +static uint64_t bit_set_low(const LuaBitSet& bits) +{ + return (bits & BIT_SET_LOW_MASK).to_ullong(); +} + +static uint64_t bit_set_high(const LuaBitSet& bits) +{ + return (bits >> BIT_SET_HALF).to_ullong(); +} + +// A bit set from its low and high 64 bits. +static LuaBitSet bit_set_make(uint64_t low, uint64_t high) +{ + return LuaBitSet(high) << BIT_SET_HALF | LuaBitSet(low); +} + +// (008bc330, 0085e490, 0085e4d0, 0085e4f0, 0085e510, 00592200, 0085e530, 0085e560, 0085e5c0) Registers Lua's +// BitSet128, the 128 bit flags tears and bombs carry, with l and h as its halves. +// Get and Set ignore bits past 127, which the original wraps into the 128. +void lua_api_bit_set128_register(lua_State* state) +{ + lua_class_begin(state, "BitSet128", LUA_CLASS_BIT_SET128); + lua_static(state, "__call", [](LuaIgnored, int64_t low, int64_t high) { return bit_set_make(low, high); }); + lua_method(state, "__band", [](const LuaBitSet& a, const LuaBitSet& b) { return a & b; }); + lua_method(state, "__bor", [](const LuaBitSet& a, const LuaBitSet& b) { return a | b; }); + lua_method(state, "__bxor", [](const LuaBitSet& a, const LuaBitSet& b) { return a ^ b; }); + lua_method(state, "__bnot", [](const LuaBitSet& bits) { return ~bits; }); + lua_method(state, "__eq", [](const LuaBitSet& a, const LuaBitSet& b) { return a == b; }); + lua_method(state, "__tostring", [](const LuaBitSet& bits) { + char text[64]; + std::snprintf(text, sizeof(text), "BitSet128: %016llx%016llx", (unsigned long long)bit_set_high(bits), + (unsigned long long)bit_set_low(bits)); + return std::string(text); + }); + lua_method(state, "Get", [](const LuaBitSet& bits, uint32_t bit) { return bit < bits.size() && bits[bit]; }); + lua_method(state, "Set", [](LuaBitSet& bits, uint32_t bit, bool isSet) { + if (bit < bits.size()) bits[bit] = isSet; + }); + lua_property( + state, "l", [](const LuaBitSet& bits) { return (int64_t)bit_set_low(bits); }, + [](LuaBitSet& bits, int64_t low) { bits = bit_set_make(low, bit_set_high(bits)); }); + lua_property( + state, "h", [](const LuaBitSet& bits) { return (int64_t)bit_set_high(bits); }, + [](LuaBitSet& bits, int64_t high) { bits = bit_set_make(bit_set_low(bits), high); }); + lua_class_end(state); +} diff --git a/src/lua_api_color.cpp b/src/lua_api_color.cpp new file mode 100644 index 0000000..21796b8 --- /dev/null +++ b/src/lua_api_color.cpp @@ -0,0 +1,55 @@ +#include "classes.h" +#include "anm2.h" +#include "fx_layers.h" +#include "lua_api.h" +#include + +// A Color property: a channel of the tint or the offset. +template +static void color_channel_add(lua_State* state, const char* name) +{ + lua_property( + state, name, [](ColorMod& color) { return (color.*Part)[Channel]; }, + [](ColorMod& color, float value) { (color.*Part)[Channel] = value; }); +} + +// (008bb5c0, 008bb3b0, 008a9360) Registers Lua's Color, the game's ColorMod: a tint, a colorize and an offset, with +// multiplication changing the left color and returning it, and KColor, a plain color. +void lua_api_color_register(lua_State* state) +{ + lua_class_begin(state, "Color", LUA_CLASS_COLOR); + lua_static(state, "__call", [](LuaIgnored, float r, float g, float b, float a, float ro, float go, float bo) { + return ColorMod{{r, g, b, a}, {0, 0, 0, 0}, {ro, go, bo}}; + }); + lua_static(state, "Lerp", [](ColorMod from, ColorMod to, float t) { return color_lerp(from, to, t); }); + color_channel_add<&ColorMod::_tint, 0>(state, "R"); + color_channel_add<&ColorMod::_tint, 1>(state, "G"); + color_channel_add<&ColorMod::_tint, 2>(state, "B"); + color_channel_add<&ColorMod::_tint, 3>(state, "A"); + color_channel_add<&ColorMod::_offset, 0>(state, "RO"); + color_channel_add<&ColorMod::_offset, 1>(state, "GO"); + color_channel_add<&ColorMod::_offset, 2>(state, "BO"); + lua_method(state, "Reset", [](ColorMod& color) { color = COLOR_DEFAULT; }); + lua_method(state, "SetTint", [](ColorMod& color, float r, float g, float b, float a) { + std::ranges::copy(std::initializer_list{r, g, b, a}, color._tint); + }); + lua_method(state, "SetColorize", [](ColorMod& color, float r, float g, float b, float amount) { + std::ranges::copy(std::initializer_list{r, g, b, amount}, color._colorize); + }); + lua_method(state, "SetOffset", [](ColorMod& color, float r, float g, float b) { + std::ranges::copy(std::initializer_list{r, g, b}, color._offset); + }); + lua_method(state, "__mul", [](ColorMod& color, ColorMod other) -> ColorMod& { + color_multiply(color, other); + return color; + }); + lua_class_end(state); + + lua_class_begin(state, "KColor", LUA_CLASS_KCOLOR); + lua_static(state, "__call", [](LuaIgnored, float r, float g, float b, float a) { return kcolor_rgba(r, g, b, a); }); + lua_field<&KColor::_alpha>(state, "Alpha"); + lua_field<&KColor::_red>(state, "Red"); + lua_field<&KColor::_green>(state, "Green"); + lua_field<&KColor::_blue>(state, "Blue"); + lua_class_end(state); +} diff --git a/src/lua_api_entities.cpp b/src/lua_api_entities.cpp new file mode 100644 index 0000000..071706a --- /dev/null +++ b/src/lua_api_entities.cpp @@ -0,0 +1,276 @@ +#include "classes.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "lua_api.h" + +// Registers Lua's EntityTear and EntityProjectile, the shots of players and enemies. +static void shots_register(lua_State* state) +{ + lua_class_begin(state, "EntityTear", LUA_CLASS_TEAR, LUA_CLASS_ENTITY); + lua_field<&Entity_Tear::height>(state, "Height"); + lua_field<&Entity_Tear::fallingSpeed>(state, "FallingSpeed"); + lua_field<&Entity_Tear::fallingAccel>(state, "FallingAcceleration"); + lua_property( + state, "Scale", [](Entity_Tear& tear) { return tear.fScale; }, + [](Entity_Tear& tear, float scale) { tear.fScale = scale; }); + lua_field<&Entity_Tear::tearFlags>(state, "TearFlags"); + lua_field_get<&Entity_Tear::tearIdx>(state, "TearIndex"); + lua_field<&Entity_Tear::rotation>(state, "Rotation"); + lua_field<&Entity_Tear::waitFrames>(state, "WaitFrames"); + lua_field<&Entity_Tear::homingFriction>(state, "HomingFriction"); + lua_field<&Entity_Tear::baseScale>(state, "BaseScale"); + lua_field<&Entity_Tear::baseDamage>(state, "BaseDamage"); + lua_field<&Entity_Tear::knockbackMultiplier>(state, "KnockbackMultiplier"); + lua_field<&Entity_Tear::continueVelocity>(state, "ContinueVelocity"); + lua_field<&Entity_Tear::parentOffset>(state, "ParentOffset"); + lua_field<&Entity_Tear::posDisplacement>(state, "PosDisplacement"); + lua_field<&Entity_Tear::stickDiff>(state, "StickDiff"); + lua_field<&Entity_Tear::stickTimer>(state, "StickTimer"); + lua_field<&Entity_Tear::isCanTriggerStreakEnd>(state, "CanTriggerStreakEnd"); + lua_method(state, "ChangeVariant", [](Entity_Tear& tear, int variant) { tear.ChangeVariant(variant); }); + lua_method(state, "SetWaitFrames", [](Entity_Tear& tear, int frames) { tear.waitFrames = frames; }); + lua_method(state, "SetKnockbackMultiplier", + [](Entity_Tear& tear, float multiplier) { tear.knockbackMultiplier = multiplier; }); + lua_method(state, "SetParentOffset", [](Entity_Tear& tear, Vector offset) { tear.parentOffset = offset; }); + lua_class_end(state); + + lua_class_begin(state, "EntityProjectile", LUA_CLASS_PROJECTILE, LUA_CLASS_ENTITY); + lua_field<&Entity_Projectile::height>(state, "Height"); + lua_field<&Entity_Projectile::fallingSpeed>(state, "FallingSpeed"); + lua_field<&Entity_Projectile::fallingAccel>(state, "FallingAccel"); + lua_field<&Entity_Projectile::homingStrength>(state, "HomingStrength"); + lua_field<&Entity_Projectile::curvingStrength>(state, "CurvingStrength"); + lua_field<&Entity_Projectile::acceleration>(state, "Acceleration"); + lua_field<&Entity_Projectile::wiggleFrameOffset>(state, "WiggleFrameOffset"); + lua_field<&Entity_Projectile::changeFlags>(state, "ChangeFlags"); + lua_field<&Entity_Projectile::changeVelocity>(state, "ChangeVelocity"); + lua_field<&Entity_Projectile::changeTimeout>(state, "ChangeTimeout"); + lua_field<&Entity_Projectile::scale>(state, "Scale"); + lua_field<&Entity_Projectile::projectileFlags>(state, "ProjectileFlags"); + lua_field<&Entity_Projectile::damage>(state, "Damage"); + lua_method(state, "AddHeight", [](Entity_Projectile& shot, float amount) { shot.AddHeight(amount); }); + lua_method(state, "AddFallingSpeed", [](Entity_Projectile& shot, float amount) { shot.fallingSpeed += amount; }); + lua_method(state, "AddFallingAccel", [](Entity_Projectile& shot, float amount) { shot.fallingAccel += amount; }); + lua_method(state, "AddScale", [](Entity_Projectile& shot, float amount) { shot.scale += amount; }); + lua_method(state, "AddProjectileFlags", + [](Entity_Projectile& shot, uint64_t flags) { shot.AddProjectileFlags(flags); }); + lua_method(state, "AddChangeFlags", [](Entity_Projectile& shot, uint64_t flags) { shot.changeFlags |= flags; }); + lua_class_end(state); +} + +// Registers Lua's EntityBomb, EntityKnife and EntityLaser, the players' other weapons. +static void weapons_register(lua_State* state) +{ + lua_class_begin(state, "EntityBomb", LUA_CLASS_BOMB, LUA_CLASS_ENTITY); + lua_field<&Entity_Bomb::tearFlags>(state, "Flags"); + lua_field<&Entity_Bomb::isFetus>(state, "IsFetus"); + lua_field<&Entity_Bomb::explosionDamage>(state, "ExplosionDamage"); + lua_field<&Entity_Bomb::radiusMultiplier>(state, "RadiusMultiplier"); + lua_method(state, "SetExplosionCountdown", + [](Entity_Bomb& bomb, int countdown) { bomb.SetExplosionCountdown(countdown); }); + lua_class_end(state); + + lua_class_begin(state, "EntityKnife", LUA_CLASS_KNIFE, LUA_CLASS_ENTITY); + lua_field<&Entity_Knife::tearFlags>(state, "TearFlags"); + lua_field<&Entity_Knife::rotation>(state, "Rotation"); + lua_field<&Entity_Knife::rotationOffset>(state, "RotationOffset"); + lua_field<&Entity_Knife::maxDistance>(state, "MaxDistance"); + lua_field<&Entity_Knife::charge>(state, "Charge"); + lua_field<&Entity_Knife::scale>(state, "Scale"); + lua_field<&Entity_Knife::pathOffset>(state, "PathOffset"); + lua_field<&Entity_Knife::pathFollowSpeed>(state, "PathFollowSpeed"); + lua_method(state, "Shoot", [](Entity_Knife& knife, float charge, float range) { knife.Shoot(charge, range); }); + lua_method(state, "IsFlying", [](Entity_Knife& knife) { return knife.isFlying; }); + lua_method(state, "GetKnifeDistance", [](Entity_Knife& knife) { return knife.knifeDistance; }); + lua_method(state, "GetKnifeVelocity", [](Entity_Knife& knife) { return knife.knifeVelocity; }); + lua_method(state, "SetPathFollowSpeed", [](Entity_Knife& knife, float speed) { knife.pathFollowSpeed = speed; }); + lua_class_end(state); + + lua_class_begin(state, "EntityLaser", LUA_CLASS_LASER, LUA_CLASS_ENTITY); + lua_field<&Entity_Laser::tearFlags>(state, "TearFlags"); + lua_field<&Entity_Laser::angleDegrees>(state, "Angle"); + lua_field<&Entity_Laser::angleDegrees>(state, "AngleDegrees"); + lua_field<&Entity_Laser::startAngleDegrees>(state, "StartAngleDegrees"); + lua_field<&Entity_Laser::lastAngleDegrees>(state, "LastAngleDegrees"); + lua_field<&Entity_Laser::parentOffset>(state, "ParentOffset"); + lua_field<&Entity_Laser::timeout>(state, "Timeout"); + lua_field<&Entity_Laser::maxDistance>(state, "MaxDistance"); + lua_field<&Entity_Laser::radius>(state, "Radius"); + lua_field<&Entity_Laser::curveStrength>(state, "CurveStrength"); + lua_field<&Entity_Laser::laserLength>(state, "LaserLength"); + lua_field<&Entity_Laser::rotationDegrees>(state, "RotationDegrees"); + lua_field<&Entity_Laser::rotationSpd>(state, "RotationSpd"); + lua_field<&Entity_Laser::homingType>(state, "HomingType"); + lua_field<&Entity_Laser::blackHpDropChance>(state, "BlackHpDropChance"); + lua_field<&Entity_Laser::endPoint>(state, "EndPoint"); + lua_field<&Entity_Laser::isShrink>(state, "Shrink"); + lua_field<&Entity_Laser::isOneHit>(state, "OneHit"); + lua_field<&Entity_Laser::isGridHit>(state, "GridHit"); + lua_field<&Entity_Laser::isSampleLaser>(state, "SampleLaser"); + lua_field<&Entity_Laser::isFirstUpdate>(state, "FirstUpdate"); + lua_field<&Entity_Laser::isActiveRotating>(state, "IsActiveRotating"); + lua_field<&Entity_Laser::isDisableFollowParent>(state, "DisableFollowParent"); + lua_method(state, "SetTimeout", [](Entity_Laser& laser, int timeout) { laser.timeout = timeout; }); + lua_method(state, "SetOneHit", [](Entity_Laser& laser, bool isOneHit) { laser.isOneHit = isOneHit; }); + lua_method(state, "SetMaxDistance", [](Entity_Laser& laser, float distance) { laser.maxDistance = distance; }); + lua_method(state, "SetHomingType", [](Entity_Laser& laser, uint32_t type) { laser.homingType = type; }); + lua_method(state, "SetBlackHpDropChance", + [](Entity_Laser& laser, float chance) { laser.blackHpDropChance = chance; }); + lua_method(state, "IsCircleLaser", [](Entity_Laser& laser) { return laser.IsCircleLaser(); }); + lua_method(state, "IsSampleLaser", [](Entity_Laser& laser) { return laser.isSampleLaser; }); + lua_class_end(state); +} + +// Registers Lua's EntityFamiliar and EntityEffect. +static void companions_register(lua_State* state) +{ + lua_class_begin(state, "EntityFamiliar", LUA_CLASS_FAMILIAR, LUA_CLASS_ENTITY); + lua_field<&Entity_Familiar::player>(state, "Player"); + lua_field<&Entity_Familiar::state>(state, "State"); + lua_field<&Entity_Familiar::coins>(state, "Coins"); + lua_field<&Entity_Familiar::hearts>(state, "Hearts"); + lua_field<&Entity_Familiar::keys>(state, "Keys"); + lua_field<&Entity_Familiar::fireCooldown>(state, "FireCooldown"); + lua_field<&Entity_Familiar::headFrameDelay>(state, "HeadFrameDelay"); + lua_field<&Entity_Familiar::moveDirection>(state, "MoveDirection"); + lua_field<&Entity_Familiar::shootDirection>(state, "ShootDirection"); + lua_field<&Entity_Familiar::lastDirection>(state, "LastDirection"); + lua_field<&Entity_Familiar::orbitAngleOffset>(state, "OrbitAngleOffset"); + lua_field<&Entity_Familiar::orbitDistance>(state, "OrbitDistance"); + lua_field<&Entity_Familiar::orbitSpeed>(state, "OrbitSpeed"); + lua_field<&Entity_Familiar::orbitLayer>(state, "OrbitLayer"); + lua_field<&Entity_Familiar::roomClearCount>(state, "RoomClearCount"); + lua_field_get<&Entity_Familiar::isDelayed>(state, "IsDelayed"); + lua_field_get<&Entity_Familiar::isFollower>(state, "IsFollower"); + lua_method(state, "AddCoins", [](Entity_Familiar& familiar, int count) { familiar.AddCoins(count); }); + lua_method(state, "AddHearts", [](Entity_Familiar& familiar, int amount) { familiar.AddHearts(amount); }); + lua_method(state, "AddKeys", [](Entity_Familiar& familiar, int amount) { familiar.AddKeys(amount); }); + lua_method(state, "FollowParent", [](Entity_Familiar& familiar) { familiar.FollowParent(); }); + lua_method(state, "FollowPosition", + [](Entity_Familiar& familiar, Vector position) { familiar.FollowPosition(position); }); + lua_method(state, "GetOrbitPosition", + [](Entity_Familiar& familiar, Vector center) { return familiar.GetOrbitPosition(center); }); + lua_static(state, "GetOrbitDistance", [](int layer) { return Entity_Familiar::GetOrbitDistance(layer); }); + lua_method(state, "Shoot", [](Entity_Familiar& familiar) { familiar.Shoot(); }); + lua_method(state, "PlayChargeAnim", + [](Entity_Familiar& familiar, int direction) { familiar.PlayChargeAnim(direction); }); + lua_method(state, "PlayShootAnim", + [](Entity_Familiar& familiar, int direction) { familiar.PlayShootAnim(direction); }); + lua_method(state, "PlayFloatAnim", + [](Entity_Familiar& familiar, int direction) { familiar.PlayFloatAnim(direction); }); + lua_method(state, "MoveDiagonally", [](Entity_Familiar& familiar, float speed) { familiar.MoveDiagonally(speed); }); + lua_method(state, "AddToFollowers", [](Entity_Familiar& familiar) { familiar.AddToFollowers(); }); + lua_method(state, "RemoveFromFollowers", [](Entity_Familiar& familiar) { familiar.RemoveFromFollowers(); }); + lua_method(state, "AddToDelayed", [](Entity_Familiar& familiar) { familiar.AddToDelayed(); }); + lua_method(state, "RemoveFromDelayed", [](Entity_Familiar& familiar) { familiar.RemoveFromDelayed(); }); + lua_method(state, "AddToOrbit", [](Entity_Familiar& familiar, int layer) { familiar.AddToOrbit(layer); }); + lua_method(state, "RemoveFromOrbit", [](Entity_Familiar& familiar) { familiar.RemoveFromOrbit(); }); + lua_class_end(state); + + lua_class_begin(state, "EntityEffect", LUA_CLASS_EFFECT, LUA_CLASS_ENTITY); + lua_field<&Entity_Effect::state>(state, "State"); + lua_field<&Entity_Effect::timeout>(state, "Timeout"); + lua_field<&Entity_Effect::lifespan>(state, "LifeSpan"); + lua_field<&Entity_Effect::rotation>(state, "Rotation"); + lua_field<&Entity_Effect::scale>(state, "Scale"); + lua_field<&Entity_Effect::fallingSpeed>(state, "FallingSpeed"); + lua_field<&Entity_Effect::fallingAcceleration>(state, "FallingAcceleration"); + lua_field<&Entity_Effect::height>(state, "m_Height"); + lua_field<&Entity_Effect::minRadius>(state, "MinRadius"); + lua_field<&Entity_Effect::maxRadius>(state, "MaxRadius"); + lua_field<&Entity_Effect::isFollowing>(state, "IsFollowing"); + lua_field<&Entity_Effect::parentOffset>(state, "ParentOffset"); + lua_field<&Entity_Effect::damageSource>(state, "DamageSource"); + lua_method(state, "SetTimeout", [](Entity_Effect& effect, int frames) { effect.SetTimeout(frames); }); + lua_method(state, "SetRadii", [](Entity_Effect& effect, float minRadius, float maxRadius) { + effect.SetRadii(minRadius, maxRadius); + }); + lua_method(state, "FollowParent", [](Entity_Effect& effect, Entity* parent) { effect.FollowParent(parent); }); + lua_method(state, "SetDamageSource", [](Entity_Effect& effect, int type) { effect.damageSource = type; }); + lua_class_end(state); +} + +// Registers Lua's EntityNPC, enemies and other characters, and EntityPickup. +static void npc_pickup_register(lua_State* state) +{ + lua_class_begin(state, "EntityNPC", LUA_CLASS_NPC, LUA_CLASS_ENTITY); + lua_field<&Entity_NPC::state>(state, "State"); + lua_field<&Entity_NPC::stateFrame>(state, "StateFrame"); + lua_field<&Entity_NPC::i1>(state, "I1"); + lua_field<&Entity_NPC::i2>(state, "I2"); + lua_field<&Entity_NPC::v1>(state, "V1"); + lua_field<&Entity_NPC::v2>(state, "V2"); + lua_field<&Entity_NPC::projectileCooldown>(state, "ProjectileCooldown"); + lua_field<&Entity_NPC::projectileDelay>(state, "ProjectileDelay"); + lua_field_get<&Entity_NPC::groupIdx>(state, "GroupIdx"); + lua_property( + state, "Scale", [](Entity_NPC& npc) { return npc.scale; }, + [](Entity_NPC& npc, float scale) { npc.SetScale(scale); }); + lua_property( + state, "EntityRef", [](Entity_NPC& npc) { return npc.entityRef.get(); }, + [](Entity_NPC& npc, Entity* entity) { npc.entityRef = entity; }); + lua_property(state, "ParentNPC", [](Entity_NPC& npc) { return dynamic_cast(npc.parent.get()); }); + lua_property(state, "ChildNPC", [](Entity_NPC& npc) { return dynamic_cast(npc.child.get()); }); + lua_method(state, "Morph", [](Entity_NPC& npc, int type, int variant, int subType, int championColor) { + npc.Morph(type, variant, subType, championColor); + }); + lua_method(state, "MakeChampion", [](Entity_NPC& npc, uint32_t seed, int championColor, bool isInit) { + npc.MakeChampion(seed, championColor, isInit); + }); + lua_method(state, "IsChampion", [](Entity_NPC& npc) { return npc.isChampion; }); + lua_method(state, "GetChampionColorIdx", [](Entity_NPC& npc) { return npc.championColorIdx; }); + lua_method(state, "GetBossColorIdx", [](Entity_NPC& npc) { return npc.bosscoloridx; }); + lua_method(state, "GetPlayerTarget", [](Entity_NPC& npc) { return npc.GetPlayerTarget(); }); + lua_method(state, "CalcTargetPosition", [](Entity_NPC& npc, float limit) { return npc.CalcTargetPosition(limit); }); + lua_method(state, "PlaySound", [](Entity_NPC& npc, int id, float volume, int frameDelay, bool isLoop, float pitch) { + npc.PlaySound(id, volume, frameDelay, isLoop, pitch); + }); + lua_method(state, "AnimWalkFrame", + [](Entity_NPC& npc, std::string_view horizontal, std::string_view vertical, float speed) { + npc.AnimWalkFrame(horizontal, vertical, speed); + }); + lua_method(state, "MakeSplat", [](Entity_NPC& npc, float size) { return npc.MakeSplat(size); }); + lua_method(state, "KillUnique", [](Entity_NPC& npc) { npc.KillUnique(); }); + lua_class_end(state); + + lua_class_begin(state, "EntityPickup", LUA_CLASS_PICKUP, LUA_CLASS_ENTITY); + lua_field<&Entity_Pickup::charge>(state, "Charge"); + lua_field<&Entity_Pickup::price>(state, "Price"); + lua_field<&Entity_Pickup::shopItemId>(state, "ShopItemId"); + lua_field<&Entity_Pickup::timeout>(state, "Timeout"); + lua_field<&Entity_Pickup::isTouched>(state, "Touched"); + lua_field<&Entity_Pickup::state>(state, "State"); + lua_field<&Entity_Pickup::wait>(state, "Wait"); + lua_field<&Entity_Pickup::isAutoUpdatePrice>(state, "AutoUpdatePrice"); + lua_field<&Entity_Pickup::optionsPickupIndex>(state, "OptionsPickupIndex"); + lua_method(state, "IsShopItem", [](Entity_Pickup& pickup) { return pickup.IsShopItem(); }); + lua_method(state, "Morph", + [](Entity_Pickup& pickup, int type, int variant, int subType, bool isKeepPrice, bool isKeepSeed, + bool isIgnoreModifiers) { + pickup.Morph(type, variant, subType, isKeepPrice, isKeepSeed, isIgnoreModifiers); + }); + lua_method(state, "AppearFast", [](Entity_Pickup& pickup) { pickup.AppearFast(); }); + lua_method(state, "TryOpenChest", + [](Entity_Pickup& pickup, Entity_Player* player) { return pickup.TryOpenChest(player); }); + lua_method(state, "PlayDropSound", [](Entity_Pickup& pickup) { pickup.PlayDropSound(); }); + lua_method(state, "PlayPickupSound", [](Entity_Pickup& pickup) { pickup.PlayPickupSound(); }); + lua_method(state, "GetCoinValue", [](Entity_Pickup& pickup) { return pickup.GetCoinValue(); }); + lua_method(state, "CanReroll", [](Entity_Pickup& pickup) { return pickup.CanReroll(); }); + lua_class_end(state); +} + +void lua_api_entities_register(lua_State* state) +{ + shots_register(state); + weapons_register(state); + companions_register(state); + npc_pickup_register(state); +} diff --git a/src/lua_api_entity.cpp b/src/lua_api_entity.cpp new file mode 100644 index 0000000..3adc9e9 --- /dev/null +++ b/src/lua_api_entity.cpp @@ -0,0 +1,258 @@ +#include "classes.h" +#include "entity.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "lua_api.h" + +// The color Entity.Color reads for no entity. +constexpr ColorMod COLOR_NO_ENTITY = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SIZE_MULTI_CONFIG = -1; + +// 006b5e60 The table scripts keep with an entity, made on first use and freed when the entity goes. +static int entity_data_get(lua_State* state) +{ + Entity& entity = lua_get(state, 1); + if (entity.dataRef == LUA_REF_NONE) + { + lua_newtable(state); + entity.dataRef = luaL_ref(state, LUA_REGISTRYINDEX); + } + lua_rawgeti(state, LUA_REGISTRYINDEX, entity.dataRef); + return 1; +} + +// Adds a To method casting an entity to a subclass, nil when it is not one. +template +static void entity_cast_add(lua_State* state, const char* name) +{ + lua_method(state, name, [](Entity* entity) { return dynamic_cast(entity); }); +} + +// Adds a property for one of the entity pointers an entity links to. +template +static void entity_link_add(lua_State* state, const char* name) +{ + lua_property( + state, name, [](Entity& entity) { return (entity.*Link).get(); }, + [](Entity& entity, Entity* target) { entity.*Link = target; }); +} + +// (008bb770) Registers EntityRef, a snapshot of a damage source, and EntityPtr, a pointer that clears itself when its +// entity goes. +static void entity_ref_register(lua_State* state) +{ + lua_class_begin(state, "EntityRef", LUA_CLASS_ENTITY_REF); + lua_static(state, "__call", [](LuaIgnored, Entity* entity) { return EntityRef(entity); }); + lua_field<&EntityRef::type>(state, "Type"); + lua_field<&EntityRef::variant>(state, "Variant"); + lua_field<&EntityRef::spawnerType>(state, "SpawnerType"); + lua_field<&EntityRef::spawnerVariant>(state, "SpawnerVariant"); + lua_field<&EntityRef::position>(state, "Position"); + lua_field<&EntityRef::entity>(state, "Entity"); + lua_property( + state, "IsCharmed", [](EntityRef& ref) { return ref.IsCharmed(); }, + [](EntityRef& ref, bool isSet) { + ref.flags = isSet ? ref.flags | ENTITY_REF_CHARMED : ref.flags & ~ENTITY_REF_CHARMED; + }); + lua_property( + state, "IsFriendly", [](EntityRef& ref) { return ref.IsFriendly(); }, + [](EntityRef& ref, bool isSet) { + ref.flags = isSet ? ref.flags | ENTITY_REF_FRIENDLY : ref.flags & ~ENTITY_REF_FRIENDLY; + }); + lua_class_end(state); + + lua_class_begin(state, "EntityPtr", LUA_CLASS_ENTITY_PTR); + lua_static(state, "__call", [](LuaIgnored, Entity* entity) { + EntityPtr pointer; + pointer = entity; + return pointer; + }); + lua_gc_set(state); + lua_method(state, "SetReference", [](EntityPtr& pointer, Entity* entity) { pointer = entity; }); + lua_property(state, "Ref", [](EntityPtr& pointer) { return pointer.get(); }); + lua_class_end(state); +} + +// Registers Lua's Entity: what every entity has, its links, status effects and the casts to its subclasses. +// Position, Velocity, SizeMulti and Color read copies, the sprite's offset, scale, the target position and colors are +// read by reference, as in the original. +static void entity_class_register(lua_State* state) +{ + lua_class_begin(state, "Entity", LUA_CLASS_ENTITY); + lua_pushcfunction(state, entity_data_get); + lua_table_set(state, -2, "GetData"); + + lua_field<&Entity::friction>(state, "Friction"); + lua_field<&Entity::pos>(state, "Position"); + lua_field<&Entity::velocity>(state, "Velocity"); + lua_property( + state, "Color", [](Entity* entity) { return entity ? entity->color : COLOR_NO_ENTITY; }, + [](Entity* entity, ColorMod color) { + if (entity) entity->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + }); + lua_field_get<&Entity::type>(state, "Type"); + lua_field<&Entity::variant>(state, "Variant"); + lua_field<&Entity::subtype>(state, "SubType"); + lua_field<&Entity::spawnerType>(state, "SpawnerType"); + lua_field<&Entity::spawnerVariant>(state, "SpawnerVariant"); + lua_property(state, "SplatColor", [](Entity& entity) -> ColorMod& { return entity.splatColor; }, + [](Entity& entity, ColorMod color) { entity.splatColor = color; }); + lua_field<&Entity::isVisible>(state, "Visible"); + lua_property(state, "PositionOffset", [](Entity& entity) -> Vector& { return entity.posOffset; }, + [](Entity& entity, Vector offset) { entity.posOffset = offset; }); + lua_field<&Entity::renderZOffset>(state, "RenderZOffset"); + lua_field<&Entity::sortingLayer>(state, "SortingLayer"); + lua_property( + state, "FlipX", [](Entity& entity) { return entity.sprite.isFlipX; }, + [](Entity& entity, bool isFlipped) { entity.sprite.isFlipX = isFlipped; }); + lua_property(state, "SpriteOffset", [](Entity& entity) -> Vector& { return entity.sprite.offset; }, + [](Entity& entity, Vector offset) { entity.sprite.offset = offset; }); + lua_property(state, "SpriteScale", [](Entity& entity) -> Vector& { return entity.sprite.scale; }, + [](Entity& entity, Vector scale) { entity.sprite.scale = scale; }); + lua_property( + state, "SpriteRotation", [](Entity& entity) { return entity.sprite.rotation; }, + [](Entity& entity, float rotation) { entity.sprite.rotation = rotation; }); + lua_property( + state, "Size", [](Entity& entity) { return entity.size; }, + [](Entity& entity, float size) { + entity.SetSize(size, vector_make(SIZE_MULTI_CONFIG, SIZE_MULTI_CONFIG), -1); + }); + lua_field<&Entity::sizeMulti>(state, "SizeMulti"); + lua_field<&Entity::mass>(state, "Mass"); + lua_field<&Entity::maxHitPoints>(state, "MaxHitPoints"); + lua_field<&Entity::health>(state, "HitPoints"); + lua_field_get<&Entity::index>(state, "Index"); + lua_property(state, "TargetPosition", [](Entity& entity) -> Vector& { return entity.targetPosition; }, + [](Entity& entity, Vector position) { entity.targetPosition = position; }); + lua_field<&Entity::entityGridCollisionClass>(state, "GridCollisionClass"); + lua_field<&Entity::entityCollisionClass>(state, "EntityCollisionClass"); + lua_field<&Entity::collisionDamage>(state, "CollisionDamage"); + lua_field_get<&Entity::spawnGridIndex>(state, "SpawnGridIndex"); + lua_property(state, "FrameCount", [](Entity& entity) { return entity.FrameCount(); }); + lua_field_get<&Entity::initSeed>(state, "InitSeed"); + lua_property(state, "DropSeed", [](Entity& entity) { return entity.dropRNG._seed; }); + lua_field<&Entity::renderDepthOffset>(state, "DepthOffset"); + entity_link_add<&Entity::parent>(state, "Parent"); + entity_link_add<&Entity::child>(state, "Child"); + entity_link_add<&Entity::target>(state, "Target"); + entity_link_add<&Entity::spawnerEntity>(state, "SpawnerEntity"); + + lua_method(state, "Update", [](Entity& entity) { entity.Update(); }); + lua_method(state, "Render", [](Entity& entity, Vector offset) { entity.Render(offset); }); + lua_method(state, "RenderShadowLayer", + [](Entity& entity, Vector offset) { return entity.RenderShadowLayer(offset); }); + lua_method(state, "PostRender", [](Entity& entity) { entity.PostRender(); }); + lua_method(state, "TakeDamage", + [](Entity& entity, float damage, uint64_t flags, const EntityRef& source, int countdown) { + return entity.TakeDamage(damage, flags, source, countdown); + }); + lua_method(state, "HasMortalDamage", [](Entity& entity) { return entity.HasMortalDamage(); }); + lua_method(state, "Kill", [](Entity& entity) { entity.Kill(EntityRef()); }); + lua_method(state, "KillWithSource", [](Entity& entity, const EntityRef& source) { entity.Kill(source); }); + lua_method(state, "Die", [](Entity& entity) { entity.isDead = true; }); + lua_method(state, "Remove", [](Entity& entity) { entity.Remove(); }); + lua_method(state, "BloodExplode", [](Entity& entity) { entity.BloodExplode(); }); + lua_method(state, "AddVelocity", [](Entity& entity, Vector added) { entity.AddVelocity_divided(added, false); }); + lua_method(state, "MultiplyFriction", [](Entity& entity, float scale) { entity.friction *= scale; }); + lua_method(state, "SetColor", + [](Entity& entity, ColorMod color, int duration, int priority, bool isFadeout, bool isShared) { + entity.SetColor(color, duration, priority, isFadeout, isShared); + }); + lua_method(state, "GetColor", [](Entity& entity) -> ColorMod& { return entity.sprite.color; }); + lua_method(state, "SetSpriteFrame", + [](Entity& entity, std::string_view animation, int frame) { entity.SetSpriteFrame(animation, frame); }); + lua_method(state, "SetSpriteOverlayFrame", [](Entity& entity, std::string_view animation, int frame) { + entity.SetSpriteOverlayFrame(animation, frame); + }); + lua_method(state, "SetSize", [](Entity& entity, float size, Vector sizeMulti, int gridCollisionPoints) { + entity.SetSize(size, sizeMulti, gridCollisionPoints); + }); + lua_method(state, "CollidesWithGrid", [](Entity& entity) { return entity.isCollidesWithGrid; }); + lua_method(state, "IsEnemy", [](Entity& entity) { return entity.IsEnemy(); }); + lua_method(state, "IsActiveEnemy", [](Entity& entity, bool isDeadIncluded) { + return entity.IsActiveEnemy(isDeadIncluded ? DEAD_INCLUDED : DEAD_EXCLUDED); + }); + lua_method(state, "IsVulnerableEnemy", + [](Entity& entity, Entity* source) { return entity.IsVulnerableEnemy(source); }); + lua_method(state, "IsFlying", [](Entity& entity) { return entity.IsFlying(); }); + lua_method(state, "AddEntityFlags", [](Entity& entity, uint64_t flags) { entity.AddEntityFlags(flags); }); + lua_method(state, "ClearEntityFlags", [](Entity& entity, uint64_t flags) { entity.ClearEntityFlags(flags); }); + lua_method(state, "GetEntityFlags", [](Entity& entity) { return entity.flags; }); + lua_method(state, "HasEntityFlags", [](Entity& entity, uint64_t flags) { return entity.HasEntityFlags(flags); }); + lua_method(state, "HasFullHealth", [](Entity& entity) { return entity.HasFullHealth(); }); + lua_method(state, "AddHealth", [](Entity& entity, float amount) { entity.AddHealth(amount); }); + + lua_method(state, "AddPoison", + [](Entity& entity, const EntityRef& source, int duration, float damage, bool isIgnoreBoss) { + entity.AddPoison(source, duration, damage, isIgnoreBoss); + }); + lua_method(state, "AddFreeze", [](Entity& entity, const EntityRef& source, int duration, bool isIgnoreBoss) { + entity.AddFreeze(source, duration, isIgnoreBoss); + }); + lua_method(state, "AddSlowing", + [](Entity& entity, const EntityRef& source, int duration, float amount, ColorMod color, + bool isIgnoreBoss) { entity.AddSlowing(source, duration, amount, color, isIgnoreBoss); }); + lua_method(state, "AddCharmed", + [](Entity& entity, const EntityRef& source, int duration, bool isIgnoreBoss, bool isAddKillScore) { + entity.AddCharmed(source, duration, isIgnoreBoss, isAddKillScore); + }); + lua_method(state, "AddConfusion", [](Entity& entity, const EntityRef& source, int duration, bool isIgnoreBoss) { + entity.AddConfusion(source, duration, isIgnoreBoss); + }); + lua_method(state, "AddMidasFreeze", [](Entity& entity, const EntityRef& source, int duration, bool isIgnoreBoss) { + entity.AddMidasFreeze(source, duration, isIgnoreBoss); + }); + lua_method(state, "AddFear", [](Entity& entity, const EntityRef& source, int duration, bool isIgnoreBoss) { + entity.AddFear(source, duration, isIgnoreBoss); + }); + lua_method(state, "AddBurn", + [](Entity& entity, const EntityRef& source, int duration, float damage, bool isIgnoreBoss) { + entity.AddBurn(source, duration, damage, isIgnoreBoss); + }); + lua_method(state, "AddShrink", [](Entity& entity, const EntityRef& source, int duration, bool isIgnoreBoss) { + entity.AddShrink(source, duration, isIgnoreBoss); + }); + lua_method(state, "RemoveStatusEffects", [](Entity& entity) { entity.RemoveStatusEffects(); }); + + lua_method(state, "Exists", [](Entity& entity) { return entity.isExists; }); + lua_method(state, "IsDead", [](Entity& entity) { return entity.isDead; }); + lua_method(state, "IsVisible", [](Entity& entity) { return entity.isVisible; }); + lua_method(state, "IsInvincible", [](Entity& entity) { return entity.isInvincible; }); + lua_method(state, "CanShutDoors", [](Entity& entity) { return entity.CanShutDoors(); }); + lua_method(state, "IsBoss", [](Entity& entity) { return entity.IsBoss(); }); + lua_method(state, "GetBossID", [](Entity& entity) { return entity.GetBossID(); }); + lua_method(state, "GetLastParent", [](Entity& entity) { return entity.GetLastParent(); }); + lua_method(state, "GetLastChild", [](Entity& entity) { return entity.GetLastChild(); }); + lua_method(state, "HasCommonParentWithEntity", + [](Entity& entity, Entity* other) { return entity.HasCommonParentWithEntity(other); }); + lua_method(state, "IsFrame", + [](Entity& entity, int frequency, int offset) { return entity.IsFrame(frequency, offset); }); + lua_method(state, "GetDropRNG", [](Entity& entity) -> RNG& { return entity.dropRNG; }); + lua_method(state, "GetSprite", [](Entity& entity) -> ANM2& { return entity.sprite; }); + + entity_cast_add(state, "ToPlayer"); + entity_cast_add(state, "ToEffect"); + entity_cast_add(state, "ToNPC"); + entity_cast_add(state, "ToPickup"); + entity_cast_add(state, "ToFamiliar"); + entity_cast_add(state, "ToBomb"); + entity_cast_add(state, "ToKnife"); + entity_cast_add(state, "ToLaser"); + entity_cast_add(state, "ToTear"); + entity_cast_add(state, "ToProjectile"); + lua_class_end(state); +} + +void lua_api_entity_register(lua_State* state) +{ + entity_ref_register(state); + entity_class_register(state); +} diff --git a/src/lua_api_entity_player.cpp b/src/lua_api_entity_player.cpp new file mode 100644 index 0000000..887b414 --- /dev/null +++ b/src/lua_api_entity_player.cpp @@ -0,0 +1,401 @@ +#include "classes.h" +#include "active_items.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "item_config.h" +#include "lua_api.h" +#include "temporary_effects.h" +#include "weapon.h" + +// The weapon a player's fire delay belongs to: the override in slot 0, else the first. +static Weapon* player_weapon_main(Entity_Player& player) +{ + return player.weapons[0] ? player.weapons[0].get() : player.weapons[1].get(); +} + +// Registers the player's health: the hearts of each kind, their limits, and the charges some characters use. +static void player_health_register(lua_State* state) +{ + lua_method(state, "GetHearts", [](Entity_Player& player) { return player.redHearts; }); + lua_method(state, "GetMaxHearts", [](Entity_Player& player) { return player.maxHearts; }); + lua_method(state, "GetSoulHearts", [](Entity_Player& player) { return player.soulHearts; }); + lua_method(state, "GetBlackHearts", [](Entity_Player& player) { return player.blackHearts; }); + lua_method(state, "GetEternalHearts", [](Entity_Player& player) { return player.eternalHearts; }); + lua_method(state, "GetGoldenHearts", [](Entity_Player& player) { return player.goldenHearts; }); + lua_method(state, "GetBoneHearts", [](Entity_Player& player) { return player.boneHearts; }); + lua_method(state, "GetRottenHearts", [](Entity_Player& player) { return player.rottenHearts; }); + lua_method(state, "GetBrokenHearts", [](Entity_Player& player) { return player.brokenHearts; }); + lua_method(state, "GetJarHearts", [](Entity_Player& player) { return player.jarHearts; }); + lua_method(state, "GetJarFlies", [](Entity_Player& player) { return player.jarFlies; }); + lua_method(state, "GetEffectiveMaxHearts", [](Entity_Player& player) { return player.GetEffectiveMaxHearts(); }); + lua_method(state, "GetHeartLimit", + [](Entity_Player& player, bool isKeeperBypass) { return player.GetHeartLimit(isKeeperBypass); }); + lua_method(state, "GetExtraLives", [](Entity_Player& player) { return player.GetExtraLives(); }); + lua_method(state, "WillPlayerRevive", [](Entity_Player& player) { return player.WillPlayerRevive(); }); + lua_method(state, "HasFullHearts", [](Entity_Player& player) { return player.HasFullHearts(); }); + lua_method(state, "IsBlackHeart", [](Entity_Player& player, int heart) { return player.IsBlackHeart(heart); }); + lua_method(state, "IsBoneHeart", [](Entity_Player& player, int heart) { return player.IsBoneHeart(heart); }); + lua_method(state, "AddMaxHearts", [](Entity_Player& player, int amount, bool isIgnoreKeeper) { + player.AddMaxHearts(amount, isIgnoreKeeper); + }); + lua_method(state, "AddHearts", [](Entity_Player& player, int amount) { player.AddHearts(amount, false, false); }); + lua_method(state, "AddSoulHearts", [](Entity_Player& player, int amount) { player.AddSoulHearts(amount, false); }); + lua_method(state, "AddBlackHearts", [](Entity_Player& player, int amount) { player.AddBlackHearts(amount); }); + lua_method(state, "RemoveBlackHeart", [](Entity_Player& player, int heart) { player.RemoveBlackHeart(heart); }); + lua_method(state, "AddEternalHearts", [](Entity_Player& player, int amount) { player.AddEternalHearts(amount); }); + lua_method(state, "AddGoldenHearts", + [](Entity_Player& player, int amount) { player.AddGoldenHearts(amount, false); }); + lua_method(state, "AddBoneHearts", [](Entity_Player& player, int amount) { player.AddBoneHearts(amount); }); + lua_method(state, "AddRottenHearts", + [](Entity_Player& player, int amount) { player.AddRottenHearts(amount, false); }); + lua_method(state, "AddBrokenHearts", [](Entity_Player& player, int amount) { player.AddBrokenHearts(amount); }); + lua_method(state, "AddJarHearts", [](Entity_Player& player, int amount) { player.AddJarHearts(amount); }); + lua_method(state, "AddJarFlies", [](Entity_Player& player, int amount) { player.AddJarFlies(amount); }); + lua_method(state, "SetFullHearts", [](Entity_Player& player) { player.SetFullHearts(); }); + lua_method(state, "CanPickRedHearts", [](Entity_Player& player) { return player.CanPickRedHearts(); }); + lua_method(state, "CanPickSoulHearts", [](Entity_Player& player) { return player.CanPickSoulHearts(); }); + lua_method(state, "CanPickBlackHearts", [](Entity_Player& player) { return player.CanPickBlackHearts(); }); + lua_method(state, "CanPickGoldenHearts", [](Entity_Player& player) { return player.CanPickGoldenHearts(); }); + lua_method(state, "CanPickBoneHearts", [](Entity_Player& player) { return player.CanPickBoneHearts(); }); + lua_method(state, "CanPickRottenHearts", [](Entity_Player& player) { return player.CanPickRottenHearts(); }); + lua_method(state, "AddSoulCharge", [](Entity_Player& player, int amount) { player.AddSoulCharge(amount); }); + lua_method(state, "SetSoulCharge", [](Entity_Player& player, int amount) { player.SetSoulCharge(amount); }); + lua_method(state, "GetEffectiveSoulCharge", [](Entity_Player& player) { return player.GetEffectiveSoulCharge(); }); + lua_method(state, "AddBloodCharge", [](Entity_Player& player, int amount) { player.AddBloodCharge(amount); }); + lua_method(state, "SetBloodCharge", [](Entity_Player& player, int amount) { player.SetBloodCharge(amount); }); + lua_method(state, "GetEffectiveBloodCharge", + [](Entity_Player& player) { return player.GetEffectiveBloodCharge(); }); + lua_method(state, "HasInvincibility", [](Entity_Player& player, uint64_t flags, const EntityRef& source) { + return player.HasInvincibility(flags, source); + }); +} + +// Registers the player's pickups and items: consumables, collectibles, trinkets, actives, pocket items and costumes. +static void player_items_register(lua_State* state) +{ + lua_method(state, "GetNumCoins", [](Entity_Player& player) { return player.numCoins; }); + lua_method(state, "GetNumBombs", [](Entity_Player& player) { return player.numBombs; }); + lua_method(state, "GetNumKeys", [](Entity_Player& player) { return player.numKeys; }); + lua_method(state, "GetNumGigaBombs", [](Entity_Player& player) { return player.numGigaBombs; }); + lua_method(state, "GetNumBlueFlies", [](Entity_Player& player) { return player.numBlueFlies; }); + lua_method(state, "GetNumBlueSpiders", [](Entity_Player& player) { return player.numBlueSpiders; }); + lua_method(state, "HasGoldenKey", [](Entity_Player& player) { return player.hasGoldenKey; }); + lua_method(state, "HasGoldenBomb", [](Entity_Player& player) { return player.hasGoldenBomb; }); + lua_method(state, "AddCoins", [](Entity_Player& player, int amount) { player.AddCoins(amount); }); + lua_method(state, "AddBombs", [](Entity_Player& player, int amount) { player.AddBombs(amount); }); + lua_method(state, "AddKeys", [](Entity_Player& player, int amount) { player.AddKeys(amount); }); + lua_method(state, "AddGigaBombs", [](Entity_Player& player, int amount) { player.AddGigaBombs(amount); }); + lua_method(state, "AddGoldenKey", [](Entity_Player& player) { player.AddGoldenKey(); }); + lua_method(state, "RemoveGoldenKey", [](Entity_Player& player) { player.RemoveGoldenKey(); }); + lua_method(state, "AddGoldenBomb", [](Entity_Player& player) { player.AddGoldenBomb(); }); + lua_method(state, "RemoveGoldenBomb", [](Entity_Player& player) { player.RemoveGoldenBomb(); }); + lua_method(state, "TryUseKey", [](Entity_Player& player) { return player.TryUseKey(); }); + lua_method(state, "AddBlueFlies", [](Entity_Player& player, int amount, Vector position, Entity* target) { + return player.AddBlueFlies(amount, position, target); + }); + lua_method(state, "RemoveBlueFly", [](Entity_Player& player) { player.RemoveBlueFly(); }); + lua_method(state, "AddBlueSpider", [](Entity_Player& player, Vector position) { player.AddBlueSpider(position); }); + lua_method(state, "ThrowBlueSpider", [](Entity_Player& player, Vector position, Vector target) { + return player.ThrowBlueSpider(position, target); + }); + lua_method(state, "AddPrettyFly", [](Entity_Player& player) { player.AddPrettyFly(); }); + + lua_method(state, "HasCollectible", [](Entity_Player& player, int id, bool isOwnedOnly) { + return player.HasCollectible(id, isOwnedOnly ? ITEM_CHECK_OWNED : ITEM_CHECK_MODIFIED); + }); + lua_method(state, "GetCollectibleNum", [](Entity_Player& player, int id, bool isOwnedOnly) { + return player.GetCollectibleNum(id, isOwnedOnly ? ITEM_CHECK_OWNED : ITEM_CHECK_MODIFIED); + }); + lua_method(state, "GetCollectibleCount", [](Entity_Player& player) { return player.GetCollectibleCount(); }); + lua_method(state, "AddCollectible", + [](Entity_Player& player, int id, int charge, bool isFirstTime, int slot, int varData) { + player.AddCollectible(id, charge, isFirstTime, slot, varData); + }); + lua_method(state, "RemoveCollectible", + [](Entity_Player& player, int id, bool isOwnedOnly, int slot, bool isRemoveFromForm) { + player.RemoveCollectible(id, isOwnedOnly, slot, isRemoveFromForm); + }); + lua_method(state, "CanAddCollectible", [](Entity_Player& player, int id) { return player.CanAddCollectible(id); }); + lua_method(state, "GetCollectibleRNG", + [](Entity_Player& player, int id) -> RNG& { return player.GetCollectibleRNG(id); }); + lua_method(state, "HasTrinket", [](Entity_Player& player, uint32_t id, bool isOwnedOnly) { + return player.HasTrinket(id, isOwnedOnly ? ITEM_CHECK_OWNED : ITEM_CHECK_MODIFIED); + }); + lua_method(state, "GetTrinket", [](Entity_Player& player, uint32_t slot) { return player.GetTrinket(slot); }); + lua_method(state, "GetTrinketMultiplier", + [](Entity_Player& player, uint32_t id) { return player.GetTrinketMultiplier(id); }); + lua_method(state, "GetMaxTrinkets", [](Entity_Player& player) { return player.GetMaxTrinkets(); }); + lua_method(state, "AddTrinket", + [](Entity_Player& player, int id, bool isFirstTime) { player.AddTrinket(id, isFirstTime); }); + lua_method(state, "TryRemoveTrinket", + [](Entity_Player& player, uint32_t id) { return player.TryRemoveTrinket(id); }); + lua_method(state, "DropTrinket", [](Entity_Player& player, Vector position, bool isReplaceTick) { + return player.DropTrinket(position, isReplaceTick); + }); + lua_method(state, "TryHoldTrinket", [](Entity_Player& player, int id) { return player.TryHoldTrinket(id); }); + lua_method(state, "GetTrinketRNG", [](Entity_Player& player, int id) -> RNG& { return player.GetTrinketRNG(id); }); + lua_method(state, "HasPlayerForm", [](Entity_Player& player, int form) { return player.HasPlayerForm(form); }); + lua_method(state, "GetZodiacEffect", [](Entity_Player& player) { return player.GetZodiacEffect(); }); + + lua_method(state, "GetActiveItem", [](Entity_Player& player, int slot) { return player.GetActiveItem(slot); }); + lua_method(state, "GetActiveCharge", [](Entity_Player& player, int slot) { return player.GetActiveCharge(slot); }); + lua_method(state, "GetBatteryCharge", + [](Entity_Player& player, int slot) { return player.GetBatteryCharge(slot); }); + lua_method(state, "GetActiveSubCharge", + [](Entity_Player& player, int slot) { return player.GetActiveSubCharge(slot); }); + lua_method(state, "SetActiveCharge", + [](Entity_Player& player, int charge, int slot) { player.SetActiveCharge(charge, slot); }); + lua_method(state, "DischargeActiveItem", + [](Entity_Player& player, uint32_t slot) { player.DischargeActiveItem(slot, false); }); + lua_method(state, "NeedsCharge", [](Entity_Player& player, int slot) { return player.NeedsCharge(slot); }); + lua_method(state, "FullCharge", [](Entity_Player& player, int slot, bool isForced) { + return (int)player.FullCharge(slot, isForced, false); + }); + lua_method(state, "UseActiveItem", [](Entity_Player& player, int item, uint32_t flags, int slot, int varData) { + player.UseActiveItem({item, flags, slot, varData}); + }); + lua_method(state, "SwapActiveItems", [](Entity_Player& player) { player.SwapActiveItems(); }); + lua_method(state, "SetPocketActiveItem", [](Entity_Player& player, int item, int slot, bool isKeptInPools) { + player.SetPocketActiveItem(item, slot, isKeptInPools); + }); + lua_method(state, "GetCard", [](Entity_Player& player, int slot) { return player.GetCard(slot); }); + lua_method(state, "GetPill", [](Entity_Player& player, int slot) { return player.GetPill(slot); }); + lua_method(state, "SetCard", [](Entity_Player& player, int slot, int card) { player.SetCard(slot, card); }); + lua_method(state, "SetPill", [](Entity_Player& player, int slot, int color) { player.SetPill(slot, color); }); + lua_method(state, "AddCard", [](Entity_Player& player, int card) { player.AddCard(card); }); + lua_method(state, "AddPill", [](Entity_Player& player, int color) { player.AddPill(color); }); + lua_method(state, "GetMaxPocketItems", [](Entity_Player& player) { return player.GetMaxPocketItems(); }); + lua_method(state, "DropPocketItem", + [](Entity_Player& player, int slot, Vector position) { player.DropPocketItem(slot, position); }); + lua_method(state, "UseCard", [](Entity_Player& player, int card, uint32_t flags) { player.UseCard(card, flags); }); + lua_method(state, "UsePill", [](Entity_Player& player, int effect, int color, uint32_t flags) { + player.UsePill(effect, color, flags); + }); + lua_method(state, "GetCardRNG", [](Entity_Player& player, int card) -> RNG& { return player.GetCardRNG(card); }); + lua_method(state, "GetPillRNG", + [](Entity_Player& player, int effect) -> RNG& { return player.GetPillRNG(effect); }); + lua_method(state, "IsItemQueueEmpty", [](Entity_Player& player) { return player.IsItemQueueEmpty(); }); + lua_method(state, "FlushQueueItem", [](Entity_Player& player) { return player.FlushQueueItem(); }); + + lua_method(state, "AddCostume", [](Entity_Player& player, ItemConfig_Item* item, bool isItemStateOnly) { + player.AddCostume(item, isItemStateOnly); + }); + lua_method(state, "AddNullCostume", [](Entity_Player& player, int costume) { player.AddNullCostume(costume); }); + lua_method(state, "RemoveCostume", + [](Entity_Player& player, ItemConfig_Item* item) { player.RemoveCostume(item); }); + lua_method(state, "ClearCostumes", [](Entity_Player& player) { player.ClearCostumes(); }); + lua_method(state, "TryRemoveCollectibleCostume", [](Entity_Player& player, int id, bool isKeepPersistent) { + player.TryRemoveCollectibleCostume(id, isKeepPersistent); + }); + lua_method(state, "TryRemoveTrinketCostume", + [](Entity_Player& player, int id) { player.TryRemoveTrinketCostume(id); }); + lua_method(state, "TryRemoveNullCostume", [](Entity_Player& player, int id) { player.TryRemoveNullCostume(id); }); + lua_method(state, "AddPlayerFormCostume", + [](Entity_Player& player, int form) { player.AddPlayerFormCostume(form); }); + lua_method(state, "GetEffects", [](Entity_Player& player) -> TemporaryEffects& { return player.temporaryEffects; }); + lua_method(state, "ClearTemporaryEffects", [](Entity_Player& player) { player.ClearTemporaryEffects(); }); +} + +// Registers the player's animations, controls and the rest of the EntityPlayer methods. +static void player_misc_register(lua_State* state) +{ + lua_method(state, "GetName", [](Entity_Player& player) -> const std::string& { return player.name; }); + lua_method(state, "GetPlayerType", [](Entity_Player& player) { return player.playerType; }); + lua_method(state, "ChangePlayerType", + [](Entity_Player& player, int type) { player.ChangePlayerType(type, false); }); + lua_method(state, "AddCacheFlags", [](Entity_Player& player, uint32_t flags) { player.AddCacheFlags(flags); }); + lua_method(state, "EvaluateItems", [](Entity_Player& player) { player.EvaluateItems(); }); + lua_method(state, "RespawnFamiliars", [](Entity_Player& player) { player.RespawnFamiliars(); }); + lua_method(state, "IsSubPlayer", [](Entity_Player& player) { return (bool)player.IsSubPlayer(); }); + lua_method(state, "GetSubPlayer", [](Entity_Player& player) { return player.subPlayer; }); + lua_method(state, "GetMainTwin", [](Entity_Player& player) { return player.GetMainTwin(); }); + lua_method(state, "GetOtherTwin", [](Entity_Player& player) { return player.twin_get(); }); + lua_method(state, "IsCoopGhost", [](Entity_Player& player) { return player.isCoopGhost; }); + lua_method(state, "IsHoldingItem", [](Entity_Player& player) { return player.IsHoldingItem(); }); + lua_method(state, "IsHeldItemVisible", [](Entity_Player& player) { return player.isHeldItemVisible; }); + lua_method(state, "CanShoot", [](Entity_Player& player) { return player.canShoot; }); + lua_method(state, "UpdateCanShoot", [](Entity_Player& player) { player.UpdateCanShoot(); }); + lua_method(state, "HasWeaponType", [](Entity_Player& player, int type) { return player.HasWeaponType(type); }); + lua_method(state, "GetActiveWeaponEntity", [](Entity_Player& player) { return player.GetActiveWeaponEntity(); }); + lua_method(state, "HasTimedItem", [](Entity_Player& player) { return player.HasTimedItem(); }); + lua_method(state, "AreControlsEnabled", [](Entity_Player& player) { return player.AreControlsEnabled(); }); + lua_method(state, "GetMovementDirection", [](Entity_Player& player) { return player.moveDirection; }); + lua_method(state, "GetFireDirection", [](Entity_Player& player) { return player.fireDirection; }); + lua_method(state, "GetHeadDirection", [](Entity_Player& player) { return player.headDirection; }); + lua_method(state, "GetAimDirection", [](Entity_Player& player) -> Vector& { return player.aimDirection; }); + lua_method(state, "GetLastDirection", [](Entity_Player& player) -> Vector& { return player.lastDirection; }); + lua_method(state, "GetMovementVector", [](Entity_Player& player) -> Vector& { return player.movementVector; }); + lua_method(state, "GetRecentMovementVector", + [](Entity_Player& player) -> Vector& { return player.recentMovementVector; }); + lua_method(state, "GetVelocityBeforeUpdate", [](Entity_Player& player) -> Vector& { return player.lastVelocity; }); + lua_method(state, "GetMovementJoystick", [](Entity_Player& player) { return player.GetMovementJoystick(); }); + lua_method(state, "GetShootingJoystick", [](Entity_Player& player) { return player.GetShootingJoystick(); }); + lua_method(state, "GetFlyingOffset", [](Entity_Player& player) { return player.GetFlyingOffset(); }); + lua_method(state, "AreOpposingShootDirectionsPressed", + [](Entity_Player& player) { return player.areOpposingShootDirectionsPressed; }); + lua_method(state, "GetDamageCooldown", [](Entity_Player& player) { return player.damageCooldown; }); + lua_method(state, "ResetDamageCooldown", [](Entity_Player& player) { player.ResetDamageCooldown(); }); + lua_method(state, "SetMinDamageCooldown", + [](Entity_Player& player, int cooldown) { player.SetMinDamageCooldown(cooldown); }); + lua_method(state, "GetLastDamageFlags", [](Entity_Player& player) { return player.lastDamageFlags; }); + lua_method(state, "GetLastDamageSource", + [](Entity_Player& player) -> EntityRef& { return player.lastDamageSource; }); + lua_method(state, "GetTotalDamageTaken", [](Entity_Player& player) { return player.totalDamageTaken; }); + lua_method(state, "GetBodyColor", [](Entity_Player& player) { return player.bodyColor; }); + lua_method(state, "GetHeadColor", [](Entity_Player& player) { return player.headColor; }); + lua_method(state, "DonateLuck", [](Entity_Player& player, int luck) { player.DonateLuck(luck); }); + lua_method(state, "Revive", [](Entity_Player& player) { player.Revive(); }); + lua_method(state, "TryHoldEntity", + [](Entity_Player& player, Entity* entity) { return player.TryHoldEntity(entity); }); + lua_method(state, "ThrowHeldEntity", + [](Entity_Player& player, Vector velocity) { return player.ThrowHeldEntity(velocity); }); + lua_method(state, "AddMinisaac", [](Entity_Player& player, Vector position, bool isPlayAnim) { + return player.AddMinisaac(position, isPlayAnim); + }); + lua_method(state, "AddFriendlyDip", + [](Entity_Player& player, int subType, Vector position) { player.AddFriendlyDip(subType, position); }); + lua_method(state, "ThrowFriendlyDip", [](Entity_Player& player, int subType, Vector position, Vector target) { + player.ThrowFriendlyDip(subType, position, target); + }); + lua_method(state, "AddWisp", + [](Entity_Player& player, int item, Vector position, bool isAdjustOrbit, bool isDontUpdate) { + return player.AddWisp(item, position, isAdjustOrbit, isDontUpdate); + }); + lua_method(state, "AddItemWisp", [](Entity_Player& player, int item, Vector position, bool isAdjustOrbit) { + return player.AddItemWisp(item, position, isAdjustOrbit); + }); + lua_method(state, "AddSwarmFlyOrbital", + [](Entity_Player& player, Vector position) { return player.AddSwarmFlyOrbital(position); }); + lua_method(state, "TriggerBookOfVirtues", + [](Entity_Player& player, int item, int charge) { player.TriggerBookOfVirtues(item, charge); }); + lua_method( + state, "FireTear", + [](Entity_Player& player, Vector position, Vector velocity, uint32_t flags, Entity* source, + float damageMultiplier) { return player.FireTear({position, velocity}, flags, source, damageMultiplier); }); + lua_method(state, "FireBomb", [](Entity_Player& player, Vector position, Vector velocity, Entity* source) { + return player.FireBomb(position, velocity, source); + }); + lua_method(state, "GetTearHitParams", + [](Entity_Player& player, WeaponType weapon, float damageScale, int displacement, Entity* source) { + return player.GetTearHitParams(weapon, damageScale, displacement, source); + }); + + lua_method(state, "AnimateCollectible", + [](Entity_Player& player, int id, std::string_view anim, std::string_view spriteAnim) { + player.AnimateCollectible(id, anim, spriteAnim); + }); + lua_method(state, "AnimateTrinket", + [](Entity_Player& player, int id, std::string_view anim, std::string_view spriteAnim) { + player.AnimateTrinket(id, anim, spriteAnim); + }); + lua_method(state, "AnimateCard", + [](Entity_Player& player, int id, std::string_view anim) { player.AnimateCard(id, anim); }); + lua_method(state, "AnimatePill", + [](Entity_Player& player, int color, std::string_view anim) { player.AnimatePill(color, anim); }); + lua_method(state, "AnimatePickup", + [](Entity_Player& player, ANM2* sprite, bool isHideShadow, std::string_view anim) { + player.AnimatePickup(sprite, isHideShadow, anim); + }); + lua_method(state, "AnimateTrapdoor", [](Entity_Player& player) { player.AnimateTrapdoor(); }); + lua_method(state, "AnimateLightTravel", [](Entity_Player& player) { player.AnimateLightTravel(); }); + lua_method(state, "AnimateAppear", [](Entity_Player& player) { player.AnimateAppear(); }); + lua_method(state, "AnimateTeleport", [](Entity_Player& player, bool isUp) { player.AnimateTeleport(isUp); }); + lua_method(state, "AnimateHappy", [](Entity_Player& player) { player.AnimateHappy(); }); + lua_method(state, "AnimateSad", [](Entity_Player& player) { player.AnimateSad(); }); + lua_method(state, "AnimatePitfallIn", [](Entity_Player& player) { player.AnimatePitfallIn(false); }); + lua_method(state, "AnimatePitfallOut", [](Entity_Player& player) { player.AnimatePitfallOut(); }); + lua_method(state, "PlayExtraAnimation", + [](Entity_Player& player, std::string_view anim) { player.PlayExtraAnimation(anim); }); + lua_method(state, "QueueExtraAnimation", + [](Entity_Player& player, std::string_view anim) { player.QueueExtraAnimation(anim); }); + lua_method(state, "IsExtraAnimationFinished", + [](Entity_Player& player) { return player.IsExtraAnimationFinished(); }); + lua_method(state, "StopExtraAnimation", [](Entity_Player& player) { player.StopExtraAnimation(); }); +} + +// Registers the player's stats, which mods change in MC_EVALUATE_CACHE. +static void player_stats_register(lua_State* state) +{ + lua_property( + state, "FireDelay", [](Entity_Player& player) { return player.FireDelay(); }, + [](Entity_Player& player, float delay) { + if (Weapon* weapon = player_weapon_main(player)) weapon->fireDelay = delay; + }); + lua_field<&Entity_Player::maxFireDelay>(state, "MaxFireDelay"); + lua_field<&Entity_Player::shotSpeed>(state, "ShotSpeed"); + lua_field<&Entity_Player::damage>(state, "Damage"); + lua_field<&Entity_Player::tearHeight>(state, "TearHeight"); + lua_field<&Entity_Player::tearFallingSpeed>(state, "TearFallingSpeed"); + lua_field<&Entity_Player::tearFallingAcceleration>(state, "TearFallingAcceleration"); + lua_field<&Entity_Player::tearRange>(state, "TearRange"); + lua_field<&Entity_Player::moveSpeed>(state, "MoveSpeed"); + lua_field<&Entity_Player::tearFlags>(state, "TearFlags"); + lua_field<&Entity_Player::tearColor>(state, "TearColor"); + lua_field<&Entity_Player::laserColor>(state, "LaserColor"); + lua_field<&Entity_Player::canFly>(state, "CanFly"); + lua_field<&Entity_Player::luck>(state, "Luck"); + lua_field<&Entity_Player::babySkin>(state, "BabySkin"); + lua_field<&Entity_Player::itemHoldCooldown>(state, "ItemHoldCooldown"); + lua_field<&Entity_Player::samsonBerserkCharge>(state, "SamsonBerserkCharge"); + lua_field<&Entity_Player::ibsCharge>(state, "IBSCharge"); + lua_field<&Entity_Player::tearsOffset>(state, "TearsOffset"); + lua_field_get<&Entity_Player::controllerIndex>(state, "ControllerIndex"); + lua_property( + state, "ControlsEnabled", [](Entity_Player& player) { return player.isControlsEnabled; }, + [](Entity_Player& player, bool isEnabled) { player.isControlsEnabled = isEnabled; }); + lua_field<&Entity_Player::controlsCooldown>(state, "ControlsCooldown"); + lua_method(state, "SpriteScale", [](Entity_Player& player) { return player.SpriteScale(); }); +} + +// Registers Lua's EntityPlayer, TemporaryEffects and TearParams. +void lua_api_entity_player_register(lua_State* state) +{ + lua_class_begin(state, "EntityPlayer", LUA_CLASS_PLAYER, LUA_CLASS_ENTITY); + player_health_register(state); + player_items_register(state); + player_misc_register(state); + player_stats_register(state); + lua_class_end(state); + + lua_class_begin(state, "TemporaryEffects", LUA_CLASS_TEMPORARY_EFFECTS); + lua_method(state, "AddCollectibleEffect", [](TemporaryEffects& effects, int id, bool isAddCostume, int count) { + effects.AddCollectibleEffect(id, isAddCostume, count); + }); + lua_method(state, "AddTrinketEffect", [](TemporaryEffects& effects, int id, bool isAddCostume, int count) { + effects.AddTrinketEffect(id, isAddCostume, count); + }); + lua_method(state, "AddNullEffect", [](TemporaryEffects& effects, int id, bool isAddCostume, int count) { + effects.AddNullEffect(id, isAddCostume, count); + }); + lua_method(state, "RemoveCollectibleEffect", + [](TemporaryEffects& effects, int id, int count) { effects.RemoveCollectibleEffect(id, count); }); + lua_method(state, "RemoveTrinketEffect", + [](TemporaryEffects& effects, int id, int count) { effects.RemoveTrinketEffect(id, count); }); + lua_method(state, "RemoveNullEffect", + [](TemporaryEffects& effects, int id, int count) { effects.RemoveNullEffect(id, count); }); + lua_method(state, "HasCollectibleEffect", + [](TemporaryEffects& effects, int id) { return effects.HasCollectibleEffect(id); }); + lua_method(state, "HasTrinketEffect", + [](TemporaryEffects& effects, int id) { return effects.HasTrinketEffect(id); }); + lua_method(state, "HasNullEffect", [](TemporaryEffects& effects, int id) { return effects.HasNullEffect(id); }); + lua_method(state, "GetCollectibleEffectNum", + [](TemporaryEffects& effects, int id) { return effects.GetCollectibleEffectNum(id); }); + lua_method(state, "GetTrinketEffectNum", + [](TemporaryEffects& effects, int id) { return effects.GetTrinketEffectNum(id); }); + lua_method(state, "GetNullEffectNum", + [](TemporaryEffects& effects, int id) { return effects.GetNullEffectNum(id); }); + lua_method(state, "ClearEffects", [](TemporaryEffects& effects) { effects.ClearEffects(false); }); + lua_class_end(state); + + lua_class_begin(state, "TearParams", LUA_CLASS_TEAR_PARAMS); + lua_field<&TearParams::tearVariant>(state, "TearVariant"); + lua_field<&TearParams::bombVariant>(state, "BombVariant"); + lua_field<&TearParams::tearColor>(state, "TearColor"); + lua_field<&TearParams::tearFlags>(state, "TearFlags"); + lua_field<&TearParams::tearDamage>(state, "TearDamage"); + lua_field<&TearParams::tearScale>(state, "TearScale"); + lua_field<&TearParams::tearHeight>(state, "TearHeight"); + lua_class_end(state); +} diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp new file mode 100644 index 0000000..5dc8649 --- /dev/null +++ b/src/lua_api_game.cpp @@ -0,0 +1,174 @@ +#include "classes.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "game.h" +#include "hud.h" +#include "item_pool.h" +#include "lua_api.h" +#include "manager.h" +#include "music_manager.h" +#include "seeds.h" +#include "sfx_manager.h" + +// Registers Lua's Game: the run's level, room, players, pools, seeds and HUD, spawning, and its state flags and +// counters. Game is also the Level it derives from. +static void game_register(lua_State* state) +{ + lua_class_begin(state, "Game", LUA_CLASS_GAME); + lua_method(state, "GetLevel", [](Game& game) -> Level& { return game; }); + lua_method(state, "GetRoom", [](Game& game) { return game.room.get(); }); + lua_method(state, "GetPlayer", [](Game& game, int index) { return game.GetPlayer(index); }); + lua_method(state, "GetNumPlayers", [](Game& game) { return (int)game.playerManager.playerList.size(); }); + lua_method(state, "GetNearestPlayer", [](Game&, Vector position) { return game_nearest_player(position); }); + lua_method(state, "GetItemPool", [](Game& game) -> ItemPool& { return game.itemPool; }); + lua_method(state, "GetHUD", [](Game& game) -> HUD& { return game.hud; }); + lua_method(state, "GetSeeds", [](Game& game) -> Seeds& { return game.seedEffects; }); + lua_method(state, "GetFrameCount", [](Game& game) { return game.frameCount; }); + lua_method(state, "IsPaused", [](Game& game) { return game.IsPaused(); }); + lua_method(state, "IsGreedMode", [](Game& game) { return game.IsGreedMode(); }); + lua_method(state, "GetStateFlag", [](Game& game, GameStateFlag flag) { return game.GetStateFlag(flag); }); + lua_method(state, "SetStateFlag", [](Game& game, int flag, bool isSet) { + game.gameStateFlags = isSet ? game.gameStateFlags | 1ull << flag : game.gameStateFlags & ~(1ull << flag); + }); + lua_method(state, "ShakeScreen", [](Game&, int timeout) { game_shake_screen(timeout); }); + lua_method(state, "Spawn", [](Game& game, int type, int variant, Vector position, Vector velocity, Entity* spawner, + int subType, uint32_t seed) { + return game.Spawn({position, velocity, spawner, subType, type, variant, seed}); + }); + lua_method(state, "GetVictoryLap", [](Game& game) { return game.victoryLap; }); + lua_method(state, "GetDevilRoomDeals", [](Game& game) { return game.devilRoomDeals; }); + lua_method(state, "GetLastDevilRoomStage", [](Game& game) { return game.lastDevilRoomStage; }); + lua_method(state, "GetTreasureRoomVisitCount", [](Game& game) { return game.treasureRoomsVisited; }); + lua_method(state, "GetStagesWithoutDamage", [](Game& game) { return game.stagesWithoutDamage; }); + lua_method(state, "GetStagesWithoutHeartsPicked", [](Game& game) { return game.stagesWithoutHeartsPicked; }); + lua_method(state, "GetDarknessModifier", [](Game& game) { return game.darknessModifier; }); + lua_method(state, "GetScreenShakeCountdown", [](Game& game) { return game.screenShakeTimer; }); + lua_field<&Game::challenge>(state, "Challenge"); + lua_field<&Game::difficulty>(state, "Difficulty"); + lua_field<&Game::timeCounter>(state, "TimeCounter"); + lua_field<&Game::blueWombParTime>(state, "BlueWombParTime"); + lua_field<&Game::bossRushParTime>(state, "BossRushParTime"); + lua_field<&Game::screenShakeOffset>(state, "ScreenShakeOffset"); + lua_class_end(state); +} + +// Registers Lua's HUD, ItemPool and Seeds, the parts of a run Game hands out. +static void game_parts_register(lua_State* state) +{ + lua_class_begin(state, "HUD", LUA_CLASS_HUD); + lua_method(state, "IsVisible", [](HUD& hud) { return hud.IsVisible(); }); + lua_method(state, "SetVisible", [](HUD& hud, bool isShown) { hud.SetVisible(isShown); }); + lua_method(state, "FlashChargeBar", + [](HUD& hud, Entity_Player* player, int slot) { hud.FlashChargeBar(player, slot); }); + lua_method(state, "InvalidateActiveItem", + [](HUD& hud, Entity_Player* player, int slot) { hud.InvalidateActiveItem(player, slot); }); + lua_method(state, "InvalidateCraftingItem", + [](HUD& hud, Entity_Player* player) { hud.InvalidateCraftingItem(player); }); + lua_method(state, "ShowItemText", [](HUD& hud, Entity_Player* player, ItemConfig_Item* item) { + hud.ShowItemText(player, item); + }); + lua_class_end(state); + + lua_class_begin(state, "ItemPool", LUA_CLASS_ITEM_POOL); + lua_method(state, "GetCollectible", + [](ItemPool& pool, ItemPoolType poolType, uint32_t seed, uint32_t flags, int defaultItem, + int fallbackPool) { return pool.GetCollectible(poolType, seed, flags, defaultItem, fallbackPool); }); + lua_method(state, "RemoveCollectible", [](ItemPool& pool, int collectible) { + return pool.RemoveCollectible(collectible, REMOVE_ANY, REMOVE_APPLY); + }); + lua_method(state, "GetTrinket", [](ItemPool& pool, bool isPeek) { + return pool.GetTrinket(isPeek ? TRINKET_DRAW_PEEK : TRINKET_DRAW_TAKE); + }); + lua_method(state, "RemoveTrinket", [](ItemPool& pool, int trinket) { return pool.RemoveTrinket(trinket); }); + lua_method(state, "ResetTrinkets", [](ItemPool& pool) { pool.ResetTrinkets(); }); + lua_method(state, "GetCard", [](ItemPool&, uint32_t seed, bool isPlaying, bool isRunes, bool isOnlyRunes) { + return ItemPool::GetCard(seed, isPlaying, isRunes, isOnlyRunes); + }); + lua_method(state, "GetPill", [](ItemPool&, uint32_t seed) { return ItemPool::GetPill(seed); }); + lua_method(state, "GetPillEffect", + [](ItemPool& pool, uint32_t color, Entity_Player* player) { return pool.GetPillEffect(color, player); }); + lua_method(state, "IdentifyPill", [](ItemPool& pool, uint32_t color) { pool.IdentifyPill(color); }); + lua_method(state, "IsPillIdentified", [](ItemPool& pool, uint32_t color) { return pool.IsPillIdentified(color); }); + lua_method(state, "ForceAddPillEffect", [](ItemPool& pool, int effect) { return pool.ForceAddPillEffect(effect); }); + lua_method(state, "GetLastPool", [](ItemPool& pool) { return pool.GetLastPool(); }); + lua_method(state, "GetPoolForRoom", + [](ItemPool& pool, int roomType, uint32_t seed) { return pool.GetPoolForRoom(roomType, seed); }); + lua_method(state, "AddRoomBlacklist", [](ItemPool& pool, int collectible) { pool.AddRoomBlacklist(collectible); }); + lua_method(state, "ResetRoomBlacklist", [](ItemPool& pool) { pool.ResetRoomBlacklist(); }); + lua_method(state, "AddBibleUpgrade", + [](ItemPool& pool, int add, int poolType) { pool.AddBibleUpgrade(add, poolType); }); + lua_class_end(state); + + lua_class_begin(state, "Seeds", LUA_CLASS_SEEDS); + lua_method(state, "GetStartSeed", [](Seeds& seeds) { return seeds.GetStartSeed(); }); + lua_method(state, "IsCustomRun", [](Seeds& seeds) { return seeds.isCustomRun; }); + lua_method(state, "GetStartSeedString", [](Seeds& seeds) { return seeds.GetStartSeedString(); }); + lua_method(state, "GetNextSeed", [](Seeds& seeds) { return seeds.GetNextSeed(); }); + lua_method(state, "GetStageSeed", [](Seeds& seeds, int stage) { return seeds.GetStageSeed(stage); }); + lua_method(state, "GetPlayerInitSeed", [](Seeds& seeds) { return seeds.GetPlayerInitSeed(); }); + lua_method(state, "HasSeedEffect", [](Seeds& seeds, uint32_t effect) { return seeds.HasSeedEffect(effect); }); + lua_method(state, "AddSeedEffect", [](Seeds& seeds, int effect) { seeds.AddSeedEffect(effect); }); + lua_method(state, "RemoveSeedEffect", [](Seeds& seeds, int effect) { seeds.RemoveSeedEffect(effect); }); + lua_method(state, "CanAddSeedEffect", [](Seeds& seeds, uint32_t effect) { return seeds.CanAddSeedEffect(effect); }); + lua_static(state, "Seed2String", [](uint32_t seed) { return Seeds::Seed2String(seed); }); + lua_static(state, "String2Seed", [](std::string_view seed) { return Seeds::String2Seed(seed); }); + lua_static(state, "IsStringValidSeed", [](std::string_view seed) { return Seeds::IsStringValidSeed(seed); }); + lua_class_end(state); +} + +// Registers Lua's SFXManager and MusicManager, the sound effects and music the scripts reach through the global +// functions of the same names. +static void sound_register(lua_State* state) +{ + lua_class_begin(state, "SFXManager", LUA_CLASS_SFX_MANAGER); + lua_method(state, "Play", [](SFXManager& sfx, int sound, float volume, int frameDelay, bool isLooped, float pitch, + float pan) { + sfx.Play(sound, {volume, frameDelay, isLooped ? SOUND_LOOP : SOUND_ONCE, pitch, pan}); + }); + lua_method(state, "Stop", [](SFXManager& sfx, int sound) { sfx.Stop(sound); }); + lua_method(state, "IsPlaying", [](SFXManager& sfx, int sound) { return sfx.IsPlaying(sound); }); + lua_method(state, "Preload", [](SFXManager& sfx, int sound) { sfx.Preload(sound); }); + lua_method(state, "AdjustVolume", + [](SFXManager& sfx, int sound, float volume) { sfx.AdjustVolume(sound, volume); }); + lua_method(state, "AdjustPitch", [](SFXManager& sfx, int sound, float pitch) { sfx.AdjustPitch(sound, pitch); }); + lua_method(state, "StopLoopingSounds", [](SFXManager& sfx) { sfx.StopLoopingSounds(); }); + lua_method(state, "SetAmbientSound", [](SFXManager& sfx, int sound, float volume, float pitch) { + sfx.SetAmbientSound(sound, volume, pitch); + }); + lua_method(state, "GetAmbientSoundVolume", + [](SFXManager& sfx, int sound) { return sfx.GetAmbientSoundVolume(sound); }); + lua_class_end(state); + + lua_class_begin(state, "MusicManager", LUA_CLASS_MUSIC_MANAGER); + lua_method(state, "Play", [](MusicManager& music, int track, float volume) { music.Play(track, volume); }); + lua_method(state, "Fadein", + [](MusicManager& music, int track, float volume, float rate) { music.Fadein(track, volume, rate); }); + lua_method(state, "Crossfade", [](MusicManager& music, int track, float rate) { music.Crossfade(track, rate); }); + lua_method(state, "Fadeout", [](MusicManager& music, float rate) { music.Fadeout(rate); }); + lua_method(state, "Queue", [](MusicManager& music, int track) { music.Queue(track); }); + lua_method(state, "Pause", [](MusicManager& music) { music.Pause(); }); + lua_method(state, "Resume", [](MusicManager& music) { music.Resume(); }); + lua_method(state, "EnableLayer", [](MusicManager& music, int layer, bool isInstant) { + music.EnableLayer(layer, isInstant ? LAYER_INSTANT : LAYER_FADE); + }); + lua_method(state, "DisableLayer", [](MusicManager& music, int layer) { music.DisableLayer(layer); }); + lua_method(state, "IsLayerEnabled", [](MusicManager& music, int layer) { return music.IsLayerEnabled(layer); }); + lua_method(state, "Enable", [](MusicManager& music) { music.Enable(); }); + lua_method(state, "Disable", [](MusicManager& music) { music.Disable(); }); + lua_method(state, "IsEnabled", [](MusicManager& music) { return music.IsEnabled(); }); + lua_method(state, "PitchSlide", [](MusicManager& music, float pitch) { music.PitchSlide(pitch); }); + lua_method(state, "ResetPitch", [](MusicManager& music) { music.ResetPitch(); }); + lua_method(state, "VolumeSlide", + [](MusicManager& music, float volume, float rate) { music.VolumeSlide(volume, rate); }); + lua_method(state, "UpdateVolume", [](MusicManager& music) { music.UpdateVolume(); }); + lua_method(state, "GetCurrentMusicID", [](MusicManager& music) { return music.GetCurrentMusicID(); }); + lua_method(state, "GetQueuedMusicID", [](MusicManager& music) { return music.GetQueuedMusicID(); }); + lua_class_end(state); +} + +void lua_api_game_register(lua_State* state) +{ + game_register(state); + game_parts_register(state); + sound_register(state); +} diff --git a/src/lua_api_isaac.cpp b/src/lua_api_isaac.cpp new file mode 100644 index 0000000..65d26ac --- /dev/null +++ b/src/lua_api_isaac.cpp @@ -0,0 +1,650 @@ +#include "classes.h" +#include "data.h" +#include "entity.h" +#include "entity_bomb.h" +#include "entity_familiar.h" +#include "entity_list.h" +#include "entity_player.h" +#include "font.h" +#include "fx_layers.h" +#include "game.h" +#include "grid_entity.h" +#include "kage_input.h" +#include "lua_api.h" +#include "manager.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "platform.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include +#include +#include +#include +#include + +constexpr const char* LUA_EXTENSION = ".lua"; +constexpr const char* MOD_SAVE_FILE = "/save%d.dat"; +constexpr const char* SCRIPTS_FOLDER = "scripts/"; +constexpr const char* PATH_SEPARATORS = "/\\"; +constexpr const char* PRINT_SEPARATOR = " "; +constexpr float GRID_ROUNDING = 0.5f; +constexpr float SCREEN_DISTANCE_SCALE = 0.65f; +constexpr int GRID_INDEX_LIMIT = 448; +constexpr int LUA_TYPE_NONE = 0; +constexpr int SAVE_SLOT_DEFAULT = 1; +constexpr uint32_t PARTITIONS_ALL = 0xffffffff; + +// What FindByType asks for: a type, and a variant and subtype unless -1. +struct EntityTypeQuery +{ + int type = 0; + int variant = -1; + int subType = -1; + bool isCached = false; + bool isFriendlyIgnored = false; +}; + +// Pushes entities as a Lua array of Entity objects. +static void entities_push(lua_State* state, const std::vector& entities) +{ + lua_createtable(state, (int)entities.size(), 0); + for (size_t i = 0; i < entities.size(); i++) + { + lua_push(state, entities[i]); + lua_rawseti(state, -2, (lua_Integer)i + 1); + } +} + +// An optional integer argument, fallback when it is nil or missing. +static int integer_optional(lua_State* state, int index, int fallback) +{ + return lua_type(state, index) <= LUA_TYPE_NONE ? fallback : (int)luaL_checkinteger(state, index); +} + +// 0041af60 The updated entities of a type a query may see, as EntityList::QuerySublist lists them: wisps of a subtype +// from the wisp list, others filtered from the update list and kept in the type cache when asked to. +static EntityList_EL entities_by_type(EntityList& list, const EntityTypeQuery& query) +{ + if (query.type == ENTITY_FAMILIAR && query.variant == Entity_Familiar::WISP) + { + EntityList_EL wisps; + for (Entity* wisp : list.wispEL) + if (query.subType == -1 || wisp->subtype == query.subType) wisps.push_back(wisp); + return wisps; + } + + std::array key = {query.type, query.variant, query.subType}; + if (query.isCached) + { + auto cached = list.typeCache.find(key); + if (cached != list.typeCache.end()) return cached->second; + } + + EntityList_EL found; + for (Entity* entity : list.updateEL) + if (entity->IsType(query.type, query.variant < 0 ? -1 : query.variant, + query.subType < 0 ? -1 : query.subType) && + !entity->HasEntityFlags(FLAG_NO_QUERY) && + !(query.isFriendlyIgnored && entity->HasEntityFlags(FLAG_FRIENDLY))) + found.push_back(entity); + if (query.isCached) list.typeCache[key] = found; + return found; +} + +// 0086ef50 The player of an index (0 when nil), nil past the last. Nothing at all without a game or players. +static int player_get(lua_State* state) +{ + if (!g_game || g_game->playerManager.playerList.empty()) return 0; + lua_push(state, g_game->GetPlayer(integer_optional(state, 1, 0))); + return 1; +} + +// 0086fb20 Every entity the room updates, as an array. +static int room_entities_get(lua_State* state) +{ + entities_push(state, g_game->room->entityList.updateEL); + return 1; +} + +// 008707b0 The entities of a type, and of a variant and subtype unless nil or -1, maybe cached, maybe without the +// friendly ones. An empty array without a game. +static int entities_find_by_type(lua_State* state) +{ + if (!g_game) + { + lua_newtable(state); + return 1; + } + + EntityTypeQuery query = {.isCached = (bool)lua_toboolean(state, 4), + .isFriendlyIgnored = (bool)lua_toboolean(state, 5)}; + query.subType = integer_optional(state, 3, -1); + query.variant = integer_optional(state, 2, -1); + query.type = (int)luaL_checkinteger(state, 1); + entities_push(state, entities_by_type(g_game->room->entityList, query)); + return 1; +} + +// 008704f0 The entities of the partitions (all when nil) within a radius of a position. +static int entities_find_in_radius(lua_State* state) +{ + if (!g_game) + { + lua_newtable(state); + return 1; + } + + uint32_t partitions = lua_isnoneornil(state, 3) ? PARTITIONS_ALL : (uint32_t)luaL_checkinteger(state, 3); + float radius = (float)luaL_checknumber(state, 2); + Vector position = lua_get(state, 1); + entities_push(state, entity_query_radius(position, radius, partitions)); + return 1; +} + +// 00870b40 How many entities of a type (0 for nil), variant and subtype (-1 for nil) a spawner spawned. 0 without a +// game. +static int entities_count(lua_State* state) +{ + if (!g_game) + { + lua_pushinteger(state, 0); + return 1; + } + + int subType = integer_optional(state, 4, -1); + int variant = integer_optional(state, 3, -1); + int type = integer_optional(state, 2, 0); + Entity* spawner = lua_get(state, 1); + lua_pushinteger(state, g_game->room->entityList.CountEntities(spawner, type, variant, subType)); + return 1; +} + +// 0086f0d0 Spawns a grid entity at the tile under a position, unless something other than a decoration or web stands +// there and the spawn is not forced. The grid entity it made, nil if none. The original also spawns at index -1 for a +// position outside the room, which is skipped here. +static GridEntity* grid_spawn(int type, int variant, Vector position, bool isForced) +{ + Room& room = *g_game->room; + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + GRID_ROUNDING); + int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + GRID_ROUNDING); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return nullptr; + + int index = room.gridWidth * row + column; + uint32_t seed = Random(); + if (index >= GRID_INDEX_LIMIT) + { + room.SpawnGridEntity(index, (GridEntityType)type, variant, seed, 0); + return nullptr; + } + + GridEntity* standing = room.gridEntities[index]; + if (standing && standing->type != GRID_DECORATION && standing->type != GRID_SPIDERWEB && !isForced) return nullptr; + room.SpawnGridEntity(index, (GridEntityType)type, variant, seed, 0); + return room.gridEntities[index]; +} + +// The first registered mod whose table is argument 1. +static LuaMod* mod_find(lua_State* state) +{ + for (LuaMod& mod : lua_engine_get().mods) + { + lua_rawgeti(state, LUA_REGISTRYINDEX, mod.tableRef); + bool isMatch = lua_compare(state, -1, 1, LUA_OPEQ); + lua_pop(state, 1); + if (isMatch) return &mod; + } + return nullptr; +} + +// The save file of the mod whose table is argument 1, in its folder, for the current save slot. +static std::optional mod_data_path(lua_State* state) +{ + LuaMod* mod = mod_find(state); + if (!mod) return std::nullopt; + + char file[32]; + std::snprintf(file, sizeof(file), MOD_SAVE_FILE, + g_manager->currentSaveSlot ? g_manager->currentSaveSlot : SAVE_SLOT_DEFAULT); + return mod->directory.substr(0, mod->directory.find_last_of(PATH_SEPARATORS)) + file; +} + +// 00870f40 Registers a mod's table with its name and API version, in the folder of the mod loading or the script. +static int mod_register(lua_State* state) +{ + LuaEngine& engine = lua_engine_get(); + ModEntry* loading = g_manager->modManager.loadingMod; + + LuaMod mod; + mod.directory = loading ? loading->dataDirectory : engine.scriptPath; + mod.scriptPath = engine.scriptPath; + mod.apiVersion = (int)luaL_checkinteger(state, 3); + mod.name = luaL_checkstring(state, 2); + lua_pushvalue(state, 1); + mod.tableRef = luaL_ref(state, LUA_REGISTRYINDEX); + engine.mods.push_back(mod); + engine.scriptApiVersion = mod.apiVersion; + return 0; +} + +// 008711f0 Writes a mod's data string to its save file, making its folders as the save data manager does. +static int mod_data_save(lua_State* state) +{ + std::string data = luaL_checkstring(state, 2); + std::optional path = mod_data_path(state); + if (!path) return 0; + + std::error_code error; + std::filesystem::create_directories(std::filesystem::path(*path).parent_path(), error); + std::ofstream file(*path, std::ios::binary); + if (!file) log_printf(LOG_INFO, "Could not open %s for writing!\n", path->c_str()); + file << data; + return 0; +} + +// 00871550 A mod's saved data string, empty without one. +static int mod_data_load(lua_State* state) +{ + std::optional path = mod_data_path(state); + std::ifstream file(path.value_or(""), std::ios::binary); + if (path && !file) log_printf(LOG_INFO, "Could not open %s for reading!\n", path->c_str()); + + std::stringstream data; + data << file.rdbuf(); + lua_push(state, data.str()); + return 1; +} + +// 00871980 Whether a mod has a save file. +static int mod_data_has(lua_State* state) +{ + std::optional path = mod_data_path(state); + std::error_code error; + lua_pushboolean(state, path && std::filesystem::exists(*path, error)); + return 1; +} + +// 00871c10 Deletes a mod's save file. +static int mod_data_remove(lua_State* state) +{ + std::optional path = mod_data_path(state); + std::error_code error; + if (path) std::filesystem::remove(*path, error); + return 0; +} + +// 0085f0f0 The file a module name is in: dots become folders and .lua is added, searched in resources/scripts/, the +// running script's folder, and that folder under the mods folder. Empty when none exists, with tried listing them. +static std::string module_path_find(std::string_view name, std::string& tried) +{ + std::string module(name); + bool isLuaFile = module.ends_with(LUA_EXTENSION); + if (isLuaFile) module.resize(module.size() - std::strlen(LUA_EXTENSION)); + std::ranges::replace(module, '.', '/'); + module += LUA_EXTENSION; + + std::string scriptPath = lua_engine_get().scriptPath; + std::string local = scriptPath.substr(0, scriptPath.find_last_of(PATH_SEPARATORS)) + "/" + module; + for (const std::string& path : {resource_path(SCRIPTS_FOLDER + module), local, platform.modsDirectory + local}) + { + std::error_code error; + if (std::filesystem::exists(path, error)) return path; + tried += "\n\tno file '" + path + "'"; + } + return ""; +} + +// 0085fec0 require without the package library: a module already loaded, else the file module_path_find gives, +// run once with its name and path, its result (true for none) kept as loaded. +static int module_require(lua_State* state) +{ + const char* name = luaL_checkstring(state, 1); + lua_settop(state, 1); + lua_getfield(state, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + if (lua_getfield(state, 2, name) != LUA_TNIL && lua_toboolean(state, -1)) return 1; + lua_pop(state, 1); + + // 0085fcc0 The module's loader and its path, or why there is none. + std::string tried; + std::string path = module_path_find(name, tried); + if (path.empty()) return luaL_error(state, "module '%s' not found:%s", name, tried.c_str()); + if (luaL_loadfile(state, path.c_str()) != LUA_OK) + return luaL_error(state, "error loading module '%s' from file '%s':\n\t%s", name, path.c_str(), + lua_tostring(state, -1)); + + lua_pushstring(state, name); + lua_pushstring(state, path.c_str()); + lua_call(state, 2, 1); + if (!lua_isnil(state, -1)) lua_setfield(state, 2, name); + else lua_pop(state, 1); + if (lua_getfield(state, 2, name) == LUA_TNIL) + { + lua_pushboolean(state, true); + lua_pushvalue(state, -1); + lua_setfield(state, 2, name); + } + return 1; +} + +// 00860000 Runs a module's file every time, returning what it returns. Its name back when no file is found. +static int module_include(lua_State* state) +{ + std::string tried; + std::string path = module_path_find(luaL_checkstring(state, 1), tried); + if (path.empty()) return 1; + + int top = lua_gettop(state); + if (luaL_loadfile(state, path.c_str()) != LUA_OK) return luaL_error(state, "%s", lua_tostring(state, -1)); + lua_call(state, 0, LUA_MULTRET); + return lua_gettop(state) - top; +} + +// 008601f0 Prints its arguments, through tostring and joined by spaces, on the console once a game exists. +static int console_print(lua_State* state) +{ + if (!g_game) return 0; + + int count = lua_gettop(state); + std::string text; + lua_getglobal(state, "tostring"); + for (int i = 1; i <= count; i++) + { + lua_pushvalue(state, -1); + lua_pushvalue(state, i); + lua_call(state, 1, 1); + if (i > 1) text += PRINT_SEPARATOR; + if (const char* part = lua_tostring(state, -1)) text += part; + lua_pop(state, 1); + } + g_game->console.Print(text); + g_game->console.Print("\n"); + return 0; +} + +// 008603d0 An object's pointer hidden by the engine's mask, the same for every userdata of one object. +static int pointer_hash_get(lua_State* state) +{ + if (!lua_isuserdata(state, 1)) + { + lua_settop(state, -2); + return luaL_error(state, "The parameter is not an user data!"); + } + void* object = *(void**)lua_touserdata(state, 1); + lua_pushinteger(state, (lua_Integer)((uintptr_t)object ^ lua_engine_get().pointerMask)); + return 1; +} + +// Text drawn with the console font, as RenderText and RenderScaledText draw it. +static void text_render(std::string_view text, Vector position, Vector scale, KColor color) +{ + FontSettings settings; + g_manager->font5_terminus8.DrawString(text, position, scale, color, settings); +} + +// The id of the last entry of a list whose name matches, fallback for none. +template +static int id_by_name_find(const List& list, std::string_view name, Name entryName, Id entryId, int fallback) +{ + for (auto entry = list.rbegin(); entry != list.rend(); ++entry) + if (entryName(*entry) == name) return entryId(*entry); + return fallback; +} + +// (0086ef30, 0086f090, 0086f0a0, 0086f1b0, 0086f280, 0086f370, 0086f3a0, 0086f3d0, 0086f400, 0086f4b0, 0086f4f0) +// (0086f520, 0086f5b0, 0086f6e0, 0086f760, 0086f800, 0086f880, 0086f900, 0086f980, 0086f9f0, 0086fa50, 0086fab0) +// (0086fc30, 0086fc40, 0086ffa0, 00870020, 00870130, 00870220, 00870390, 008703c0, 008704c0, 00870d70, 00870da0) +// (00870dd0, 00870de0, 00870df0) Registers the Isaac namespace. +static void isaac_register(lua_State* state) +{ + lua_namespace_begin(state, "Isaac"); + for (auto [name, function] : {std::pair{"GetPlayer", player_get}, {"GetRoomEntities", room_entities_get}, + {"FindByType", entities_find_by_type}, {"FindInRadius", entities_find_in_radius}, + {"CountEntities", entities_count}, {"RegisterMod", mod_register}, + {"SaveModData", mod_data_save}, {"LoadModData", mod_data_load}, + {"HasModData", mod_data_has}, {"RemoveModData", mod_data_remove}}) + { + lua_pushcfunction(state, function); + lua_table_set(state, -3, name); + } + + lua_method(state, "DebugString", [](std::string_view text) { + log_printf(LOG_INFO, "Lua Debug: %.*s\n", (int)text.size(), text.data()); + }); + lua_method(state, "GetFrameCount", []() { return g_manager->framecount; }); + lua_method(state, "Spawn", + [](int type, int variant, int subType, Vector position, Vector velocity, Entity* spawner) { + return g_game->Spawn({position, velocity, spawner, subType, type, variant, Random()}); + }); + lua_method(state, "GridSpawn", grid_spawn); + lua_method(state, "RenderText", [](std::string_view text, float x, float y, float r, float g, float b, float a) { + text_render(text, vector_make(x, y), vector_make(1, 1), kcolor_rgba(r, g, b, a)); + }); + lua_method( + state, "RenderScaledText", + [](std::string_view text, float x, float y, float scaleX, float scaleY, float r, float g, float b, float a) { + text_render(text, vector_make(x, y), vector_make(scaleX, scaleY), kcolor_rgba(r, g, b, a)); + }); + lua_method(state, "GetTextWidth", + [](std::string_view text) { return g_manager->font5_terminus8.GetStringWidth(text); }); + lua_method(state, "GetRandomPosition", []() { return g_game->room->GetRandomPosition(0); }); + lua_method(state, "GetFreeNearPosition", [](Vector position, float step) { + return room_free_pickup_position_find({.position = position, .step = step}); + }); + lua_method(state, "Explode", [](Vector position, Entity* source, float damage) { + explosion_effects({.position = position, .source = source, .damage = damage}); + }); + lua_method(state, "AddPillEffectToPool", [](int pillEffect) { g_game->itemPool.ForceAddPillEffect(pillEffect); }); + lua_method(state, "GetChallenge", []() { return g_game->challenge; }); + lua_method(state, "GetTime", []() { + return (uint32_t)std::chrono::duration_cast(std::chrono::nanoseconds(GetTimeNs())) + .count(); + }); + lua_method(state, "ExecuteCommand", [](std::string_view command) { + std::string output; + if (!g_game) return output; + g_game->console.RunCommand(command, &output, nullptr); + if (output.ends_with('\n')) output.pop_back(); + return output; + }); + lua_method(state, "ConsoleOutput", [](std::string_view text) { + if (g_game) g_game->console.Print(text); + }); + lua_method(state, "GetItemConfig", []() -> ItemConfig& { return g_manager->itemConfig; }); + lua_method(state, "CountEnemies", []() { + EntityList& list = g_game->room->entityList; + return g_game ? std::max(list.enemyCount + list.pendingEnemyCount, 0) : 0; + }); + lua_method(state, "CountBosses", []() { + EntityList& list = g_game->room->entityList; + return g_game ? std::max(list.bossCount + list.pendingBossCount, 0) : 0; + }); + lua_method(state, "SetBuiltInCallbackState", [](int callback, bool isEnabled) { + if ((uint32_t)callback < LUA_CALLBACK_COUNT) lua_engine_get().enabledCallbacks[callback] = isEnabled; + }); + lua_method(state, "GetBuiltInCallbackState", [](int callback) { + return (uint32_t)callback < LUA_CALLBACK_COUNT && lua_engine_get().enabledCallbacks[callback]; + }); + + lua_method(state, "WorldToScreen", [](Vector position) { + if (!g_game) return position; + Vector screen = vector_add(render_position_get(position, RENDER_SNAPPED), g_game->room->renderScrollOffset); + return vector_add(screen, g_game->screenShakeOffset); + }); + lua_method(state, "WorldToRenderPosition", + [](Vector position) { return render_position_get(position, RENDER_SNAPPED); }); + lua_method(state, "WorldToScreenDistance", + [](Vector distance) { return vector_scale(distance, SCREEN_DISTANCE_SCALE); }); + lua_method(state, "ScreenToWorldDistance", + [](Vector distance) { + return vector_make(distance.x / SCREEN_DISTANCE_SCALE, distance.y / SCREEN_DISTANCE_SCALE); + }); + lua_method(state, "GetScreenWidth", []() { return g_screenWidth; }); + lua_method(state, "GetScreenHeight", []() { return g_screenHeight; }); + lua_method(state, "GetScreenPointScale", []() { return g_screenPointScale; }); + + lua_method(state, "GetItemIdByName", [](std::string_view name) { return LuaEngine::Isaac_GetItemIdByName(name); }); + lua_method(state, "GetEntityTypeByName", [](std::string_view name) { + auto& entities = g_manager->entityConfig.entities; + return id_by_name_find(entities, name, [](auto& entry) -> const std::string& { return entry.second.name; }, + [](auto& entry) { return entry.second.id; }, 0); + }); + lua_method(state, "GetEntityVariantByName", [](std::string_view name) { + auto& entities = g_manager->entityConfig.entities; + return id_by_name_find(entities, name, [](auto& entry) -> const std::string& { return entry.second.name; }, + [](auto& entry) { return entry.second.variant; }, -1); + }); + lua_method(state, "GetTrinketIdByName", [](std::string_view name) { + return id_by_name_find(g_manager->itemConfig.trinkets, name, [](auto& item) { return item ? item->name : ""; }, + [](auto& item) { return item->id; }, -1); + }); + lua_method(state, "GetPlayerTypeByName", [](std::string_view name, bool isTainted) { + auto& players = g_manager->entityConfig.players; + for (auto player = players.rbegin(); player != players.rend(); ++player) + { + bool isPlayerTainted = + !player->bSkinParentName.empty() || (player->id >= PLAYER_ISAAC_B && player->id <= PLAYER_THESOUL_B); + if (player->name == name && isPlayerTainted == isTainted) return player->id; + } + return -1; + }); + lua_method(state, "GetCardIdByName", [](std::string_view name) { + return id_by_name_find(g_manager->itemConfig.cards, name, [](auto& card) { return card ? card->hudAnim : ""; }, + [](auto& card) { return card->id; }, -1); + }); + lua_method(state, "GetPillEffectByName", [](std::string_view name) { + return id_by_name_find( + g_manager->itemConfig.pillEffects, name, [](auto& pill) { return pill ? pill->name : ""; }, + [](auto& pill) { return pill->id; }, -1); + }); + lua_method(state, "GetChallengeIdByName", [](std::string_view name) { + auto& challenges = g_manager->challengeParams; + for (size_t i = 0; i < challenges.size(); i++) + if (challenges[i].name == name) return (int)i; + return -1; + }); + lua_method(state, "GetCostumeIdByPath", [](std::string_view path) { + return id_by_name_find(g_manager->itemConfig.nullItems, path, + [](auto& item) -> std::string& { return item->costume.anm2Path; }, + [](auto& item) { return item->id; }, -1); + }); + lua_method(state, "GetCurseIdByName", [](std::string_view name) { + return id_by_name_find( + g_game->roomConfig.curses, name, [](auto& curse) -> const std::string& { return curse.displayName; }, + [](auto& curse) { return curse.id; }, -1); + }); + lua_method(state, "GetMusicIdByName", [](std::string_view name) { + return id_by_name_find(g_manager->musicManager.tracks, name, + [](auto& track) -> const std::string& { return track.name; }, + [](auto& track) { return track.id; }, -1); + }); + lua_method(state, "GetSoundIdByName", [](std::string_view name) { + return id_by_name_find(g_manager->sfxManager.sounds, name, + [](auto& sound) -> const std::string& { return sound.name; }, + [](auto& sound) { return sound.id; }, -1); + }); + lua_class_end(state); +} + +// (0086fc70, 0086fca0, 0086fcd0, 0086fd10, 0086fd40, 0086fd70) Registers the Input namespace: buttons and actions +// on one controller. Action values are 1 or 0, as the analog values are not read yet. +static void input_register(lua_State* state) +{ + lua_namespace_begin(state, "Input"); + lua_method(state, "IsButtonTriggered", [](int button, int controller) { + auto device = KAGE::Input::manager.device_find(controller); + return device && device->is_button_triggered(button); + }); + lua_method(state, "IsButtonPressed", [](int button, int controller) { + auto device = KAGE::Input::manager.device_find(controller); + return device && device->is_button_pressed(button); + }); + lua_method(state, "GetButtonValue", [](int button, int controller) { + auto device = KAGE::Input::manager.device_find(controller); + return device ? device->button_value(button) : 0.0f; + }); + lua_method(state, "IsActionTriggered", [](ButtonAction action, int controller) { + return is_controller_action(controller, action, ACTION_TRIGGERED); + }); + lua_method(state, "IsActionPressed", [](ButtonAction action, int controller) { + return is_controller_action(controller, action, ACTION_PRESSED); + }); + lua_method(state, "GetActionValue", [](ButtonAction action, int controller) { + return is_controller_action(controller, action, ACTION_PRESSED) ? 1.0f : 0.0f; + }); + lua_class_end(state); +} + +// Registers the Options namespace, read-only for now: the original's setters clamp and apply each option. +static void options_register(lua_State* state) +{ + lua_namespace_begin(state, "Options"); + lua_property(state, "MusicVolume", [](LuaIgnored) { return g_manager->optionsConfig.musicVolume; }); + lua_property(state, "SFXVolume", [](LuaIgnored) { return g_manager->optionsConfig.sfxVolume; }); + lua_property(state, "MapOpacity", [](LuaIgnored) { return g_manager->optionsConfig.mapOpacity; }); + lua_property(state, "Fullscreen", [](LuaIgnored) { return g_manager->optionsConfig.isFullscreen; }); + lua_property(state, "Filter", [](LuaIgnored) { return g_manager->optionsConfig.isFilterEnabled; }); + lua_property(state, "Gamma", [](LuaIgnored) { return g_manager->optionsConfig.gamma; }); + lua_property(state, "DisplayPopups", [](LuaIgnored) { return g_manager->optionsConfig.popupsMode; }); + lua_property(state, "CameraStyle", [](LuaIgnored) { return g_manager->optionsConfig.cameraStyle; }); + lua_property(state, "ExtraHUDStyle", [](LuaIgnored) { return g_manager->optionsConfig.historyHudMode; }); + lua_property(state, "HUDOffset", [](LuaIgnored) { return g_manager->optionsConfig.hudOffset; }); + lua_property(state, "FoundHUD", [](LuaIgnored) { return g_manager->optionsConfig.isFoundHudEnabled; }); + lua_property(state, "RumbleEnabled", [](LuaIgnored) { return g_manager->optionsConfig.isRumbleEnabled; }); + lua_property(state, "ChargeBars", [](LuaIgnored) { return g_manager->optionsConfig.isChargeBarsEnabled; }); + lua_property(state, "BulletVisibility", + [](LuaIgnored) { return g_manager->optionsConfig.isBulletVisibilityEnabled; }); + lua_property(state, "VSync", [](LuaIgnored) { return g_manager->optionsConfig.isVsyncEnabled; }); + lua_property(state, "PauseOnFocusLost", + [](LuaIgnored) { return g_manager->optionsConfig.isPauseOnFocusLostEnabled; }); + lua_property(state, "MouseControl", [](LuaIgnored) { return g_manager->optionsConfig.isMouseControlEnabled; }); + lua_property(state, "AnnouncerVoiceMode", [](LuaIgnored) { return g_manager->optionsConfig.announcerVoiceMode; }); + lua_property(state, "MaxScale", [](LuaIgnored) { return g_manager->optionsConfig.maxScale; }); + lua_property(state, "MaxRenderScale", [](LuaIgnored) { return g_manager->optionsConfig.maxRenderScale; }); + lua_property(state, "ConsoleFont", [](LuaIgnored) { return g_manager->optionsConfig.consoleFont; }); + lua_property(state, "FadedConsoleDisplay", + [](LuaIgnored) { return g_manager->optionsConfig.isFadedConsoleDisplayEnabled; }); + lua_property(state, "SaveCommandHistory", + [](LuaIgnored) { return g_manager->optionsConfig.isSaveCommandHistoryEnabled; }); + lua_property(state, "UseBorderlessFullscreen", + [](LuaIgnored) { return !g_manager->optionsConfig.isExclusiveFullscreen; }); + lua_property(state, "DebugConsoleEnabled", + [](LuaIgnored) { return g_manager->optionsConfig.isDebugConsoleEnabled; }); + lua_property(state, "JacobEsauControls", [](LuaIgnored) { return g_manager->optionsConfig.jacobEsauControls; }); + lua_property(state, "Language", [](LuaIgnored) { return std::string(Manager::GetLanguage()); }); + lua_class_end(state); +} + +// (0067f070, 0086fc60) Registers the global functions: Random, RandomVector, Game_0 +// (main.lua names it Game), SFXManager, MusicManager, GetPtrHash, include, print and, in a normal state, require. +static void globals_register(lua_State* state) +{ + lua_pushglobaltable(state); + lua_pushglobaltable(state); + lua_method(state, "Random", []() { return Random(); }); + lua_method(state, "RandomVector", random_direction); + lua_method(state, "Game_0", []() { return g_game; }); + lua_method(state, "SFXManager", []() -> SFXManager& { return g_manager->sfxManager; }); + lua_method(state, "MusicManager", []() -> MusicManager& { return g_manager->musicManager; }); + for (auto [name, function] : + {std::pair{"GetPtrHash", pointer_hash_get}, {"include", module_include}, {"print", console_print}}) + { + lua_pushcfunction(state, function); + lua_table_set(state, -3, name); + } + if (lua_engine_get().mode == LUA_MODE_NORMAL) + { + lua_pushcfunction(state, module_require); + lua_table_set(state, -3, "require"); + } + lua_pop(state, 2); +} + +void lua_api_isaac_register(lua_State* state) +{ + globals_register(state); + isaac_register(state); + input_register(state); + options_register(state); +} diff --git a/src/lua_api_item_config.cpp b/src/lua_api_item_config.cpp new file mode 100644 index 0000000..3d62eee --- /dev/null +++ b/src/lua_api_item_config.cpp @@ -0,0 +1,131 @@ +#include "classes.h" +#include "item_config.h" +#include "lua_api.h" + +// Registers a list of configs Config hands out: its Size, and Get, nil past the end where the original reads on. +template +static void config_list_register(lua_State* state, const char* name, LuaClass luaClass) +{ + using List = std::vector>; + lua_class_begin(state, name, luaClass); + lua_property(state, "Size", [](List& list) { return (int)list.size(); }); + lua_method(state, "Get", + [](List& list, uint32_t index) { return index < list.size() ? list[index].get() : nullptr; }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); +} + +// Registers ItemConfig.Item, a collectible, trinket or null item, and ItemConfig.Costume. +static void item_register(lua_State* state) +{ + lua_class_begin(state, "Item", LUA_CLASS_ITEM_CONFIG_ITEM); + lua_method(state, "IsCollectible", [](ItemConfig_Item& item) { return item.IsCollectible(); }); + lua_method(state, "IsTrinket", [](ItemConfig_Item& item) { return item.IsTrinket(); }); + lua_method(state, "IsNull", [](ItemConfig_Item& item) { return item.IsNull(); }); + lua_method(state, "HasTags", [](ItemConfig_Item& item, uint64_t tags) { return item.HasTags(tags); }); + lua_method(state, "IsAvailable", [](ItemConfig_Item& item) { return item.IsAvailable(UNLOCK_CHECKED); }); + lua_field<&ItemConfig_Item::type>(state, "Type"); + lua_field<&ItemConfig_Item::id>(state, "ID"); + lua_field<&ItemConfig_Item::name>(state, "Name"); + lua_field<&ItemConfig_Item::desc>(state, "Description"); + lua_field<&ItemConfig_Item::gfxFilename>(state, "GfxFileName"); + lua_field<&ItemConfig_Item::achievementId>(state, "AchievementID"); + lua_field<&ItemConfig_Item::cacheFlags>(state, "CacheFlags"); + lua_field<&ItemConfig_Item::addMaxHearts>(state, "AddMaxHearts"); + lua_field<&ItemConfig_Item::addHearts>(state, "AddHearts"); + lua_field<&ItemConfig_Item::addSoulHearts>(state, "AddSoulHearts"); + lua_field<&ItemConfig_Item::addBlackHearts>(state, "AddBlackHearts"); + lua_field<&ItemConfig_Item::addBombs>(state, "AddBombs"); + lua_field<&ItemConfig_Item::addKeys>(state, "AddKeys"); + lua_field<&ItemConfig_Item::addCoins>(state, "AddCoins"); + lua_field<&ItemConfig_Item::maxCharges>(state, "MaxCharges"); + lua_field<&ItemConfig_Item::maxCooldown>(state, "MaxCooldown"); + lua_field<&ItemConfig_Item::isSpecial>(state, "Special"); + lua_field<&ItemConfig_Item::devilPrice>(state, "DevilPrice"); + lua_field<&ItemConfig_Item::initCharge>(state, "InitCharge"); + lua_field<&ItemConfig_Item::chargeType>(state, "ChargeType"); + lua_field<&ItemConfig_Item::shopPrice>(state, "ShopPrice"); + lua_field<&ItemConfig_Item::isPassiveCache>(state, "PassiveCache"); + lua_field<&ItemConfig_Item::isAddCostumeOnPickup>(state, "AddCostumeOnPickup"); + lua_field<&ItemConfig_Item::isHidden>(state, "Hidden"); + lua_field<&ItemConfig_Item::isPersistentEffect>(state, "PersistentEffect"); + lua_field<&ItemConfig_Item::isClearEffectsOnRemove>(state, "ClearEffectsOnRemove"); + lua_field<&ItemConfig_Item::tags>(state, "Tags"); + lua_field<&ItemConfig_Item::quality>(state, "Quality"); + lua_field<&ItemConfig_Item::craftingQuality>(state, "CraftingQuality"); + lua_property(state, "Costume", [](ItemConfig_Item& item) -> ItemConfig_Costume& { return item.costume; }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + + lua_class_begin(state, "Costume", LUA_CLASS_ITEM_CONFIG_COSTUME); + lua_field<&ItemConfig_Costume::id>(state, "ID"); + lua_field<&ItemConfig_Costume::anm2Path>(state, "Anm2Path"); + lua_field<&ItemConfig_Costume::priority>(state, "Priority"); + lua_field<&ItemConfig_Costume::isHasOverlay>(state, "HasOverlay"); + lua_field<&ItemConfig_Costume::isFlying>(state, "IsFlying"); + lua_field<&ItemConfig_Costume::isHasSkinAlt>(state, "HasSkinAlt"); + lua_field<&ItemConfig_Costume::skinColor>(state, "SkinColor"); + lua_field<&ItemConfig_Costume::isOverwriteColor>(state, "OverwriteColor"); + lua_class_end(state, LUA_SCOPE_NAMESPACE); +} + +// Registers ItemConfig.Card and ItemConfig.PillEffect, the pocket items pocketitems.xml describes. +static void pocket_items_register(lua_State* state) +{ + lua_class_begin(state, "Card", LUA_CLASS_ITEM_CONFIG_CARD); + lua_field<&ItemConfig_Card::id, ItemConfig_Card>(state, "ID"); + lua_field<&ItemConfig_Card::achievementId, ItemConfig_Card>(state, "AchievementID"); + lua_field<&ItemConfig_Card::name, ItemConfig_Card>(state, "Name"); + lua_field<&ItemConfig_Card::desc, ItemConfig_Card>(state, "Description"); + lua_field<&ItemConfig_Card::hudAnim>(state, "HudAnim"); + lua_field<&ItemConfig_Card::isGreedModeAllowed, ItemConfig_Card>(state, "GreedModeAllowed"); + lua_field<&ItemConfig_Card::pickupSubtype>(state, "PickupSubtype"); + lua_field<&ItemConfig_Card::cardType>(state, "CardType"); + lua_field<&ItemConfig_Card::announcerVoice, ItemConfig_Card>(state, "AnnouncerVoice"); + lua_field<&ItemConfig_Card::announcerDelay, ItemConfig_Card>(state, "AnnouncerDelay"); + lua_field<&ItemConfig_Card::mimicCharge, ItemConfig_Card>(state, "MimicCharge"); + lua_method(state, "IsCard", [](ItemConfig_Card& card) { return card.IsCard(); }); + lua_method(state, "IsRune", [](ItemConfig_Card& card) { return card.IsRune(); }); + lua_method(state, "IsAvailable", [](ItemConfig_Card& card) { return card.IsAvailable(); }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + + lua_class_begin(state, "PillEffect", LUA_CLASS_ITEM_CONFIG_PILL); + lua_field<&ItemConfig_Pill::id, ItemConfig_Pill>(state, "ID"); + lua_field<&ItemConfig_Pill::achievementId, ItemConfig_Pill>(state, "AchievementID"); + lua_field<&ItemConfig_Pill::name, ItemConfig_Pill>(state, "Name"); + lua_field<&ItemConfig_Pill::isGreedModeAllowed, ItemConfig_Pill>(state, "GreedModeAllowed"); + lua_field<&ItemConfig_Pill::announcerVoice, ItemConfig_Pill>(state, "AnnouncerVoice"); + lua_field<&ItemConfig_Pill::announcerVoiceSuper>(state, "AnnouncerVoiceSuper"); + lua_field<&ItemConfig_Pill::announcerDelay, ItemConfig_Pill>(state, "AnnouncerDelay"); + lua_field<&ItemConfig_Pill::mimicCharge, ItemConfig_Pill>(state, "MimicCharge"); + lua_field<&ItemConfig_Pill::effectClass>(state, "EffectClass"); + lua_field<&ItemConfig_Pill::effectSubClass>(state, "EffectSubClass"); + lua_method(state, "IsAvailable", [](ItemConfig_Pill& pill) { return pill.IsAvailable(); }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); +} + +// Registers the ItemConfig namespace: the config classes, their lists, and Config, which Isaac.GetItemConfig returns. +void lua_api_item_config_register(lua_State* state) +{ + lua_namespace_begin(state, "ItemConfig"); + item_register(state); + pocket_items_register(state); + config_list_register(state, "ItemConfigList", LUA_CLASS_ITEM_CONFIG_ITEM_LIST); + config_list_register(state, "CardConfigList", LUA_CLASS_ITEM_CONFIG_CARD_LIST); + config_list_register(state, "PillConfigList", LUA_CLASS_ITEM_CONFIG_PILL_LIST); + + lua_class_begin(state, "Config", LUA_CLASS_ITEM_CONFIG); + lua_method(state, "GetCollectible", [](ItemConfig& config, int id) { return config.GetCollectible(id); }); + lua_method(state, "GetTrinket", [](ItemConfig& config, uint32_t id) { return config.GetTrinket(id); }); + lua_method(state, "GetNullItem", [](ItemConfig& config, int id) { return config.GetNullItem(id); }); + lua_method(state, "GetCard", [](ItemConfig& config, int id) { return config.GetCard(id); }); + lua_method(state, "GetPillEffect", [](ItemConfig& config, int id) { return config.GetPillEffect(id); }); + lua_method(state, "GetCollectibles", [](ItemConfig& config) -> auto& { return config.collectibles; }); + lua_method(state, "GetTrinkets", [](ItemConfig& config) -> auto& { return config.trinkets; }); + lua_method(state, "GetNullItems", [](ItemConfig& config) -> auto& { return config.nullItems; }); + lua_method(state, "GetCards", [](ItemConfig& config) -> auto& { return config.cards; }); + lua_method(state, "GetPillEffects", [](ItemConfig& config) -> auto& { return config.pillEffects; }); + lua_static(state, "IsValidCollectible", [](int id) { return ItemConfig::IsValidCollectible(id); }); + lua_static(state, "ShouldAddCostumeOnPickup", + [](ItemConfig_Item* item) { return ItemConfig::ShouldAddCostumeOnPickup(item); }); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + lua_class_end(state); +} diff --git a/src/lua_api_rng.cpp b/src/lua_api_rng.cpp new file mode 100644 index 0000000..a4aa012 --- /dev/null +++ b/src/lua_api_rng.cpp @@ -0,0 +1,18 @@ +#include "classes.h" +#include "lua_api.h" +#include "seeds.h" + +constexpr RNG LUA_RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; + +// (008bbcf0) Registers Lua's RNG: a default seeded constructor and the game's RNG methods. +void lua_api_rng_register(lua_State* state) +{ + lua_class_begin(state, "RNG", LUA_CLASS_RNG); + lua_static(state, "__call", [](LuaIgnored) { return LUA_RNG_DEFAULT; }); + lua_method(state, "GetSeed", [](RNG& rng) { return rng._seed; }); + lua_method(state, "SetSeed", [](RNG& rng, uint32_t seed, uint32_t shiftIndex) { rng.SetSeed(seed, shiftIndex); }); + lua_method(state, "RandomInt", [](RNG& rng, uint32_t max) { return rng.RandomInt(max); }); + lua_method(state, "RandomFloat", [](RNG& rng) { return rng.RandomFloat(); }); + lua_method(state, "Next", [](RNG& rng) { return rng.Next(); }); + lua_class_end(state); +} diff --git a/src/lua_api_room.cpp b/src/lua_api_room.cpp new file mode 100644 index 0000000..56ba20f --- /dev/null +++ b/src/lua_api_room.cpp @@ -0,0 +1,289 @@ +#include "classes.h" +#include "entity_npc.h" +#include "game.h" +#include "grid_entity.h" +#include "grid_entity_door.h" +#include "level.h" +#include "lua_api.h" +#include "room.h" +#include "room_config.h" +#include "room_descriptor.h" +#include "room_grid.h" + +// Registers Lua's Level, which Game is: the floor's stage, curses, rooms and maps. +static void level_register(lua_State* state) +{ + lua_class_begin(state, "Level", LUA_CLASS_LEVEL); + lua_method(state, "GetStage", [](Level& level) { return level.stage; }); + lua_method(state, "GetStageType", [](Level& level) { return level.stageType; }); + lua_method(state, "GetAbsoluteStage", [](Level& level) { return level.GetAbsoluteStage(); }); + lua_method(state, "IsAltStage", [](Level& level) { return level.IsAltStage(); }); + lua_method(state, "IsAscent", [](Level& level) { return level.IsAscent(); }); + lua_method(state, "IsPreAscent", [](Level& level) { return level.IsPreAscent(); }); + lua_method(state, "IsNextStageAvailable", [](Level& level) { return level.IsNextStageAvailable(); }); + lua_method(state, "SetStage", [](Level& level, int stage, int stageType) { level.SetStage(stage, stageType); }); + lua_method(state, "SetNextStage", [](Level& level) { level.SetNextStage(); }); + lua_method(state, "GetName", [](Level& level) { return level.GetName(); }); + lua_method(state, "GetCurseName", [](Level& level) { return level.GetCurseName(); }); + lua_method(state, "ShowName", [](Level& level, bool isSticky) { level.ShowName(isSticky); }); + lua_method(state, "GetCurses", [](Level& level) { return level.GetCurses(); }); + lua_method(state, "AddCurse", + [](Level& level, uint32_t curses, bool isShowName) { level.AddCurse(curses, isShowName); }); + lua_method(state, "RemoveCurses", [](Level& level, uint32_t curses) { level.RemoveCurses(curses); }); + lua_static(state, "CanStageHaveCurseOfLabyrinth", + [](uint32_t stage) { return Level::CanStageHaveCurseOfLabyrinth(stage); }); + lua_method(state, "GetStateFlag", [](Level& level, int flag) { return level.GetStateFlag(flag); }); + lua_method(state, "SetStateFlag", [](Level& level, int flag, bool isSet) { level.SetStateFlag(flag, isSet); }); + + lua_method(state, "GetCurrentRoom", [](Level& level) { return level.room.get(); }); + lua_method(state, "GetCurrentRoomIndex", [](Level& level) { return level.currentRoomIdx; }); + lua_method(state, "GetPreviousRoomIndex", [](Level& level) { return level.lastRoomIdx; }); + lua_method(state, "GetStartingRoomIndex", [](Level& level) { return level.startingRoomIdx; }); + lua_method(state, "GetRoomCount", [](Level& level) { return level.nbRooms; }); + lua_method(state, "GetCurrentRoomDesc", [](Level& level) { return level.GetCurrentRoomDesc(); }); + lua_method(state, "GetLastRoomDesc", [](Level& level) { return level.GetLastRoomDesc(); }); + lua_method(state, "GetRoomByIdx", + [](Level& level, int index, int dimension) { return level.GetRoomByIdx(index, dimension); }); + lua_method(state, "QueryRoomTypeIndex", + [](Level& level, int roomType, bool isVisited, RNG& rng, bool isIgnoreGroup) { + return level.QueryRoomTypeIndex(roomType, isVisited, rng, isIgnoreGroup); + }); + lua_method(state, "GetRandomRoomIndex", [](Level& level, bool isErrorRoom, uint32_t seed) { + return level.GetRandomRoomIndex(isErrorRoom, seed); + }); + lua_method(state, "GetRooms", [](Level& level) { return LuaRoomList{level.roomList.data(), level.nbRooms}; }); + lua_method(state, "GetNonCompleteRoomIndex", [](Level& level) { return level.GetNonCompleteRoomIndex(); }); + lua_method(state, "ChangeRoom", [](Level& level, int index, int dimension) { level.ChangeRoom(index, dimension); }); + lua_method(state, "GetEnterPosition", [](Level& level) { return level.GetEnterPosition(); }); + lua_field<&Level::enterDoor>(state, "EnterDoor"); + lua_field<&Level::leaveDoor>(state, "LeaveDoor"); + lua_field<&Level::dungeonReturnRoomIndex>(state, "DungeonReturnRoomIndex"); + lua_field<&Level::dungeonReturnPosition>(state, "DungeonReturnPosition"); + lua_field<&Level::greedModeWave>(state, "GreedModeWave"); + lua_method(state, "CanOpenChallengeRoom", + [](Level& level, int index) { return level.CanOpenChallengeRoom(index); }); + lua_method(state, "MakeRedRoomDoor", + [](Level& level, int index, int slot) { return level.MakeRedRoomDoor(index, slot); }); + lua_method(state, "UncoverHiddenDoor", + [](Level& level, int index, int slot) { level.UncoverHiddenDoor(index, slot); }); + + lua_method(state, "UpdateVisibility", [](Level& level) { level.UpdateVisibility(); }); + lua_method(state, "ApplyMapEffect", [](Level& level) { level.ApplyMapEffect(); }); + lua_method(state, "ApplyBlueMapEffect", [](Level& level) { level.ApplyBlueMapEffect(); }); + lua_method(state, "ApplyCompassEffect", + [](Level& level, bool isPersistent) { level.ApplyCompassEffect(isPersistent); }); + lua_method(state, "RemoveCompassEffect", [](Level& level) { level.RemoveCompassEffect(); }); + lua_method(state, "ShowMap", [](Level& level) { level.ShowMap(); }); + lua_method(state, "GetCanSeeEverything", [](Level& level) { return level.isCanSeeEverything; }); + lua_method(state, "SetCanSeeEverything", [](Level& level, bool isOn) { level.isCanSeeEverything = isOn; }); + lua_method(state, "GetHeartPicked", [](Level& level) { return level.isHeartPicked; }); + lua_method(state, "SetHeartPicked", [](Level& level) { level.isHeartPicked = true; }); + lua_method(state, "HasBossChallenge", [](Level& level) { return level.isBossChallenge; }); + lua_method(state, "IsDevilRoomDisabled", [](Level& level) { return level.isDevilRoomDisabled; }); + lua_method(state, "DisableDevilRoom", [](Level& level) { level.isDevilRoomDisabled = true; }); + lua_method(state, "CanSpawnDevilRoom", [](Level& level) { return level.CanSpawnDevilRoom(); }); + lua_method(state, "InitializeDevilAngelRoom", [](Level& level, bool isForceAngel, bool isForceDevil) { + level.InitializeDevilAngelRoom(isForceAngel, isForceDevil); + }); + lua_method(state, "GetDevilAngelRoomRNG", [](Level& level) -> RNG& { return level.devilAngelRoomRNG; }); + lua_method(state, "GetDungeonPlacementSeed", [](Level& level) { return level.dungeonPlacementSeed; }); + lua_method(state, "GetAngelRoomChance", [](Level& level) { return level.angelRoomChance; }); + lua_method(state, "AddAngelRoomChance", [](Level& level, float chance) { level.angelRoomChance += chance; }); + lua_method(state, "GetPlanetariumChance", [](Level& level) { return level.GetPlanetariumChance(); }); + lua_method(state, "SetRedHeartDamage", [](Level& level) { level.SetRedHeartDamage(); }); + lua_method(state, "ForceHorsemanBoss", [](Level& level, uint32_t seed) { return level.ForceHorsemanBoss(seed); }); + lua_class_end(state); + + lua_class_begin(state, "RoomList", LUA_CLASS_ROOM_LIST); + lua_property(state, "Size", [](LuaRoomList& list) { return list.count; }); + lua_method(state, "__len", [](LuaRoomList& list) { return list.count; }); + lua_method(state, "Get", [](LuaRoomList& list, int index) { + return index >= 0 && index < list.count ? &list.rooms[index] : nullptr; + }); + lua_class_end(state); + + lua_namespace_begin(state, "RoomConfig"); + lua_class_begin(state, "Room", LUA_CLASS_ROOM_CONFIG_ROOM); + lua_field_get<&RoomConfig_Room::stageId>(state, "StageID"); + lua_field_get<&RoomConfig_Room::type>(state, "Type"); + lua_field_get<&RoomConfig_Room::variant>(state, "Variant"); + lua_field_get<&RoomConfig_Room::originalVariant>(state, "OriginalVariant"); + lua_field_get<&RoomConfig_Room::mode>(state, "Mode"); + lua_field_get<&RoomConfig_Room::subtype>(state, "Subtype"); + lua_field_get<&RoomConfig_Room::name>(state, "Name"); + lua_field_get<&RoomConfig_Room::difficulty>(state, "Difficulty"); + lua_field_get<&RoomConfig_Room::initialWeight>(state, "InitialWeight"); + lua_field_get<&RoomConfig_Room::weight>(state, "Weight"); + lua_field_get<&RoomConfig_Room::doors>(state, "Doors"); + lua_property(state, "SpawnCount", [](RoomConfig_Room& room) { return (int)room.spawns.size(); }); + lua_field_get<&RoomConfig_Room::width>(state, "Width"); + lua_field_get<&RoomConfig_Room::height>(state, "Height"); + lua_field_get<&RoomConfig_Room::shape>(state, "Shape"); + lua_class_end(state, LUA_SCOPE_NAMESPACE); + lua_class_end(state); + + lua_class_begin(state, "RoomDescriptor", LUA_CLASS_ROOM_DESCRIPTOR); + lua_field<&RoomDescriptor::data>(state, "Data"); + lua_field<&RoomDescriptor::overrideData>(state, "OverrideData"); + lua_field<&RoomDescriptor::gridIndex>(state, "GridIndex"); + lua_field<&RoomDescriptor::safeGridIndex>(state, "SafeGridIndex"); + lua_field<&RoomDescriptor::listIndex>(state, "ListIndex"); + lua_field<&RoomDescriptor::visitedCount>(state, "VisitedCount"); + lua_field<&RoomDescriptor::clearCount>(state, "ClearCount"); + lua_field<&RoomDescriptor::poopCount>(state, "PoopCount"); + lua_field<&RoomDescriptor::pitsCount>(state, "PitsCount"); + lua_field<&RoomDescriptor::displayFlags>(state, "DisplayFlags"); + lua_field<&RoomDescriptor::flags>(state, "Flags"); + lua_field<&RoomDescriptor::allowedDoors>(state, "AllowedDoors"); + lua_field<&RoomDescriptor::spawnSeed>(state, "SpawnSeed"); + lua_field<&RoomDescriptor::awardSeed>(state, "AwardSeed"); + lua_field<&RoomDescriptor::decorationSeed>(state, "DecorationSeed"); + lua_field<&RoomDescriptor::shopItemIdx>(state, "ShopItemIdx"); + lua_field<&RoomDescriptor::shopItemDiscountIdx>(state, "ShopItemDiscountIdx"); + lua_field<&RoomDescriptor::deliriumDistance>(state, "DeliriumDistance"); + lua_property( + state, "Clear", [](RoomDescriptor& room) { return (bool)(room.flags & ROOM_DESCRIPTOR_FLAG_CLEAR); }, + [](RoomDescriptor& room, bool isClear) { + room.flags = isClear ? room.flags | ROOM_DESCRIPTOR_FLAG_CLEAR : room.flags & ~ROOM_DESCRIPTOR_FLAG_CLEAR; + }); + lua_class_end(state); +} + +// Registers Lua's GridEntity, the base of rocks, pits, doors and the other tiles of a room. +static void grid_entity_register(lua_State* state) +{ + lua_class_begin(state, "GridEntity", LUA_CLASS_GRID_ENTITY); + lua_method(state, "GetType", [](GridEntity& grid) { return grid.type; }); + lua_method(state, "GetVariant", [](GridEntity& grid) { return grid.variant; }); + lua_method(state, "GetGridIndex", [](GridEntity& grid) { return grid.gridIndex; }); + lua_method(state, "GetSprite", [](GridEntity& grid) -> ANM2& { return grid.sprite; }); + lua_method(state, "GetRNG", [](GridEntity& grid) -> RNG& { return grid.rng; }); + lua_method(state, "Update", [](GridEntity& grid) { grid.Update(); }); + lua_method(state, "Render", [](GridEntity& grid, Vector offset) { grid.Render(offset); }); + lua_method(state, "PostInit", [](GridEntity& grid) { grid.PostInit(); }); + lua_method(state, "Hurt", [](GridEntity& grid, int damage) { return grid.Hurt(damage, EntityRef()); }); + lua_method(state, "HurtWithSource", + [](GridEntity& grid, int damage, const EntityRef& source) { return grid.Hurt(damage, source); }); + lua_method(state, "Destroy", + [](GridEntity& grid, bool isImmediate) { return grid.Destroy(isImmediate, EntityRef()); }); + lua_method(state, "DestroyWithSource", [](GridEntity& grid, bool isImmediate, const EntityRef& source) { + return grid.Destroy(isImmediate, source); + }); + lua_property(state, "Position", [](GridEntity& grid) { return grid.Position(); }); + lua_field<&GridEntity::state>(state, "State"); + lua_field<&GridEntity::varData>(state, "VarData"); + lua_field<&GridEntity::collisionClass>(state, "CollisionClass"); + lua_class_end(state); +} + +// Registers Lua's Room: the current room's grid, entities, doors, clear state and the doors it may spawn. +static void room_register(lua_State* state) +{ + lua_class_begin(state, "Room", LUA_CLASS_ROOM); + lua_method(state, "GetType", [](Room& room) { return room.roomType; }); + lua_method(state, "GetBackdropType", [](Room& room) { return room.backdropType; }); + lua_method(state, "GetRoomShape", [](Room& room) { return room.GetRoomShape(); }); + lua_method(state, "GetRoomConfigStage", [](Room& room) { return room.GetRoomConfigStage(); }); + lua_method(state, "IsInitialized", [](Room& room) { return room.isInitialized; }); + lua_method(state, "IsFirstVisit", [](Room& room) { return room.isFirstVisit; }); + lua_method(state, "IsClear", [](Room& room) { return room.IsClear(); }); + lua_method(state, "SetClear", [](Room& room, bool isClear) { room.SetClear(isClear); }); + lua_method(state, "IsSacrificeDone", [](Room& room) { return room.IsSacrificeDone(); }); + lua_method(state, "SetSacrificeDone", [](Room& room, bool isDone) { room.SetSacrificeDone(isDone); }); + lua_method(state, "IsAmbushDone", [](Room& room) { return room.IsAmbushDone(); }); + lua_method(state, "SetAmbushDone", [](Room& room, bool isDone) { room.SetAmbushDone(isDone); }); + lua_method(state, "IsFirstEnemyDead", [](Room& room) { return room.isFirstEnemyDead; }); + lua_method(state, "GetFrameCount", [](Room& room) { return room.GetFrameCount(); }); + lua_method(state, "GetAliveEnemiesCount", [](Room& room) { return room.GetAliveEnemiesCount(); }); + lua_method(state, "GetAliveBossesCount", [](Room& room) { return room.GetAliveBossesCount(); }); + lua_method(state, "GetBossID", [](Room& room) { return room.bossId; }); + lua_method(state, "GetSecondBossID", [](Room& room) { return room.secondBossId; }); + lua_method(state, "GetShopLevel", [](Room& room) { return room.shopLevel; }); + lua_method(state, "GetDecorationSeed", [](Room& room) { return room.GetDecorationSeed(); }); + lua_method(state, "GetSpawnSeed", [](Room& room) { return room.GetSpawnSeed(); }); + lua_method(state, "GetAwardSeed", [](Room& room) { return room.GetAwardSeed(); }); + lua_method(state, "GetDeliriumDistance", [](Room& room) { return room.GetDeliriumDistance(); }); + lua_method(state, "GetDevilRoomChance", [](Room& room) { return room.GetDevilRoomChance(); }); + lua_method(state, "GetLightingAlpha", [](Room& room) { return room.GetLightingAlpha(); }); + lua_method(state, "GetBrokenWatchState", [](Room& room) { return room.GetBrokenWatchState(); }); + lua_method(state, "SetBrokenWatchState", + [](Room& room, BrokenWatchState watchState) { room.SetBrokenWatchState(watchState); }); + lua_method(state, "HasSlowDown", [](Room& room) { return room.HasSlowDown(); }); + lua_method(state, "SetSlowDown", [](Room& room, int duration) { room.SetSlowDown(duration); }); + lua_method(state, "HasWater", [](Room& room) { return room.HasWater(); }); + lua_method(state, "HasWaterPits", [](Room& room) { return room.HasWaterPits(); }); + lua_method(state, "HasLava", [](Room& room) { return room.HasLava(); }); + lua_method(state, "HasCurseMist", [](Room& room) { return room.HasCurseMist(); }); + lua_method(state, "IsMirrorWorld", [](Room&) { return Room::IsMirrorWorld(); }); + lua_method(state, "IsCurrentRoomLastBoss", [](Room&) { return Room::IsCurrentRoomLastBoss(); }); + lua_method(state, "IsLShapedRoom", [](Room& room) { return room.IsLShapedRoom(); }); + lua_method(state, "TurnGold", [](Room& room) { room.TurnGold(); }); + lua_method(state, "PlayMusic", [](Room& room) { room.PlayMusic(); }); + + lua_method(state, "GetTopLeftPos", [](Room& room) { return room.topLeftPos; }); + lua_method(state, "GetBottomRightPos", [](Room& room) { return room.bottomRightPos; }); + lua_method(state, "GetCenterPos", [](Room&) { return Room::GetCenterPos(); }); + lua_method(state, "GetRenderScrollOffset", [](Room& room) -> Vector& { return room.renderScrollOffset; }); + lua_method(state, "GetRenderSurfaceTopLeft", [](Room& room) -> Vector& { return room.renderSurfaceTopLeft; }); + lua_method(state, "GetWaterCurrent", [](Room& room) { return room.waterCurrent; }); + lua_method(state, "GetRandomPosition", [](Room& room, float margin) { return room.GetRandomPosition(margin); }); + lua_method(state, "GetRandomTileIndex", [](Room& room, uint32_t seed) { return room.GetRandomTileIndex(seed); }); + lua_method(state, "IsPositionInRoom", + [](Room& room, Vector position, float margin) { return room.IsPositionInRoom(position, margin); }); + lua_method(state, "GetClampedPosition", + [](Room& room, Vector position, float margin) { return room.GetClampedPosition(position, margin); }); + lua_method(state, "FindFreePickupSpawnPosition", [](Room&, Vector position, float step, bool isAvoidActive, + bool isAllowPits) { + return room_free_pickup_position_find( + {.position = position, .step = step, .isAvoidActiveEntities = isAvoidActive, .isAllowPits = isAllowPits}); + }); + lua_method(state, "CheckLine", [](Room&, Vector start, Vector end, int mode, int threshold) { + return room_check_line(start, end, mode, threshold); + }); + + lua_method(state, "GetGridWidth", [](Room& room) { return room.gridWidth; }); + lua_method(state, "GetGridHeight", [](Room& room) { return room.gridHeight; }); + lua_method(state, "GetGridSize", [](Room& room) { return room.GetGridSize(); }); + lua_method(state, "GetGridIndex", [](Room& room, Vector position) { return room.GetGridIndex(position); }); + lua_method(state, "GetGridPosition", [](Room& room, int index) { return room.GetGridPosition(index); }); + lua_method(state, "GetGridEntity", [](Room& room, uint32_t index) { return room.GetGridEntity(index); }); + lua_method(state, "GetGridEntityFromPos", [](Room&, Vector position) { return room_grid_entity_at(position); }); + lua_method(state, "GetGridCollision", [](Room& room, int index) { return room.GetGridCollision(index); }); + lua_method(state, "GetGridCollisionAtPos", [](Room&, Vector position) { return room_grid_collision_at(position); }); + lua_method(state, "GetGridPath", [](Room& room, int index) { return room.GetGridPath(index); }); + lua_method(state, "SetGridPath", [](Room& room, int index, int value) { return room.SetGridPath(index, value); }); + lua_method(state, "SpawnGridEntity", + [](Room& room, int index, GridEntityType type, int variant, uint32_t seed, int varData) { + return room.SpawnGridEntity(index, type, variant, seed, varData); + }); + lua_method(state, "GetDoor", [](Room& room, int slot) -> GridEntity* { return room.GetDoor(slot); }); + lua_method(state, "IsDoorSlotAllowed", [](Room& room, int slot) { return room.IsDoorSlotAllowed(slot); }); + lua_method(state, "RemoveDoor", [](Room& room, int slot) { room.RemoveDoor(slot); }); + lua_method(state, "TrySpawnDevilRoomDoor", [](Room& room, bool isAnimated, bool isForced) { + return room.TrySpawnDevilRoomDoor(isAnimated, isForced); + }); + lua_method(state, "TrySpawnBossRushDoor", [](Room& room, bool isIgnoreTime, bool isForced) { + return room.TrySpawnBossRushDoor(isIgnoreTime, isForced); + }); + lua_method(state, "TrySpawnMegaSatanRoomDoor", + [](Room& room, bool isForced) { return room.TrySpawnMegaSatanRoomDoor(isForced); }); + lua_method(state, "TrySpawnBlueWombDoor", [](Room& room, bool isFirstTime, bool isIgnoreTime, bool isForced) { + return room.TrySpawnBlueWombDoor(isFirstTime, isIgnoreTime, isForced); + }); + lua_method(state, "TrySpawnTheVoidDoor", + [](Room& room, bool isForced) { return room.TrySpawnTheVoidDoor(isForced); }); + lua_method(state, "TrySpawnSecretShop", + [](Room& room, bool isForced) { return room.TrySpawnSecretShop(isForced); }); + lua_method(state, "TrySpawnSecretExit", [](Room& room, bool isAnimated, bool isForced) { + return room.TrySpawnSecretExit(isAnimated, isForced); + }); + lua_method(state, "TrySpawnSpecialQuestDoor", [](Room& room) { return room.TrySpawnSpecialQuestDoor(); }); + lua_class_end(state); +} + +void lua_api_room_register(lua_State* state) +{ + level_register(state); + grid_entity_register(state); + room_register(state); +} diff --git a/src/lua_api_sprite.cpp b/src/lua_api_sprite.cpp new file mode 100644 index 0000000..ffa6210 --- /dev/null +++ b/src/lua_api_sprite.cpp @@ -0,0 +1,144 @@ +#include "classes.h" +#include "anm2.h" +#include "font.h" +#include "lua_api.h" + +// Registers Lua's Sprite, the game's ANM2: loading, playing and rendering an animation and its overlay, and its +// offset, scale, rotation, color, flips and speed. Sprites scripts construct are destroyed with their userdata. +static void sprite_register(lua_State* state) +{ + lua_class_begin(state, "Sprite", LUA_CLASS_SPRITE); + lua_static(state, "__call", [](LuaIgnored) { return ANM2(); }); + lua_gc_set(state); + + lua_method(state, "Load", [](ANM2& sprite, std::string_view path, bool isLoadGraphics) { + sprite.Load(path, isLoadGraphics ? GRAPHICS_LOAD : GRAPHICS_DEFER); + }); + lua_method(state, "Reload", [](ANM2& sprite) { sprite.Reload(); }); + lua_method(state, "LoadGraphics", [](ANM2& sprite) { sprite.LoadGraphics(); }); + lua_method(state, "ReplaceSpritesheet", [](ANM2& sprite, int layerId, std::string_view path) { + sprite.ReplaceSpritesheet(layerId, path); + }); + lua_method(state, "IsLoaded", [](ANM2& sprite) { return sprite.isLoaded; }); + lua_method(state, "GetFilename", [](ANM2& sprite) -> const std::string& { return sprite.filename; }); + lua_method(state, "GetLayerCount", [](ANM2& sprite) { return (int)sprite.layerStates.size(); }); + lua_method(state, "Reset", [](ANM2& sprite) { sprite.Reset(); }); + lua_method(state, "Update", [](ANM2& sprite) { sprite.Update(); }); + lua_method(state, "Render", [](ANM2& sprite, Vector position, Vector topLeft, Vector bottomRight) { + sprite.Render({position, topLeft, bottomRight}); + }); + lua_method(state, "RenderLayer", + [](ANM2& sprite, int layerId, Vector position, Vector topLeft, Vector bottomRight) { + sprite.RenderLayer(layerId, {position, topLeft, bottomRight}); + }); + + lua_method(state, "Play", [](ANM2& sprite, std::string_view name, bool isForced) { + sprite.Play(name, isForced ? PLAY_FORCED : PLAY_UNFORCED); + }); + lua_method(state, "PlayRandom", [](ANM2& sprite, uint32_t seed) { sprite.PlayRandom(seed); }); + lua_method(state, "SetAnimation", [](ANM2& sprite, std::string_view name, bool isReset) { + return sprite.SetAnimation(name, isReset ? SWITCH_RESET : SWITCH_KEEP_FRAME); + }); + lua_method(state, "SetFrame", [](ANM2& sprite, std::string_view name, int frame) { sprite.SetFrame(name, frame); }); + lua_method(state, "SetFrame_1", [](ANM2& sprite, float frame) { sprite.SetFrame(frame); }); + lua_method(state, "SetLastFrame", [](ANM2& sprite) { sprite.SetLastFrame(); }); + lua_method(state, "SetLayerFrame", + [](ANM2& sprite, int layerId, int frame) { sprite.SetLayerFrame(layerId, frame); }); + lua_method(state, "GetFrame", [](ANM2& sprite) { return sprite.GetFrame(); }); + lua_method(state, "Stop", [](ANM2& sprite) { sprite.Stop(); }); + lua_method(state, "IsPlaying", [](ANM2& sprite, std::string_view name) { return sprite.IsPlaying(name); }); + lua_method(state, "IsFinished", [](ANM2& sprite, std::string_view name) { return sprite.IsFinished(name); }); + lua_method(state, "IsEventTriggered", + [](ANM2& sprite, std::string_view name) { return sprite.IsEventTriggered(name); }); + lua_method(state, "WasEventTriggered", + [](ANM2& sprite, std::string_view name) { return sprite.WasEventTriggered(name); }); + lua_method(state, "GetAnimation", [](ANM2& sprite) -> const std::string& { return sprite.GetAnimation(); }); + lua_method(state, "GetDefaultAnimation", + [](ANM2& sprite) -> const std::string& { return sprite.GetDefaultAnimationName(); }); + lua_method(state, "GetDefaultAnimationName", + [](ANM2& sprite) -> const std::string& { return sprite.GetDefaultAnimationName(); }); + + lua_method(state, "PlayOverlay", [](ANM2& sprite, std::string_view name, bool isForced) { + sprite.PlayOverlay(name, isForced ? PLAY_FORCED : PLAY_UNFORCED); + }); + lua_method(state, "SetOverlayAnimation", [](ANM2& sprite, std::string_view name, bool isReset) { + return sprite.SetOverlayAnimation(name, isReset ? SWITCH_RESET : SWITCH_KEEP_FRAME); + }); + lua_method(state, "SetOverlayFrame", + [](ANM2& sprite, std::string_view name, int frame) { sprite.SetOverlayFrame(name, frame); }); + lua_method(state, "SetOverlayRenderPriority", + [](ANM2& sprite, bool isFirst) { sprite.isOverlayRenderFirst = isFirst; }); + lua_method(state, "GetOverlayFrame", [](ANM2& sprite) { return sprite.GetOverlayFrame(); }); + lua_method(state, "RemoveOverlay", [](ANM2& sprite) { sprite.RemoveOverlay(); }); + lua_method(state, "IsOverlayPlaying", + [](ANM2& sprite, std::string_view name) { return sprite.IsOverlayPlaying(name); }); + lua_method(state, "IsOverlayFinished", + [](ANM2& sprite, std::string_view name) { return sprite.IsOverlayFinished(name); }); + lua_method(state, "GetOverlayAnimation", + [](ANM2& sprite) -> const std::string& { return sprite.GetOverlayAnimation(); }); + + lua_field<&ANM2::offset, ANM2>(state, "Offset"); + lua_field<&ANM2::scale, ANM2>(state, "Scale"); + lua_field<&ANM2::rotation, ANM2>(state, "Rotation"); + lua_field<&ANM2::color, ANM2>(state, "Color"); + lua_field<&ANM2::isFlipX, ANM2>(state, "FlipX"); + lua_field<&ANM2::isFlipY, ANM2>(state, "FlipY"); + lua_field<&ANM2::playbackSpeed, ANM2>(state, "PlaybackSpeed"); + lua_class_end(state); +} + +// Registers Lua's Font, a bitmap font scripts load and draw text with, and FontRenderSettings, how DrawString lays +// text out. +static void font_register(lua_State* state) +{ + lua_class_begin(state, "FontRenderSettings", LUA_CLASS_FONT_SETTINGS); + lua_static(state, "__call", [](LuaIgnored) { return FontSettings(); }); + lua_method(state, "SetAlignment", + [](FontSettings& settings, DrawStringAlignment alignment) { settings.alignment = alignment; }); + lua_method(state, "GetAlignment", [](FontSettings& settings) { return settings.alignment; }); + lua_method(state, "SetMaxCharacters", + [](FontSettings& settings, int16_t count) { settings.maxCharacters = count; }); + lua_method(state, "GetMaxCharacters", [](FontSettings& settings) { return settings.maxCharacters; }); + lua_method(state, "EnableAutoWrap", [](FontSettings& settings, bool isOn) { + settings.wrapMode = isOn ? FONT_WRAP_WORDS : FONT_WRAP_NONE; + }); + lua_method(state, "IsAutoWrapEnabled", [](FontSettings& settings) { return settings.wrapMode == FONT_WRAP_WORDS; }); + lua_method(state, "EnableTruncation", [](FontSettings& settings, bool isOn) { + settings.wrapMode = isOn ? FONT_WRAP_TRUNCATE : FONT_WRAP_NONE; + }); + lua_method(state, "IsTruncationEnabled", + [](FontSettings& settings) { return settings.wrapMode == FONT_WRAP_TRUNCATE; }); + lua_method(state, "SetMaxLineWidth", [](FontSettings& settings, uint16_t width) { settings.maxLineWidth = width; }); + lua_method(state, "GetMaxLineWidth", [](FontSettings& settings) { return settings.maxLineWidth; }); + lua_method(state, "SetLineHeightModifier", + [](FontSettings& settings, float modifier) { settings.lineHeightModifier = modifier; }); + lua_method(state, "GetLineHeightModifier", [](FontSettings& settings) { return settings.lineHeightModifier; }); + lua_method(state, "SetMissingCharacterOverride", + [](FontSettings& settings, int character) { settings.missingCharacterOverride = character; }); + lua_class_end(state); + + lua_class_begin(state, "Font", LUA_CLASS_FONT); + lua_static(state, "__call", [](LuaIgnored) { return Font(); }); + lua_gc_set(state); + lua_method(state, "Load", [](Font& font, std::string_view path) { return font.Load(path); }); + lua_method(state, "Unload", [](Font& font) { font.Unload(); }); + lua_method(state, "IsLoaded", [](Font& font) { return font.isLoaded; }); + lua_method(state, "GetCharacterWidth", + [](Font& font, uint32_t character) { return font.GetCharacterWidth(character); }); + lua_method(state, "GetStringWidth", [](Font& font, std::string_view text) { return font.GetStringWidth(text); }); + lua_method(state, "GetLineHeight", [](Font& font) { return font.GetLineHeight(); }); + lua_method(state, "GetBaselineHeight", [](Font& font) { return font.GetBaselineHeight(); }); + lua_method(state, "SetMissingCharacter", + [](Font& font, uint32_t character) { font.SetMissingCharacter(character); }); + lua_method(state, "DrawString", [](Font& font, std::string_view text, float x, float y, float scaleX, float scaleY, + KColor color, FontSettings& settings) { + font.DrawString(text, vector_make(x, y), vector_make(scaleX, scaleY), color, settings); + }); + lua_class_end(state); +} + +void lua_api_sprite_register(lua_State* state) +{ + sprite_register(state); + font_register(state); +} diff --git a/src/lua_api_vector.cpp b/src/lua_api_vector.cpp new file mode 100644 index 0000000..67aa2c5 --- /dev/null +++ b/src/lua_api_vector.cpp @@ -0,0 +1,69 @@ +#include "classes.h" +#include "lua_api.h" +#include "npc_ai.h" + +// The vector with each axis clamped between the corners. +static Vector vector_clamped(const Vector& vector, float minX, float minY, float maxX, float maxY) +{ + return vector_make(std::min(std::max(vector.x, minX), maxX), std::min(std::max(vector.y, minY), maxY)); +} + +// The vector turned by angle degrees. +static Vector vector_rotated(const Vector& vector, float angle) +{ + float cosine = std::cos(angle * DEGREES_TO_RADIANS); + float sine = std::sin(angle * DEGREES_TO_RADIANS); + return vector_make(vector.x * cosine - vector.y * sine, vector.y * cosine + vector.x * sine); +} + +// (008bb260, 0085e630) Registers Lua's Vector: its constructor, X and Y, the math methods and the arithmetic +// metamethods. The methods are those of the game's Vector, Lerp changing the vector and returning it. +void lua_api_vector_register(lua_State* state) +{ + lua_class_begin(state, "Vector", LUA_CLASS_VECTOR); + lua_static(state, "__call", [](LuaIgnored, float x, float y) { return vector_make(x, y); }); + lua_static(state, "FromAngle", vector_from_angle); + lua_field<&Vector::x>(state, "X"); + lua_field<&Vector::y>(state, "Y"); + + lua_method(state, "Normalize", [](Vector& vector) { vector = vector_normalized(vector); }); + lua_method(state, "Normalized", [](Vector& vector) { return vector_normalized(vector); }); + lua_method(state, "Dot", [](Vector& vector, const Vector& other) { return vector_dot(vector, other); }); + lua_method(state, "Cross", + [](Vector& vector, const Vector& other) { return other.y * vector.x - vector.y * other.x; }); + lua_method(state, "Lerp", [](Vector& vector, const Vector& target, float t, bool isClamped) -> Vector& { + if (isClamped) t = std::min(std::max(t, 0.0f), 1.0f); + vector = vector_add(vector_scale(vector_sub(target, vector), t), vector); + return vector; + }); + lua_method(state, "Distance", + [](Vector& vector, const Vector& other) { return vector_length(vector_sub(vector, other)); }); + lua_method(state, "DistanceSquared", + [](Vector& vector, const Vector& other) { return vector_length_squared(vector_sub(vector, other)); }); + lua_method(state, "Rotated", [](Vector& vector, float angle) { return vector_rotated(vector, angle); }); + lua_method(state, "GetAngleDegrees", [](Vector& vector) { return vector_angle(vector); }); + lua_method(state, "Resize", [](Vector& vector, float length) { vector = vector_resized(vector, length); }); + lua_method(state, "Resized", [](Vector& vector, float length) { return vector_resized(vector, length); }); + lua_method(state, "Clamp", [](Vector& vector, float minX, float minY, float maxX, float maxY) { + vector = vector_clamped(vector, minX, minY, maxX, maxY); + }); + lua_method(state, "Clamped", [](Vector& vector, float minX, float minY, float maxX, float maxY) { + return vector_clamped(vector, minX, minY, maxX, maxY); + }); + lua_method(state, "Length", [](Vector& vector) { return vector_length(vector); }); + lua_method(state, "LengthSquared", [](Vector& vector) { return vector_length_squared(vector); }); + + lua_method(state, "__add", [](Vector& a, const Vector& b) { return vector_add(a, b); }); + lua_method(state, "__sub", [](Vector& a, const Vector& b) { return vector_sub(a, b); }); + lua_method(state, "__mul", [](Vector& vector, float scale) { return vector_scale(vector, scale); }); + lua_method(state, "__div", [](Vector& vector, float divisor) { + return vector_make(vector.x / divisor, vector.y / divisor); + }); + lua_method(state, "__unm", [](Vector& vector) { return vector_make(-vector.x, -vector.y); }); + lua_method(state, "__tostring", [](Vector& vector) { + char text[64]; + std::snprintf(text, sizeof(text), "%g %g", vector.x, vector.y); + return std::string(text); + }); + lua_class_end(state); +} diff --git a/src/lua_callbacks.cpp b/src/lua_callbacks.cpp index 5fd7e96..d3691cd 100644 --- a/src/lua_callbacks.cpp +++ b/src/lua_callbacks.cpp @@ -4,6 +4,7 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_knife.h" +#include "entity_laser.h" #include "entity_npc.h" #include "entity_pickup.h" #include "entity_player.h" @@ -11,24 +12,11 @@ #include "entity_tear.h" #include "game.h" #include "log.h" -#include -#include - -extern "C" -{ -#include "lua.h" -} +#include "lua_api.h" constexpr int CALLBACK_PARAM_NONE = -1; constexpr int PILL_EFFECT_UNCHANGED = -1; -// A game object a callback hands to Lua by pointer, and the class whose metatable it gets. -struct LuaObject -{ - void* object; - LuaClass luaClass; -}; - // One run of a callback: the name its errors log, its id, and the parameter mods filter it by. struct CallbackRun { @@ -43,52 +31,6 @@ void lua_callback_check(LuaCallback callback, const char* name) if (lua_engine_get().enabledCallbacks[callback]) reconstruction_missing(name); } -// Pushes a callback argument: integers and booleans as themselves. -static void value_push(lua_State* state, int value) -{ - lua_pushinteger(state, value); -} - -static void value_push(lua_State* state, unsigned int value) -{ - lua_pushinteger(state, value); -} - -static void value_push(lua_State* state, bool value) -{ - lua_pushboolean(state, value); -} - -// Pushes an object as a userdata holding its pointer, with its class's metatable, or nil for none. -static void value_push(lua_State* state, LuaObject value) -{ - if (!value.object) return lua_pushnil(state); - *(void**)lua_newuserdata(state, sizeof(void*)) = value.object; - lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(value.luaClass)); - lua_setmetatable(state, -2); -} - -// Pushes a copy Lua owns, as LuaBridge's UserdataValue: the copy's pointer first, as an object's, then the copy. -template -static void copy_push(lua_State* state, const T& value, LuaClass luaClass) -{ - static_assert(std::is_trivially_destructible_v); - void** block = (void**)lua_newuserdata(state, sizeof(void*) + sizeof(T)); - *block = new (block + 1) T(value); - lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(luaClass)); - lua_setmetatable(state, -2); -} - -static void value_push(lua_State* state, const RNG& value) -{ - copy_push(state, value, LUA_CLASS_RNG); -} - -static void value_push(lua_State* state, const Vector& value) -{ - copy_push(state, value, LUA_CLASS_VECTOR); -} - // Calls _RunCallback with a callback's id, its filter parameter and its arguments when a mod added a function for it, // leaving its one result on the stack. Whether it ran, false without a function or on an error, which is logged. // The callers, result readers and error throws the original instantiates per callback are this and its readers @@ -109,9 +51,9 @@ static bool callback_run(LuaEngine& engine, CallbackRun run, Args... args) lua_State* state = engine.state; lua_rawgeti(state, LUA_REGISTRYINDEX, engine.runCallbackRef); - value_push(state, (int)run.id); - value_push(state, run.param); - (value_push(state, args), ...); + lua_push(state, (int)run.id); + lua_push(state, run.param); + (lua_push(state, args), ...); if (lua_pcall(state, sizeof...(Args) + 2, 1, 0) == LUA_OK) return true; lua_error_log(state, run.name); @@ -138,10 +80,22 @@ static int callback_integer_run(LuaEngine& engine, CallbackRun run, int fallback return isInteger ? (int)result : fallback; } -// Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing. -static LuaResult collision_run(LuaEngine& engine, CallbackRun run, LuaObject entity, Entity* collider, bool isLow) +// Runs a callback whose result, when not nil, is a boolean that replaces fallback. +template +static bool callback_boolean_run(LuaEngine& engine, CallbackRun run, bool fallback, Args... args) { - if (!callback_run(engine, run, entity, LuaObject{collider, LUA_CLASS_ENTITY}, isLow)) return LUA_RESULT_NIL; + if (!callback_run(engine, run, args...)) return fallback; + + bool result = lua_isnil(engine.state, -1) ? fallback : lua_toboolean(engine.state, -1); + lua_pop(engine.state, 1); + return result; +} + +// Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing. +template +static LuaResult collision_run(LuaEngine& engine, CallbackRun run, T* entity, Entity* collider, bool isLow) +{ + if (!callback_run(engine, run, entity, collider, isLow)) return LUA_RESULT_NIL; LuaResult result = lua_isnil(engine.state, -1) ? LUA_RESULT_NIL : lua_toboolean(engine.state, -1) ? LUA_RESULT_TRUE @@ -183,62 +137,62 @@ static void elements_pop(lua_State* state, T&... values) LuaResult LuaEngine::PreBombCollision(Entity_Bomb* bomb, Entity* collider, bool isLow) { CallbackRun run = {"PreBombCollision", MC_PRE_BOMB_COLLISION, (int)bomb->variant}; - return collision_run(*this, run, {bomb, LUA_CLASS_BOMB}, collider, isLow); + return collision_run(*this, run, bomb, collider, isLow); } // 008610d0 Runs MC_PRE_FAMILIAR_COLLISION, filtered by the familiar's variant. LuaResult LuaEngine::PreFamiliarCollision(Entity_Familiar* familiar, Entity* collider, bool isLow) { CallbackRun run = {"PreFamiliarCollision", MC_PRE_FAMILIAR_COLLISION, (int)familiar->variant}; - return collision_run(*this, run, {familiar, LUA_CLASS_FAMILIAR}, collider, isLow); + return collision_run(*this, run, familiar, collider, isLow); } // 00861c40 Runs MC_PRE_KNIFE_COLLISION, filtered by the knife's subtype. LuaResult LuaEngine::PreKnifeCollision(Entity_Knife* knife, Entity* collider, bool isLow) { CallbackRun run = {"PreKnifeCollision", MC_PRE_KNIFE_COLLISION, (int)knife->subtype}; - return collision_run(*this, run, {knife, LUA_CLASS_KNIFE}, collider, isLow); + return collision_run(*this, run, knife, collider, isLow); } // 00860d70 Runs MC_PRE_NPC_COLLISION, filtered by the NPC's type. LuaResult LuaEngine::PreNPCCollision(Entity_NPC* npc, Entity* collider, bool isLow) { CallbackRun run = {"PreNPCCollision", MC_PRE_NPC_COLLISION, (int)npc->type}; - return collision_run(*this, run, {npc, LUA_CLASS_NPC}, collider, isLow); + return collision_run(*this, run, npc, collider, isLow); } // 008631b0 Runs MC_PRE_PICKUP_COLLISION, filtered by the pickup's variant. LuaResult LuaEngine::PrePickupCollision(Entity_Pickup* pickup, Entity* collider, bool isLow) { CallbackRun run = {"PrePickupCollision", MC_PRE_PICKUP_COLLISION, (int)pickup->variant}; - return collision_run(*this, run, {pickup, LUA_CLASS_PICKUP}, collider, isLow); + return collision_run(*this, run, pickup, collider, isLow); } // 00864300 Runs MC_PRE_PLAYER_COLLISION, filtered by the player's variant. LuaResult LuaEngine::PrePlayerCollide(Entity_Player* player, Entity* collider, bool isLow) { CallbackRun run = {"PrePlayerCollision", MC_PRE_PLAYER_COLLISION, (int)player->variant}; - return collision_run(*this, run, {player, LUA_CLASS_PLAYER}, collider, isLow); + return collision_run(*this, run, player, collider, isLow); } // 00862760 Runs MC_PRE_PROJECTILE_COLLISION, filtered by the projectile's variant. LuaResult LuaEngine::PreProjectileCollision(Entity_Projectile* projectile, Entity* collider, bool isLow) { CallbackRun run = {"PreProjectileCollision", MC_PRE_PROJECTILE_COLLISION, (int)projectile->variant}; - return collision_run(*this, run, {projectile, LUA_CLASS_PROJECTILE}, collider, isLow); + return collision_run(*this, run, projectile, collider, isLow); } // 00862d70 Runs MC_PRE_TEAR_COLLISION, filtered by the tear's variant. LuaResult LuaEngine::PreTearCollision(Entity_Tear* tear, Entity* collider, bool isLow) { CallbackRun run = {"PreTearCollision", MC_PRE_TEAR_COLLISION, (int)tear->variant}; - return collision_run(*this, run, {tear, LUA_CLASS_TEAR}, collider, isLow); + return collision_run(*this, run, tear, collider, isLow); } // 00865340 Runs MC_GET_CARD for a card the pools drew. The card a mod chose, or the drawn one. int LuaEngine::GetCard(const LuaCardDraw& draw) { - return callback_integer_run(*this, {"GetCard", MC_GET_CARD}, draw.card, LuaObject{draw.rng, LUA_CLASS_RNG}, + return callback_integer_run(*this, {"GetCard", MC_GET_CARD}, draw.card, draw.rng, draw.card, draw.isPlaying, draw.isRunes, draw.isOnlyRunes); } @@ -268,7 +222,7 @@ int LuaEngine::GetTrinket(int trinket, const RNG& rng) std::optional LuaEngine::InputAction(Entity* entity, int hook, int action) { CallbackRun run = {"PreActionHookB", MC_INPUT_ACTION, hook}; - if (!callback_run(*this, run, LuaObject{entity, LUA_CLASS_ENTITY}, hook, action)) return std::nullopt; + if (!callback_run(*this, run, entity, hook, action)) return std::nullopt; std::optional value; if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1); @@ -296,11 +250,41 @@ int LuaEngine::PreGetCollectible(const LuaCollectibleDraw& draw) return callback_integer_run(*this, run, 0, draw.poolType, draw.isDecrease, draw.seed); } +// 00864560 Runs MC_ENTITY_TAKE_DMG for a hit, filtered by the entity's type. Whether the hit lands, false only when a +// mod returned false. +bool LuaEngine::EntityTakeDamage(Entity* entity, float damage, uint64_t damageFlags, const EntityRef& source, + int countdown) +{ + CallbackRun run = {"EntityTakeDamage", MC_ENTITY_TAKE_DMG, entity->type}; + return callback_boolean_run(*this, run, true, entity, damage, damageFlags, &source, countdown); +} + +// 008667d0 Runs MC_PRE_ENTITY_DEVOLVE, filtered by the entity's type. Whether a mod skips the devolve. +bool LuaEngine::PreEntityDevolve(Entity* entity) +{ + return callback_boolean_run(*this, {"PreEntityDevolve", MC_PRE_ENTITY_DEVOLVE, entity->type}, false, entity); +} + +// 00866220 Runs MC_PRE_SPAWN_CLEAN_AWARD with copies of the award RNG and position. Whether a mod skips the award. +// The original throws past its callers on a Lua error. This logs it and spawns the award. +bool LuaEngine::PreSpawnCleanAward(const RNG& rng, const Vector& position) +{ + return callback_boolean_run(*this, {"PreSpawnCleanAward", MC_PRE_SPAWN_CLEAN_AWARD}, false, rng, position); +} + +// 00863760 Runs MC_PRE_USE_ITEM for an active item, filtered by its type. Whether a mod skips the use. +bool LuaEngine::PreUseItem(const LuaItemUse& use) +{ + CallbackRun run = {"PreUseItem", MC_PRE_USE_ITEM, use.collectibleType}; + return callback_boolean_run(*this, run, false, use.collectibleType, use.rng, use.player, use.useFlags, + use.activeSlot, use.customVarData); +} + // 00860960 Runs MC_PRE_NPC_UPDATE, filtered by the NPC's type. Whether a mod skips the NPC's AI this frame. bool LuaEngine::PreNPCUpdate(Entity_NPC* npc) { CallbackRun run = {"PreNPCUpdate", MC_PRE_NPC_UPDATE, (int)npc->type}; - if (!callback_run(*this, run, LuaObject{npc, LUA_CLASS_NPC})) return false; + if (!callback_run(*this, run, npc)) return false; bool isSkipped = lua_toboolean(state, -1); lua_pop(state, 1); @@ -312,7 +296,7 @@ bool LuaEngine::PreNPCUpdate(Entity_NPC* npc) void LuaEngine::Callback_PreEntitySpawn(EntitySpawn& spawn) { if (!callback_run(*this, {"PreEntitySpawn", MC_PRE_ENTITY_SPAWN}, spawn.type, spawn.variant, spawn.subType, - spawn.position, spawn.velocity, LuaObject{spawn.spawner, LUA_CLASS_ENTITY}, spawn.seed)) + spawn.position, spawn.velocity, spawn.spawner, spawn.seed)) return; elements_pop(state, spawn.type, spawn.variant, spawn.subType, spawn.seed); } @@ -322,7 +306,7 @@ void LuaEngine::Callback_PreEntitySpawn(EntitySpawn& spawn) void LuaEngine::PostPickupSelection(Entity_Pickup* pickup, int& variant, int& subType) { CallbackRun run = {"PostPickupSelection", MC_POST_PICKUP_SELECTION}; - if (callback_run(*this, run, LuaObject{pickup, LUA_CLASS_PICKUP}, variant, subType)) + if (callback_run(*this, run, pickup, variant, subType)) elements_pop(state, variant, subType); } @@ -331,8 +315,8 @@ void LuaEngine::PostPickupSelection(Entity_Pickup* pickup, int& variant, int& su bool LuaEngine::UseItem(LuaItemUse& use) { CallbackRun run = {"PostUseItem", MC_USE_ITEM, use.collectibleType}; - if (!callback_run(*this, run, use.collectibleType, LuaObject{use.rng, LUA_CLASS_RNG}, - LuaObject{use.player, LUA_CLASS_PLAYER}, use.useFlags, use.activeSlot, use.customVarData)) + if (!callback_run(*this, run, use.collectibleType, use.rng, + use.player, use.useFlags, use.activeSlot, use.customVarData)) return false; bool isShowAnimation = false; @@ -350,49 +334,91 @@ bool LuaEngine::UseItem(LuaItemUse& use) // 00863e90 Runs MC_EVALUATE_CACHE for a player's stat, filtered by the cache flag. void LuaEngine::EvaluateItems(Entity_Player* player, int cacheFlag) { - callback_notify(*this, {"PostEvaluateItems", MC_EVALUATE_CACHE, cacheFlag}, LuaObject{player, LUA_CLASS_PLAYER}, + callback_notify(*this, {"PostEvaluateItems", MC_EVALUATE_CACHE, cacheFlag}, player, cacheFlag); } +// 008635a0 Runs MC_FAMILIAR_INIT, filtered by the familiar's variant. +void LuaEngine::FamiliarInit(Entity_Familiar* familiar) +{ + callback_notify(*this, {"FamiliarInit", MC_FAMILIAR_INIT, familiar->variant}, familiar); +} + +// 00860f00 Runs MC_FAMILIAR_UPDATE, filtered by the familiar's variant. +void LuaEngine::FamiliarUpdate(Entity_Familiar* familiar) +{ + callback_notify(*this, {"FamiliarUpdate", MC_FAMILIAR_UPDATE, familiar->variant}, familiar); +} + +// 00860fe0 Runs MC_POST_FAMILIAR_RENDER with the render offset, filtered by the familiar's variant. +void LuaEngine::PostFamiliarRender(Entity_Familiar* familiar, const Vector& offset) +{ + callback_notify(*this, {"PostFamiliarRender", MC_POST_FAMILIAR_RENDER, familiar->variant}, familiar, offset); +} + +// 00861ea0 Runs MC_POST_BOMB_INIT, filtered by the bomb's variant. +void LuaEngine::PostBombInit(Entity_Bomb* bomb) +{ + callback_notify(*this, {"PostBombInit", MC_POST_BOMB_INIT, bomb->variant}, bomb); +} + +// 00861f80 Runs MC_POST_BOMB_UPDATE, filtered by the bomb's variant. +void LuaEngine::PostBombUpdate(Entity_Bomb* bomb) +{ + callback_notify(*this, {"PostBombUpdate", MC_POST_BOMB_UPDATE, bomb->variant}, bomb); +} + +// 00862060 Runs MC_POST_BOMB_RENDER with the render offset, filtered by the bomb's variant. +void LuaEngine::PostBombRender(Entity_Bomb* bomb, const Vector& offset) +{ + callback_notify(*this, {"PostBombRender", MC_POST_BOMB_RENDER, bomb->variant}, bomb, offset); +} + // 00861330 Runs MC_POST_EFFECT_INIT, filtered by the effect's variant. void LuaEngine::PostEffectInit(Entity_Effect* effect) { callback_notify(*this, {"PostEffectInit", MC_POST_EFFECT_INIT, (int)effect->variant}, - LuaObject{effect, LUA_CLASS_EFFECT}); + effect); } // 008614f0 Runs MC_POST_EFFECT_RENDER with the render offset, filtered by the effect's variant. void LuaEngine::PostEffectRender(Entity_Effect* effect, const Vector& offset) { callback_notify(*this, {"PostEffectRender", MC_POST_EFFECT_RENDER, (int)effect->variant}, - LuaObject{effect, LUA_CLASS_EFFECT}, offset); + effect, offset); } // 00861410 Runs MC_POST_EFFECT_UPDATE, filtered by the effect's variant. void LuaEngine::PostEffectUpdate(Entity_Effect* effect) { callback_notify(*this, {"PostEffectUpdate", MC_POST_EFFECT_UPDATE, (int)effect->variant}, - LuaObject{effect, LUA_CLASS_EFFECT}); + effect); } // 00866140 Runs MC_POST_ENTITY_KILL, filtered by the entity's type. void LuaEngine::PostEntityKill(Entity* entity) { callback_notify(*this, {"PostEntityKill", MC_POST_ENTITY_KILL, (int)entity->type}, - LuaObject{entity, LUA_CLASS_ENTITY}); + entity); } // Runs MC_POST_ENTITY_REMOVE for Entity::ReleaseLuaRef, filtered by the entity's type. void LuaEngine::PostEntityRemove(Entity* entity) { callback_notify(*this, {"PostEntityRemove", MC_POST_ENTITY_REMOVE, (int)entity->type}, - LuaObject{entity, LUA_CLASS_ENTITY}); + entity); } // 00863f70 Runs MC_POST_FIRE_TEAR for a tear a player fired. void LuaEngine::PostFireTear(Entity_Tear* tear) { - callback_notify(*this, {"PostFireTear", MC_POST_FIRE_TEAR}, LuaObject{tear, LUA_CLASS_TEAR}); + callback_notify(*this, {"PostFireTear", MC_POST_FIRE_TEAR}, tear); +} + +// 00864fc0 Runs MC_POST_GAME_END with whether the run ended in a game over. +void LuaEngine::PostGameEnd(bool isGameOver) +{ + callback_notify(*this, {"PostGameEnd", MC_POST_GAME_END}, isGameOver); } // 00864ee0 Runs MC_POST_GAME_STARTED with whether the run continues a saved one. @@ -405,7 +431,37 @@ void LuaEngine::PostGameStart(bool isContinued) void LuaEngine::PostKnifeInit(Entity_Knife* knife) { callback_notify(*this, {"PostKnifeInit", MC_POST_KNIFE_INIT, (int)knife->subtype}, - LuaObject{knife, LUA_CLASS_KNIFE}); + knife); +} + +// 00861970 Runs MC_POST_KNIFE_UPDATE, filtered by the knife's subtype. +void LuaEngine::PostKnifeUpdate(Entity_Knife* knife) +{ + callback_notify(*this, {"PostKnifeUpdate", MC_POST_KNIFE_UPDATE, knife->subtype}, knife); +} + +// 00861a50 Runs MC_POST_KNIFE_RENDER with the render offset, filtered by the knife's subtype. +void LuaEngine::PostKnifeRender(Entity_Knife* knife, const Vector& offset) +{ + callback_notify(*this, {"PostKnifeRender", MC_POST_KNIFE_RENDER, knife->subtype}, knife, offset); +} + +// 008615e0 Runs MC_POST_LASER_INIT, filtered by the laser's variant. +void LuaEngine::PostLaserInit(Entity_Laser* laser) +{ + callback_notify(*this, {"PostLaserInit", MC_POST_LASER_INIT, laser->variant}, laser); +} + +// 008616c0 Runs MC_POST_LASER_UPDATE, filtered by the laser's variant. +void LuaEngine::PostLaserUpdate(Entity_Laser* laser) +{ + callback_notify(*this, {"PostLaserUpdate", MC_POST_LASER_UPDATE, laser->variant}, laser); +} + +// 008617a0 Runs MC_POST_LASER_RENDER with the render offset, filtered by the laser's variant. +void LuaEngine::PostLaserRender(Entity_Laser* laser, const Vector& offset) +{ + callback_notify(*this, {"PostLaserRender", MC_POST_LASER_RENDER, laser->variant}, laser, offset); } // 00865260 Runs MC_POST_NEW_LEVEL once a floor is generated and its first room entered. @@ -423,54 +479,91 @@ void LuaEngine::PostNewRoom() // 00860c90 Runs MC_POST_NPC_DEATH, filtered by the NPC's type. void LuaEngine::PostNPCDeath(Entity_NPC* npc) { - callback_notify(*this, {"PostNPCDeath", MC_POST_NPC_DEATH, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}); + callback_notify(*this, {"PostNPCDeath", MC_POST_NPC_DEATH, (int)npc->type}, npc); } // 00860880 Runs MC_POST_NPC_INIT, filtered by the NPC's type. void LuaEngine::PostNPCInit(Entity_NPC* npc) { - callback_notify(*this, {"PostNPCInit", MC_POST_NPC_INIT, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}); + callback_notify(*this, {"PostNPCInit", MC_POST_NPC_INIT, (int)npc->type}, npc); } // 00860ba0 Runs MC_POST_NPC_RENDER with the render offset, filtered by the NPC's type. void LuaEngine::PostNPCRender(Entity_NPC* npc, const Vector& offset) { - callback_notify(*this, {"PostNPCRender", MC_POST_NPC_RENDER, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}, + callback_notify(*this, {"PostNPCRender", MC_POST_NPC_RENDER, (int)npc->type}, npc, offset); } // 00860ac0 Runs MC_NPC_UPDATE after an NPC's AI, filtered by the NPC's type. void LuaEngine::PostNPCUpdate(Entity_NPC* npc) { - callback_notify(*this, {"PostNPCUpdate", MC_NPC_UPDATE, (int)npc->type}, LuaObject{npc, LUA_CLASS_NPC}); + callback_notify(*this, {"PostNPCUpdate", MC_NPC_UPDATE, (int)npc->type}, npc); } // 00862f00 Runs MC_POST_PICKUP_INIT, filtered by the pickup's variant. void LuaEngine::PostPickupInit(Entity_Pickup* pickup) { callback_notify(*this, {"PostPickupInit", MC_POST_PICKUP_INIT, (int)pickup->variant}, - LuaObject{pickup, LUA_CLASS_PICKUP}); + pickup); } // 008630c0 Runs MC_POST_PICKUP_RENDER with the render offset, filtered by the pickup's variant. void LuaEngine::PostPickupRender(Entity_Pickup* pickup, const Vector& offset) { callback_notify(*this, {"PostPickupRender", MC_POST_PICKUP_RENDER, (int)pickup->variant}, - LuaObject{pickup, LUA_CLASS_PICKUP}, offset); + pickup, offset); } // 00862fe0 Runs MC_POST_PICKUP_UPDATE, filtered by the pickup's variant. void LuaEngine::PostPickupUpdate(Entity_Pickup* pickup) { callback_notify(*this, {"PostPickupUpdate", MC_POST_PICKUP_UPDATE, (int)pickup->variant}, - LuaObject{pickup, LUA_CLASS_PICKUP}); + pickup); } // 00864050 Runs MC_POST_PLAYER_INIT, filtered by the player's variant. void LuaEngine::PostPlayerInit(Entity_Player* player) { callback_notify(*this, {"PostPlayerInit", MC_POST_PLAYER_INIT, (int)player->variant}, - LuaObject{player, LUA_CLASS_PLAYER}); + player); +} + +// 00863be0 Runs MC_POST_PEFFECT_UPDATE, filtered by the player's character. +void LuaEngine::PostPEffectUpdate(Entity_Player* player) +{ + callback_notify(*this, {"PostPEffectUpdate", MC_POST_PEFFECT_UPDATE, player->playerType}, player); +} + +// 00864130 Runs MC_POST_PLAYER_UPDATE, filtered by the player's variant. +void LuaEngine::PostPlayerUpdate(Entity_Player* player) +{ + callback_notify(*this, {"PostPlayerUpdate", MC_POST_PLAYER_UPDATE, player->variant}, player); +} + +// 00864210 Runs MC_POST_PLAYER_RENDER with the render offset, filtered by the player's variant. +void LuaEngine::PostPlayerRender(Entity_Player* player, const Vector& offset) +{ + callback_notify(*this, {"PostPlayerRender", MC_POST_PLAYER_RENDER, player->variant}, player, offset); +} + +// 008624b0 Runs MC_POST_PROJECTILE_INIT, filtered by the projectile's variant. +void LuaEngine::PostProjectileInit(Entity_Projectile* projectile) +{ + callback_notify(*this, {"PostProjectileInit", MC_POST_PROJECTILE_INIT, projectile->variant}, projectile); +} + +// 00862590 Runs MC_POST_PROJECTILE_UPDATE, filtered by the projectile's variant. +void LuaEngine::PostProjectileUpdate(Entity_Projectile* projectile) +{ + callback_notify(*this, {"PostProjectileUpdate", MC_POST_PROJECTILE_UPDATE, projectile->variant}, projectile); +} + +// 00862670 Runs MC_POST_PROJECTILE_RENDER with the render offset, filtered by the projectile's variant. +void LuaEngine::PostProjectileRender(Entity_Projectile* projectile, const Vector& offset) +{ + callback_notify(*this, {"PostProjectileRender", MC_POST_PROJECTILE_RENDER, projectile->variant}, projectile, + offset); } // 00863680 Runs MC_POST_RENDER after the game renders. @@ -482,21 +575,21 @@ void LuaEngine::PostRender() // 008629c0 Runs MC_POST_TEAR_INIT, filtered by the tear's variant. void LuaEngine::PostTearInit(Entity_Tear* tear) { - callback_notify(*this, {"PostTearInit", MC_POST_TEAR_INIT, (int)tear->variant}, LuaObject{tear, LUA_CLASS_TEAR}); + callback_notify(*this, {"PostTearInit", MC_POST_TEAR_INIT, (int)tear->variant}, tear); } // 00862b80 Runs MC_POST_TEAR_RENDER with the render offset, filtered by the tear's variant. void LuaEngine::PostTearRender(Entity_Tear* tear, const Vector& offset) { callback_notify(*this, {"PostTearRender", MC_POST_TEAR_RENDER, (int)tear->variant}, - LuaObject{tear, LUA_CLASS_TEAR}, offset); + tear, offset); } // 00862aa0 Runs MC_POST_TEAR_UPDATE, filtered by the tear's variant. void LuaEngine::PostTearUpdate(Entity_Tear* tear) { callback_notify(*this, {"PostTearUpdate", MC_POST_TEAR_UPDATE, (int)tear->variant}, - LuaObject{tear, LUA_CLASS_TEAR}); + tear); } // 008607a0 Runs MC_POST_UPDATE after the game updates. @@ -505,9 +598,21 @@ void LuaEngine::PostUpdate() callback_notify(*this, {"PostUpdate", MC_POST_UPDATE}); } +// 008650a0 Runs MC_PRE_GAME_EXIT with whether the run is saved (its error handler 0086512e). +void LuaEngine::PreGameExit(bool isSaving) +{ + callback_notify(*this, {"PreGameExit", MC_PRE_GAME_EXIT}, isSaving); +} + +// 00863cc0 Runs MC_USE_CARD for a card a player used, filtered by the card. +void LuaEngine::UseCard(int card, Entity_Player* player, unsigned int useFlags) +{ + callback_notify(*this, {"PostUseCard", MC_USE_CARD, card}, card, player, useFlags); +} + // 00863da0 Runs MC_USE_PILL for a pill effect, filtered by it. void LuaEngine::UsePill(int pillEffect, Entity_Player* player, unsigned int useFlags) { callback_notify(*this, {"PostUsePillEffect", MC_USE_PILL, pillEffect}, pillEffect, - LuaObject{player, LUA_CLASS_PLAYER}, useFlags); + player, useFlags); } diff --git a/src/lua_engine.cpp b/src/lua_engine.cpp index 29d3e9f..1492281 100644 --- a/src/lua_engine.cpp +++ b/src/lua_engine.cpp @@ -1,4 +1,5 @@ #include "lua_engine.h" +#include "lua_api.h" #include "classes.h" #include "data.h" #include "game.h" @@ -11,16 +12,6 @@ #include #include -// classes.h declares the original's Lua imports, and its luaL_newstate differs from Lua's only in its return type. -// Lua's is renamed away here, as Init opens the state the way the original's reserved heap did. -#define luaL_newstate lua_newstate_auxiliary -extern "C" -{ -#include "lauxlib.h" -#include "lua.h" -#include "lualib.h" -} -#undef luaL_newstate constexpr const char* ENUMS_SCRIPT = "scripts/enums.lua"; constexpr const char* MAIN_SCRIPT = "scripts/main.lua"; @@ -33,13 +24,13 @@ constexpr const char* PATH_SEPARATORS = "/\\"; constexpr const char* RUN_CALLBACK = "_RunCallback"; constexpr const char* UNLOAD_MOD = "_UnloadMod"; +constexpr uint64_t NS_PER_MS = 1000000; constexpr int API_VERSION_NONE = -1; constexpr int API_VERSION_CURRENT = 1; constexpr int GC_COOLDOWN_FRAMES = 600; constexpr int GC_SHRINK_DIVISOR = 100; constexpr int GC_SHRINK_MIN = 10; constexpr int GC_STEP_MAX = 10000; -constexpr uint64_t NS_PER_MS = 1000000; constexpr uint32_t MASK_SALT = 0xdeadbeef; constexpr int MASK_SHIFTS[] = {4, 5, 11}; @@ -153,7 +144,7 @@ static void mod_unload(LuaEngine& engine, LuaMod& mod) // 008604c0 Opens a state with the pointer mask hashed from the time, the sandboxed libraries or, in debug mode, every // library with require searching resources/scripts/, then runs enums.lua and main.lua, as RunBundledScript did // (0086e5e0), and takes their _RunCallback and _UnloadMod. The state always opens as on the reserved heap, with the -// C heap in its place, since --luaheapsize is ignored. RegisterAPI is not called until it is reconstructed. +// C heap in its place, since --luaheapsize is ignored. void LuaEngine::Init(LuaMode luaMode) { pointerMask = pointer_mask_make((uint32_t)(GetTimeNs() / NS_PER_MS)); @@ -176,16 +167,22 @@ void LuaEngine::Init(LuaMode luaMode) } mode = luaMode; - log_printf(LOG_WARN, "**The mod API is not reconstructed yet, so scripts run without the Isaac table\n"); + RegisterAPI(); RunScript(resource_path(ENUMS_SCRIPT)); RunScript(resource_path(MAIN_SCRIPT)); runCallbackRef = global_take(state, RUN_CALLBACK); unloadModRef = global_take(state, UNLOAD_MOD); } +// 00866960 Registers the mod API: the classes, then the namespaces and the global functions, which replace the +// SFXManager and MusicManager classes with the functions returning them. void LuaEngine::RegisterAPI() { - reconstruction_missing("LuaEngine::RegisterAPI 00866960"); + for (auto registerPart : {lua_api_vector_register, lua_api_color_register, lua_api_rng_register, + lua_api_bit_set128_register, lua_api_sprite_register, lua_api_entity_register, + lua_api_entities_register, lua_api_entity_player_register, lua_api_game_register, + lua_api_room_register, lua_api_item_config_register, lua_api_isaac_register}) + registerPart(state); } // 0086e520 Unloads every registered mod, releases the engine's references and closes the state. diff --git a/src/lua_engine.h b/src/lua_engine.h index 6957432..713137c 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -14,11 +14,13 @@ struct Entity_Bomb; struct Entity_Effect; struct Entity_Familiar; struct Entity_Knife; +struct Entity_Laser; struct Entity_NPC; struct Entity_Pickup; struct Entity_Player; struct Entity_Projectile; struct Entity_Tear; +struct EntityRef; struct EntitySpawn; struct RNG; struct Vector; @@ -30,20 +32,52 @@ constexpr int LUA_MEMORY_HISTORY_SIZE = 128; // Lua's LUA_NOREF: a registry reference to nothing. constexpr int LUA_REF_NONE = -2; -// The game classes callbacks hand objects of to Lua, each with the registry key of the metatable the API gives it. +// The game classes the API binds, each with the registry key of the metatable its objects get. enum LuaClass { + LUA_CLASS_BIT_SET128, + LUA_CLASS_COLOR, LUA_CLASS_ENTITY, LUA_CLASS_BOMB, LUA_CLASS_EFFECT, LUA_CLASS_FAMILIAR, LUA_CLASS_KNIFE, + LUA_CLASS_LASER, LUA_CLASS_NPC, LUA_CLASS_PICKUP, LUA_CLASS_PLAYER, LUA_CLASS_PROJECTILE, - LUA_CLASS_RNG, LUA_CLASS_TEAR, + LUA_CLASS_ENTITY_PTR, + LUA_CLASS_ENTITY_REF, + LUA_CLASS_FONT, + LUA_CLASS_FONT_SETTINGS, + LUA_CLASS_GAME, + LUA_CLASS_GRID_ENTITY, + LUA_CLASS_HUD, + LUA_CLASS_ITEM_CONFIG, + LUA_CLASS_ITEM_CONFIG_CARD, + LUA_CLASS_ITEM_CONFIG_CARD_LIST, + LUA_CLASS_ITEM_CONFIG_COSTUME, + LUA_CLASS_ITEM_CONFIG_ITEM, + LUA_CLASS_ITEM_CONFIG_ITEM_LIST, + LUA_CLASS_ITEM_CONFIG_PILL, + LUA_CLASS_ITEM_CONFIG_PILL_LIST, + LUA_CLASS_ITEM_POOL, + LUA_CLASS_KCOLOR, + LUA_CLASS_LEVEL, + LUA_CLASS_MUSIC_MANAGER, + LUA_CLASS_PROJECTILE_PARAMS, + LUA_CLASS_RNG, + LUA_CLASS_ROOM, + LUA_CLASS_ROOM_CONFIG_ROOM, + LUA_CLASS_ROOM_DESCRIPTOR, + LUA_CLASS_ROOM_LIST, + LUA_CLASS_SEEDS, + LUA_CLASS_SFX_MANAGER, + LUA_CLASS_SPRITE, + LUA_CLASS_TEAR_PARAMS, + LUA_CLASS_TEMPORARY_EFFECTS, LUA_CLASS_VECTOR, LUA_CLASS_COUNT }; @@ -115,20 +149,36 @@ struct LuaEngine int PostCurseEval(int curses); int PostGetCollectible(const LuaCollectibleDraw& draw); int PreGetCollectible(const LuaCollectibleDraw& draw); + bool EntityTakeDamage(Entity* entity, float damage, uint64_t damageFlags, const EntityRef& source, int countdown); + bool PreEntityDevolve(Entity* entity); bool PreNPCUpdate(Entity_NPC* npc); + bool PreSpawnCleanAward(const RNG& rng, const Vector& position); + bool PreUseItem(const LuaItemUse& use); void Callback_PreEntitySpawn(EntitySpawn& spawn); void PostPickupSelection(Entity_Pickup* pickup, int& variant, int& subType); bool UseItem(LuaItemUse& use); void EvaluateItems(Entity_Player* player, int cacheFlag); + void FamiliarInit(Entity_Familiar* familiar); + void FamiliarUpdate(Entity_Familiar* familiar); + void PostBombInit(Entity_Bomb* bomb); + void PostBombRender(Entity_Bomb* bomb, const Vector& offset); + void PostBombUpdate(Entity_Bomb* bomb); void PostEffectInit(Entity_Effect* effect); void PostEffectRender(Entity_Effect* effect, const Vector& offset); void PostEffectUpdate(Entity_Effect* effect); void PostEntityKill(Entity* entity); void PostEntityRemove(Entity* entity); + void PostFamiliarRender(Entity_Familiar* familiar, const Vector& offset); void PostFireTear(Entity_Tear* tear); + void PostGameEnd(bool isGameOver); void PostGameStart(bool isContinued); void PostKnifeInit(Entity_Knife* knife); + void PostKnifeRender(Entity_Knife* knife, const Vector& offset); + void PostKnifeUpdate(Entity_Knife* knife); + void PostLaserInit(Entity_Laser* laser); + void PostLaserRender(Entity_Laser* laser, const Vector& offset); + void PostLaserUpdate(Entity_Laser* laser); void PostNewLevel(); void PostNewRoom(); void PostNPCDeath(Entity_NPC* npc); @@ -138,12 +188,20 @@ struct LuaEngine void PostPickupInit(Entity_Pickup* pickup); void PostPickupRender(Entity_Pickup* pickup, const Vector& offset); void PostPickupUpdate(Entity_Pickup* pickup); + void PostPEffectUpdate(Entity_Player* player); void PostPlayerInit(Entity_Player* player); + void PostPlayerRender(Entity_Player* player, const Vector& offset); + void PostPlayerUpdate(Entity_Player* player); + void PostProjectileInit(Entity_Projectile* projectile); + void PostProjectileRender(Entity_Projectile* projectile, const Vector& offset); + void PostProjectileUpdate(Entity_Projectile* projectile); void PostRender(); void PostTearInit(Entity_Tear* tear); void PostTearRender(Entity_Tear* tear, const Vector& offset); void PostTearUpdate(Entity_Tear* tear); void PostUpdate(); + void PreGameExit(bool isSaving); + void UseCard(int card, Entity_Player* player, unsigned int useFlags); void UsePill(int pillEffect, Entity_Player* player, unsigned int useFlags); }; diff --git a/src/manager.cpp b/src/manager.cpp index 091d1cf..411cdda 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -202,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_GURG = 301; constexpr uint32_t FART_GURG_CHANCE = 20; constexpr uint32_t FART_RNG_SEED = 0x69696969; constexpr uint32_t FART_RNG_SHIFT_INDEX = 11; diff --git a/src/minimap.cpp b/src/minimap.cpp index c82b776..13a4e9b 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -86,7 +86,6 @@ constexpr int ICON_TREASURE_MAP = 2; constexpr int ICON_RESTOCK = 4; constexpr int ICON_MIND = 5; -constexpr int STAGE_HOME = 35; constexpr int CHALLENGE_SPEED = 22; constexpr int SPEED_TIME_LIMIT = 28800; constexpr int FRAMES_PER_SECOND = 30; @@ -108,7 +107,6 @@ constexpr float SCORE_Y = 46; constexpr int CHALLENGE_APRILS_FOOL = 32; constexpr RNG APRILS_FOOL_RNG = {0, 1, 5, 16}; -constexpr int STAGE_VOID = 12; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int SUBTYPE_MINESHAFT_ENTRANCE = 10; constexpr int SUBTYPE_MIRROR_ROOM = 34; @@ -851,7 +849,7 @@ void Minimap::Render() bool isLost = curses_get() & CURSE_OF_THE_LOST; float hudAlpha = game.roomTransition.get_hud_alpha(); const RoomConfig_Room* room = game.room->descriptor->data; - if (room && room->type == ROOM_DUNGEON && room->stageId == STAGE_HOME) + if (room && room->type == ROOM_DUNGEON && room->stageId == STAGE_ID_HOME) { if (game.dailyChallenge._id != 0) render_score_time(1); return; diff --git a/src/nightmare_scene.cpp b/src/nightmare_scene.cpp index 0c2e568..7f9fa1e 100644 --- a/src/nightmare_scene.cpp +++ b/src/nightmare_scene.cpp @@ -28,7 +28,6 @@ constexpr int BACKGROUND_STATIC_LAYER = 7; constexpr int BUBBLE_STATIC_LAYER = 9; constexpr unsigned int STATIC_LAYER_FLAGS = ANIM_RENDER_STATIC | ANIM_RENDER_IGNORE_GAME_TIME; -constexpr uint32_t STAGE_ID_HOME = 26; constexpr uint32_t STAGE_LAST_WITH_DREAM_CATCHER = 6; // A Game state flag set once Dream Catcher showed this chapter, letting its nightmare be skipped. constexpr uint64_t GAME_STATE_DREAM_CATCHER_SHOWN = 1ull << 48; @@ -37,13 +36,9 @@ constexpr uint32_t FADE_IN_FRAMES = 30; constexpr float FADE_FRAMES = 15; 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_ICONS_PER_CHAPTER = 3; constexpr int STAGE_ICONS_PER_ALT_CHAPTER = 2; // The stage whose icon the void's slot shows again. -constexpr int STAGE_VOID = 12; constexpr int STAGE_VOID_SLOT = 10; static bool is_attr_present(DataNode node, std::string_view name) @@ -121,7 +116,6 @@ constexpr int ICON_HIDDEN = -1; constexpr int STAGE_BAR_LAST = 6; constexpr int STAGE_BAR_LAST_WOMB = 8; constexpr int STAGE_BAR_LAST_GREED = 7; -constexpr int STAGE_BLUE_WOMB = 9; constexpr int STAGE_HOME_SLOT = 13; constexpr int ACHIEVEMENT_WOMB = 4; constexpr int CLOCK_LAST_STAGE = 6; @@ -184,7 +178,7 @@ void NightmareScene::Show(bool isSameStageShown) backgroundSprite.offset = center; bubbleSprite.offset = center; if (!nightmarePaths.empty()) nightmareIndex = (nightmareIndex + 1) % (int)nightmarePaths.size(); - bool isAltPath = game.stageType == STAGE_TYPE_REPENTANCE || game.stageType == STAGE_TYPE_REPENTANCE_B; + bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; stageIndex = isAltPath ? (int)game.stage : (int)game.stage - 1; isSameStage = isSameStageShown; g_manager->musicManager.Play(isDogma ? MUSIC_DOGMA_NIGHTMARE : MUSIC_JINGLE_NIGHTMARE, @@ -403,7 +397,7 @@ void NightmareScene::Update() (game.stage > 0 && game.stage <= STAGE_LAST_WITH_DREAM_CATCHER && (game.gameStateFlags & GAME_STATE_DREAM_CATCHER_SHOWN)); bool isSkipped = isDreamCatcherSkippable && is_action(ACTION_MENU_CONFIRM, ACTION_TRIGGERED); - if (game.GetStageID() == STAGE_ID_HOME && is_action(ACTION_MENU_CONFIRM, ACTION_TRIGGERED)) isSkipped = true; + if (game.GetStageID() == STAGE_ID_VOID && is_action(ACTION_MENU_CONFIRM, ACTION_TRIGGERED)) isSkipped = true; uint32_t sceneFrame = (uint32_t)sceneDelay * 2; if (!(frame & 1)) @@ -447,7 +441,7 @@ void NightmareScene::Update() void NightmareScene::record_stage(int stage, int stageType) { bool isGreed = g_game->IsGreedMode(); - bool isAltPath = stageType == STAGE_TYPE_REPENTANCE || stageType == STAGE_TYPE_REPENTANCE_B; + bool isAltPath = stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; int chapter = isGreed ? stage - 1 : (stage - 1) / 2; int icon = 0; diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index b045a1b..2aa128f 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -1,6 +1,6 @@ #include "npc_ai.h" #include "boss_ai.h" -#include "npc_basement.h" +#include "npc_caves.h" #include "game.h" #include "manager.h" #include "npc_fireplace.h" @@ -112,7 +112,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 19: case 89: case 239: - return (void)NpcAI::ENTITY_LARRYJR(&npc); + return boss_larry_jr_update(npc); case 20: case 43: return boss_monstro_update(npc); @@ -122,21 +122,21 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 55: case 237: case 243: - return (void)NpcAI::ENTITY_MAGGOT(&npc); + return npc_maggot_update(npc); case 22: case 205: case 817: return npc_hive_update(npc); case 24: case 278: - return (void)NpcAI::ENTITY_GLOBIN(&npc); + return npc_globin_update(npc); case 25: - return (void)NpcAI::ENTITY_BOOMFLY(&npc); + return npc_boom_fly_update(npc); case 26: - return (void)NpcAI::ENTITY_MAW(&npc); + return npc_maw_update(npc); case 27: case 859: - return (void)NpcAI::ENTITY_HOST(&npc); + return npc_host_update(npc); case 28: return (void)NpcAI::ENTITY_CHUB(&npc); case 29: @@ -148,11 +148,11 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 840: return npc_hopper_update(npc); case 30: - return (void)NpcAI::ENTITY_BOIL(&npc); + return npc_boil_update(npc); case 32: case 279: case 301: - return (void)NpcAI::ENTITY_BRAIN(&npc); + return npc_brain_update(npc); case 33: return npc_fireplace_update(npc); case 35: @@ -219,7 +219,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 66: return (void)NpcAI::ENTITY_DEATH(&npc); case 67: - return (void)NpcAI::ENTITY_DUKE(&npc); + return boss_duke_update(npc); case 68: return (void)NpcAI::ENTITY_PEEP(&npc); case 69: @@ -254,7 +254,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 87: return (void)NpcAI::ENTITY_GURGLE(&npc); case 88: - return (void)NpcAI::ENTITY_WALKINGBOIL(&npc); + return npc_walking_boil_update(npc); case 90: return (void)NpcAI::ENTITY_HANGER(&npc); case 91: @@ -290,7 +290,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) return (void)NpcAI::ENTITY_MOBILE_HOST(&npc); case 206: case 207: - return (void)NpcAI::ENTITY_BABY_LONG_LEGS(&npc); + return npc_baby_long_legs_update(npc); case 209: return (void)NpcAI::ENTITY_FAT_SACK(&npc); case 212: @@ -313,7 +313,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 221: return (void)NpcAI::ENTITY_COD_WORM(&npc); case 222: - return (void)NpcAI::ENTITY_RING_OF_FLIES(&npc); + return npc_ring_fly_update(npc); case 224: return (void)NpcAI::ENTITY_OOB(&npc); case 225: @@ -321,7 +321,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 226: case 227: case 277: - return (void)NpcAI::ENTITY_SKINNY(&npc); + return npc_skinny_update(npc); case 228: case 251: return (void)NpcAI::ENTITY_HOMUNCULUS(&npc); @@ -340,7 +340,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 255: case 276: case 289: - return (void)NpcAI::ENTITY_ROUND_WORM(&npc); + return npc_round_worm_update(npc); case 245: return (void)NpcAI::ENTITY_POOP(&npc); case 256: @@ -350,7 +350,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 260: return (void)NpcAI::ENTITY_THE_HAUNT(&npc); case 261: - return (void)NpcAI::ENTITY_DINGLE(&npc); + return boss_dingle_update(npc); case 262: return (void)NpcAI::ENTITY_MEGA_MAW(&npc); case 263: @@ -382,7 +382,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) if (npc.isDead) npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); return; case 281: - return (void)NpcAI::ENTITY_SWARM(&npc); + return npc_swarm_update(npc); case 288: return (void)NpcAI::ENTITY_DUKIE(&npc); case 290: @@ -390,7 +390,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 291: return (void)NpcAI::ENTITY_PITFALL(&npc); case 292: - return (void)NpcAI::ENTITY_MOVABLE_TNT(&npc); + return npc_movable_tnt_update(npc); case 293: return (void)NpcAI::ENTITY_ULTRA_COIN(&npc); case 294: @@ -406,11 +406,11 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 299: return (void)NpcAI::ENTITY_GREED_GAPER(&npc); case 300: - return (void)NpcAI::ENTITY_MUSHROOM(&npc); + return npc_mushroom_update(npc); case 303: return (void)NpcAI::ENTITY_BLISTER(&npc); case 306: - return (void)NpcAI::ENTITY_PORTAL(&npc); + return npc_portal_update(npc); case 307: return (void)NpcAI::ENTITY_TARBOY(&npc); case 308: @@ -426,7 +426,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 403: return (void)NpcAI::ENTITY_FORSAKEN(&npc); case 404: - return (void)NpcAI::ENTITY_LITTLE_HORN(&npc); + return boss_little_horn_update(npc); case 405: return (void)NpcAI::ENTITY_RAG_MAN(&npc); case 406: @@ -460,7 +460,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 811: return (void)NpcAI::ENTITY_DEEP_GAPER(&npc); case 812: - return (void)NpcAI::ENTITY_SUB_HORF(&npc); + return npc_sub_horf_update(npc); case 813: return (void)NpcAI::ENTITY_BLURB(&npc); case 814: @@ -542,7 +542,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 867: return (void)NpcAI::ENTITY_MOTHERS_SHADOW(&npc); case 868: - return (void)NpcAI::ENTITY_ARMYFLY(&npc); + return npc_army_fly_update(npc); case 873: return (void)NpcAI::ENTITY_FLY_TRAP(&npc); case 874: @@ -606,7 +606,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 907: return (void)NpcAI::ENTITY_GIDEON(&npc); case 908: - return (void)NpcAI::ENTITY_BABY_PLUM(&npc); + return boss_baby_plum_update(npc); case 909: return npc.variant == 10 ? NpcAI::ENTITY_SCOURGE_chain(&npc) : NpcAI::ENTITY_SCOURGE(&npc); case 910: diff --git a/src/npc_ai.h b/src/npc_ai.h index 23b4208..b3d0c18 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -21,8 +21,8 @@ enum NpcSound : int SOUND_MEAT_IMPACTS = 77, SOUND_ZOMBIE_WALKER_KID = 165, SOUND_MONSTER_GRUNT_0 = 167, - SOUND_SUMMONSOUND = 286, - SOUND_SUMMON_POOF = 872 + SOUND_SUMMON_POOF = 286, + SOUND_SUMMON_WAVE = 872 }; inline Vector vector_add(Vector a, Vector b) diff --git a/src/npc_army_fly.cpp b/src/npc_army_fly.cpp new file mode 100644 index 0000000..4cdd8ca --- /dev/null +++ b/src/npc_army_fly.cpp @@ -0,0 +1,229 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "deathmatch_manager.h" +#include "entity_player.h" +#include "room_grid.h" + +// Army flies line up into marching columns: one joins the back of another within 42 and the column follows its head, 40 +// apart at up to 8. The head marches along the grid's axes at 1.6, wobbling, turning before walls and toward its target +// (one time in three, within 600) or at random, every 8 to 22 frames. +constexpr float ARMY_FLY_JOIN_RANGE = 42; +constexpr float ARMY_FLY_GAP = 40; +constexpr float ARMY_FLY_FOLLOW_SPEED = 8; +constexpr int ARMY_FLY_FIRST_TURN = 10; +constexpr int ARMY_FLY_MERGE_FRAMES = 4; +constexpr uint32_t ARMY_FLY_MERGE_MASK = 7; +constexpr float ARMY_FLY_SEEK_RANGE = 600; +constexpr uint32_t ARMY_FLY_SEEK_ODDS = 3; +constexpr uint32_t ARMY_FLY_TURN_ODDS = 5; +constexpr float ARMY_FLY_NO_DOT = -1000; +constexpr uint32_t ARMY_FLY_TURN_FRAMES = 15; +constexpr int ARMY_FLY_TURN_MIN = 8; +constexpr float ARMY_FLY_SPEED = 1.6f; +constexpr float ARMY_FLY_CONFUSED_SPEED = 0.6f; +constexpr float ARMY_FLY_WOBBLE = 20; +constexpr float ARMY_FLY_CONFUSED_WOBBLE = 40; +constexpr float ARMY_FLY_WOBBLE_PERIOD = 10; +constexpr float ARMY_FLY_FRICTION = 0.8f; +constexpr uint64_t FLAG_ARMY_FLY_SCATTERED = FLAG_FREEZE | FLAG_CONFUSION; + +// One of the four directions from another, turned a number of quarter turns clockwise. +static int army_fly_turn(int direction, int quarters) +{ + return (direction + quarters) & 3; +} + +// The grid collision a cell's width ahead in a direction. +static uint32_t army_fly_ahead_collision(Entity_NPC& npc, int direction) +{ + return room_grid_collision_at(vector_add(npc.pos, vector_scale(vector_from_direction(direction), GRID_CELL_SIZE))); +} + +// Every fly from this one back sets its group to a column's. +static void army_fly_group_set(Entity* fly, int group) +{ + for (; fly; fly = fly->child) static_cast(fly)->groupIdx = group; +} + +// A turn to the left or right, away from a wall (at random when both sides are open). +static void army_fly_turn_aside(Entity_NPC& npc) +{ + uint32_t left = army_fly_ahead_collision(npc, army_fly_turn(npc.i1, 1)); + uint32_t right = army_fly_ahead_collision(npc, army_fly_turn(npc.i1, 3)); + bool isRightRolled = (Random() & 1) == 0; + bool isRight = (isRightRolled || left == COLLISION_WALL) && right != COLLISION_WALL; + npc.i1 = army_fly_turn(npc.i1, isRight ? 3 : 1); +} + +// A new fly joins the back of the nearest column within 42 that is not its own, and takes its group. +static void army_fly_enlist(Entity_NPC& npc) +{ + npc.groupIdx = (int)npc.index; + std::vector flies = entity_query(npc.type, npc.variant); + for (int i = (int)flies.size() - 1; i >= 0; i--) + { + Entity* fly = flies[i]; + if (fly == &npc || fly->parent.get() == &npc || fly->child) continue; + if (vector_length(vector_sub(npc.pos, fly->pos)) >= ARMY_FLY_JOIN_RANGE) continue; + + bool isOwnColumn = false; + for (Entity* link = fly; link; link = link->parent) isOwnColumn = isOwnColumn || link == &npc; + if (!isOwnColumn) npc.parent = fly; + } + + if (npc.parent) + { + Entity_NPC* back = npc.ParentNPC(); + back->child = &npc; + Entity* head = npc.GetLastParent(); + army_fly_group_set(head, (int)head->index); + back->vectorDeque1.push_back(npc.pos); + } + npc.state = NPC_STATE_MOVE; + npc.i1 = -1; + npc.i2 = ARMY_FLY_FIRST_TURN; +} + +// A column's head meeting another column's tail within 42 joins its back. Whether it did. +static bool army_fly_column_join(Entity_NPC& npc) +{ + for (Entity* entity : entity_query_radius(npc.pos, ARMY_FLY_JOIN_RANGE, QUERY_ENEMIES)) + { + if (entity->type != npc.type || (npc.variant != -1 && entity->variant != npc.variant)) continue; + Entity_NPC& tail = *static_cast(entity); + if (tail.groupIdx == npc.groupIdx || tail.child) continue; + + army_fly_group_set(&npc, tail.groupIdx); + npc.parent = &tail; + tail.child = &npc; + tail.vectorDeque1.clear(); + tail.vectorDeque1.push_back(npc.pos); + return true; + } + return false; +} + +// The head's next direction when its march runs out: toward its target one time in three (never back), else to a side +// one time in five. It marches on for 8 to 22 frames after a turn. Whether it changed direction. +static void army_fly_turn_pick(Entity_NPC& npc) +{ + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + bool isSeeking = vector_length(toward) <= ARMY_FLY_SEEK_RANGE && !npc.HasEntityFlags(FLAG_CONFUSION); + if (isSeeking) + { + if (Random() % ARMY_FLY_SEEK_ODDS != 0) return; + + int best = npc.i1; + float bestDot = ARMY_FLY_NO_DOT; + for (int quarters = 3; quarters < 6; quarters++) + { + int direction = army_fly_turn(npc.i1, quarters); + float dot = vector_dot(toward, vector_from_direction(direction)); + if (army_fly_ahead_collision(npc, direction) != COLLISION_WALL && dot > bestDot) + { + bestDot = dot; + best = direction; + } + } + if (best == npc.i1) return; + + npc.i1 = best; + npc.i2 = (int)(Random() % ARMY_FLY_TURN_FRAMES) + ARMY_FLY_TURN_MIN; + return; + } + if (Random() % ARMY_FLY_TURN_ODDS != 0 && !npc.HasEntityFlags(FLAG_CONFUSION)) return; + + army_fly_turn_aside(npc); + npc.i2 = (int)(Random() % ARMY_FLY_TURN_FRAMES) + ARMY_FLY_TURN_MIN; +} + +// The head marches on along its direction, wobbling, turning aside before a wall (slower and wilder when confused). +static void army_fly_march(Entity_NPC& npc) +{ + Vector direction = npc.i1 < 4 ? vector_from_direction(npc.i1) : vector_make(0, 0); + if (army_fly_ahead_collision(npc, npc.i1) == COLLISION_WALL) army_fly_turn_aside(npc); + + bool isConfused = npc.HasEntityFlags(FLAG_CONFUSION); + float phase = std::sin((float)(g_game->frameCount - npc.spawnFrame) * PI_F / ARMY_FLY_WOBBLE_PERIOD); + float wobble = phase * (isConfused ? ARMY_FLY_CONFUSED_WOBBLE : ARMY_FLY_WOBBLE) * DEGREES_TO_RADIANS; + float slow = isConfused ? ARMY_FLY_CONFUSED_SPEED : 1; + float c = std::cos(wobble); + float s = std::sin(wobble); + npc.velocity.x += (direction.x * c - direction.y * s) * ARMY_FLY_SPEED * slow * npc.speedMultiplier; + npc.velocity.y += (direction.y * c + direction.x * s) * ARMY_FLY_SPEED * slow * npc.speedMultiplier; +} + +// A player's army fly hands its control down the column as it dies, or up to the column's head. +static void army_fly_control_pass(Entity_NPC& npc) +{ + if (npc.parent) + { + Entity* head = npc.GetLastParent(); + bool isRival = g_game->deathmatchManager.state >= DEATHMATCH_INTRO && head->type == ENTITY_PLAYER; + bool isEnemy = head->type >= ENTITY_FIRST_ENEMY && head->type <= ENTITY_LAST_ENEMY; + if (isRival || isEnemy) npc.TransferControl(static_cast(head)); + return; + } + if (!npc.isDead) return; + + for (Entity_NPC* fly = npc.ChildNPC(); fly; fly = fly->ChildNPC()) + if (!fly->isDead) return npc.TransferControl(fly); +} + +// 0054ad80 The Army fly's AI: Skatole tames it and Lord of the Flies takes it. Flies form marching columns behind a +// head that marches the grid's axes. A frozen or confused fly breaks off, and a dying one leaves its column's back to +// march on its own. +void npc_army_fly_update(Entity_NPC& npc) +{ + npc.friction *= ARMY_FLY_FRICTION; + if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK) && !npc.IsFriendly()) + { + npc.Morph(ENTITY_FLY, 0, 0, -1); + npc.v2 = {}; + npc.v1 = {}; + return; + } + if (npc_fly_beelzebub_take(npc)) return; + if (npc.controllerID != -1) army_fly_control_pass(npc); + + if (npc.state == NPC_STATE_INIT) army_fly_enlist(npc); + if (npc.state == NPC_STATE_MOVE) + { + npc.sprite.Play("Fly"); + segment_follow(npc, SEGMENT_FOLLOW, ARMY_FLY_GAP, ARMY_FLY_FOLLOW_SPEED); + if (npc.parent && npc.HasEntityFlags(FLAG_ARMY_FLY_SCATTERED)) + { + npc.parent->child = nullptr; + npc.parent = nullptr; + army_fly_group_set(&npc, (int)npc.index); + } + + if (!npc.parent) + { + if (npc.i1 < 0) + { + uint32_t roll = Random(); + int direction = (int)roll; + if (npc.child) + direction = (int)vector_to_direction(vector_sub(npc.pos, npc.child->pos)) - 1 + (int)(roll % 3); + npc.i1 = direction & 3; + } + + bool isMerging = npc.controllerID == -1 && npc.IsFrame(ARMY_FLY_MERGE_FRAMES, 0) && + (Random() & ARMY_FLY_MERGE_MASK) == 0; + if (!isMerging || !army_fly_column_join(npc)) + { + if (npc.i2 > 0) npc.i2 -= npc_ticks_get(npc); + else army_fly_turn_pick(npc); + + if (npc.controllerID == -1) army_fly_march(npc); + else npc.pathfinder.MoveRandomlyAxisAligned(ARMY_FLY_SPEED, STATUS_OBEYED); + } + } + } + + if (!npc.isDead || !npc.child) return; + Entity_NPC* back = npc.ChildNPC(); + back->pathfinder.Reset(); + army_fly_group_set(back, back->groupIdx); +} diff --git a/src/npc_baby_long_legs.cpp b/src/npc_baby_long_legs.cpp new file mode 100644 index 0000000..124fbfa --- /dev/null +++ b/src/npc_baby_long_legs.cpp @@ -0,0 +1,151 @@ +#include "npc_caves.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "sfx_manager.h" + +// Baby Long Legs run from their target and lay spiders (the small ones a Sack and white creep). Crazy Long Legs chase +// it and burst into a ring of lobbed shots (the small ones a cross). Bursting Sack calms them. +constexpr int LONG_LEGS_SMALL = 1; +constexpr int LONG_LEGS_ENEMY_CAP = 6; +constexpr uint32_t LONG_LEGS_LAY_ODDS = 100; +constexpr uint32_t LONG_LEGS_SMALL_LAY_ODDS = 200; +constexpr uint32_t LONG_LEGS_BURST_ODDS = 50; +constexpr uint32_t LONG_LEGS_SECOND_SPIDER_ODDS = 20; +constexpr float LONG_LEGS_SPEED = 0.65f; +constexpr float LONG_LEGS_CONTROL_RANGE = 1000; +constexpr float LONG_LEGS_WALK_THRESHOLD = 0.1f; +constexpr float LONG_LEGS_FRICTION = 0.8f; +constexpr float LONG_LEGS_ATTACK_FRICTION = 0.5f; +constexpr float LONG_LEGS_STEERED_PLAYBACK = 1.5f; +constexpr float LONG_LEGS_SHOT_SPEED = 8; +constexpr float LONG_LEGS_SHOT_SPEED_RANGE = 2; +constexpr float LONG_LEGS_SHOT_HEIGHT = 10; +constexpr float LONG_LEGS_SHOT_FALL = -10; +constexpr float LONG_LEGS_SHOT_FALL_ACCEL = 0.5f; +constexpr uint64_t FLAG_LONG_LEGS_SCARED = FLAG_FEAR | FLAG_SHRINK; + +// Whether a player steering it presses to attack or aims at its target. +static bool long_legs_is_steered_attack(Entity_NPC& npc) +{ + return npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) || + npc.IsTargetInAttackRange(LONG_LEGS_CONTROL_RANGE, 7, false); +} + +// Wandering about, calmed or confused: at random, or toward its target when steered. +static void long_legs_wander(Entity_NPC& npc) +{ + if (npc.controllerID == -1) npc.pathfinder.MoveRandomly(STATUS_OBEYED); + else npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, LONG_LEGS_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); +} + +// A Baby Long Legs keeps away from its target and now and then stops to lay (more rarely the small one, never with six +// or more enemies around). +static void baby_long_legs_walk(Entity_NPC& npc, bool isCalm) +{ + if (npc.HasEntityFlags(FLAG_CONFUSION) || isCalm) return long_legs_wander(npc); + + if (npc.controllerID == -1) npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + else npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, LONG_LEGS_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + if (npc.GetAliveEnemyCount() >= LONG_LEGS_ENEMY_CAP) return; + + uint32_t odds = npc.variant == LONG_LEGS_SMALL ? LONG_LEGS_SMALL_LAY_ODDS : LONG_LEGS_LAY_ODDS; + bool isLaying = npc.controllerID != -1 + ? long_legs_is_steered_attack(npc) + : (npc.pathfinder.evadeMovementCountdown < 1 && random_below((int)(odds / 2)) == 0) || + random_below((int)odds) == 0; + if (isLaying && !npc.HasEntityFlags(FLAG_LONG_LEGS_SCARED)) npc.state = NPC_STATE_ATTACK; +} + +// A Crazy Long Legs chases its target and bursts one time in 50 while it sees it. Scared, it runs. +static void crazy_long_legs_walk(Entity_NPC& npc, bool isCalm) +{ + Vector targetPos = npc.GetPlayerTarget()->pos; + if (npc.HasEntityFlags(FLAG_LONG_LEGS_SCARED)) + { + if (npc.controllerID == -1) npc.pathfinder.EvadeTarget(targetPos, STATUS_OBEYED); + else npc.pathfinder.FindGridPath(targetPos, LONG_LEGS_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + return; + } + if (npc.HasEntityFlags(FLAG_CONFUSION) || isCalm) return long_legs_wander(npc); + + npc.pathfinder.FindGridPath(targetPos, LONG_LEGS_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + bool isBursting = npc.controllerID != -1 ? long_legs_is_steered_attack(npc) + : npc.pathfinder.hasDirectPath && Random() % LONG_LEGS_BURST_ODDS == 0; + if (isBursting) npc.state = NPC_STATE_ATTACK; +} + +// Laying: a spider (sometimes two) at its event, or a Sack and white creep for the small one. +static void baby_long_legs_lay(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_SPIDER_COUGH, 1, 2, false, 1); + if (npc.variant == LONG_LEGS_SMALL) + { + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BOIL, .variant = 2, .seed = Random()}); + g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_WHITE, + .seed = Random()}); + return; + } + if (npc.variant != 0) return; + + Vector velocity = random_direction(); + g_game->Spawn( + {.position = npc.pos, .velocity = velocity, .spawner = &npc, .type = ENTITY_SPIDER, .seed = Random()}); + if (Random() % LONG_LEGS_SECOND_SPIDER_ODDS != 0) return; + g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(velocity, -1), + .spawner = &npc, + .type = ENTITY_SPIDER, + .seed = Random()}); +} + +// Bursting: a ring of eight lobbed shots at 8 to 10 (a cross of four for the small one). +static void crazy_long_legs_burst(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + params.fallingAccelModifier = LONG_LEGS_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = LONG_LEGS_SHOT_FALL; + params.heightModifier = LONG_LEGS_SHOT_HEIGHT; + float roll = random_unit(); + Vector velocity = vector_make(roll * LONG_LEGS_SHOT_SPEED_RANGE + LONG_LEGS_SHOT_SPEED, 0); + npc.FireProjectiles(npc.pos, velocity, npc.variant != 0 ? PROJECTILES_CROSS : PROJECTILES_EIGHT, params); +} + +// 00531ab0 The long legs' AI: Baby Long Legs run and lay spiders, Crazy Long Legs chase and burst into shots. Bursting +// Sack and confusion leave them wandering, fear and shrinking make the crazy ones run. +void npc_baby_long_legs_update(Entity_NPC& npc) +{ + bool isCalm = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_BURSTING_SACK, LAZARUS_SHARE_CHECK) && + !npc.IsFriendly(); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + return; + } + if (npc.state == NPC_STATE_MOVE) + { + npc.sprite.playbackSpeed = 1; + if (npc.type == ENTITY_BABY_LONG_LEGS) baby_long_legs_walk(npc, isCalm); + else crazy_long_legs_walk(npc, isCalm); + npc.AnimWalkFrame("Walk", "Walk", LONG_LEGS_WALK_THRESHOLD); + npc.friction = LONG_LEGS_FRICTION; + return; + } + if (npc.state != NPC_STATE_ATTACK) return; + + bool isLayer = npc.type == ENTITY_BABY_LONG_LEGS; + npc.sprite.Play(isLayer ? "Lay Egg" : "Attack"); + if (npc.controllerID != -1) npc.sprite.playbackSpeed = LONG_LEGS_STEERED_PLAYBACK; + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered(isLayer ? "Lay" : "Shoot")) + { + if (isLayer) baby_long_legs_lay(npc); + else crazy_long_legs_burst(npc); + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + npc.friction *= LONG_LEGS_ATTACK_FRICTION; +} diff --git a/src/npc_basement.h b/src/npc_basement.h index 68d587e..f590709 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -11,6 +11,42 @@ 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); +void npc_round_worm_update(Entity_NPC& npc); +void npc_ring_fly_update(Entity_NPC& npc); +void npc_skinny_update(Entity_NPC& npc); +void npc_brain_update(Entity_NPC& npc); +void npc_sub_horf_update(Entity_NPC& npc); +void npc_army_fly_update(Entity_NPC& npc); +void npc_bulb_update(Entity_NPC& npc); +void npc_mama_fly_update(Entity_NPC& npc); +void npc_portal_update(Entity_NPC& npc); +void npc_swarm_update(Entity_NPC& npc); +void npc_boil_update(Entity_NPC& npc); +void npc_walking_boil_update(Entity_NPC& npc); +void npc_baby_long_legs_update(Entity_NPC& npc); +void npc_movable_tnt_update(Entity_NPC& npc); + +// spawn_small_maggot_jump: a small maggot leaping from a position, a height up, onto a spot it keeps clear. +Entity_NPC* small_maggot_jump_spawn(const Vector& position, float height, const Vector& spot); + +// Lord of the Flies takes a fly as a blue fly of its own. Whether it did. +bool npc_fly_beelzebub_take(Entity_NPC& npc); + +// A Butter Bean fart (Game::ButterBeanFart's arguments): where, from whom, how far it reaches, whether its cloud +// shows, and whether it knocks enemies away hard. +struct ButterBeanFart +{ + Vector position{}; + Entity* source = nullptr; + float radius = 0; + bool isShowEffect = true; + bool isSuperKnockback = false; +}; + +void game_butter_bean_fart(const ButterBeanFart& fart); + +// Room::GetLaserTarget: where a beam from a position along a direction first meets a pit, block or wall. +Vector room_laser_target_get(const Vector& position, const Vector& direction); // Keeps an overlay animation playing, restarting it once it ends or another shows. inline void npc_overlay_loop(ANM2& sprite, std::string_view name) @@ -23,10 +59,43 @@ inline void npc_overlay_loop(ANM2& sprite, std::string_view name) sprite.overlayAnimState.isPlaying = true; } +// Keeps an animation playing, restarting it once it ends (when it loops) or another shows. +inline void npc_anim_loop(ANM2& sprite, std::string_view name) +{ + const AnimationData* data = sprite.animState.animData; + bool isShown = data && data->name == name && (!data->isLooping || sprite.animState.isPlaying); + if (isShown || !sprite.SetAnimation(name, SWITCH_KEEP_FRAME)) return; + + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; +} + +// Isaac::GetAxisAlignedUnitVectorFromDir: the unit step of a direction (left, up, right, down), none for others. +inline Vector vector_from_direction(int direction) +{ + switch (direction) + { + case 0: + return vector_make(-1, 0); + case 1: + return vector_make(0, -1); + case 2: + return vector_make(1, 0); + case 3: + return vector_make(0, 1); + default: + return vector_make(0, 0); + } +} + // 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. +// The green of the splats of the sickly enemies (g_colorGreenSplat). +constexpr ColorMod COLOR_GREEN_SPLAT = {{1, 1, 1, 1}, {0.63f, 0.85f, 0.32f, 1}, {0, 0, 0}}; + +// The shoot and groan actions a controlled enemy reads, and the flags that keep an enemy off its target. constexpr int CONTROLLER_ACTION_SHOOT = 9; +constexpr int CONTROLLER_ACTION_GROAN = 10; constexpr uint64_t FLAG_DISTRACTED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; diff --git a/src/npc_boil.cpp b/src/npc_boil.cpp new file mode 100644 index 0000000..c1bf0e5 --- /dev/null +++ b/src/npc_boil.cpp @@ -0,0 +1,331 @@ +#include "npc_caves.h" +#include "game.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" + +// The Boil family: the Boil spits a spray of blood, the Gut a big exploding glob, the Sack a spider. +constexpr int BOIL_GUT = 1; +constexpr int BOIL_SACK = 2; +constexpr ColorMod GUT_SPLAT = {{0.2f, 1, 0.2f, 1}, {0, 0, 0, 0}, {0, 0.5f, 0}}; +constexpr ColorMod SACK_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 1, 1}}; +constexpr ColorMod GUT_GLOB_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; +constexpr uint64_t FLAG_BOIL_CALM = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// A Boil starts at 7 health (up to 80% of its health on Hard) and grows back to full, faster the longer it grows (half +// as fast for Gurdy's), its shrink frame showing how grown it is. Blasts from enemies don't hurt it. +constexpr float BOIL_START_HEALTH = 7; +constexpr float BOIL_HARD_SHARE = 0.8f; +constexpr float BOIL_GROWTH = 1.2f; +constexpr float BOIL_GROWTH_STEP = 0.02f; +constexpr float BOIL_GURDY_GROWTH_STEP = 0.01f; +constexpr float BOIL_GROWTH_DAMP = 0.8f; +constexpr float BOIL_SHRINK_FRAMES = 13; +constexpr float BOIL_FRICTION = 0.8f; + +// Grown, it attacks one frame in 50 when its target is within 230 (a quarter of those beyond), a Sack not with 8 or +// more enemies around and only one time in as many as there are. Its target counts as near within 230 to 250. +constexpr uint32_t BOIL_ATTACK_ODDS = 50; +constexpr float BOIL_ATTACK_RANGE = 230; +constexpr float BOIL_CONTROL_RANGE = 1000; +constexpr int SACK_ENEMY_CAP = 8; +constexpr float BOIL_NEAR = 250; +constexpr float BOIL_NEAR_RANGE = 20; +constexpr float BOIL_STEER_REACH = 100; +constexpr float BOIL_SPRAY_TRAJECTORY = 10; +constexpr int BOIL_SPRAY_SHOTS = 3; +constexpr float GUT_VOLUME = 0.7f; +constexpr int GUT_COOLDOWN = -50; +constexpr float GUT_SLOW = 0.55f; +constexpr float GUT_SPEED_MIN = 0.6f; +constexpr float GUT_SCALE = 1.6f; +constexpr float GUT_FALL_ACCEL = -0.3f; +constexpr float GUT_FALL_SHARE = 0.7f; +constexpr float GUT_FALL = -13; +constexpr float SACK_NEAR_STEP = 70; +constexpr float SACK_FAR_STEP = 100; +constexpr float SACK_STEER_REACH = 80; +constexpr float SACK_SPIDER_RISE = -8; +constexpr float SACK_SPIDER_HEIGHT = -10; +constexpr float SACK_SPIDER_SHARE = 0.04f; + +// Whether a hit is an explosion an enemy set off (not the player's, a familiar's, a friend's nor TNT), which Boils +// shrug off. +static bool boil_is_enemy_blast(const DamageEvent& event) +{ + return event.damageFlags & DAMAGE_EXPLOSION && !(event.source.flags & ENTITY_REF_FRIENDLY) && + event.source.type != ENTITY_PLAYER && event.source.spawnerType != ENTITY_PLAYER && + event.source.spawnerType != ENTITY_FAMILIAR && !(event.damageFlags & DAMAGE_TNT); +} + +// Enemy blasts do not hurt it, and any hit that lands restarts its growth. +static void boil_damage_filter(Entity_NPC& npc) +{ + if (npc.pendingDamage <= 0 || npc.damageEvents.empty()) return; + + float taken = 0; + for (DamageEvent& event : npc.damageEvents) + if (boil_is_enemy_blast(event)) event.damage = 0; + else taken += event.damage; + if (taken > 0) npc.v1.x = 0; +} + +// Growing back: health rises by a growth that speeds up as it grows, the shrink frame following it. +static void boil_grow(Entity_NPC& npc) +{ + float growth = npc.v1.x; + npc.health = std::min(growth * BOIL_GROWTH * npc.speedMultiplier + npc.health, npc.maxHitPoints); + float step = npc.spawnerType == ENTITY_GURDY ? BOIL_GURDY_GROWTH_STEP : BOIL_GROWTH_STEP; + npc.v1.x = npc.speedMultiplier * step + growth; + if (npc.variant == BOIL_SACK) npc.v1.x *= npc_friction_scaled(BOIL_GROWTH_DAMP, npc.speedMultiplier); + npc.v1.x *= npc_friction_scaled(BOIL_GROWTH_DAMP, npc.speedMultiplier); + + int grown = (int)(std::max(npc.health / npc.maxHitPoints, 0.0f) * BOIL_SHRINK_FRAMES); + if (npc.sprite.SetAnimation("Shrink", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat((float)((int)BOIL_SHRINK_FRAMES - grown)); + npc.sprite.animState.isPlaying = false; + } +} + +// Fully grown and idle: it may start an attack (a Sack crowded or unlucky only shakes), showing its full grown frame. +static void boil_attack_pick(Entity_NPC& npc, float distance) +{ + bool isInRange = false; + if (npc.controllerID != -1) isInRange = npc.IsTargetInAttackRange(BOIL_CONTROL_RANGE, 7, false); + else if (Random() % BOIL_ATTACK_ODDS == 0) isInRange = distance < BOIL_ATTACK_RANGE || (Random() & 3) == 0; + + bool isShaking = npc.controllerID != -1 && npc.IsControllerActionPressed(CONTROLLER_ACTION_GROAN); + if (!isShaking && isInRange && npc.variant == BOIL_SACK) + { + int enemies = npc.GetAliveEnemyCount(); + isShaking = enemies >= SACK_ENEMY_CAP || random_below(enemies) != 0; + } + if (isShaking) npc.state = NPC_STATE_ATTACK2; + else if (isInRange) + { + npc.state = NPC_STATE_ATTACK; + npc.UpdateControllerMovement(true); + } + + if (npc.sprite.SetAnimation("Shrink", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } +} + +// What a Boil's attack aims at: the spot its shots land on, whether its target is near, whether a player steers its +// spider, and how high that spider leaps from. +struct BoilShot +{ + Vector target{}; + float spiderHeight = 0; + bool isNear = false; + bool isSteered = false; +}; + +// The Gut's glob: one big slow exploding green shot, a random speed when its target is near. +static void gut_glob(Entity_NPC& npc, const BoilShot& shot) +{ + Entity_Projectile* glob = npc.FireBossProjectiles(1, shot.target, BOIL_SPRAY_TRAJECTORY, ProjectileParams()); + glob->projectileFlags |= PROJECTILE_EXPLODE; + glob->scale = GUT_SCALE; + Vector velocity = vector_scale(glob->velocity, GUT_SLOW); + if (shot.isNear) velocity = vector_scale(velocity, random_unit() + GUT_SPEED_MIN); + glob->velocity = velocity; + glob->fallingAccel += GUT_FALL_ACCEL; + glob->fallingSpeed = glob->fallingSpeed * GUT_FALL_SHARE + GUT_FALL; + glob->SetColor(GUT_GLOB_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// The Sack's spider: it leaps out onto a free spot between it and its target (near itself when far), or where its +// player steers. +static void sack_spider(Entity_NPC& npc, const BoilShot& shot) +{ + FreeSpotSearch search{.position = npc.pos, .step = SACK_FAR_STEP}; + if (shot.isSteered) + search = {.position = vector_add(npc.pos, vector_scale(npc.controllerMovement, SACK_STEER_REACH))}; + else if (shot.isNear) + search = {.position = vector_scale(vector_add(npc.GetPlayerTarget()->pos, npc.pos), 0.5f), + .step = SACK_NEAR_STEP}; + Vector spot = room_free_pickup_position_find(search); + + auto* spider = static_cast( + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_SPIDER, .seed = Random()})); + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(spot), GRID_PATH_FREED); + spider->targetPosition = spider->pos; + spider->pos = npc.pos; + spider->posOffset.y += shot.spiderHeight; + spider->state = NPC_STATE_JUMP; + spider->v2.y = SACK_SPIDER_RISE; + spider->velocity = vector_scale(vector_sub(spider->targetPosition, npc.pos), SACK_SPIDER_SHARE); + spider->v1 = spider->velocity; +} + +// The attack's "Shoot": the Boil's spray of three or four, the Gut's glob or the Sack's spider. +static void boil_shoot(Entity_NPC& npc, const BoilShot& shot) +{ + if (npc.variant == BOIL_GUT) + { + npc.PlaySound(SOUND_HEARTOUT, GUT_VOLUME, 2, false, 1); + return gut_glob(npc, shot); + } + if (npc.variant == BOIL_SACK) + { + npc.PlaySound(SOUND_BOIL_HATCH, 1, 2, false, 1); + return sack_spider(npc, shot); + } + + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + int shots = (int)(Random() & 1) + BOIL_SPRAY_SHOTS; + npc.FireBossProjectiles(shots, shot.target, BOIL_SPRAY_TRAJECTORY, params); +} + +// Whether its target counts as near for a shot: within 230 to 250, never for Gurdy's. +static bool boil_is_target_near(Entity_NPC& npc, float distance) +{ + return distance < BOIL_NEAR - random_unit() * BOIL_NEAR_RANGE && npc.spawnerType != ENTITY_GURDY; +} + +// A Boil's shot: on its target when near, else nowhere in particular. A controlled one throws 100 times that from +// itself (the original scales the target's position, not its player's steering). +static void boil_attack_shoot(Entity_NPC& npc, float distance) +{ + BoilShot shot{.spiderHeight = SACK_SPIDER_HEIGHT, .isNear = boil_is_target_near(npc, distance)}; + shot.isSteered = !vector_is_zero(npc.controllerMovement); + if (shot.isNear) shot.target = npc.GetPlayerTarget()->pos; + if (shot.isSteered) shot.target = vector_add(vector_scale(shot.target, BOIL_STEER_REACH), npc.pos); + if (npc.variant == BOIL_GUT) npc.projectileCooldown = GUT_COOLDOWN; + boil_shoot(npc, shot); +} + +// 00517150 The Boil family's AI: they sit and grow back to full health, then spray blood, lob an exploding glob or +// throw out a spider. A hit restarts their growth, and blasts from other enemies do not hurt them. +void npc_boil_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + float health = BOIL_START_HEALTH; + if (g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER) + { + float roll = random_unit(); + health = (std::max(npc.maxHitPoints * BOIL_HARD_SHARE, BOIL_START_HEALTH) - BOIL_START_HEALTH) * roll + + BOIL_START_HEALTH; + } + npc.health = health; + npc.v1.x = 0; + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_IDLE; + if (npc.variant == BOIL_GUT) npc.splatColor = GUT_SPLAT; + else if (npc.variant == BOIL_SACK) npc.splatColor = SACK_SPLAT; + return; + } + + npc.friction *= BOIL_FRICTION; + boil_damage_filter(npc); + float distance = vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (npc.health < npc.maxHitPoints) + { + boil_grow(npc); + npc.state = NPC_STATE_IDLE; + } + else if (npc.state == NPC_STATE_IDLE && !npc.HasEntityFlags(FLAG_BOIL_CALM)) boil_attack_pick(npc, distance); + else + { + bool isAttacking = npc.state == NPC_STATE_ATTACK; + npc_anim_loop(npc.sprite, isAttacking ? "Shoot" : "Shake"); + if (isAttacking) + { + if (npc.controllerID == -1) npc.controllerMovement = {}; + else + { + Vector input = npc.GetControllerMovementInput(0.1f); + if (!vector_is_zero(input)) npc.controllerMovement = input; + } + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) boil_attack_shoot(npc, distance); + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + } + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} + +// A Walking Boil wanders (running from its target when scared), attacking one frame in 50 near its target (a quarter of +// those beyond 230), a Walking Sack only with fewer than 8 enemies around and one time in as many as there are. Its +// player steers its shots 150 out and its spider 80 out. +constexpr float WALKING_BOIL_FRICTION = 0.75f; +constexpr float WALKING_BOIL_SCARED_FRICTION = 0.8f; +constexpr float WALKING_BOIL_WALK_THRESHOLD = 0.1f; +constexpr float WALKING_BOIL_STEER_REACH = 150; +constexpr float WALKING_SACK_SPIDER_HEIGHT = -30; +constexpr float BOIL_STEER_DEADZONE = 0.1f; + +// The player's steering for its next shot, none without a player. +static Vector walking_boil_steering(Entity_NPC& npc) +{ + return npc.controllerID == -1 ? vector_make(0, 0) : npc.GetControllerMovementInput(BOIL_STEER_DEADZONE); +} + +// Walking about until it decides to attack. +static void walking_boil_walk(Entity_NPC& npc, float distance) +{ + 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 *= WALKING_BOIL_SCARED_FRICTION; + } + npc.AnimWalkFrame("WalkHori", "WalkVert", WALKING_BOIL_WALK_THRESHOLD); + + bool isReady = npc.controllerID == -1 ? Random() % BOIL_ATTACK_ODDS == 0 + : npc.IsTargetInAttackRange(BOIL_CONTROL_RANGE, 7, false); + bool isAttacking = isReady && !npc.HasEntityFlags(FLAG_BOIL_CALM) && + (npc.controllerID != -1 || distance < BOIL_ATTACK_RANGE || (Random() & 3) == 0); + if (isAttacking && npc.variant == BOIL_SACK) + { + int enemies = npc.GetAliveEnemyCount(); + isAttacking = enemies < SACK_ENEMY_CAP && random_below(enemies) == 0; + } + if (isAttacking) + { + npc.controllerMovement = walking_boil_steering(npc); + npc.state = NPC_STATE_ATTACK; + } + npc.projectileCooldown = 0; +} + +// 0051b570 The Walking Boil family's AI: they wander like their sitting kin never could, then stop to spray blood, lob +// an exploding glob or throw out a spider. Blasts from other enemies do not hurt them. +void npc_walking_boil_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + if (npc.variant == BOIL_GUT) npc.splatColor = GUT_SPLAT; + else if (npc.variant == BOIL_SACK) npc.splatColor = SACK_SPLAT; + return; + } + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if (boil_is_enemy_blast(event)) event.damage = 0; + npc.friction *= WALKING_BOIL_FRICTION; + float distance = vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (npc.state == NPC_STATE_MOVE) return walking_boil_walk(npc, distance); + + Vector steering = walking_boil_steering(npc); + if (npc.controllerID == -1 || !vector_is_zero(steering)) npc.controllerMovement = steering; + npc_anim_loop(npc.sprite, "Shoot"); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) + { + BoilShot shot{.spiderHeight = WALKING_SACK_SPIDER_HEIGHT, .isNear = boil_is_target_near(npc, distance)}; + shot.isSteered = npc.controllerID != -1; + if (shot.isNear) shot.target = npc.GetPlayerTarget()->pos; + if (shot.isSteered && !vector_is_zero(npc.controllerMovement)) + shot.target = vector_add(vector_scale(npc.controllerMovement, WALKING_BOIL_STEER_REACH), npc.pos); + boil_shoot(npc, shot); + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; +} diff --git a/src/npc_boom_fly.cpp b/src/npc_boom_fly.cpp new file mode 100644 index 0000000..d4fba51 --- /dev/null +++ b/src/npc_boom_fly.cpp @@ -0,0 +1,471 @@ +#include "npc_caves.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "player_manager.h" +#include "room.h" +#include "sfx_manager.h" + +// The Boom Fly's variants: the plain and red ones, the drowned one, the Dragon Fly, the Bone Fly, the sick one and +// the tainted one. +enum BoomFlyVariant : int +{ + BOOM_FLY_PLAIN, + BOOM_FLY_RED, + BOOM_FLY_DROWNED, + BOOM_FLY_DRAGON, + BOOM_FLY_BONE, + BOOM_FLY_SICK, + BOOM_FLY_TAINTED +}; + +// It bounces along the diagonals, a little slower drowned or while Skatole calms it, and flees what scares it. +constexpr float BOOM_FLY_FRICTION = 0.9f; +constexpr float BOOM_FLY_ACCEL = 0.45f; +constexpr float BOOM_FLY_DROWNED_ACCEL = 0.4f; +constexpr float BOOM_FLY_SKATOLE_ACCEL = 0.25f; +constexpr float BOUNCE_STEER_SHARE = 0.5f; +constexpr float BOOM_FLY_FLEE_RANGE = 120; +constexpr float BOOM_FLY_FLEE_SCALE = 0.02f; +constexpr float BOOM_FLY_ATTACK_FRICTION = 0.8f; + +// A thrown or dropped Boom Fly: it keeps its throw velocity, or bobs down onto its spot while growing back. +constexpr float BOOM_FLY_BOB_PULL = 0.1f; +constexpr float BOOM_FLY_GROW_FRICTION = 0.7f; +constexpr float BOOM_FLY_DROP_PULL = 0.1f; + +// The Bone Fly shoots a bone at a target within 200 in a clear line close to one of its axes, every third frame. +constexpr int BONE_AIM_FRAMES = 3; +constexpr int BONE_AIM_RANGE_FRAMES = 7; +constexpr float BONE_AIM_LEAD = 16; +constexpr float BONE_AIM_MARGIN = 20; +constexpr float BONE_AIM_AXIS = 20; +constexpr float BONE_AIM_RANGE = 200; +constexpr float BONE_CONTROLLED_RANGE = 1000; +constexpr float BONE_SHOT_SPEED = 10; +constexpr ColorMod BONE_SHOT_COLOR = {{0.91764706f, 0.89411765f, 0.88235295f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The death blasts: each variant's explosion, then its shots, Charger, fire or gas. +constexpr float BLAST_DAMAGE = 40; +constexpr float DROWNED_SHOT_SPEED = 8; +constexpr float DROWNED_HARD_SHOT_SPEED = 10; +constexpr int DROWNED_CHARGER_ODDS = 3; +constexpr int DROWNED_CHARGER_VARIANT = 1; +constexpr float DROWNED_CHARGER_HEALTH = 0.5f; +constexpr float DRAGON_SHOT_SCALE = 2; +constexpr float DRAGON_SHOT_FALL = 1; +constexpr ColorMod DRAGON_SHOT_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.3f, 0}}; +constexpr float BONE_RING_SPEED = 9; +constexpr float BONE_RING_HARD_SPEED = 10; +constexpr float BONE_RING_SHOTS = 3; +constexpr float RED_RING_SHOTS = 6; +constexpr float RING_SPEED = 8; +constexpr float RING_HARD_SPEED = 10; +constexpr ColorMod SICK_BLAST_COLOR = {{1, 1, 1, 1}, {1, 1, 0, 0.5f}, {0, 0, 0}}; +constexpr ColorMod SICK_SHOT_COLOR = {{1, 1, 1, 1}, {1.5f, 2, 1, 1}, {0, 0, 0}}; +constexpr float SICK_SHOT_SPEED = 10; +constexpr float SICK_SHOTS = 6; +constexpr int SICK_CLOUDS = 8; +constexpr float SICK_CLOUD_TURN = 45; +constexpr float SICK_CLOUD_JITTER = 16; +constexpr float SICK_CLOUD_JITTER_HALF = 8; +constexpr float SICK_CLOUD_SPEED = 13; +constexpr float SICK_CLOUD_SPEED_RANGE = 6; +constexpr int SICK_CLOUD_TIMEOUT = 300; +constexpr int SICK_CLOUD_CHIMERA_TIMEOUT = 150; + +// The sick Boom Fly trails gas every 10 frames of its own time. +constexpr float SICK_TRAIL_INTERVAL = 10; +constexpr int SICK_TRAIL_TIMEOUT = 90; +constexpr float SICK_TRAIL_SCALE = 0.7f; + +// The tainted one plays its explosion, flashing tracers along the four axes, then blows up big. +constexpr int TAINTED_TRACERS = 4; +constexpr float TAINTED_TRACER_RISE = 30; +constexpr int TAINTED_TRACER_TIMEOUT = 25; +constexpr ColorMod TAINTED_TRACER_COLOR = {{0.8f, 0.4f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float TAINTED_DAMAGE = 80; +constexpr float TAINTED_RADIUS = 1.5f; +constexpr int TAINTED_SHAKE = 10; +constexpr int TAINTED_DUSTS = 10; +constexpr float TAINTED_DUST_SPREAD = 0.8f; +constexpr float TAINTED_DUST_SHIFT = 0.4f; +constexpr float TAINTED_DUST_TURN = 36; +constexpr float TAINTED_DUST_SPEED = 10; +constexpr float TAINTED_DUST_SPEED_RANGE = 5; +constexpr float TAINTED_DUST_SPIN = 2; +constexpr float TAINTED_DUST_SPIN_RANGE = 10; +constexpr int TAINTED_DUST_TIMEOUT = 15; +constexpr int TAINTED_DUST_DEPTH = -600; +constexpr float TAINTED_DUST_SCALE = 2; +constexpr ColorMod TAINTED_DUST_COLOR = {{0.8f, 0.68f, 0.65f, 0.6f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int TAINTED_WAVES = 4; +constexpr int TAINTED_BLOOM_FRAMES = 6; +constexpr float TAINTED_FRICTION = 0.6f; +constexpr int EFFECT_EXPLOSION_WAVE = 187; +constexpr int EFFECT_GENERIC_TRACER = 198; +constexpr float TAINTED_WAVE_TURN = 90; + +constexpr ColorMod DRAGON_SPLAT_COLOR = {{0, 0, 0, 1.1f}, {0, 0, 0, 0}, {1, 0.5137255f, 0.003921569f}}; +constexpr ColorMod GREEN_SPLAT_COLOR = {{1, 1, 1, 1}, {0.63f, 0.85f, 0.32f, 1}, {0, 0, 0}}; + +// The first frame: it flies off in a random direction, with the blood of its kind. +static void boom_fly_init(Entity_NPC& npc) +{ + if (npc.variant == BOOM_FLY_DRAGON) npc.splatColor = DRAGON_SPLAT_COLOR; + else if (npc.variant == BOOM_FLY_BONE) npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + else if (npc.variant == BOOM_FLY_SICK) npc.splatColor = GREEN_SPLAT_COLOR; + + npc.state = NPC_STATE_MOVE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.velocity = random_direction(); +} + +// A thrown Boom Fly flies straight until it hits the grid. A dropped one bobs down onto its spot growing back to size. +static void boom_fly_carried_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_SUICIDE) + { + npc.velocity = npc.targetPosition; + if (!npc.isCollidesWithGrid) return; + + npc.targetPosition = {}; + npc.state = NPC_STATE_MOVE; + } + else if (npc.state == NPC_STATE_SPECIAL) + { + npc.v1.x -= npc.posOffset.y * BOOM_FLY_BOB_PULL * npc.speedMultiplier; + npc.posOffset.y += npc.v1.x * npc.speedMultiplier; + float grow = npc_friction_scaled(BOOM_FLY_GROW_FRICTION, npc.speedMultiplier); + float scale = (1 - npc.sprite.scale.x) * (1 - grow) + npc.sprite.scale.x; + npc.sprite.scale = vector_make(scale, scale); + npc.velocity = vector_scale(vector_sub(npc.targetPosition, npc.pos), BOOM_FLY_DROP_PULL); + } +} + +// The Bone Fly's bone at its target (or where its controller steers), once its attack animation shoots. +static void boom_fly_attack_update(Entity_NPC& npc) +{ + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot") && + npc.variant == BOOM_FLY_BONE) + { + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (!vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + + ProjectileParams params; + params.variant = PROJECTILE_BONE; + params.color = BONE_SHOT_COLOR; + npc.PlaySound(SOUND_SCAMPER, 1, 2, false, 1); + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(aim), BONE_SHOT_SPEED), PROJECTILES_SINGLE, + params); + } + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_MOVE; + return; + } + npc.friction *= BOOM_FLY_ATTACK_FRICTION; +} + +// Whether the Bone Fly sees its target: every third frame, within 200 in a clear line, close to one of its axes from +// where the target is heading. A friendly one leaves players alone. +static bool bone_fly_is_aimed(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + if (!npc.IsTargetInAttackRange(BONE_CONTROLLED_RANGE, BONE_AIM_RANGE_FRAMES, false)) return false; + npc.UpdateControllerMovement(true); + return true; + } + if (!npc.IsFrame(BONE_AIM_FRAMES, (int)npc.index)) return false; + if (npc.HasEntityFlags(FLAG_FRIENDLY) && npc.GetPlayerTarget()->type == ENTITY_PLAYER) return false; + + Room& room = *g_game->room; + Vector target = npc.GetPlayerTarget()->pos; + Vector lead = npc.GetPlayerTarget()->velocity; + float share = random_unit() * BONE_AIM_LEAD; + Vector spot = room.GetClampedPositionImpl(vector_add(target, vector_scale(lead, share)), BONE_AIM_MARGIN, + BONE_AIM_MARGIN, BONE_AIM_MARGIN, BONE_AIM_MARGIN); + Vector delta = vector_sub(npc.pos, spot); + if (std::abs(delta.x) >= BONE_AIM_AXIS && std::abs(delta.y) >= BONE_AIM_AXIS) return false; + if (vector_length(delta) >= BONE_AIM_RANGE) return false; + return room_check_line(npc.pos, spot, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); +} + +// The tainted one's blast once its explosion animation ends: a big explosion, a shaken screen, dust and four waves +// along the axes, a ground poof and a flash of bloom. +static void tainted_explode(Entity_NPC& npc) +{ + npc.Kill(EntityRef()); + explosion_effects({.position = npc.pos, + .source = &npc, + .damage = TAINTED_DAMAGE, + .radiusMultiplier = TAINTED_RADIUS, + .isLineCheck = false}); + game_shake_screen(TAINTED_SHAKE); + + for (int i = 0; i < TAINTED_DUSTS; i++) + { + float angle = (random_unit() * TAINTED_DUST_SPREAD + ((float)i - TAINTED_DUST_SHIFT)) * TAINTED_DUST_TURN * + DEGREES_TO_RADIANS; + float sine = std::sin(angle); + uint32_t seed = Random(); + float speed = random_unit() * TAINTED_DUST_SPEED_RANGE + TAINTED_DUST_SPEED; + Vector velocity = vector_make(std::cos(angle) * speed, sine * speed); + auto* dust = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + dust->rotation = random_unit() * TAINTED_DUST_SPIN_RANGE + TAINTED_DUST_SPIN; + dust->SetTimeout((int)(Random() % TAINTED_DUST_TIMEOUT) + TAINTED_DUST_TIMEOUT); + dust->SetColor(TAINTED_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->renderZOffset = TAINTED_DUST_DEPTH; + dust->sprite.scale = vector_make(TAINTED_DUST_SCALE, TAINTED_DUST_SCALE); + } + for (int i = 0; i < TAINTED_WAVES; i++) + { + Entity* wave = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_EXPLOSION_WAVE, + .seed = Random()}); + wave->targetPosition = vector_from_angle((float)i * TAINTED_WAVE_TURN); + wave->Update(); + } + npc.MakeGroundPoof(npc.pos, COLOR_DEFAULT, 1); + g_game->bloomDuration = TAINTED_BLOOM_FRAMES; + g_game->bloomTimer = TAINTED_BLOOM_FRAMES; + g_game->bloomStrength = 1; +} + +// The Bone Fly's ring of three bones, turned to face its target's side. +static void bone_fly_burst(Entity_NPC& npc) +{ + Random(); + float angle = 0; + switch (vector_to_direction(vector_sub(npc.GetPlayerTarget()->pos, npc.pos))) + { + case DIRECTION_LEFT: + angle = PI_F; + break; + case DIRECTION_UP: + angle = -PI_F / 2; + break; + case DIRECTION_RIGHT: + break; + case DIRECTION_DOWN: + angle = PI_F / 2; + break; + default: + angle = random_unit() * PI_F; + } + ProjectileParams params; + params.variant = PROJECTILE_BONE; + params.circleAngle = angle; + params.color = BONE_SHOT_COLOR; + float speed = game_is_hard_mode() ? BONE_RING_HARD_SPEED : BONE_RING_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, BONE_RING_SHOTS), PROJECTILES_RING, params); +} + +// The sick Boom Fly's death: a gassy blast, a ring of shots (but for Chimera's) and eight gas clouds around it. +static void sick_fly_burst(Entity_NPC& npc) +{ + explosion_effects({.color = SICK_BLAST_COLOR, .position = npc.pos, .source = &npc, .damage = BLAST_DAMAGE}); + bool isChimeras = npc.spawnerType == ENTITY_CHIMERA; + if (!isChimeras) + { + ProjectileParams params; + params.color = SICK_SHOT_COLOR; + npc.FireProjectiles(npc.pos, vector_make(SICK_SHOT_SPEED, SICK_SHOTS), PROJECTILES_RING, params); + } + for (int i = 0; i < SICK_CLOUDS; i++) + { + float turn = random_unit() * SICK_CLOUD_JITTER - SICK_CLOUD_JITTER_HALF + (float)i * SICK_CLOUD_TURN; + float speed = random_unit() * SICK_CLOUD_SPEED_RANGE + SICK_CLOUD_SPEED; + auto* cloud = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(vector_from_angle(turn), speed), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + cloud->SetTimeout(isChimeras ? SICK_CLOUD_CHIMERA_TIMEOUT : SICK_CLOUD_TIMEOUT); + cloud->Update(); + } +} + +// The tainted one does not die yet: it turns untouchable and starts its explosion, with tracers flashing where the +// blast will reach. +static void tainted_fly_start(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_ATTACK2) return; + + npc.state = NPC_STATE_ATTACK2; + npc_anim_restart(npc.sprite, "Explode"); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isDead = false; + npc.RemoveStatusEffects(); + npc.isInvincible = true; + for (int i = 0; i < TAINTED_TRACERS; i++) + { + Vector axis = direction_unit(i); + auto* tracer = static_cast(g_game->Spawn({.position = vector_make(npc.pos.x, npc.pos.y - TAINTED_TRACER_RISE), + .type = ENTITY_EFFECT, + .variant = EFFECT_GENERIC_TRACER, + .seed = Random()})); + tracer->FollowParent(&npc); + tracer->sprite.color = TAINTED_TRACER_COLOR; + tracer->targetPosition = axis; + tracer->SetTimeout(TAINTED_TRACER_TIMEOUT); + tracer->Update(); + } +} + +// What a dying Boom Fly leaves by variant: an explosion, and the drowned one's cross of shots and now and then a +// drowned Charger, the Dragon Fly's fire, the Bone Fly's bones, the sick one's gas, the red one's ring of shots. The +// tainted one starts exploding instead. A shrunk one only dies. +static void boom_fly_death(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_SHRINK) && npc.variant != BOOM_FLY_BONE) return; + + Explosion blast = {.color = npc.color, .position = npc.pos, .source = &npc, .damage = BLAST_DAMAGE}; + switch (npc.variant) + { + case BOOM_FLY_PLAIN: + return explosion_effects(blast); + case BOOM_FLY_DROWNED: + { + explosion_effects(blast); + ProjectileParams params; + float speed = game_is_hard_mode() ? DROWNED_HARD_SHOT_SPEED : DROWNED_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_PLUS, params); + if (Random() % DROWNED_CHARGER_ODDS != 0 || room_grid_collision_at(npc.pos) != 0) return; + + Entity* charger = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_CHARGER, + .variant = DROWNED_CHARGER_VARIANT, + .seed = Random()}); + charger->Update(); + charger->maxHitPoints *= DROWNED_CHARGER_HEALTH; + charger->health = charger->maxHitPoints; + return; + } + case BOOM_FLY_DRAGON: + { + ProjectileParams params; + params.color = DRAGON_SHOT_COLOR; + params.scale = DRAGON_SHOT_SCALE; + params.fallingAccelModifier = DRAGON_SHOT_FALL; + params.bulletFlags |= npc.subtype != 0 ? PROJECTILE_FIRE_WAVE_X : PROJECTILE_FIRE_WAVE; + return npc.FireProjectiles(npc.pos, {}, PROJECTILES_SINGLE, params); + } + case BOOM_FLY_BONE: + return bone_fly_burst(npc); + case BOOM_FLY_SICK: + return sick_fly_burst(npc); + case BOOM_FLY_TAINTED: + return tainted_fly_start(npc); + default: + { + ProjectileParams params; + float speed = game_is_hard_mode() ? RING_HARD_SPEED : RING_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, RED_RING_SHOTS), PROJECTILES_RING, params); + } + } +} + +// The sick Boom Fly's trail of gas, every 10 frames of its own time. +static void sick_fly_trail(Entity_NPC& npc) +{ + if (npc.GetIntervalTicks(SICK_TRAIL_INTERVAL, 0) == 0) return; + + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit(); + Vector drift = vector_make(std::cos(angle) * reach, std::sin(angle) * reach); + auto* cloud = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = vector_add(drift, drift), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = seed})); + cloud->SetTimeout(SICK_TRAIL_TIMEOUT); + cloud->sprite.scale = vector_make(SICK_TRAIL_SCALE, SICK_TRAIL_SCALE); + cloud->Update(); +} + +// Pushes a bouncer along the diagonal it moves on at a steady acceleration, steered by its controller. A confused +// one wanders instead, and the push reports it did not happen. +bool npc_bounce_push(Entity_NPC& npc, float accel) +{ + bool isControlled = npc.controllerID != -1; + if (npc.HasEntityFlags(FLAG_CONFUSION) && !isControlled) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return false; + } + Vector push = vector_make(npc.velocity.x < 0 ? -accel : accel, npc.velocity.y < 0 ? -accel : accel); + if (isControlled) + { + float steer = vector_length(push) * BOUNCE_STEER_SHARE; + push = vector_add(push, vector_scale(npc.GetControllerInput(0), steer)); + } + npc.AddVelocity_divided(push, false); + return true; +} + +// It bounces along the diagonals, slower drowned or while Skatole calms it, and flees a scaring target within 120. +static void boom_fly_move(Entity_NPC& npc) +{ + float accel = npc.variant == BOOM_FLY_DROWNED ? BOOM_FLY_DROWNED_ACCEL : BOOM_FLY_ACCEL; + bool isCalmed = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK); + if (isCalmed && !npc.HasEntityFlags(FLAG_FRIENDLY)) accel = BOOM_FLY_SKATOLE_ACCEL; + if (!npc_bounce_push(npc, accel) || !npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + float share = std::clamp((BOOM_FLY_FLEE_RANGE - distance) * BOOM_FLY_FLEE_SCALE, 0.0f, 1.0f); + if (distance > 0) away = vector_scale(away, share / distance); + npc.AddVelocity_divided(away, false); +} + +// 0050f280 The Boom Fly's AI: it bounces along the diagonals and explodes as it dies, each variant leaving its own +// blast. The Bone Fly shoots bones, the sick one trails gas, and the tainted one plays a long explosion first. A +// player transformed into Beelzebub charms it. +void npc_boom_fly_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return boom_fly_init(npc); + + Entity_Player* beelzebub = g_game->playerManager.GetRandomPlayer(npc.initSeed); + if (beelzebub && !npc.isDead && !npc.HasEntityFlags(FLAG_FRIENDLY)) + npc.AddCharmed(EntityRef(beelzebub), -1, true, false); + if (!npc.isDead) boom_fly_carried_update(npc); + + npc.friction *= BOOM_FLY_FRICTION; + if (npc.state == NPC_STATE_ATTACK) boom_fly_attack_update(npc); + else if (npc.state == NPC_STATE_ATTACK2) + { + if (npc_anim_is_done(npc)) tainted_explode(npc); + npc.friction *= TAINTED_FRICTION; + } + else + { + npc.sprite.Play("Fly"); + bool isBoneReady = npc.variant == BOOM_FLY_BONE && !npc.HasEntityFlags(FLAG_DISTRACTED); + if (isBoneReady && bone_fly_is_aimed(npc)) + { + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + } + } + + boom_fly_move(npc); + if (npc.IsControllerActionTriggered(CONTROLLER_ACTION_SHOOT)) npc.Kill(EntityRef()); + if (npc.isDead) return boom_fly_death(npc); + if (npc.variant == BOOM_FLY_SICK) sick_fly_trail(npc); +} diff --git a/src/npc_brain.cpp b/src/npc_brain.cpp new file mode 100644 index 0000000..cea24b9 --- /dev/null +++ b/src/npc_brain.cpp @@ -0,0 +1,206 @@ +#include "npc_caves.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_tear.h" +#include "sfx_manager.h" + +// The Brain, the Black Globin's head and the Poison Mind each crawl about bleeding and leaving creep, then lunge. +constexpr uint64_t FLAG_BRAIN_CALM = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; +constexpr uint64_t FLAG_BRAIN_HELD = FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; +constexpr ColorMod POISON_MIND_SPLAT = {{0, 1, 0, 1}, {0, 0, 0, 0}, {0, 0.19607845f, 0}}; + +// They bleed a splat every third frame and keep their cell cheap to walk through. +constexpr float BRAIN_SPLAT_FRAMES = -3; +constexpr float BRAIN_SPLAT_MIN = 0.2f; +constexpr float BRAIN_SPLAT_RANGE = 0.39f; +constexpr int BRAIN_GRID_PATH_LIMIT = 950; + +// The Brain crawls the grid's axes at 0.75 and lunges along one when its target lines up within 200. The Black Globin's +// head chases at 0.5. The Poison Mind drifts diagonally, turning every few seconds, and lunges diagonally. +constexpr float BRAIN_SPEED = 0.75f; +constexpr float BRAIN_FRICTION_X = 0.85f; +constexpr float BRAIN_FRICTION_Y = 0.8f; +constexpr float GLOBIN_HEAD_SPEED = 0.5f; +constexpr float POISON_MIND_FRICTION = 0.8f; +constexpr uint32_t POISON_MIND_TURN_FRAMES = 90; +constexpr float POISON_MIND_DIAGONAL = 0.7853982f; +constexpr float POISON_MIND_PUSH = 0.5f; +constexpr int BRAIN_AIM_FRAMES = 7; +constexpr float BRAIN_AIM_LEAD = 16; +constexpr float BRAIN_MARGIN = 20; +constexpr float BRAIN_LINE_WIDTH = 20; +constexpr float BRAIN_RANGE = 200; +constexpr int BRAIN_SOUND_DELAY = 30; +constexpr float BRAIN_LUNGE_FRICTION = 0.8f; +constexpr float BRAIN_CENTERING = 0.1f; + +// Their creep: every 12 frames (24 in a crowd of five or more), or 6 frames later while fast. +constexpr int BRAIN_CROWD = 5; +constexpr int BRAIN_CREEP_FRAMES = 12; +constexpr int BRAIN_CROWD_CREEP_FRAMES = 24; +constexpr float BRAIN_CREEP_FAST_SQUARED = 9; +constexpr float BRAIN_CREEP_SCALE = 1.23f; +constexpr float POISON_MIND_BLAST_DAMAGE = 40; + +// One of the four axis directions turned by an angle in radians. +static Vector brain_turn(const Vector& direction, float angle) +{ + float c = std::cos(angle); + float s = std::sin(angle); + return vector_make(c * direction.x - s * direction.y, s * direction.x + c * direction.y); +} + +// Where the target will be in a moment, kept in the room. +static Vector brain_target_lead(Entity_NPC& npc) +{ + Vector targetPos = npc.GetPlayerTarget()->pos; + Vector targetVelocity = npc.GetPlayerTarget()->velocity; + Vector lead = vector_add(targetPos, vector_scale(targetVelocity, random_unit() * BRAIN_AIM_LEAD)); + return g_game->room->GetClampedPosition(lead, BRAIN_MARGIN); +} + +// The Poison Mind drifts along a diagonal it changes every few seconds or on a wall (its player's steered one when +// controlled), and lunges diagonally when its target lines up. +static void poison_mind_drift(Entity_NPC& npc) +{ + npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(POISON_MIND_FRICTION, npc.speedMultiplier)); + npc.stateFrame -= npc_ticks_get(npc); + if (npc.stateFrame < 0 || npc.isCollidesWithGrid) + { + npc.stateFrame = (int)(Random() % POISON_MIND_TURN_FRAMES); + npc.targetPosition = brain_turn(vector_from_direction((int)(Random() & 3)), POISON_MIND_DIAGONAL); + } + if (npc.controllerID != -1) + { + npc.targetPosition = npc.GetControllerInput(0); + if (!vector_is_zero(npc.targetPosition)) + { + Vector input = npc.targetPosition; + Vector diagonal = + brain_turn(vector_cardinal(brain_turn(input, -POISON_MIND_DIAGONAL)), POISON_MIND_DIAGONAL); + npc.targetPosition = vector_scale(diagonal, vector_length(input)); + } + } + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, POISON_MIND_PUSH * npc.speedMultiplier)); + + if (!npc.GetIntervalTicks(BRAIN_AIM_FRAMES, (float)(npc.index % BRAIN_AIM_FRAMES)) || npc.controllerID != -1 || + npc.HasEntityFlags(FLAG_BRAIN_CALM)) + return; + Vector gap = vector_sub(npc.pos, brain_target_lead(npc)); + Vector turned = brain_turn(gap, POISON_MIND_DIAGONAL); + if (std::abs(turned.x) >= BRAIN_LINE_WIDTH && std::abs(turned.y) >= BRAIN_LINE_WIDTH) return; + if (vector_length(gap) >= BRAIN_RANGE) return; + + npc.targetPosition = vector_resized(gap, -1); + npc.state = NPC_STATE_ATTACK; + npc_sound_play(SOUND_POISON_MIND_HURT, 1, 2, 1); +} + +// The Brain crawls the grid's axes, squelching on each new spot, and lunges along one when its target lines up. +static void brain_crawl(Entity_NPC& npc) +{ + Vector lastSpot = npc.pathfinder.movementTarget; + npc.pathfinder.MoveRandomlyAxisAligned(BRAIN_SPEED, STATUS_OBEYED); + npc.velocity.x *= npc_friction_scaled(BRAIN_FRICTION_X, npc.speedMultiplier); + npc.velocity.y *= npc_friction_scaled(BRAIN_FRICTION_Y, npc.speedMultiplier); + bool isBrain = npc.type == ENTITY_BRAIN; + if (isBrain && !vector_is_zero(vector_sub(lastSpot, npc.pathfinder.movementTarget))) + npc_sound_play(SOUND_BRAIN_MOVE, 1, BRAIN_SOUND_DELAY, 1); + + if (!npc.IsFrame(BRAIN_AIM_FRAMES, npc.index) || npc.controllerID != -1 || npc.HasEntityFlags(FLAG_BRAIN_CALM)) + return; + Room& room = *g_game->room; + Vector lead = brain_target_lead(npc); + Vector cell = room.GetGridPosition(npc.pathfinder.gridIndex); + Vector gap = vector_sub(cell, lead); + if (std::abs(gap.x) >= BRAIN_LINE_WIDTH && std::abs(gap.y) >= BRAIN_LINE_WIDTH) return; + if (vector_length(gap) >= BRAIN_RANGE || !room_check_line(cell, lead, LINE_MODE_GROUND, 0)) return; + + if (std::abs(gap.x) <= std::abs(gap.y)) npc.targetPosition = vector_make(0, gap.y >= 0 ? -1 : 1); + else npc.targetPosition = vector_make(gap.x >= 0 ? -1 : 1, 0); + npc.state = NPC_STATE_ATTACK; + if (isBrain) npc_sound_play(SOUND_BRAIN_MOVE, 1, BRAIN_SOUND_DELAY, 1); +} + +// The lunge: on along its direction, kept to its cell's line (but the Poison Mind), until it hits a wall or a status +// effect or a forced target or a player stops it. +static void brain_lunge(Entity_NPC& npc) +{ + if (npc.isCollidesWithGrid || npc.HasEntityFlags(FLAG_BRAIN_HELD) || npc.forcedTarget || npc.controllerID != -1) + { + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; + npc.state = NPC_STATE_MOVE; + npc.targetPosition = {}; + return; + } + + npc.friction *= BRAIN_LUNGE_FRICTION; + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, npc.speedMultiplier / npc.friction)); + if (npc.type == ENTITY_POISON_MIND) return; + + Vector cell = g_game->room->GetGridPosition(npc.pathfinder.gridIndex); + if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) + npc.pos.x = cell.x * BRAIN_CENTERING + npc.pos.x * (1 - BRAIN_CENTERING); + else npc.pos.y = npc.pos.y * (1 - BRAIN_CENTERING) + cell.y * BRAIN_CENTERING; +} + +// Red creep (the Poison Mind's green) behind it, every 12 frames or 24 in a crowd, or half way between while fast. +static void brain_creep_update(Entity_NPC& npc) +{ + int interval = npc.GetAliveEnemyCount() < BRAIN_CROWD ? BRAIN_CREEP_FRAMES : BRAIN_CROWD_CREEP_FRAMES; + int offset = (int)(npc.index % (uint32_t)interval); + bool isCreepTick = npc.GetIntervalTicks((float)interval, (float)offset) > 0; + bool isFastTick = npc.GetIntervalTicks((float)interval, (float)(offset + interval / 2)) > 0; + bool isFast = vector_length_squared(npc.velocity) > BRAIN_CREEP_FAST_SQUARED; + if (npc.HasEntityFlags(FLAG_SHRINK) || !(isCreepTick || (isFast && isFastTick))) return; + + int variant = npc.type == ENTITY_POISON_MIND ? EFFECT_CREEP_GREEN : EFFECT_CREEP_RED; + Entity_Effect* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()})); + creep->sprite.scale = vector_make(BRAIN_CREEP_SCALE, BRAIN_CREEP_SCALE); + creep->rotation = 0; + creep->Update(); +} + +// 00512110 The Brain's AI, shared with the Black Globin's head and the Poison Mind: they bleed and leave creep as they +// crawl about (the head chasing), lunging when their target lines up. The Poison Mind bursts into a poison blast. +void npc_brain_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + if (npc.type != ENTITY_POISON_MIND) return; + + npc.splatColor = POISON_MIND_SPLAT; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + return; + } + + if (npc.GetIntervalTicks(BRAIN_SPLAT_FRAMES, 0) != 0) + npc.MakeSplat(random_unit() * BRAIN_SPLAT_RANGE + BRAIN_SPLAT_MIN) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.pos); + if (cell >= 0 && room.gridPaths[cell] <= BRAIN_GRID_PATH_LIMIT) room.gridPaths[cell] = GRID_PATH_FREED; + npc_anim_loop(npc.sprite, "Walk"); + npc.pathfinder.UpdateGridIndex(); + + if (npc.state != NPC_STATE_MOVE) brain_lunge(npc); + else if (npc.type == ENTITY_BLACK_GLOBIN_HEAD) + { + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), GLOBIN_HEAD_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + npc.sprite.isFlipX = npc.velocity.x > 0; + } + else if (npc.type == ENTITY_POISON_MIND) poison_mind_drift(npc); + else brain_crawl(npc); + + brain_creep_update(npc); + if (!npc.isDead || npc.type != ENTITY_POISON_MIND || npc.HasEntityFlags(FLAG_SHRINK)) return; + + Explosion blast{.position = npc.pos, .source = &npc, .damage = POISON_MIND_BLAST_DAMAGE}; + blast.tearFlags[TEAR_POISON] = true; + explosion_effects(blast); +} diff --git a/src/npc_bulb.cpp b/src/npc_bulb.cpp new file mode 100644 index 0000000..a713c4d --- /dev/null +++ b/src/npc_bulb.cpp @@ -0,0 +1,231 @@ +#include "npc_basement.h" +#include "entity_player.h" +#include "game.h" +#include "item_config.h" +#include "manager.h" +#include "room.h" + +// The Bulb, and the Black Bulb that always attacks and bursts into a plus of shots. +constexpr int BULB_BLACK = 6; +constexpr ColorMod BULB_SPLAT = {{0, 0, 0, 0.6f}, {0, 0, 0, 0}, {0.7f, 0.7f, 0}}; +constexpr uint64_t FLAG_BULB_CALM = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// A Bulb hovers, jittering every 5 frames (2 when attacking) by 1 to 6, and flits about every 10 to 69 frames. A calm +// one flits off 30 to 60 away or circles its target by 60. One drawn by a player's charged active dashes at it. +constexpr uint32_t BULB_WAIT = 60; +constexpr int BULB_WAIT_MIN = 10; +constexpr float BULB_HOVER_FRICTION = 0.85f; +constexpr float BULB_JITTER_FRAMES = 5; +constexpr float BULB_ANGRY_JITTER_FRAMES = 2; +constexpr float BULB_JITTER_MIN = 1; +constexpr float BULB_JITTER_RANGE = 5; +constexpr float BULB_NEAR = 100; +constexpr uint32_t BULB_CIRCLE_ODDS = 3; +constexpr float BULB_FLIT_MIN = 30; +constexpr float BULB_FLIT_RANGE = 30; +constexpr float BULB_CIRCLE_TURN = 60; +constexpr float BULB_CIRCLE_RADIUS = 60; +constexpr float BULB_MARGIN = 8; +constexpr uint32_t BULB_FLIT_WAIT = 24; +constexpr int BULB_FLIT_WAIT_MIN = 6; +constexpr int BULB_FLIT_FRAMES = 6; +constexpr float BULB_FLIT_KICK = 4; +constexpr float BULB_FLIT_PUSH = 2; +constexpr float BULB_FLIT_MAX = 12; + +// Its dash: past its target's side by 20 to 50 (or 0.4 of the way), turned 75 degrees, or straight through where its +// target heads when near (one time in two). +constexpr float BULB_DASH_MIN = 20; +constexpr float BULB_DASH_RANGE = 30; +constexpr float BULB_DASH_SHARE = 0.4f; +constexpr float BULB_DASH_TURN = 75; +constexpr float BULB_DASH_NEAR = 80; +constexpr float BULB_DASH_LEAD = 0.025f; +constexpr int BULB_DASH_FRAMES = 6; +constexpr int BULB_LUNGE_FRAMES = 8; +constexpr uint32_t BULB_DASH_WAIT = 20; +constexpr int BULB_DASH_WAIT_MIN = 5; +constexpr uint32_t BULB_LUNGE_WAIT = 50; +constexpr int BULB_LUNGE_WAIT_MIN = 30; +constexpr float BULB_DASH_PUSH = 8; +constexpr float BULB_DASH_MAX = 20; +constexpr float BLACK_BULB_SHOT_SPEED = 10; + +// Whether a player holds an active item with charge in it, which draws a Bulb to attack. +static bool bulb_is_charge_near(Entity* target) +{ + if (target->type != ENTITY_PLAYER) return false; + + Entity_Player& player = *static_cast(target); + int charge = 0; + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + if (!g_manager->itemConfig.GetCollectible(player.activeItems[slot].item)) continue; + + int maxCharge = player.GetActiveMaxCharge(slot); + if (maxCharge > 0) charge += maxCharge == 1 ? 1 : player.activeItems[slot].charge; + } + return charge > 0; +} + +// A calm Bulb's flit: away 30 to 60 when far from its target (and one time in three when near), else round its target. +static void bulb_flit(Entity_NPC& npc, Entity* target) +{ + bool isFar = vector_length(vector_sub(npc.pos, target->pos)) >= BULB_NEAR; + if (isFar || Random() % BULB_CIRCLE_ODDS == 0) + { + Vector direction = random_direction(); + npc.v1 = vector_scale(direction, random_unit() * BULB_FLIT_RANGE + BULB_FLIT_MIN); + npc.targetPosition = vector_add(npc.pos, npc.v1); + npc.v1 = vector_normalized(npc.v1); + } + else + { + Vector toward = vector_normalized(vector_sub(target->pos, npc.pos)); + float angle = (float)npc.i2 * BULB_CIRCLE_TURN * DEGREES_TO_RADIANS; + float c = std::cos(angle); + float s = std::sin(angle); + Vector turned = vector_make(c * toward.x - s * toward.y, c * toward.y + s * toward.x); + Vector spot = vector_sub(npc.pos, vector_scale(turned, BULB_CIRCLE_RADIUS)); + npc.targetPosition = g_game->room->GetClampedPosition(spot, BULB_MARGIN); + npc.v1 = vector_normalized(vector_sub(npc.targetPosition, npc.pos)); + } + npc.i1 = (int)(Random() % BULB_FLIT_WAIT) + BULB_FLIT_WAIT_MIN; + npc.stateFrame = BULB_FLIT_FRAMES; + npc.i2 = -npc.i2; + npc.state = NPC_STATE_MOVE; + npc.sprite.isFlipX = npc.targetPosition.x < npc.pos.x; + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, BULB_FLIT_KICK * npc.speedMultiplier)); +} + +// An angry Bulb's dash past its target's side, or straight through where it heads when near. +static void bulb_dash(Entity_NPC& npc, Entity* target) +{ + Vector aim = npc.CalcTargetPosition(0); + Vector away = vector_sub(npc.pos, aim); + float distance = vector_length(away); + Vector direction = vector_normalized(away); + float dash = std::max(random_unit() * BULB_DASH_RANGE + BULB_DASH_MIN, distance * BULB_DASH_SHARE); + Vector past = vector_sub(away, vector_scale(direction, dash)); + float angle = (float)npc.i2 * BULB_DASH_TURN * DEGREES_TO_RADIANS; + float c = std::cos(angle); + float s = std::sin(angle); + Vector spot = vector_make(c * past.x - s * past.y + aim.x, c * past.y + s * past.x + aim.y); + + float facing = aim.x; + int dashFrames = BULB_DASH_FRAMES; + if (npc.HasEntityFlags(FLAG_BULB_CALM) || distance >= BULB_DASH_NEAR || (Random() & 1) != 0) + { + npc.targetPosition = g_game->room->GetClampedPosition(spot, BULB_MARGIN); + npc.v1 = vector_normalized(vector_sub(npc.targetPosition, npc.pos)); + npc.i1 = (int)(Random() % BULB_DASH_WAIT) + BULB_DASH_WAIT_MIN; + } + else + { + Vector lead = vector_add(target->pos, vector_scale(target->velocity, distance * BULB_DASH_LEAD)); + facing = lead.x; + Vector through = vector_sub(lead, npc.pos); + npc.targetPosition = vector_add(vector_add(through, through), npc.pos); + npc.v1 = vector_normalized(vector_sub(npc.targetPosition, npc.pos)); + dashFrames = BULB_LUNGE_FRAMES; + npc.i1 = (int)(Random() % BULB_LUNGE_WAIT) + BULB_LUNGE_WAIT_MIN; + } + npc.stateFrame = dashFrames; + npc.i2 = -npc.i2; + npc.state = NPC_STATE_ATTACK; + npc.sprite.isFlipX = facing < npc.pos.x; + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, BULB_DASH_PUSH * npc.speedMultiplier)); +} + +// Hovering: it jitters and, once its wait runs out, flits (or dashes when angry). +static void bulb_hover(Entity_NPC& npc, Entity* target, bool isAngry) +{ + if (npc.GetIntervalTicks(isAngry ? BULB_ANGRY_JITTER_FRAMES : BULB_JITTER_FRAMES, 0) != 0) + { + npc.velocity = vector_sub(npc.velocity, vector_scale(npc.v1, npc.speedMultiplier)); + Vector direction = random_direction(); + npc.v1 = vector_scale(direction, random_unit() * BULB_JITTER_RANGE + BULB_JITTER_MIN); + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, npc.speedMultiplier)); + } + int ticks = npc_ticks_get(npc); + npc.i1 -= isAngry ? ticks * 2 : ticks; + if (npc.i1 >= 1) return; + + if (isAngry) bulb_dash(npc, target); + else bulb_flit(npc, target); +} + +// How a Bulb travels to its spot: a flit, or a dash that bounces off walls and burns its time twice as fast. +enum BulbTravel +{ + BULB_FLIT, + BULB_DASH +}; + +// Moving on toward its spot at a push and up to a top speed. It hovers again once past its spot or out of time. +static void bulb_travel(Entity_NPC& npc, BulbTravel travel) +{ + bool isDash = travel == BULB_DASH; + float push = isDash ? BULB_DASH_PUSH : BULB_FLIT_PUSH; + float maxSpeed = isDash ? BULB_DASH_MAX : BULB_FLIT_MAX; + + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, push * npc.speedMultiplier)); + float speed = vector_length(npc.velocity); + if (speed > maxSpeed && speed > 0) npc.velocity = vector_scale(npc.velocity, maxSpeed / speed); + if (isDash && npc.isCollidesWithGrid) + { + Vector normal = vector_scale(npc.gridCollisionNormal, -1); + npc.v1 = vector_sub(npc.v1, vector_scale(normal, vector_dot(npc.v1, normal) * 2)); + } + + npc.stateFrame -= npc_ticks_get(npc) * (isDash ? 2 : 1); + bool isAhead = vector_dot(vector_sub(npc.targetPosition, npc.pos), npc.v1) >= 0; + if (isAhead && npc.stateFrame > 0) return; + + npc.velocity = vector_sub(npc.velocity, vector_scale(npc.v1, push * npc.speedMultiplier)); + npc.state = NPC_STATE_IDLE; + npc.v1 = {}; +} + +// 0054bca0 The Bulb's AI: Lord of the Flies charms it. It hovers about, lit while it holds stolen charge, and dashes at +// a player holding a charged active item (the Black Bulb always, bursting into four shots as it dies). +void npc_bulb_update(Entity_NPC& npc) +{ + Entity_Player* beelzebub = g_game->playerManager.GetRandomPlayer(npc.initSeed); + if (beelzebub && !npc.isDead) npc.AddCharmed(EntityRef(beelzebub), -1, true, false); + + Entity* target = npc.GetPlayerTarget(); + bool isAngry = + npc.HasEntityFlags(FLAG_CHARM) || npc.forcedTarget || npc.variant == BULB_BLACK || bulb_is_charge_near(target); + bool isTamed = + !npc.IsFriendly() && g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK); + if (isTamed) isAngry = false; + std::string_view animation = isAngry ? "Dash" : npc.projectileCooldown < 1 ? "Fly" : "FlyLit"; + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.v1 = {}; + npc.i1 = (int)(Random() % BULB_WAIT) + BULB_WAIT_MIN; + uint32_t side = Random(); + npc.projectileCooldown = 0; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.i2 = (int)(side & 1) * 2 - 1; + if (npc.variant == SUCKER_BULB) npc.splatColor = BULB_SPLAT; + } + else if (npc.state == NPC_STATE_IDLE || npc.state == NPC_STATE_MOVE || npc.state == NPC_STATE_JUMP || + npc.state == NPC_STATE_ATTACK) + { + npc.sprite.Play(animation); + npc.friction *= BULB_HOVER_FRICTION; + if (npc.state == NPC_STATE_IDLE) bulb_hover(npc, target, isAngry); + else bulb_travel(npc, npc.state == NPC_STATE_MOVE ? BULB_FLIT : BULB_DASH); + } + + if (!npc.isDead || npc.variant != BULB_BLACK || npc.HasEntityFlags(FLAG_SHRINK)) return; + + // The original builds its shot's params twice, drawing two circle angles. + ProjectileParams discarded; + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(BLACK_BULB_SHOT_SPEED, 0), PROJECTILES_PLUS, params); +} diff --git a/src/npc_caves.h b/src/npc_caves.h new file mode 100644 index 0000000..056744d --- /dev/null +++ b/src/npc_caves.h @@ -0,0 +1,37 @@ +#pragma once + +#include "npc_basement.h" + +// The Caves, Catacombs and Flooded Caves enemies' AIs the dispatcher (npc_ai_update) runs by type. +void npc_boom_fly_update(Entity_NPC& npc); +void npc_maw_update(Entity_NPC& npc); +void npc_globin_update(Entity_NPC& npc); +void npc_host_update(Entity_NPC& npc); +void npc_maggot_update(Entity_NPC& npc); +void npc_mushroom_update(Entity_NPC& npc); + +// Pushes a bouncer (the Boom Fly, the floating Host) along its diagonal, steered by its controller. False when a +// confused one wanders instead. +bool npc_bounce_push(Entity_NPC& npc, float accel); + +// Restarts an animation from its first frame, the way the AIs force one to play anew. +inline void npc_anim_restart(ANM2& sprite, std::string_view name) +{ + if (!sprite.SetAnimation(name, SWITCH_KEEP_FRAME)) return; + + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; +} + +// Whether its animation stopped playing, or it has none. +inline bool npc_anim_is_done(Entity_NPC& npc) +{ + return !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; +} + +// Math::timescale_factor: a per-frame friction scaled to the NPC's speed, unchanged at full speed. +inline float npc_friction_scaled(float friction, float speedMultiplier) +{ + if (speedMultiplier == 1) return friction; + return friction / ((friction + speedMultiplier) - friction * speedMultiplier); +} diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index 86dcdf9..3656738 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -14,26 +14,17 @@ #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; @@ -41,14 +32,12 @@ 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. @@ -78,7 +67,6 @@ 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; diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp index c10d6b6..9aa74d7 100644 --- a/src/npc_fireplace.cpp +++ b/src/npc_fireplace.cpp @@ -1,4 +1,5 @@ #include "npc_fireplace.h" +#include "entity_bomb.h" #include "entity_effect.h" #include "entity_pickup.h" #include "entity_player.h" @@ -261,7 +262,7 @@ static void fire_damage_update(Entity_NPC& npc) fire_play(npc, DISAPPEAR); Entity_Player* player = fire_putter_get(npc); if (player && player->HasCollectible(COLLECTIBLE_BLACK_POWDER)) - reconstruction_missing("NpcAI::ENTITY_FIREPLACE 006d18d0: Black Powder's blast (Game::BombExplosionEffects)"); + explosion_effects({.position = npc.pos, .source = player, .damage = BLACK_POWDER_DAMAGE}); } else if ((npc.variant == FIRE_BLUE || npc.variant == FIRE_PURPLE) && isLit) { diff --git a/src/npc_fly.cpp b/src/npc_fly.cpp index baa4689..467f913 100644 --- a/src/npc_fly.cpp +++ b/src/npc_fly.cpp @@ -10,7 +10,6 @@ // 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; @@ -534,8 +533,8 @@ static void fly_drift_update(Entity_NPC& npc) void npc_fly_update(Entity_NPC& npc) { 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); + return npc_bulb_update(npc); + if (npc.type == ENTITY_SUCKER && npc.variant == SUCKER_MAMA_FLY) return npc_mama_fly_update(npc); if (npc.state == NPC_STATE_INIT) fly_init(npc); PlayerManager& players = g_game->playerManager; diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index d193a31..b81c7ff 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -1,7 +1,13 @@ -#include "npc_ai.h" +#include "npc_basement.h" +#include "deathmatch_manager.h" #include "entity_effect.h" +#include "entity_player.h" +#include "entity_tear.h" #include "game.h" +#include "manager.h" #include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" // The gaper's kin this AI runs, and the enemies they get up as. constexpr int ENTITY_NULLS = 252; @@ -22,13 +28,8 @@ constexpr int BLOOD_EXPLOSION_BEAM = 2; constexpr int SOUND_STONE_WALKER = 50; constexpr int SOUND_MONSTER_ROAR_2 = 116; -constexpr int SOUND_ANGRY_GURGLE = 167; -constexpr int SOUND_HEARTIN = 212; -constexpr int SOUND_HEARTOUT = 213; constexpr int SOUND_STONESHOOT = 262; -constexpr int CONTROLLER_ACTION_ATTACK = 9; -constexpr int CONTROLLER_ACTION_GROAN = 10; constexpr int LAYER_STONEY_CROSS = 1; constexpr int NULL_STONEY_CROSS = 2; @@ -246,7 +247,7 @@ static bool fatty_attack_check(Entity_NPC& npc) if (vector_length_squared(vector_sub(target->pos, npc.pos)) >= FATTY_ATTACK_RANGE_SQUARED) return false; if (Random() % FATTY_ATTACK_ODDS != 0) return false; } - else if (!npc.IsControllerActionPressed(CONTROLLER_ACTION_ATTACK) && + else if (!npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) && vector_is_zero(npc.GetControllerMovementInput(CONTROLLER_DEADZONE))) return false; return npc.stateFrame >= FATTY_WINDUP; @@ -315,6 +316,112 @@ static void conjoined_beam_update(Entity_NPC& npc) npc.stateFrame += npc.update_ticks_get(); } +// A Butter Bean fart pushes what it catches up to 7 away (half as far when heavier than 20) and turns the player's +// shots back. Gigante Bean doubles its reach and push, hurts the enemies a player's fart catches by 10, and confuses +// them at three beans. +constexpr float BUTTER_BEAN_PUSH = 7; +constexpr float BUTTER_BEAN_HEAVY_MASS = 20; +constexpr float BUTTER_BEAN_HEAVY_SHARE = 0.5f; +constexpr float BUTTER_BEAN_DRAG = 0.5f; +constexpr float BUTTER_BEAN_DOUBLE_PUSH = 1.5f; +constexpr float BUTTER_BEAN_BIG = 1.8f; +constexpr float BUTTER_BEAN_DAMAGE = 10; +constexpr int BUTTER_BEAN_DAMAGE_COUNTDOWN = 30; +constexpr int BUTTER_BEAN_CONFUSION_FRAMES = 90; +constexpr float BUTTER_BEAN_ECHO_VOLUME = 1.2f; +constexpr int BUTTER_BEAN_ECHO_DELAY = 20; +constexpr float BUTTER_BEAN_ECHO_PITCH = 0.5f; +constexpr int BUTTER_BEAN_SHAKE = 3; +constexpr ColorMod BUTTER_BEAN_COLOR = {{1.8f, 0.7f, 1.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float FATTY_FART_RADIUS = 120; + +// Whether a fart pushes an entity: vulnerable enemies, bombs and pickups, the enemies' shots for a player's fart, a +// rival's tears in versus mode, and the players for anyone else's. +static bool butter_bean_is_pushed(const ButterBeanFart& fart, Entity& entity, bool isPlayerSource) +{ + if (&entity == fart.source || entity.mass == 0 || entity.HasEntityFlags(FLAG_NO_KNOCKBACK)) return false; + bool isRivalTear = g_game->deathmatchManager.state >= DEATHMATCH_INTRO && entity.type == ENTITY_TEAR && + !entity.IsDescendantOf(fart.source); + return entity.IsVulnerableEnemy(nullptr) || entity.type == ENTITY_BOMB || entity.type == ENTITY_PICKUP || + (entity.type == ENTITY_PROJECTILE && isPlayerSource) || isRivalTear || + (!isPlayerSource && entity.type == ENTITY_PLAYER); +} + +// 00704360 Game::ButterBeanFart: a fart that pushes everything in its radius away, turning back the shots a player's +// or familiar's fart catches. Gigante Bean doubles it, and a player's shown fart shoots its candle. +void game_butter_bean_fart(const ButterBeanFart& fart) +{ + float radius = fart.radius; + float scale = 1; + int beans = 0; + Entity_Player* player = fart.source ? static_cast(fart.source->GetPlayerAncestor()) : nullptr; + if (player && player->HasTrinket(TRINKET_GIGANTE_BEAN)) + { + radius += radius; + scale = 2; + beans = player->GetTrinketMultiplier(TRINKET_GIGANTE_BEAN); + } + if (fart.isShowEffect) + { + Entity* cloud = g_game->Spawn( + {.position = fart.position, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + cloud->SetColor(BUTTER_BEAN_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + cloud->sprite.scale = vector_make(scale, scale); + } + if (scale > BUTTER_BEAN_BIG) + { + SFXManager& sfx = g_manager->sfxManager; + sfx.Stop(SOUND_FART); + sfx.Play(SOUND_FART, {.frameDelay = 0}); + sfx.Play(SOUND_FART, + {.volume = BUTTER_BEAN_ECHO_VOLUME, .frameDelay = BUTTER_BEAN_ECHO_DELAY, .pitch = BUTTER_BEAN_ECHO_PITCH}); + game_shake_screen(BUTTER_BEAN_SHAKE); + } + + bool isShotTurner = fart.source && (fart.source->type == ENTITY_PLAYER || fart.source->type == ENTITY_FAMILIAR); + bool isPlayerSource = fart.source && fart.source->type == ENTITY_PLAYER; + for (Entity* entity : entity_query_radius(fart.position, radius, QUERY_ALL)) + { + if (entity->type == ENTITY_PLAYER && fart.source && fart.source->IsFriendly()) continue; + if (!butter_bean_is_pushed(fart, *entity, isPlayerSource)) continue; + + float reach = radius + entity->size; + Vector away = vector_sub(entity->pos, fart.position); + float distance = vector_length(away); + if (distance <= 0) continue; + + if (entity->type == ENTITY_PROJECTILE) + { + float speed = vector_length(entity->velocity); + if (isShotTurner) static_cast(entity)->Reflect(vector_scale(away, speed / distance)); + continue; + } + if (entity->type == ENTITY_TEAR && dynamic_cast(entity)) + { + float speed = vector_length(entity->velocity); + if (isShotTurner) + static_cast(entity)->Deflect(fart.source, vector_scale(away, speed / distance)); + continue; + } + + float push = std::min(BUTTER_BEAN_PUSH, reach - distance) * 2; + if (beans > 1) push *= BUTTER_BEAN_DOUBLE_PUSH; + if (beans > 2) entity->AddConfusion(EntityRef(fart.source), BUTTER_BEAN_CONFUSION_FRAMES, false); + if (entity->mass > BUTTER_BEAN_HEAVY_MASS) push *= BUTTER_BEAN_HEAVY_SHARE; + entity->velocity.x = away.x / distance * push * scale + entity->velocity.x * BUTTER_BEAN_DRAG; + entity->velocity.y = away.y / distance * push * scale + entity->velocity.y * BUTTER_BEAN_DRAG; + + bool isEnemy = entity->IsVulnerableEnemy(nullptr); + if (isEnemy && isPlayerSource && scale > BUTTER_BEAN_BIG) + entity->TakeDamage(BUTTER_BEAN_DAMAGE, 0, EntityRef(), BUTTER_BEAN_DAMAGE_COUNTDOWN); + if (fart.isSuperKnockback && entity->IsVulnerableEnemy(nullptr) && entity->mass > 0 && + !entity->HasEntityFlags(FLAG_NO_KNOCKBACK) && !entity->IsFriendly()) + reconstruction_missing("Game::ButterBeanFart 00704360: the super knockback (Entity::AddKnockback 006b7a80)"); + } + if (fart.source && fart.source->type == ENTITY_PLAYER && fart.isShowEffect) + static_cast(fart.source)->ShootCandle({}); +} + // A fatty's "Shoot": the Blue Conjoined Fatty spits an exploding homing shot, the others fart (the Pale Fatty with a // ring of shots, the Flaming Fatty with a fire). static void fatty_shoot(Entity_NPC& npc) @@ -331,7 +438,7 @@ static void fatty_shoot(Entity_NPC& npc) return; } - reconstruction_missing("npc_gaper_update 00508f40: the Fatty's fart (Game::ButterBeanFart 00704360, radius 120)"); + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = FATTY_FART_RADIUS}); Vector ring = vector_make(PALE_FATTY_RING_SPEED, PALE_FATTY_RING_SHOTS); if (npc.variant == FATTY_PALE) npc.FireProjectiles(npc.pos, ring, PROJECTILES_RING, ProjectileParams()); else if (npc.variant == FATTY_FLAMING) fire_spawn(npc); diff --git a/src/npc_globin.cpp b/src/npc_globin.cpp new file mode 100644 index 0000000..ade46a1 --- /dev/null +++ b/src/npc_globin.cpp @@ -0,0 +1,313 @@ +#include "npc_caves.h" +#include "sfx_manager.h" +#include "entity_effect.h" +#include "game.h" +#include "room.h" +#include "room_grid.h" + +// The Globin's variants (the Black Globin is its own type), and the subtype a Globin that rises from a poof has. +enum GlobinVariant : int +{ + GLOBIN_PLAIN, + GLOBIN_GAZING, + GLOBIN_DANK, + GLOBIN_CURSED +}; +constexpr int GLOBIN_RISING = 10; + +constexpr ColorMod DANK_GLOBIN_SPLAT_COLOR = {{0.02f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod CURSED_SPLAT_COLOR = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; + +// A walking Globin paths to its target (the cursed one's pieces at their own pace), bleeds now and then and groans +// when it sees its target. A scared one runs. +constexpr int GLOBIN_SPLAT_ODDS = 10; +constexpr float GLOBIN_SPLAT_SIZE = 0.2f; +constexpr float GLOBIN_SPLAT_RANGE = 0.5f; +constexpr float GLOBIN_WALK_THRESHOLD = 0.1f; +constexpr float GLOBIN_SPEED = 0.75f; +constexpr float GAZING_SPEED = 1.1f; +constexpr float BLACK_GLOBIN_SPEED = 0.6f; +constexpr float CURSED_SPEED = 0.65f; +constexpr float CURSED_SPEED_RANGE = 0.25f; +constexpr RNG CURSED_SPEED_RNG = {0, 11, 7, 12}; +constexpr float GLOBIN_EVADE_FRICTION = 0.8f; +constexpr float GLOBIN_FRICTION = 0.97f; +constexpr int GLOBIN_GROAN_ODDS = 3; +constexpr int GLOBIN_GROAN_DELAY = 40; +constexpr int CONTROLLER_ACTION_BOMB = 10; + +// A regenerating Globin stays put (the gazing one backs off a target within 200), then walks again. +constexpr float GAZING_PULL = 0.5f; +constexpr float GAZING_RANGE = 200; +constexpr float GAZING_MIN_RANGE = 0.01f; +constexpr float GAZING_INPUT_DEADZONE = 0.1f; +constexpr float GAZING_INPUT_SCALE = 10; +constexpr float GAZING_FRICTION = 0.83f; +constexpr float REGEN_FRICTION = 0.7f; + +// The Black Globin throws a spider toward its target each time it loses 5 health. +constexpr float BLACK_SPIDER_HEALTH = 5; +constexpr float BLACK_SPIDER_REACH = 0.75f; +constexpr float BLACK_SPIDER_RISE = -30; +constexpr float BLACK_PIECE_STEP = 40; +constexpr int SOUND_SPIDER_THROW = 181; +constexpr float SOUND_SPIDER_VOLUME = 0.25f; + +// The dank one leaves a trail of black creep as it dies, and a spider as it falls (with few enemies around). +constexpr int DANK_GLOBIN_CREEP_TIMEOUT = 210; +constexpr float DANK_GLOBIN_CREEP_SCALE = 2; +constexpr int DANK_SPIDER_ENEMY_LIMIT = 7; + +// A fallen Globin regenerates with 10 health. The cursed one comes back smaller and sometimes splits in two, more often +// the more it split and in boss rooms. Its pieces flicker untouchable for two frames. +constexpr float GLOBIN_REGEN_HEALTH = 10; +constexpr RNG CURSED_SPLIT_RNG = {0, 11, 7, 16}; +constexpr int CURSED_SPLIT_CHANCE = 15; +constexpr int CURSED_BOSS_SPLIT_CHANCE = 25; +constexpr int CURSED_SPLIT_CAP = 99; +constexpr int CURSED_SPLIT_ROLL = 100; +constexpr float CURSED_STILL_SPEED = 0.01f; +constexpr float CURSED_SPLIT_SPEED = 4; +constexpr float CURSED_SPLIT_TURN = 1.5707964f; +constexpr int CURSED_MAX_PIECES = 4; +constexpr int CURSED_FRAMES_PER_PIECE = 10; +constexpr int CURSED_RISEN_FRAME = 40; +constexpr float CURSED_HEALTH_SHARE = 0.6f; +constexpr int CURSED_INVINCIBLE_FRAMES = 2; + +// The first frame: the blood of its kind (the cursed one counts its untouchable frames before each update), then it +// walks. One that rises from a poof shows the poof and regenerates first. +static void globin_init(Entity_NPC& npc) +{ + if (npc.variant == GLOBIN_CURSED) + { + npc.splatColor = g_game->GetStageID() == STAGE_ID_GEHENNA ? COLOR_DEFAULT : CURSED_SPLAT_COLOR; + npc.aiCallFlags |= AI_CALL_PRE_UPDATE; + } + else if (npc.variant == GLOBIN_DANK) npc.splatColor = DANK_GLOBIN_SPLAT_COLOR; + + npc.v1.x = npc.health; + npc.state = NPC_STATE_MOVE; + if (npc.subtype != GLOBIN_RISING) return; + + if (npc.HasEntityFlags(FLAG_APPEAR)) + { + npc.ClearEntityFlags(FLAG_APPEAR); + Entity* poof = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->posOffset = npc.posOffset; + poof->renderDepthOffset = npc.posOffset.y + 1; + if (npc.isChampion) + poof->SetColor(champion_sprite_color_get(npc.championColorIdx), -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + } + npc.sprite.Play("ReGen"); + npc.state = NPC_STATE_IDLE; +} + +// The Black Globin throws a spider most of the way to its target each time it loses 5 health. +static void black_globin_spider_throw(Entity_NPC& npc) +{ + if (npc.v1.x - npc.health <= BLACK_SPIDER_HEALTH) return; + + npc.v1.x = npc.health; + Vector target = npc.GetPlayerTarget()->pos; + Vector reach = vector_add(npc.pos, vector_scale(vector_sub(target, npc.pos), BLACK_SPIDER_REACH)); + Vector spot = room_free_pickup_position_find({.position = reach}); + Entity_NPC::ThrowSpider(npc.pos, &npc, spot, false, BLACK_SPIDER_RISE); + npc.PlaySound(SOUND_SPIDER_THROW, SOUND_SPIDER_VOLUME, 2, false, 1); +} + +// The dank Globin's black creep where it dies, lasting a while. +static void dank_globin_creep(Entity_NPC& npc) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_BLACK, .seed = Random()})); + creep->parent = &npc; + creep->SetTimeout(DANK_GLOBIN_CREEP_TIMEOUT); + creep->sprite.scale = vector_make(DANK_GLOBIN_CREEP_SCALE, DANK_GLOBIN_CREEP_SCALE); + creep->Update(); +} + +// The walking pace: the Black Globin's slow one, the gazing one's quick one, the cursed pieces' own. +static float globin_speed_get(Entity_NPC& npc) +{ + if (npc.type == ENTITY_BLACK_GLOBIN) return BLACK_GLOBIN_SPEED; + if (npc.variant == GLOBIN_GAZING) return GAZING_SPEED; + if (npc.variant != GLOBIN_CURSED || npc.subtype == 0) return GLOBIN_SPEED; + + RNG rng = CURSED_SPEED_RNG; + rng._seed = npc.initSeed; + return rng.RandomFloat() * CURSED_SPEED_RANGE + CURSED_SPEED; +} + +// Walking: it bleeds now and then and paths to its target (or runs when scared), groaning now and then while it sees +// its target. +static void globin_walk(Entity_NPC& npc) +{ + if (Random() % GLOBIN_SPLAT_ODDS == 0) + { + Entity_Effect* splat = npc.MakeSplat(random_unit() * GLOBIN_SPLAT_RANGE + GLOBIN_SPLAT_SIZE); + splat->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + npc.AnimWalkFrame("WalkHori", "WalkVert", GLOBIN_WALK_THRESHOLD); + + bool isControlled = npc.controllerID != -1; + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && !isControlled) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= GLOBIN_EVADE_FRICTION; + } + else + { + float speed = globin_speed_get(npc); + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), speed, 0, DIRECT_PATH_FAR); + } + + bool isGroaning = isControlled ? npc.IsControllerActionTriggered(CONTROLLER_ACTION_BOMB) + : npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && + Random() % GLOBIN_GROAN_ODDS == 0; + if (isGroaning) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, GLOBIN_GROAN_DELAY, false, 1); + npc.friction *= GLOBIN_FRICTION; + npc.sprite.isFlipX = npc.velocity.x < 0; +} + +// Regenerating: it stays put (the gazing one backs off its target), then walks again once its animation ends. +static void globin_regen_update(Entity_NPC& npc) +{ + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.variant == GLOBIN_GAZING) + { + if (npc.controllerID != -1) + toward = vector_scale(npc.GetControllerInput(GAZING_INPUT_DEADZONE), GAZING_INPUT_SCALE); + float distance = vector_length(toward); + if (distance < GAZING_RANGE && distance > GAZING_MIN_RANGE) + npc.AddVelocity_divided(vector_scale(vector_scale(toward, -1), GAZING_PULL / distance), false); + npc.friction *= GAZING_FRICTION; + } + else npc.friction *= REGEN_FRICTION; + + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Regen")) npc.PlaySound(SOUND_DEATH_REVERSE, 1, 2, false, 1); + if (!npc_anim_is_done(npc)) return; + } + npc.state = NPC_STATE_MOVE; +} + +// The direction a cursed Globin splits along: across its motion, or anywhere while still. +static Vector cursed_split_direction(Entity_NPC& npc) +{ + if (vector_length_squared(npc.velocity) < CURSED_STILL_SPEED) return random_direction(); + + float cosine = std::cos(CURSED_SPLIT_TURN); + float sine = std::sin(CURSED_SPLIT_TURN); + Vector v = npc.velocity; + return vector_normalized(vector_make(v.x * cosine - v.y * sine, v.y * cosine + v.x * sine)); +} + +// The cursed Globin's second piece, flung the other way with the same health, look and frame of regeneration. +static void cursed_piece_spawn(Entity_NPC& npc, RNG& rng, Vector offset, int frame) +{ + npc.subtype++; + npc.isInvincible = true; + npc.i1 = CURSED_INVINCIBLE_FRAMES; + npc.initSeed = rng.Next(); + uint32_t seed = rng.Next(); + Entity* piece = g_game->Spawn({.position = vector_add(offset, npc.pos), + .velocity = offset, + .spawner = &npc, + .type = npc.type, + .variant = npc.variant, + .seed = seed}); + auto& other = static_cast(*piece); + other.health = npc.maxHitPoints; + other.maxHitPoints = npc.maxHitPoints; + other.sprite.Play("ReGen"); + if (frame > 0 && other.sprite.animState.animData) other.sprite.animState.SetFrameFloat((float)frame); + other.ClearEntityFlags(FLAG_APPEAR); + other.subtype = npc.subtype; + other.state = NPC_STATE_IDLE; + other.splatColor = npc.splatColor; + other.AddEntityFlags(FLAG_NO_REWARD); + other.aiCallFlags |= AI_CALL_PRE_UPDATE; + other.isInvincible = true; + other.i1 = 1; + + npc.velocity = vector_scale(offset, -1); + npc.pos = vector_sub(npc.pos, offset); +} + +// A fallen cursed Globin rises again at 60% of its health, unless a killswitch ends it. It splits in two by chance +// (always rising, even mid regeneration), else only one walking comes back. +static void cursed_globin_rise(Entity_NPC& npc) +{ + RNG rng = CURSED_SPLIT_RNG; + rng._seed = npc.initSeed; + bool isSplitting = false; + Vector direction{}; + if (!npc.HasEntityFlags(FLAG_KILLSWITCH)) + { + Room& room = *g_game->room; + int chance = (room.roomType == ROOM_BOSS ? CURSED_BOSS_SPLIT_CHANCE : CURSED_SPLIT_CHANCE) * npc.subtype; + isSplitting = rng.RandomInt(CURSED_SPLIT_ROLL) > (uint32_t)std::min(chance, CURSED_SPLIT_CAP); + if (isSplitting) direction = cursed_split_direction(npc); + } + if (!isSplitting && npc.state != NPC_STATE_MOVE) return; + + npc.isDead = false; + int frame = (CURSED_MAX_PIECES - npc.subtype) * CURSED_FRAMES_PER_PIECE; + if (npc.state != NPC_STATE_MOVE) frame = CURSED_RISEN_FRAME; + npc_anim_restart(npc.sprite, "ReGen"); + if (frame > 0 && npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat((float)frame); + + npc.state = NPC_STATE_IDLE; + npc.maxHitPoints = std::max(1.0f, npc.maxHitPoints * CURSED_HEALTH_SHARE); + npc.health = npc.maxHitPoints; + if (isSplitting) cursed_piece_spawn(npc, rng, vector_scale(direction, CURSED_SPLIT_SPEED), frame); +} + +// A fallen Globin: the Black Globin leaves its body and head, the cursed one rises (maybe split), and the others get +// up with 10 health while walking (the dank one dropping a spider), else stay down. +static void globin_death(Entity_NPC& npc) +{ + if (npc.type == ENTITY_BLACK_GLOBIN) + { + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BLACK_GLOBIN_BODY, .seed = Random()}); + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = BLACK_PIECE_STEP}); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_BLACK_GLOBIN_HEAD, .seed = seed}); + return; + } + if (npc.variant == GLOBIN_CURSED) return cursed_globin_rise(npc); + if (npc.state != NPC_STATE_MOVE) return; + + npc.isDead = false; + npc.health = GLOBIN_REGEN_HEALTH; + npc.sprite.Play("ReGen"); + npc.state = NPC_STATE_IDLE; + if (npc.variant != GLOBIN_DANK || npc.GetAliveEnemyCount() >= DANK_SPIDER_ENEMY_LIMIT) return; + + Entity* spider = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_SPIDER, .seed = Random()}); + spider->ClearEntityFlags(FLAG_APPEAR); +} + +// 0050e4d0 The Globins' AI: a Globin walks to its target and, beaten, falls and regenerates until it is finished off +// as a pile. The gazing one backs away while regenerating, the dank one leaves creep and spiders, the cursed one +// splits as it rises, and the Black Globin throws spiders and falls apart into its body and head. +void npc_globin_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (npc.i1 > 0 && --npc.i1 <= 0) npc.isInvincible = false; + return; + } + if (npc.state == NPC_STATE_INIT) return globin_init(npc); + + if (npc.type == ENTITY_BLACK_GLOBIN) black_globin_spider_throw(npc); + if (npc.isDead && npc.type == ENTITY_GLOBIN && npc.variant == GLOBIN_DANK) dank_globin_creep(npc); + + if (npc.state == NPC_STATE_MOVE) globin_walk(npc); + else globin_regen_update(npc); + if (npc.isDead) globin_death(npc); +} diff --git a/src/npc_gusher.cpp b/src/npc_gusher.cpp index ad35dc9..cc7a03a 100644 --- a/src/npc_gusher.cpp +++ b/src/npc_gusher.cpp @@ -2,23 +2,16 @@ #include "boss_ai.h" #include "entity_effect.h" #include "level.h" +#include "sfx_manager.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_HALF_SACK = 211; constexpr int ENTITY_SPLASHER = 238; -constexpr int ENTITY_BLACK_GLOBIN_BODY = 280; constexpr int SOUND_BLOBBY_WIGGLE = 3; -constexpr int SOUND_BOIL_HATCH = 181; -constexpr uint64_t DAMAGE_TNT = 1ull << 12; constexpr float WALK_THRESHOLD_GUSHER = 0.1f; constexpr float GUSHER_DEADZONE = 0.1f; -// The flooded floors' shots are tears, the Dross's puke. -constexpr int STAGE_ID_FLOODED_CAVES = 6; -constexpr int STAGE_ID_DOWNPOUR = 27; -constexpr int STAGE_ID_DROSS = 28; - // Gushers wait 20 to 39 frames to start, 40 to 59 between shots (Splashers 60 to 89), shooting at 5 along their walk // at targets within 1000. Blubbers wait 30 to 59 between bursts of three to five. constexpr int GUSHER_START_MIN = 20; diff --git a/src/npc_host.cpp b/src/npc_host.cpp new file mode 100644 index 0000000..31ef157 --- /dev/null +++ b/src/npc_host.cpp @@ -0,0 +1,304 @@ +#include "npc_caves.h" +#include "boss_ai.h" +#include "entity_effect_combat.h" +#include "entity_player.h" +#include "game.h" +#include "player_manager.h" +#include "sfx_manager.h" + +// The Host's variants: the plain one, the red one (with no shell, firing five), and the hard one whose shell slam +// cracks the floor. A subtype of 99 takes its shell off too. The floating Host drifts like a Boom Fly. +enum HostVariant : int +{ + HOST_PLAIN, + HOST_RED, + HOST_SHELL_ALT, + HOST_HARD +}; +constexpr int HOST_UNSHELLED = 99; +constexpr int ENTITY_FLOATING_HOST = 859; + +// A shelled Host shrugs off hits while closed: a hit holds it closed longer (up to 10 checks), and a big one bombs it. +constexpr float SHELL_HOLD_DAMAGE_SHARE = 0.05f; +constexpr float SHELL_HOLD_ROUNDING = 0.5f; +constexpr int SHELL_HOLD_MAX = 10; +constexpr float SHELL_BOMBED_DAMAGE = 20; + +// It peeks out to shoot a target within 240 in a clear line, checked every 7 frames, resting 7 checks after. A confused +// or scared one peeks now and then at random. +constexpr int HOST_CHECK_FRAMES = 7; +constexpr float HOST_RANGE_SQUARED = 57600; +constexpr int HOST_COOLDOWN = 7; +constexpr int HOST_PEEK_ODDS = 50; +constexpr float HOST_SHOT_SPEED = 7; +constexpr float HOST_SHOT_FALL = 0.05f; +constexpr float HOST_SHOT_VELOCITY = 1.07f; +constexpr float FLOATING_SHOT_VELOCITY = 1.2f; +constexpr int HOST_BLOOD_SUBTYPE = 1; +constexpr float HOST_BLOOD_RISE = -6; +constexpr float HOST_BLOOD_SCALE = 0.75f; +constexpr float HOST_BLOOD_DEPTH = 1; +constexpr int SOUND_HOST_SHELL = 166; + +// A controlled Host charges its shot while hiding, twice as fast when distracted, and drains the charge otherwise. +constexpr float HOST_CONTROLLED_RANGE = 1000; +constexpr float HOST_CHARGE_FRAMES = 150; +constexpr float HOST_DISTRACTED_CHARGE = 2; +constexpr float HOST_DRAIN = 3; +constexpr int HOST_CONTROLLED_COOLDOWN = 70; +constexpr float HOST_AIM_ROTATION = -1; + +// The floating Host bounces along the diagonals, the others stay put. +constexpr float FLOATING_FRICTION = 0.9f; +constexpr float FLOATING_ACCEL = 0.55f; +constexpr float HOST_FRICTION = 0.7f; + +// The hard Host's slam: a crack wave toward its target, tooth shards, a shake, and a shove for players within 120. +constexpr int SLAM_SOUND_DELAY = 10; +constexpr int EFFECT_CRACKWAVE = 72; +constexpr int CRACKWAVE_SUBTYPE = 2; +constexpr float CRACKWAVE_REACH = 20; +constexpr int EFFECT_SHARD = 35; +constexpr float SHARD_SPEED = 4; +constexpr float SHARD_SPEED_RANGE = 3; +constexpr uint32_t SHARD_EXTRA_MASK = 3; +constexpr int SHARD_COUNT = 5; +constexpr ColorMod SHARD_COLOR = {{0.54901963f, 0.48235294f, 0.48235294f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int SLAM_SHAKE = 12; +constexpr float SLAM_RANGE = 120; +constexpr float SLAM_SHOVE = 3; +constexpr float SLAM_SHOVE_HEIGHT = 9; + +// The first frame: closed on its idle's first frame, and untouchable while shelled. +static void host_init(Entity_NPC& npc, bool isShelled) +{ + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + if (npc.sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + } + if (isShelled) npc.isInvincible = true; +} + +// While its shell is closed, hits (but poison and burns) do nothing. Resting, it stays closed longer for them, and a +// big one bombs it. +static void host_shell_absorb(Entity_NPC& npc) +{ + float absorbed = 0; + bool isOpen = npc.state != NPC_STATE_IDLE && npc.sprite.animState.animData && + npc.sprite.animState.WasEventTriggered("Open") && !npc.sprite.WasEventTriggered("Close"); + if (!isOpen) + for (DamageEvent& event : npc.damageEvents) + { + if (event.damageFlags & DAMAGE_POISON_BURN) continue; + if (!(event.damageFlags & (DAMAGE_SPIKES | DAMAGE_BOOGER))) absorbed += event.damage; + event.damage = 0; + } + if (npc.state != NPC_STATE_IDLE || absorbed <= 0) return; + + npc.v2.x = std::max(0.0f, npc.v2.x - npc.pendingDamage * SHELL_HOLD_DAMAGE_SHARE); + npc.stateFrame = std::min(npc.stateFrame + (int)(npc.pendingDamage + SHELL_HOLD_ROUNDING) / 2, SHELL_HOLD_MAX); + if (absorbed <= SHELL_BOMBED_DAMAGE) return; + + npc.sprite.Play("Bombed"); + npc.v2.x = 0; +} + +// A controlled shelled Host charges its shot while hiding (but while bombed), and drains it otherwise. +static void host_charge_update(Entity_NPC& npc, bool isShelled) +{ + const AnimationData* data = npc.sprite.animState.animData; + bool isBombed = data && npc.sprite.animState.isPlaying && data->name == "Bombed"; + if (npc.HasEntityFlags(FLAG_NO_TARGET) && !isBombed && isShelled) + { + float rate = npc.HasEntityFlags(FLAG_DISTRACTED) ? HOST_DISTRACTED_CHARGE : 1; + npc.v2.y = std::min(1.0f, rate * npc.speedMultiplier / HOST_CHARGE_FRAMES + npc.v2.y); + } + else + { + npc.v2.y = std::max(0.0f, npc.v2.y - npc.speedMultiplier * HOST_DRAIN / HOST_CHARGE_FRAMES); + if (!isShelled) npc.v2.y = 0; + } + npc.UpdateChargeBar(1, 0, npc.v2.y, true); +} + +// Resting: hidden in its shell, it counts its rest down every 7 frames and peeks out to shoot a target in range. +static void host_rest_update(Entity_NPC& npc, bool isShelled) +{ + if (isShelled) npc.AddEntityFlags(FLAG_NO_TARGET); + if (npc.stateFrame <= 0) + { + npc.sprite.Play("Idle"); + if (npc.controllerID != -1) + { + if (npc.v2.y >= 1 || npc.IsTargetInAttackRange(HOST_CONTROLLED_RANGE, HOST_CHECK_FRAMES, false)) + { + npc.controllerMovement = {}; + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + npc.projectileCooldown = HOST_CONTROLLED_COOLDOWN; + } + } + else if (npc.HasEntityFlags(FLAG_CONFUSION) || npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + if (Random() % HOST_PEEK_ODDS != 0) return; + npc.state = NPC_STATE_ATTACK2; + npc.stateFrame = 0; + return; + } + else if (npc.IsFrame(HOST_CHECK_FRAMES, (int)npc.index)) + { + if (npc.projectileCooldown > 0) npc.projectileCooldown--; + else + { + Vector target = npc.GetPlayerTarget()->pos; + int mode = npc.variant == HOST_HARD ? LINE_MODE_GROUND : LINE_MODE_PROJECTILE; + bool isInRange = vector_length_squared(vector_sub(target, npc.pos)) < HOST_RANGE_SQUARED; + if (isInRange && (npc.championColorIdx == CHAMPION_TRANSPARENT || + room_check_line(npc.pos, target, mode, LINE_CHECK_THRESHOLD))) + { + npc.projectileCooldown = HOST_COOLDOWN; + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + return; + } + } + } + } + if (npc.stateFrame > 0 && npc.IsFrame(HOST_CHECK_FRAMES, (int)npc.index)) npc.stateFrame--; +} + +// The shell's thud on its Open and Close events. +static void host_thud(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (anim.animData && (anim.IsEventTriggered("Open") || anim.IsEventTriggered("Close"))) + npc.PlaySound(SOUND_HOST_SHELL, 1, 2, false, 1); +} + +// Out of its shell: its shot animation, facing where it aims. +static void host_face(Entity_NPC& npc, float aimX) +{ + npc.stateFrame++; + npc.sprite.Play("Shoot"); + npc.sprite.isFlipX = aimX < 0; +} + +// The hard Host's slam as its shell closes: a crack wave toward its target, tooth shards, a shake, and a shove for +// the players nearby (but by a friendly one). +static void hard_host_slam(Entity_NPC& npc) +{ + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, SLAM_SOUND_DELAY, 1); + Vector direction = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (npc.controllerID != -1) + direction = vector_is_zero(npc.controllerMovement) ? random_direction() : vector_normalized(npc.controllerMovement); + + auto* crack = static_cast(g_game->Spawn({.position = vector_add(vector_scale(direction, CRACKWAVE_REACH), npc.pos), + .spawner = &npc, + .subType = CRACKWAVE_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + crack->parent = &npc; + crack->rotation = vector_angle(direction); + + float speed = random_unit() * SHARD_SPEED_RANGE + SHARD_SPEED; + int count = (int)(Random() & SHARD_EXTRA_MASK) + SHARD_COUNT; + game_particles_spawn( + {.color = SHARD_COLOR, .position = npc.pos, .speed = speed, .count = count, .variant = EFFECT_SHARD}); + game_shake_screen(SLAM_SHAKE); + if (npc.IsFriendly()) return; + + for (size_t i = 0; i < g_game->playerManager.playerList.size(); i++) + { + Entity_Player* player = g_game->GetPlayer((int)i); + Vector away = vector_sub(player->pos, npc.pos); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, 1 / distance); + if (distance < SLAM_RANGE) player->TryThrow(EntityRef(&npc), vector_scale(away, SLAM_SHOVE), SLAM_SHOVE_HEIGHT); + } +} + +// Shooting: out of its shell, it fires at its target (or its controller's aim) on the Shoot event with a burst of +// blood, the hard one slamming as it closes, then rests again. +static void host_shoot_update(Entity_NPC& npc, bool isShelled, float aimX, const ProjectileParams& params) +{ + if (isShelled) npc.ClearEntityFlags(FLAG_NO_TARGET); + host_thud(npc); + AnimationState& anim = npc.sprite.animState; + bool isFired = anim.animData && (anim.WasEventTriggered("Shoot") || anim.WasEventTriggered("Close")); + if (npc.controllerID != -1 && !isFired) + { + if (npc.HasEntityFlags(FLAG_DISTRACTED)) npc.controllerMovement = {}; + else + { + npc.SpawnControlTarget(0, HOST_AIM_ROTATION); + npc.controllerMovement = vector_sub(npc.GetAimTargetPosition(), npc.pos); + } + } + host_face(npc, npc.controllerID != -1 ? npc.controllerMovement.x : aimX); + + if (anim.animData && npc.variant == HOST_HARD && anim.IsEventTriggered("Close")) hard_host_slam(npc); + if (anim.animData && anim.IsEventTriggered("Shoot")) + { + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.controllerID != -1) aim = npc.controllerMovement; + if (!vector_is_zero(aim)) + { + ProjectilesMode mode = npc.variant == HOST_RED ? PROJECTILES_FIVE : PROJECTILES_THREE; + npc.FireProjectiles(npc.pos, vector_resized(aim, HOST_SHOT_SPEED), mode, params); + Entity* blood = blood_explosion_spawn(HOST_BLOOD_SUBTYPE, npc.pos, vector_make(0, HOST_BLOOD_RISE), + COLOR_DEFAULT, {}); + blood->sprite.scale = vector_make(HOST_BLOOD_SCALE, HOST_BLOOD_SCALE); + blood->renderDepthOffset = HOST_BLOOD_DEPTH; + } + } + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.sprite.Play("Idle"); +} + +// 005111b0 The Hosts' AI: a Host hides in its shell, shrugging off hits, and peeks out to shoot a spread at a target +// in range. The red one has no shell, the hard one cracks the floor as it closes, and the floating one bounces around. +void npc_host_update(Entity_NPC& npc) +{ + bool isShelled = + npc.type == ENTITY_FLOATING_HOST || (npc.variant != HOST_RED && npc.subtype != HOST_UNSHELLED); + if (npc.state == NPC_STATE_INIT) return host_init(npc, isShelled); + + npc.isInvincible = false; + if (isShelled && npc.pendingDamage > 0) host_shell_absorb(npc); + if (npc.controllerID != -1) host_charge_update(npc, isShelled); + if (npc.type == ENTITY_FLOATING_HOST) + { + npc.friction *= FLOATING_FRICTION; + npc_bounce_push(npc, FLOATING_ACCEL); + } + else npc.friction *= HOST_FRICTION; + + float aimX = npc.GetPlayerTarget()->pos.x - npc.pos.x; + ProjectileParams params; + params.fallingAccelModifier -= HOST_SHOT_FALL; + params.velocityMulti = HOST_SHOT_VELOCITY; + if (npc.type == ENTITY_FLOATING_HOST) + { + params.velocityMulti = FLOATING_SHOT_VELOCITY; + params.isFallingKept = true; + } + + if (npc.state == NPC_STATE_IDLE) host_rest_update(npc, isShelled); + else if (npc.state == NPC_STATE_ATTACK) host_shoot_update(npc, isShelled, aimX, params); + else if (npc.state == NPC_STATE_ATTACK2) + { + if (isShelled) npc.ClearEntityFlags(FLAG_NO_TARGET); + host_thud(npc); + host_face(npc, aimX); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + } +} diff --git a/src/npc_maggot.cpp b/src/npc_maggot.cpp new file mode 100644 index 0000000..09e1fd0 --- /dev/null +++ b/src/npc_maggot.cpp @@ -0,0 +1,875 @@ +#include "npc_caves.h" +#include "sfx_manager.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "room_grid.h" +#include +#include + +// The maggot kin this AI runs: the Maggot, the Charger (drowned, dank, the Carrion Princess and My Shadow), the Spitty +// (and its tainted variant), the conjoined Spitty, the Leech (kamikaze and holy) and the Gurglings and Turdling. +constexpr int CHARGER_DROWNED = 1; +constexpr int CHARGER_DANK = 2; +constexpr int CHARGER_CARRION = 3; +constexpr int MY_SHADOW_SUBTYPE = 1; +constexpr int SPITTY_TAINTED = 1; +constexpr int LEECH_HOLY = 2; +constexpr int GURGLING_PLAIN = 0; +constexpr int GURGLING_TURDLING = 2; +constexpr int GURGLING_PAIR_SUBTYPE = 1; +constexpr int GURGLING_BOMBER_SUBTYPE = 2; +constexpr int DIP_CORN_VARIANT = 2; +constexpr int STAIN_CLIMBABLE_STATE = NPC_STATE_SPECIAL; + +constexpr ColorMod TURDLING_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; +constexpr ColorMod DANK_CHARGER_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The animations by facing: sideways, up, down. The Gurgling's run up, down, left and right. +using FacingAnims = std::array; +constexpr FacingAnims MOVE_ANIMS = {"Move Hori", "Move Up", "Move Down"}; +constexpr FacingAnims LEECH_ANIMS = {"Hori", "Up", "Down"}; +constexpr FacingAnims DASH_ANIMS = {"DashHori", "DashUp", "DashDown"}; +constexpr FacingAnims ATTACK_ANIMS = {"Attack Hori", "Attack Up", "Attack Down"}; +constexpr FacingAnims CONJOINED_MOVE_ANIMS = {"Move Hori", "Move Vert", "Move Vert"}; +constexpr FacingAnims CONJOINED_ATTACK_ANIMS = {"Attack Hori", "Attack Down", "Attack Down"}; +constexpr FacingAnims ALERT_ANIMS = {"Alert Hori", "Alert Up", "Alert Down"}; +constexpr FacingAnims RECOVER_ANIMS = {"Recover Hori", "Recover Up", "Recover Down"}; +constexpr std::array GURGLING_WALK_ANIMS = {"WalkVert", "WalkVert", "WalkLeft", "WalkRight"}; +constexpr std::array GURGLING_CHARGE_ANIMS = {"ChargeUp", "ChargeDown", "ChargeLeft", "ChargeRight"}; +enum Facing : int +{ + FACING_SIDE, + FACING_UP, + FACING_DOWN +}; + +// They wander along the grid's axes (the drowned Charger slowest) and keep their cell marked for the pathfinder. +constexpr float MAGGOT_SPEED = 0.75f; +constexpr float CHARGER_SPEED = 0.6f; +constexpr float DROWNED_SPEED = 0.54f; +constexpr float SPITTY_SPEED = 0.72f; +constexpr float LEECH_SPEED = 0.85f; +constexpr float MAGGOT_FRICTION = 0.85f; +constexpr float MAGGOT_FRICTION_Y = 0.9647058f; +constexpr int MAGGOT_GRID_PATH = 900; +constexpr int GRID_PATH_LEVELS = 1000; +constexpr float STAIN_CHASE_SCALE = 1.4f; + +// The Stain's mound lifts and tilts the maggots that crawl over it. +constexpr float STAIN_SQUASH = 0.6f; +constexpr int STAIN_CLIMB_DEPTH = 1400; +constexpr float STAIN_TILT = 35; +constexpr float STAIN_CLIMB_HEIGHT = 26; + +// A charger charges every fourth frame at a target within 200 in line with one of its axes in a clear line (a leech +// at any range), aiming ahead of it. +constexpr int CHARGE_CHECK_FRAMES = 4; +constexpr int CONTROLLER_ACTION_CHARGE = 9; +constexpr int CONTROLLER_ACTION_BURST = 8; +constexpr float CHARGE_LEAD = 16; +constexpr float CHARGE_MARGIN = 20; +constexpr float CHARGE_AXIS = 20; +constexpr float CHARGE_RANGE_SQUARED = 40000; +constexpr float CHARGE_INPUT_SCALE = 100; +constexpr float MAGGOT_CHARGE_SPEED = 1.3f; +constexpr float LEECH_CHARGE_SPEED = 1.55f; +constexpr float GURGLING_PAIR_CHARGE_SCALE = 1.5f; +constexpr float DROWNED_CHARGE_SCALE = 0.9f; +constexpr float DANK_CHARGE_SCALE = 14; +constexpr int MAGGOT_CHARGE_SOUND_DELAY = 20; + +// A charge stops at the grid or a status, when it stalls for five frames (moving less than its speed's root of two), +// or when it slows to a crawl while slowed. +constexpr float CHARGE_STALL_SQUARED = 2; +constexpr int CHARGE_STALL_FRAMES = 5; +constexpr float CHARGE_SLOW_SPEED = 3; +constexpr float CHARGER_CHARGE_FRICTION = 0.8f; +constexpr float CHARGE_FRICTION = 0.9f; +constexpr float CHARGE_ALIGN_FRICTION = 0.7f; + +// The dank Charger lunges after its alert, bouncing off walls and slowing down, leaving creep, until it recovers. +constexpr float DANK_FRICTION = 0.8f; +constexpr float DANK_STEER_FRICTION = 0.2f; +constexpr int DANK_RECOVER_FRAMES = 45; +constexpr float DANK_RECOVER_SPEED = 2; +constexpr float DANK_SLOWDOWN_START = 10; +constexpr float DANK_SLOWDOWN_FRAMES = 70; +constexpr float DANK_SLOWDOWN = 0.06f; +constexpr float DANK_ALIGN = 0.1f; +constexpr float DANK_KEEP = 0.9f; +constexpr int DANK_SPLAT_ODDS = 10; +constexpr float DANK_SPLAT_SIZE = 0.2f; +constexpr float DANK_SPLAT_RANGE = 0.5f; +constexpr int DANK_CREEP_SKIP_FRAMES = 3; +constexpr int DANK_CHARGER_CREEP_TIMEOUT = 90; +constexpr float DANK_CHARGER_CREEP_SCALE = 0.8f; + +// The Spitty spits now and then (one in 35 checks) along its facing, the conjoined one both ways, the tainted one a +// spray. The tainted one also lobs a few shots while walking and bursts into two rings as it dies. +constexpr int SPITTY_ATTACK_ODDS = 35; +constexpr float SPITTY_CONTROLLED_RANGE = 1000; +constexpr int SPITTY_RANGE_FRAMES = 7; +constexpr float SPIT_HEIGHT = 14; +constexpr float SPIT_FALL_SPEED = -0.1f; +constexpr float SPIT_FALL_ACCEL = -0.101f; +constexpr float SPITTY_SHOT_SPEED = 8; +constexpr int SPRAY_SHOTS = 10; +constexpr float SPRAY_HEIGHT = 10; +constexpr float SPRAY_SCALE = 1.7f; +constexpr float SPRAY_SCALE_STEP = 0.1f; +constexpr float SPRAY_ACCEL_STEP = 0.03f; +constexpr float SPRAY_FALL_STEP = 0.005f; +constexpr float SPRAY_FALL = 0.08f; +constexpr float SPRAY_SPEED = 18; +constexpr float SPRAY_JITTER_HALF = 0.5f; +constexpr float TAINTED_LOB_TRAJECTORY = 10; +constexpr int TAINTED_LOB_SHOTS = 3; +constexpr float TAINTED_RING_SCALE = 1.25f; +constexpr float TAINTED_RING_FALL = -0.07f; +constexpr float TAINTED_RING_SPEED = 8; +constexpr float TAINTED_RING_SHOTS = 8; +constexpr float TAINTED_RING_TURN = 0.3926991f; + +// The dying drowned Charger bursts into a cross of shots, the kamikaze and holy Leeches explode. +constexpr float DROWNED_BURST_SPEED = 8; +constexpr float DROWNED_HARD_BURST_SPEED = 10; +constexpr float LEECH_BLAST_DAMAGE = 40; +constexpr float LEECH_BLAST_RADIUS = 60; + +// A thrown maggot flies off with its throw until it leaves the room. +constexpr float THROWN_FRICTION = 0.9f; +constexpr float THROWN_EXIT_MARGIN = 80; + +// The Gurgling boss pair: its two halves bring partners, it shrugs its own kind's explosions off to 5 damage, and +// its runs leave red creep (the Turdling brown, farting now and then) and its third form trolls bombs. +constexpr float GURGLING_SELF_BLAST_DAMAGE = 5; +constexpr float GURGLING_PARTNER_STEP = 60; +constexpr float GURGLING_TRAIL_SPEED_SQUARED = 9; +constexpr float GURGLING_TRAIL_INTERVAL = 5; +constexpr float GURGLING_SPLAT_SIZE = 0.2f; +constexpr float GURGLING_SPLAT_RANGE = 0.39f; +constexpr int TURDLING_CREEP_VARIANT = 94; +constexpr int TURDLING_FART_ODDS = 3; +constexpr float TURDLING_FART_RANGE = 0.3f; +constexpr float TURDLING_FART_VOLUME = 0.5f; +constexpr float GURGLING_CREEP_SCALE = 1.23f; +constexpr float GURGLING_BOMB_INTERVAL = 15; +constexpr int GURGLING_BOMB_GRID_PATH = 900; +constexpr float GURGLING_RING_SPEED = 7.5f; +constexpr float GURGLING_RING_SHOTS = 6; +constexpr int TURDLING_DIPS = 4; +constexpr float TURDLING_DIP_TURN = 90; +constexpr int TURDLING_ENEMY_LIMIT = 8; +constexpr float TURDLING_DIP_SPEED = 10; +constexpr float TURDLING_DIP_GAP = 5; +constexpr float TURDLING_DIP_HEALTH = 0.1f; +constexpr float TURDLING_FART_REACH = 120; +constexpr float TURDLING_SOUND_VOLUME = 0.8f; +constexpr int TURDLING_SOUND_DELAY = 10; +constexpr int GURGLING_FLY_ODDS = 3; +constexpr float GURGLING_FLY_REACH = 40; +constexpr float GURGLING_FLY_SPEED = 2; + +// A summoning maggot (one Ultra Greed and the like set to summon) drops a dip behind it. +constexpr float SUMMON_DIP_REACH = 8; +constexpr float SUMMON_DIP_SPEED = 6; + +// My Shadow keeps its distance from its own kind: a push from each within 15 to 30, harder the faster it runs. +constexpr RNG SHADOW_RNG = {0, 2, 7, 25}; +constexpr float SHADOW_RANGE = 15; +constexpr float SHADOW_PUSH_BASE = 0.4f; +constexpr float SHADOW_PUSH_MIN = 0.8f; +constexpr float SHADOW_PUSH_MAX = 2; +constexpr float SHADOW_PUSH_FLOOR = 0.1f; + +// What one update of a maggot works with: the Stain it climbs, its cell, pace and facing, and whether it charges. +struct MaggotFrame +{ + Entity* stain = nullptr; + float speed = CHARGER_SPEED; + int cell = -1; + int facing = FACING_SIDE; + bool isCharger = false; + bool isClimbing = false; + bool isDank = false; +}; + +// Room::RaiseGridPathAtPos: raises a cell's pathfinding cost to a level, keeping its hundreds of other marks. +static void room_grid_path_raise(Room& room, const Vector& position, int level) +{ + int index = room.GetGridIndex(position); + if (index < 0 || level >= GRID_PATH_LEVELS) return; + + int current = room.gridPaths[index] % GRID_PATH_LEVELS; + if (current < level) room.gridPaths[index] = room.gridPaths[index] - current + level; +} + +// The Gurgling pair: a lead Gurgling brings partners until there are half again as many as the lead ones. +static void gurgling_partners_spawn(Entity_NPC& npc) +{ + std::vector pair = entity_query(ENTITY_GURGLING, GURGLING_PAIR_SUBTYPE); + int leads = 0; + for (Entity* gurgling : pair) + if (gurgling->spawnerType == 0) leads++; + + int wanted = (leads + 1) / 2 + leads; + for (int i = (int)pair.size(); i < wanted; i++) + { + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = GURGLING_PARTNER_STEP}); + g_game->Spawn({.position = spot, + .spawner = &npc, + .subType = npc.subtype, + .type = npc.type, + .variant = npc.variant, + .seed = seed}) + ->Update(); + } +} + +// The first frame: it starts wandering. The holy Leech brings its eternal fly, the lead Gurgling its partners, and the +// Turdling and dank Charger their blood colors. The update ends there. +static void maggot_init(Entity_NPC& npc) +{ + if (npc.type == ENTITY_LEECH) + { + if (npc.variant == LEECH_HOLY) + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_ETERNALFLY, .seed = Random()})->parent = + &npc; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + } + npc.state = NPC_STATE_MOVE; + bool isLeadGurgling = npc.type == ENTITY_GURGLING && npc.isBoss && npc.spawnerType == 0 && + npc.subtype == GURGLING_PAIR_SUBTYPE; + if (isLeadGurgling) gurgling_partners_spawn(npc); + + if (npc.type == ENTITY_GURGLING && npc.variant == GURGLING_TURDLING) npc.splatColor = TURDLING_SPLAT_COLOR; + else if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_DANK) npc.splatColor = DANK_CHARGER_SPLAT_COLOR; +} + +// The dying drowned Charger's cross of shots, and the kamikaze and holy Leeches' explosion. A shrunk one only dies. +static void maggot_death_burst(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_SHRINK)) return; + + if (npc.type == ENTITY_LEECH && npc.variant != 0) + { + explosion_damage({.position = npc.pos, + .source = &npc, + .damage = LEECH_BLAST_DAMAGE, + .radius = LEECH_BLAST_RADIUS}); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + } + else if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_DROWNED) + { + ProjectileParams params; + float speed = game_is_hard_mode() ? DROWNED_HARD_BURST_SPEED : DROWNED_BURST_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_CROSS, params); + } +} + +// The nearest Stain mound that can be climbed (one in its special state), if any. +static Entity* stain_find(Entity_NPC& npc) +{ + Entity* nearest = nullptr; + float best = 0; + for (Entity* stain : entity_query(ENTITY_STAIN, -1)) + { + if (static_cast(stain)->state != STAIN_CLIMBABLE_STATE) continue; + float distance = vector_length_squared(vector_sub(stain->pos, npc.pos)); + if (nearest && distance >= best) continue; + nearest = stain; + best = distance; + } + return nearest; +} + +// Over a Stain mound it draws lifted and tilted to the mound's slope (by the mound's ClimbPos height), in front of it. +// Off it, it draws plainly. Whether it climbs. +static bool stain_climb(Entity_NPC& npc, Entity* stain) +{ + npc.sprite.offset = {}; + npc.renderZOffset = 0; + npc.sprite.rotation = 0; + if (!stain) return false; + + float dx = stain->pos.x - npc.pos.x; + float dy = stain->pos.y / STAIN_SQUASH - npc.pos.y / STAIN_SQUASH; + float distance = vector_length(vector_make(dx, dy)); + if (distance >= stain->size) return false; + + npc.renderZOffset = STAIN_CLIMB_DEPTH; + float tilt = dx / stain->size * STAIN_TILT * (1 - std::abs(dy / stain->size)); + float reach = distance / stain->size; + float lift = 1 - reach * reach; + const NullFrame* climb = stain->sprite.animState.animData ? stain->sprite.animState.GetNullFrame("ClimbPos") : nullptr; + if (climb) + { + npc.sprite.offset = vector_make(0, lift * climb->pos.y); + tilt *= climb->pos.y / STAIN_CLIMB_HEIGHT; + } + npc.sprite.rotation = tilt; + npc.friction *= MAGGOT_FRICTION; + return true; +} + +// The pace it wanders at. +static float maggot_speed_get(Entity_NPC& npc) +{ + if (npc.type == ENTITY_MAGGOT) return MAGGOT_SPEED; + if (npc.type == ENTITY_LEECH) return LEECH_SPEED; + if (npc.type == ENTITY_SPITTY || npc.type == ENTITY_CONJOINED_SPITTY) return SPITTY_SPEED; + if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_DROWNED) return DROWNED_SPEED; + return CHARGER_SPEED; +} + +// The facing its animations use: the Gurgling's four ways by its motion, the others' three by their charge (while +// charging) or motion, flipped and tilted to face left (but while spitting). +static int maggot_facing_get(Entity_NPC& npc, bool isDank) +{ + if (npc.type == ENTITY_GURGLING) + { + Vector v = npc.velocity; + if (std::abs(v.x) > std::abs(v.y)) return v.x >= 0 ? 3 : 2; + return v.y >= 0 ? 1 : 0; + } + bool isCharging = npc.state == NPC_STATE_ATTACK || (isDank && npc.state == NPC_STATE_SPECIAL); + Vector v = isCharging ? npc.v1 : npc.velocity; + if (std::abs(v.x) <= std::abs(v.y)) return v.y >= 0 ? FACING_DOWN : FACING_UP; + if (npc.state == NPC_STATE_ATTACK2) return FACING_SIDE; + + npc.sprite.isFlipX = v.x < 0; + if (npc.sprite.isFlipX) npc.sprite.rotation *= -1; + return FACING_SIDE; +} + +// A thrown maggot flies on with its throw, and is gone once it leaves the room sideways. +static void maggot_thrown_update(Entity_NPC& npc) +{ + if (vector_is_zero(npc.v1)) npc.v1 = npc.targetPosition; + npc.friction *= THROWN_FRICTION; + npc.AddVelocity_divided(npc.v1, false); + + Room& room = *g_game->room; + bool isRightGone = npc.velocity.x > 0 && npc.pos.x > room.bottomRightPos.x + THROWN_EXIT_MARGIN; + bool isLeftGone = npc.velocity.x < 0 && room.topLeftPos.x - THROWN_EXIT_MARGIN > npc.pos.x; + if (isRightGone || isLeftGone) npc.Remove(); +} + +// The Turdling's dips: four corny ones flung out around it (fewer while a Delirium form has some), or a fart with too +// many enemies around. +static void turdling_dips_throw(Entity_NPC& npc) +{ + int count = npc.GetAliveEnemyCount() <= TURDLING_ENEMY_LIMIT ? TURDLING_DIPS : 0; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + count = std::min(count, TURDLING_DIPS - npc.CountRelatedEntities(ENTITY_DIP, DIP_CORN_VARIANT, nullptr)); + if (count < 1) return game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = TURDLING_FART_REACH}); + + for (int i = 0; i < count; i++) + { + Vector direction = vector_from_angle((float)i * TURDLING_DIP_TURN); + float sine = direction.y; + float cosine = direction.x; + uint32_t seed = Random(); + Vector velocity = vector_make(cosine * TURDLING_DIP_SPEED, sine * TURDLING_DIP_SPEED); + float reach = npc.size + TURDLING_DIP_GAP; + Vector spot = vector_make(reach * cosine + npc.pos.x, sine * reach + npc.pos.y); + Entity* dip = g_game->Spawn({.position = spot, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_DIP, + .variant = DIP_CORN_VARIANT, + .seed = seed}); + dip->ClearEntityFlags(FLAG_APPEAR); + dip->AddVelocity_divided(velocity, false); + dip->health = TURDLING_DIP_HEALTH; + dip->Update(); + } + npc.PlaySound(SOUND_PLOP, TURDLING_SOUND_VOLUME, TURDLING_SOUND_DELAY, false, 1); +} + +// Resting: it slows down, and the Gurglings act on their Shoot event (a ring of shots, the Turdling's dips, the boss's +// attack flies). It wanders again once its animation ends. +static void maggot_rest_update(Entity_NPC& npc) +{ + npc.friction *= MAGGOT_FRICTION; + AnimationState& anim = npc.sprite.animState; + if (npc.type == ENTITY_GURGLING && anim.animData && anim.IsEventTriggered("Shoot")) + { + if (npc.variant == GURGLING_PLAIN) + { + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(GURGLING_RING_SPEED, GURGLING_RING_SHOTS), PROJECTILES_RING, + params); + } + else if (npc.variant == GURGLING_TURDLING) turdling_dips_throw(npc); + else if (npc.subtype == 0 && Random() % GURGLING_FLY_ODDS != 0) + { + uint32_t spawned = 0; + do + { + Vector direction = random_direction(); + uint32_t seed = Random(); + Entity* fly = g_game->Spawn({.position = vector_add(vector_scale(direction, GURGLING_FLY_REACH), npc.pos), + .velocity = vector_scale(direction, GURGLING_FLY_SPEED), + .spawner = &npc, + .type = ENTITY_ATTACKFLY, + .seed = seed}); + fly->ClearEntityFlags(FLAG_APPEAR); + spawned++; + } while (spawned < Random() % GURGLING_FLY_ODDS); + } + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; +} + +// Starts a charge at its target (or its controller's push): in line with one of its axes, close and in a clear line +// from its cell, it screams and dashes along that axis. The dank one shows its alert first. +static void maggot_charge_try(Entity_NPC& npc, MaggotFrame& frame) +{ + Room& room = *g_game->room; + Vector cell = room.GetGridPosition(frame.cell); + Vector aim = npc.CalcTargetPosition(0); + Vector lead = npc.GetPlayerTarget()->velocity; + float share = random_unit(); + Vector spot = room.GetClampedPosition(vector_add(vector_scale(vector_scale(lead, share), CHARGE_LEAD), aim), + CHARGE_MARGIN); + if (frame.stain) spot = frame.stain->pos; + + bool isControlled = npc.controllerID != -1; + Vector delta = vector_sub(spot, cell); + if (isControlled) delta = vector_scale(npc.GetControllerInput(0), CHARGE_INPUT_SCALE); + if (npc.HasEntityFlags(FLAG_DISTRACTED) || frame.isClimbing) return; + if (!isControlled) + { + if (std::abs(delta.x) >= CHARGE_AXIS && std::abs(delta.y) >= CHARGE_AXIS) return; + if (vector_length_squared(delta) >= CHARGE_RANGE_SQUARED && npc.type != ENTITY_LEECH) return; + if (npc.type == ENTITY_LEECH) reconstruction_missing("Room::CheckLine 007f0df0: the leech's mode 2 line"); + if (!room_check_line(cell, spot, LINE_MODE_GROUND, 0)) return; + } + + if (npc.type == ENTITY_LEECH) npc.PlaySound(SOUND_LEECH, 1, MAGGOT_CHARGE_SOUND_DELAY, false, 1); + else if (npc.type == ENTITY_GURGLING) + { + npc.PlaySound(SOUND_CHILD_ANGRY_ROAR, 1, MAGGOT_CHARGE_SOUND_DELAY, false, 1); + npc.PlaySound(SOUND_GURGLING_ATTACK, 1, 2, false, 1); + } + else npc.PlaySound(SOUND_MAGGOTCHARGE, 1, MAGGOT_CHARGE_SOUND_DELAY, false, 1); + + npc.v1 = vector_scale(vector_cardinal(delta), npc.type == ENTITY_LEECH ? LEECH_CHARGE_SPEED : MAGGOT_CHARGE_SPEED); + if (npc.type == ENTITY_GURGLING) + { + if (npc.isBoss && npc.subtype == GURGLING_PAIR_SUBTYPE) npc.v1 = vector_scale(npc.v1, GURGLING_PAIR_CHARGE_SCALE); + } + else if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_DROWNED) + npc.v1 = vector_scale(npc.v1, DROWNED_CHARGE_SCALE); + else if (frame.isDank) npc.v1 = vector_scale(npc.v1, DANK_CHARGE_SCALE); + + npc.state = NPC_STATE_ATTACK; + npc.pathfinder.gridPathTarget = npc.pos; + npc.pathfinder.moveCountdown = 0; + npc.stateFrame = 0; + npc.v2 = npc.pos; + if (!frame.isDank) return; + + frame.facing = FACING_SIDE; + if (std::abs(npc.v1.x) <= std::abs(npc.v1.y)) frame.facing = npc.v1.y >= 0 ? FACING_DOWN : FACING_UP; + else + { + npc.sprite.isFlipX = npc.v1.x < 0; + if (npc.sprite.isFlipX) npc.sprite.rotation *= -1; + } + npc.sprite.Play(ALERT_ANIMS[frame.facing]); +} + +// A Spitty starts spitting now and then (or when its controller aims), along its facing. +static void spitty_attack_try(Entity_NPC& npc, const MaggotFrame& frame) +{ + if (npc.type != ENTITY_SPITTY && npc.type != ENTITY_CONJOINED_SPITTY) return; + + bool isReady = npc.controllerID != -1 + ? npc.IsTargetInAttackRange(SPITTY_CONTROLLED_RANGE, SPITTY_RANGE_FRAMES, false) + : Random() % SPITTY_ATTACK_ODDS == 0; + if (!isReady || npc.HasEntityFlags(FLAG_DISTRACTED)) return; + + npc.UpdateControllerMovement(true); + npc.state = NPC_STATE_ATTACK2; + npc.stateFrame = 0; + const FacingAnims& anims = npc.type == ENTITY_SPITTY ? ATTACK_ANIMS : CONJOINED_ATTACK_ANIMS; + npc.sprite.Play(anims[frame.facing], PLAY_FORCED); + npc.i1 = frame.facing; +} + +// Wandering: it walks along the grid's axes (toward a Stain mound to climb), the tainted Spitty lobbing shots, and +// starts a charge or a spit when it can. +static void maggot_wander_update(Entity_NPC& npc, MaggotFrame& frame) +{ + if (npc.type == ENTITY_LEECH) npc.sprite.Play(LEECH_ANIMS[frame.facing]); + else if (npc.type == ENTITY_GURGLING) npc.sprite.Play(GURGLING_WALK_ANIMS[frame.facing]); + else if (npc.type == ENTITY_CONJOINED_SPITTY) npc.sprite.Play(CONJOINED_MOVE_ANIMS[frame.facing]); + else npc.sprite.Play(MOVE_ANIMS[frame.facing]); + + if (!frame.stain) npc.pathfinder.MoveRandomlyAxisAligned(frame.speed, STATUS_OBEYED); + else + { + npc.pathfinder.FindGridPath(frame.stain->pos, frame.speed * STAIN_CHASE_SCALE, 0, DIRECT_PATH_FAR); + npc.velocity = vector_scale(vector_cardinal(npc.velocity), vector_length(npc.velocity)); + } + npc.friction *= MAGGOT_FRICTION; + npc.velocity.y *= npc_friction_scaled(MAGGOT_FRICTION_Y, npc.speedMultiplier); + + if (npc.type == ENTITY_SPITTY && npc.variant == SPITTY_TAINTED && npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + params = ProjectileParams(); + int count = (int)(Random() & 1) + TAINTED_LOB_SHOTS; + npc.FireBossProjectiles(count, {}, TAINTED_LOB_TRAJECTORY, params); + } + + bool isReady = frame.isCharger && (npc.controllerID != -1 ? npc.IsControllerActionPressed(CONTROLLER_ACTION_CHARGE) + : npc.IsFrame(CHARGE_CHECK_FRAMES, (int)npc.index)); + if (isReady) return maggot_charge_try(npc, frame); + spitty_attack_try(npc, frame); +} + +// The dank Charger's lunge: it bounces off walls, steers into its charge while slowing down and keeps to its cell's +// line, bleeding and leaving creep, then recovers once slow after 45 frames. +static void dank_charge_update(Entity_NPC& npc, MaggotFrame& frame) +{ + npc.friction *= DANK_FRICTION; + if (npc_anim_is_done(npc)) npc.sprite.Play(ATTACK_ANIMS[frame.facing]); + if (!npc.sprite.animState.IsLoopingAnimation()) return; + + if (npc.isCollidesWithGrid) npc.v1 = vector_scale(npc.v1, -1); + if (npc.stateFrame > DANK_RECOVER_FRAMES && vector_length(npc.v1) < DANK_RECOVER_SPEED) + { + npc.pathfinder.ResetMovementTarget(); + npc.sprite.Play(RECOVER_ANIMS[frame.facing]); + npc.state = NPC_STATE_SPECIAL; + } + else + { + npc.friction = 1; + float keep = 1 - npc_friction_scaled(DANK_STEER_FRICTION, npc.speedMultiplier); + npc.velocity.x += keep * (npc.v1.x - npc.velocity.x); + npc.velocity.y += keep * (npc.v1.y - npc.velocity.y); + float slowdown = std::clamp(((float)npc.stateFrame - DANK_SLOWDOWN_START) / DANK_SLOWDOWN_FRAMES, 0.0f, 1.0f); + npc.v1 = vector_scale(npc.v1, 1 - slowdown * DANK_SLOWDOWN); + + Vector cell = g_game->room->GetGridPosition(frame.cell); + if (npc.controllerID != -1) cell = npc.v2; + if (std::abs(npc.velocity.y) > std::abs(npc.velocity.x)) npc.pos.x = cell.x * DANK_ALIGN + npc.pos.x * DANK_KEEP; + else npc.pos.y = cell.y * DANK_ALIGN + npc.pos.y * DANK_KEEP; + npc.sprite.Play(ATTACK_ANIMS[frame.facing]); + } + + if (Random() % DANK_SPLAT_ODDS == 0) + npc.MakeSplat(random_unit() * DANK_SPLAT_RANGE + DANK_SPLAT_SIZE) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (npc.IsFrame(DANK_CREEP_SKIP_FRAMES, 0) || npc.HasEntityFlags(FLAG_SHRINK)) return; + + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_BLACK, .seed = Random()})); + creep->parent = &npc; + creep->SetTimeout(DANK_CHARGER_CREEP_TIMEOUT); + creep->sprite.scale = vector_make(DANK_CHARGER_CREEP_SCALE, DANK_CHARGER_CREEP_SCALE); + creep->Update(); +} + +// A charge: it dashes along its axis, kept on its cell's line, until it stalls, hits the grid or a status stops it +// (the Gurgling then stops short). +static void maggot_charge_update(Entity_NPC& npc, MaggotFrame& frame) +{ + if (frame.isDank) return dank_charge_update(npc, frame); + + PathFinder& path = npc.pathfinder; + float speedSquared = npc.speedMultiplier * npc.speedMultiplier; + if (vector_length_squared(vector_sub(path.gridPathTarget, npc.pos)) / speedSquared < CHARGE_STALL_SQUARED) + path.moveCountdown += npc_ticks_get(npc); + else path.moveCountdown = 0; + path.gridPathTarget = npc.pos; + + bool isSlowedStill = npc.HasEntityFlags(FLAG_SLOW) && vector_length(npc.velocity) < CHARGE_SLOW_SPEED; + if (npc.isCollidesWithGrid || npc.HasEntityFlags(FLAG_DISTRACTED) || isSlowedStill || + path.moveCountdown > CHARGE_STALL_FRAMES || frame.isClimbing) + { + path.ResetMovementTarget(); + if (npc.type != ENTITY_GURGLING) + { + npc.state = NPC_STATE_MOVE; + return; + } + npc.sprite.Play("Stop"); + npc.state = NPC_STATE_IDLE; + return; + } + + npc.friction *= npc.type == ENTITY_CHARGER ? CHARGER_CHARGE_FRICTION : CHARGE_FRICTION; + npc.AddVelocity_divided(npc.v1, false); + Vector cell = g_game->room->GetGridPosition(frame.cell); + if (npc.controllerID != -1) cell = npc.v2; + if (npc.type != ENTITY_GURGLING) + { + float keep = 1 - npc_friction_scaled(CHARGE_ALIGN_FRICTION, npc.speedMultiplier); + if (std::abs(npc.v1.y) <= std::abs(npc.v1.x)) + npc.velocity.y = ((cell.y - npc.pos.y) - npc.velocity.y) * keep + npc.velocity.y; + else npc.velocity.x = ((cell.x - npc.pos.x) - npc.velocity.x) * keep + npc.velocity.x; + } + if (npc.type == ENTITY_LEECH) npc.sprite.Play(DASH_ANIMS[frame.facing]); + else if (npc.type == ENTITY_GURGLING) npc.sprite.Play(GURGLING_CHARGE_ANIMS[frame.facing]); + else npc.sprite.Play(ATTACK_ANIMS[frame.facing]); +} + +// The way a spitting maggot faces (left, up, right or down): its controller's aim (facing it), else the facing it +// started spitting with. +static int spitty_direction_get(Entity_NPC& npc, int& facing) +{ + if (npc.controllerID == -1) + { + if (npc.i1 == FACING_SIDE) return npc.sprite.isFlipX ? DIRECTION_LEFT : DIRECTION_RIGHT; + return npc.i1 == FACING_UP ? DIRECTION_UP : DIRECTION_DOWN; + } + int direction = vector_to_direction(npc.controllerMovement); + npc.sprite.isFlipX = false; + facing = direction == DIRECTION_UP ? FACING_UP : direction == DIRECTION_DOWN ? FACING_DOWN : FACING_SIDE; + if (facing == FACING_SIDE) npc.sprite.isFlipX = direction == DIRECTION_LEFT; + + const FacingAnims& anims = npc.type == ENTITY_SPITTY ? ATTACK_ANIMS : CONJOINED_ATTACK_ANIMS; + if (!npc.sprite.IsPlaying(anims[facing])) npc.sprite.SetAnimation(anims[facing]); + return direction; +} + +// The tainted Spitty's spray: ten shots fanning wider, smaller and slower along its facing. +static void tainted_spray(Entity_NPC& npc, int direction) +{ + ProjectileParams params; + params.heightModifier = SPRAY_HEIGHT; + Vector axis = direction_unit(direction); + for (int i = 0; i < SPRAY_SHOTS; i++) + { + params.bulletFlags = PROJECTILE_ACCELERATE; + params.scale = SPRAY_SCALE - (float)i * SPRAY_SCALE_STEP; + params.acceleration = 1 - (float)i * SPRAY_ACCEL_STEP; + params.fallingAccelModifier = (float)(SPRAY_SHOTS - i) * SPRAY_FALL_STEP - SPRAY_FALL; + float angle = (random_unit() - SPRAY_JITTER_HALF) * (float)i * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + Vector shot = vector_make((cosine * axis.x - sine * axis.y) * SPRAY_SPEED, + (sine * axis.x + cosine * axis.y) * SPRAY_SPEED); + npc.FireProjectiles(npc.pos, shot, PROJECTILES_SINGLE, params); + } +} + +// Spitting: on its Shoot event it spits along its facing (the conjoined one both ways, the tainted one a spray). +static void spitty_spit_update(Entity_NPC& npc, MaggotFrame& frame) +{ + npc.friction *= MAGGOT_FRICTION; + npc.UpdateControllerMovement(false); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + npc.PlaySound(SOUND_LITTLE_SPIT, 1, 2, false, 1); + ProjectileParams params; + params.heightModifier = SPIT_HEIGHT; + params.fallingSpeedModifier = SPIT_FALL_SPEED; + params.fallingAccelModifier = SPIT_FALL_ACCEL; + int direction = spitty_direction_get(npc, frame.facing); + if (npc.type == ENTITY_SPITTY && npc.variant == SPITTY_TAINTED) return tainted_spray(npc, direction); + + Vector shot = vector_scale(direction_unit(direction), SPITTY_SHOT_SPEED); + npc.FireProjectiles(npc.pos, shot, PROJECTILES_SINGLE, params); + if (npc.type == ENTITY_CONJOINED_SPITTY) npc.FireProjectiles(npc.pos, vector_scale(shot, -1), PROJECTILES_SINGLE, params); +} + +// Summoning: on its Shoot event it farts a dip out behind it, holding it as its child. +static void maggot_summon_update(Entity_NPC& npc) +{ + npc.friction *= DANK_FRICTION; + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_FART, 1, 2, false, 1); + int direction = npc.i1 == FACING_SIDE ? (npc.sprite.isFlipX ? DIRECTION_LEFT : DIRECTION_RIGHT) + : (npc.i1 != FACING_UP ? DIRECTION_DOWN : DIRECTION_UP); + Vector behind = vector_scale(direction_unit(direction), -1); + uint32_t seed = npc.dropRNG.Next(); + Entity* dip = g_game->Spawn({.position = vector_add(vector_scale(behind, SUMMON_DIP_REACH), npc.pos), + .velocity = vector_scale(behind, SUMMON_DIP_SPEED), + .spawner = &npc, + .type = ENTITY_DIP, + .seed = seed}); + dip->ClearEntityFlags(FLAG_APPEAR); + dip->Update(); + npc.child = dip; +} + +// A running Gurgling's trail every 5 frames of its own time: blood, and creep (the Turdling's brown with farts) while +// it runs. The third boss Gurgling trolls a bomb every 15 frames instead. +static void gurgling_trail(Entity_NPC& npc) +{ + if (vector_length_squared(npc.velocity) <= GURGLING_TRAIL_SPEED_SQUARED) return; + + if (npc.GetIntervalTicks(GURGLING_TRAIL_INTERVAL, 0) != 0) + npc.MakeSplat(random_unit() * GURGLING_SPLAT_RANGE + GURGLING_SPLAT_SIZE) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (npc.variant != GURGLING_PLAIN && npc.state != NPC_STATE_ATTACK) return; + + if ((!npc.isBoss || npc.subtype == 0) && npc.GetIntervalTicks(GURGLING_TRAIL_INTERVAL, 0) != 0) + { + int variant = EFFECT_CREEP_RED; + if (npc.variant == GURGLING_TURDLING) + { + variant = TURDLING_CREEP_VARIANT; + if (Random() % TURDLING_FART_ODDS == 0) + { + float pitch = random_unit() * TURDLING_FART_RANGE + 1; + float volume = random_unit() * TURDLING_FART_RANGE + TURDLING_FART_VOLUME; + npc.PlaySound(SOUND_FART, volume, 2, false, pitch); + } + } + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()})); + creep->sprite.scale = vector_make(GURGLING_CREEP_SCALE, GURGLING_CREEP_SCALE); + creep->rotation = 0; + creep->Update(); + if (npc.isChampion) creep->SetColor(npc.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + else if (npc.variant != GURGLING_TURDLING) + { + ColorMod color = npc.color; + color._tint[3] = 1; + creep->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + return; + } + if (!npc.isBoss || npc.subtype != GURGLING_BOMBER_SUBTYPE || npc.GetIntervalTicks(GURGLING_BOMB_INTERVAL, 0) == 0) + return; + + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BOMB, .variant = BOMB_TROLL, .seed = Random()}) + ->entityCollisionClass = ENTCOLL_PLAYERONLY; + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(npc.pos), GURGLING_BOMB_GRID_PATH); +} + +// The tainted Spitty's death: two rings of orbiting shots, one each way. +static void tainted_spitty_burst(Entity_NPC& npc) +{ + ProjectileParams params; + params.targetPosition = npc.pos; + params.scale = TAINTED_RING_SCALE; + params.fallingAccelModifier = TAINTED_RING_FALL; + params.circleAngle = 0; + params.bulletFlags = PROJECTILE_ORBIT_CW; + Vector ring = vector_make(TAINTED_RING_SPEED, TAINTED_RING_SHOTS); + npc.FireProjectiles(npc.pos, ring, PROJECTILES_RING, params); + params.circleAngle = TAINTED_RING_TURN; + params.bulletFlags = PROJECTILE_ORBIT_CCW; + npc.FireProjectiles(npc.pos, ring, PROJECTILES_RING, params); +} + +// My Shadow keeps its distance from the others of its kind while wandering. +static void shadow_spread(Entity_NPC& npc) +{ + RNG rng = SHADOW_RNG; + rng._seed = npc.initSeed; + float range = rng.RandomFloat() * SHADOW_RANGE + SHADOW_RANGE; + float push = std::min(std::max(vector_length(npc.velocity) + SHADOW_PUSH_BASE, SHADOW_PUSH_MIN), SHADOW_PUSH_MAX); + + Vector total{}; + bool isVersus = g_game->deathmatchManager.state >= DEATHMATCH_INTRO; + for (Entity* other : entity_query(npc.type, npc.variant)) + { + bool isTarget = (isVersus && other->type == ENTITY_PLAYER) || Entity::is_enemy_type(other->type); + if (other->subtype != npc.subtype || !isTarget || other == &npc) continue; + + Vector away = vector_sub(npc.pos, other->pos); + float distance = vector_length(away); + if (distance <= 0 || distance >= range || push <= SHADOW_PUSH_FLOOR) continue; + total.x += push * (away.x / distance); + total.y += push * (away.y / distance); + } + npc.velocity.x += npc.speedMultiplier * total.x; + npc.velocity.y += npc.speedMultiplier * total.y; +} + +// The forward vector other code reads: the Gurgling's down, the others' facing. +static void maggot_forward_set(Entity_NPC& npc, int facing) +{ + if (npc.type == ENTITY_GURGLING) + { + npc.forwardVector = vector_make(0, 1); + return; + } + int direction = facing == FACING_UP ? DIRECTION_UP + : facing == FACING_DOWN ? DIRECTION_DOWN + : (npc.sprite.isFlipX ? DIRECTION_LEFT : DIRECTION_RIGHT); + npc.forwardVector = direction_unit(direction); +} + +// 0052db50 The maggot kin's AI: they wander along the grid's axes, and the Chargers, Leeches and Gurglings charge +// along an axis at a target in line with them while the Spitties spit along their facing. The dank Charger lunges, +// the drowned one and the Leeches burst as they die, and the Gurglings leave trails and summon. +void npc_maggot_update(Entity_NPC& npc) +{ + if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_CARRION) + reconstruction_missing("NpcAI::ENTITY_MAGGOT 0052db50: the Carrion Princess's diagonal charge"); + bool isShadow = npc.type == ENTITY_CHARGER && npc.variant == 0 && npc.subtype == MY_SHADOW_SUBTYPE; + if (npc.type == ENTITY_LEECH && npc.variant != 0 && npc.IsControllerActionPressed(CONTROLLER_ACTION_BURST)) + npc.Kill(EntityRef()); + if (npc.isDead) maggot_death_burst(npc); + if (npc.type == ENTITY_GURGLING && npc.isBoss && npc.subtype == GURGLING_BOMBER_SUBTYPE) + for (DamageEvent& event : npc.damageEvents) + if ((event.damageFlags & DAMAGE_EXPLOSION) && event.source.type == npc.type) + event.damage = GURGLING_SELF_BLAST_DAMAGE; + + MaggotFrame frame{.stain = stain_find(npc)}; + if (npc.state == NPC_STATE_INIT) return maggot_init(npc); + + frame.isClimbing = stain_climb(npc, frame.stain); + frame.isCharger = npc.type == ENTITY_CHARGER || npc.type == ENTITY_LEECH || npc.type == ENTITY_GURGLING; + bool isLeftAlone = npc.GetPlayerTarget()->type == ENTITY_PLAYER && npc.HasEntityFlags(FLAG_FRIENDLY) && + npc.controllerID == -1 && g_game->deathmatchManager.state < DEATHMATCH_INTRO; + if (isLeftAlone) frame.isCharger = false; + frame.speed = maggot_speed_get(npc); + Room& room = *g_game->room; + frame.cell = room.GetGridIndex(npc.pos); + room_grid_path_raise(room, npc.pos, MAGGOT_GRID_PATH); + frame.isDank = npc.type == ENTITY_CHARGER && npc.variant == CHARGER_DANK; + if (npc.state == NPC_STATE_SUICIDE) return maggot_thrown_update(npc); + + frame.facing = maggot_facing_get(npc, frame.isDank); + switch (npc.state) + { + case NPC_STATE_IDLE: + maggot_rest_update(npc); + break; + case NPC_STATE_MOVE: + maggot_wander_update(npc, frame); + break; + case NPC_STATE_ATTACK: + maggot_charge_update(npc, frame); + break; + case NPC_STATE_ATTACK2: + spitty_spit_update(npc, frame); + if (npc.sprite.IsFinished()) npc.state = NPC_STATE_MOVE; + break; + case NPC_STATE_SPECIAL: + npc.friction *= DANK_FRICTION; + if (npc.sprite.IsFinished()) npc.state = NPC_STATE_MOVE; + break; + case NPC_STATE_SUMMON: + maggot_summon_update(npc); + if (npc.sprite.IsFinished()) npc.state = NPC_STATE_MOVE; + break; + } + + npc.stateFrame += npc_ticks_get(npc); + maggot_forward_set(npc, frame.facing); + if (npc.type == ENTITY_GURGLING) gurgling_trail(npc); + bool isTaintedSpitty = npc.type == ENTITY_SPITTY && npc.variant == SPITTY_TAINTED; + if (npc.isDead && isTaintedSpitty && !npc.HasEntityFlags(FLAG_SHRINK)) tainted_spitty_burst(npc); + if (isShadow && npc.state == NPC_STATE_MOVE) shadow_spread(npc); +} diff --git a/src/npc_mama_fly.cpp b/src/npc_mama_fly.cpp new file mode 100644 index 0000000..6deaf84 --- /dev/null +++ b/src/npc_mama_fly.cpp @@ -0,0 +1,198 @@ +#include "npc_caves.h" +#include "boss_ai.h" +#include "room_grid.h" +#include "sfx_manager.h" + +// The Mama Fly flies to spots 80 to 200 away, as far from its target as it finds in 10 tries, and lays a Pustule on +// each (up to 10 in the room). It picks a new spot after 90 frames one time in ten. Dying, it spills three maggots. +constexpr int MAMA_FLY_PUSTULE_CAP = 10; +constexpr int MAMA_FLY_SPOT_TRIES = 10; +constexpr float MAMA_FLY_SPOT_MIN = 80; +constexpr float MAMA_FLY_SPOT_RANGE = 120; +constexpr float MAMA_FLY_SPOT_CLEARANCE = 24; +constexpr int MAMA_FLY_RESTLESS_FRAMES = 90; +constexpr uint32_t MAMA_FLY_RESTLESS_ODDS = 10; +constexpr float MAMA_FLY_SPEED = 0.6f; +constexpr float MAMA_FLY_ARRIVED = 10; +constexpr float MAMA_FLY_FRICTION = 0.8f; +constexpr float MAMA_FLY_LAY_FRICTION = 0.7f; + +// Its death: three maggots hop 0 to 80 out (onto a free tile within 64 when that lands on a block), from up to 15 out +// and 15 to 30 high, and a blood burst 10 to 70 high in its splat's color. +constexpr int MAMA_FLY_MAGGOTS = 3; +constexpr float MAMA_FLY_MAGGOT_REACH = 80; +constexpr float MAMA_FLY_FREE_TILE_RANGE = 64; +constexpr float MAMA_FLY_MAGGOT_JITTER = 38; +constexpr float MAMA_FLY_MAGGOT_HEIGHT = -30; +constexpr float MAMA_FLY_MAGGOT_HEIGHT_RANGE = 15; +constexpr float MAMA_FLY_MAGGOT_START = 15; +constexpr float MAMA_FLY_BURST_HEIGHT = -10; +constexpr float MAMA_FLY_BURST_HEIGHT_RANGE = 60; +constexpr int MAMA_FLY_BURST_SUBTYPE = 3; + +// A hopping maggot's leap: 4% of the way a frame, after 10 to 39 frames of crawling. +constexpr float MAGGOT_JUMP_RISE = -8; +constexpr float MAGGOT_JUMP_SHARE = 0.04f; +constexpr uint32_t MAGGOT_CRAWL_FRAMES = 30; +constexpr int MAGGOT_CRAWL_MIN = 10; + +// 004d8910 spawn_small_maggot_jump: a small maggot leaping from a position, a height up, onto a spot it keeps clear. +Entity_NPC* small_maggot_jump_spawn(const Vector& position, float height, const Vector& spot) +{ + Room& room = *g_game->room; + auto* maggot = + static_cast(g_game->Spawn({.position = position, .type = ENTITY_SMALL_MAGGOT, .seed = Random()})); + maggot->ClearEntityFlags(FLAG_APPEAR); + room_grid_path_mark(room, room.GetGridIndex(spot), GRID_PATH_FREED); + + maggot->v1.x = MAGGOT_JUMP_RISE; + maggot->state = NPC_STATE_SPECIAL; + maggot->i1 = 0; + maggot->targetPosition = vector_scale(vector_sub(spot, position), MAGGOT_JUMP_SHARE); + maggot->velocity = maggot->targetPosition; + maggot->posOffset.y = height; + maggot->Update(); + + maggot->pathfinder.movementTarget = vector_normalized(maggot->velocity); + RNG crawl = {maggot->initSeed, 5, 9, 7}; + maggot->pathfinder.moveCountdown = (int)crawl.RandomInt(MAGGOT_CRAWL_FRAMES) + MAGGOT_CRAWL_MIN; + return maggot; +} + +// A new spot to lay on: the free cell farthest from its target among 10 tries 80 to 200 away, kept off landing kin. +static void mama_fly_spot_pick(Entity_NPC& npc) +{ + Vector targetPos = npc.GetPlayerTarget()->pos; + if (entity_query(ENTITY_PUSTULE, -1).size() >= MAMA_FLY_PUSTULE_CAP) return; + + Room& room = *g_game->room; + Vector best{}; + float bestDistance = 0; + for (int i = 0; i < MAMA_FLY_SPOT_TRIES; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit() * MAMA_FLY_SPOT_RANGE + MAMA_FLY_SPOT_MIN; + Vector spot = vector_add(npc.pos, vector_make(std::cos(angle) * reach, std::sin(angle) * reach)); + int cell = room.GetGridIndex(spot); + if (room.GetGridCollision(cell) != COLLISION_NONE) continue; + + Vector center = room.GetGridPosition(cell); + float distance = vector_length(vector_sub(targetPos, center)); + if (distance <= bestDistance) continue; + + bool isTaken = false; + for (Entity* enemy : entity_query_radius(center, MAMA_FLY_SPOT_CLEARANCE, QUERY_ENEMIES)) + isTaken = isTaken || enemy->entityGridCollisionClass == GRIDCOLL_GROUND; + if (isTaken) continue; + + bestDistance = distance; + best = center; + } + if (vector_is_zero(best)) return; + + npc.targetPosition = best; + npc.i2 = 0; +} + +// Its death throes: three maggots hop out and blood bursts in its splat's color. +static void mama_fly_death(Entity_NPC& npc) +{ + Room& room = *g_game->room; + for (int i = 0; i < MAMA_FLY_MAGGOTS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit(); + Vector spot = vector_make(std::cos(angle) * reach * MAMA_FLY_MAGGOT_REACH + npc.pos.x, + std::sin(angle) * reach * MAMA_FLY_MAGGOT_REACH + npc.pos.y); + if ((int)room.GetGridCollision(room.GetGridIndex(spot)) >= 1) + { + Vector tile = room_free_tile_position_find(spot, MAMA_FLY_FREE_TILE_RANGE); + float y = random_unit() * MAMA_FLY_MAGGOT_JITTER - MAMA_FLY_MAGGOT_JITTER / 2 + tile.y; + float x = random_unit() * MAMA_FLY_MAGGOT_JITTER - MAMA_FLY_MAGGOT_JITTER / 2 + tile.x; + spot = vector_make(x, y); + } + Vector direction = vector_normalized(vector_sub(spot, npc.pos)); + float height = random_unit() * MAMA_FLY_MAGGOT_HEIGHT_RANGE + MAMA_FLY_MAGGOT_HEIGHT; + float start = random_unit() * MAMA_FLY_MAGGOT_START; + small_maggot_jump_spawn(vector_add(npc.pos, vector_scale(direction, start)), height, spot); + } + + float height = MAMA_FLY_BURST_HEIGHT - random_unit() * MAMA_FLY_BURST_HEIGHT_RANGE; + int subType = (int)(Random() & 1) + MAMA_FLY_BURST_SUBTYPE; + Entity* burst = g_game->Spawn({.position = npc.pos, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + burst->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + burst->sprite.offset = vector_make(0, height); + burst->renderDepthOffset = BOSS_BLOOD_DEPTH; +} + +// 004ddf00 The Mama Fly's AI: it flies to a spot far from its target, lands and lays a Pustule there unless the cell is +// blocked, then picks another. It passes through its own Pustules, and spills maggots as it dies. +void npc_mama_fly_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + Entity* collider = npc.collisionEntity; + if (collider->type == ENTITY_PUSTULE && collider->IsFriendly() == npc.IsFriendly()) npc.collisionResult = 0; + return; + } + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.i1 = 0; + npc.splatColor = COLOR_GREEN_SPLAT; + npc.aiCallFlags = AI_CALL_COLLISION; + } + else if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Idle"); + npc.i2 += npc_ticks_get(npc); + Vector destination = vector_is_zero(npc.targetPosition) ? npc.GetPlayerTarget()->pos : npc.targetPosition; + npc.pathfinder.FindGridPath(destination, MAMA_FLY_SPEED, 0, DIRECT_PATH_FAR); + if (!vector_is_zero(npc.targetPosition) && + vector_length(vector_sub(npc.targetPosition, npc.pos)) < MAMA_FLY_ARRIVED) + { + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + } + npc.sprite.isFlipX = npc.velocity.x > 0; + npc.friction *= MAMA_FLY_FRICTION; + } + else if (npc.state == NPC_STATE_ATTACK) + { + npc.friction *= MAMA_FLY_LAY_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + AnimationState& animation = npc.sprite.animState; + if (animation.animData && animation.IsEventTriggered("Sound")) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + } + if (animation.animData && animation.IsEventTriggered("Shoot")) + { + if (room_grid_collision_at(npc.pos) == COLLISION_NONE) + { + Entity* pustule = g_game->Spawn({.position = npc.pos, .type = ENTITY_PUSTULE, .seed = Random()}); + pustule->ClearEntityFlags(FLAG_APPEAR); + pustule->Update(); + } + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + } + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_IDLE; + npc.targetPosition = {}; + npc.i2 = 0; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + } + } + + bool isRestless = npc.state == NPC_STATE_IDLE && npc.i2 > MAMA_FLY_RESTLESS_FRAMES; + if (vector_is_zero(npc.targetPosition) || (isRestless && Random() % MAMA_FLY_RESTLESS_ODDS == 0)) + mama_fly_spot_pick(npc); + if (npc.isDead) mama_fly_death(npc); +} diff --git a/src/npc_maw.cpp b/src/npc_maw.cpp new file mode 100644 index 0000000..f47d888 --- /dev/null +++ b/src/npc_maw.cpp @@ -0,0 +1,133 @@ +#include "npc_caves.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "game.h" +#include "sfx_manager.h" + +// The Maw's variants: the plain one, the red one that bursts into shots and the psychic one with its eternal fly. +enum MawVariant : int +{ + MAW_PLAIN, + MAW_RED, + MAW_PSYCHIC +}; + +// It drifts toward its target, kept off the top and bottom walls, bleeding now and then. +constexpr float MAW_MARGIN_TOP = 30; +constexpr float MAW_MARGIN_BOTTOM = 10; +constexpr int MAW_SPLAT_ODDS = 10; +constexpr float MAW_SPLAT_SIZE = 0.4f; +constexpr float MAW_SPLAT_RANGE = 0.5f; +constexpr float MAW_ACCEL = 0.13f; +constexpr float MAW_RED_ACCEL_SCALE = 3; +constexpr float MAW_FRICTION = 0.93f; + +// It spits at a target within 200 in a clear line, a homing shot for the psychic one, every 28 frames. +constexpr float MAW_RANGE = 200; +constexpr int MAW_RANGE_FRAMES = 7; +constexpr int MAW_COOLDOWN = 28; +constexpr float MAW_SHOT_SPEED = 7; +constexpr float MAW_HARD_SHOT_SPEED = 10; +constexpr float PSYCHIC_SHOT_SCALE = 1.5f; +constexpr int MAW_SPIT_SUBTYPE = 5; +constexpr float MAW_SPIT_RISE = -24; +constexpr float MAW_SPIT_DEPTH = 1; +constexpr ColorMod MAW_SPIT_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0.6f, 0.1f, 0.1f}}; +constexpr ColorMod PSYCHIC_SPIT_COLOR = {{1, 1, 1, 0.6f}, {0.8f, 0.15f, 1, 1}, {0.26f, 0.05f, 0.4f}}; + +// The red Maw bursts into four shots as it dies. +constexpr float RED_BURST_SPEED = 8; + +// The first frame: it starts drifting, and the psychic one brings its eternal fly. The update ends there. +static void maw_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + if (npc.variant != MAW_PSYCHIC) return; + + Entity* fly = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_ETERNALFLY, .seed = Random()}); + fly->parent = &npc; +} + +// The spit: a blood burst in its mouth and a shot at its target (or where its controller steers). +static void maw_spit(Entity_NPC& npc) +{ + npc.PlaySound(npc.variant == MAW_PSYCHIC ? SOUND_BLOODSHOOT : SOUND_SHAKEY_KID_ROAR, 1, 2, false, 1); + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + aim = vector_resized(aim, game_is_hard_mode() ? MAW_HARD_SHOT_SPEED : MAW_SHOT_SPEED); + + auto* spit = static_cast( + blood_explosion_spawn(MAW_SPIT_SUBTYPE, npc.pos, vector_make(0, MAW_SPIT_RISE), COLOR_DEFAULT, {})); + spit->renderDepthOffset = MAW_SPIT_DEPTH; + spit->FollowParent(&npc); + spit->sprite.isFlipX = true; + + ProjectileParams params; + bool isPsychic = npc.variant == MAW_PSYCHIC; + if (isPsychic) + { + params.bulletFlags |= PROJECTILE_SMART; + params.scale = PSYCHIC_SHOT_SCALE; + } + spit->SetColor(isPsychic ? PSYCHIC_SPIT_COLOR : MAW_SPIT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); +} + +// Drifting: it idles, and starts spitting at a target in range (but for the red one), facing it. +static void maw_drift(Entity_NPC& npc, Vector toward) +{ + if (npc_anim_is_done(npc)) npc.sprite.Play("Idle"); + + bool isReady = npc.variant != MAW_RED && npc.projectileCooldown < 1; + if (isReady && npc.IsTargetInAttackRange(MAW_RANGE, MAW_RANGE_FRAMES, false)) + { + npc.state = NPC_STATE_ATTACK; + npc_anim_restart(npc.sprite, "Shoot"); + npc.projectileCooldown = MAW_COOLDOWN; + npc.UpdateControllerMovement(true); + npc.sprite.isFlipX = npc.controllerID == -1 ? toward.x < 0 : npc.controllerMovement.x < 0; + } + + float distance = vector_length(toward); + if (distance <= 0 || npc.friction == 0) return; + float accel = MAW_ACCEL / distance; + if (npc.variant == MAW_RED) accel *= MAW_RED_ACCEL_SCALE; + npc.velocity.y = npc.speedMultiplier * toward.y * accel / npc.friction + npc.velocity.y; + npc.velocity.x = npc.speedMultiplier * toward.x * accel / npc.friction + npc.velocity.x; +} + +// Spitting: it shoots on the Shoot event, then drifts again with its idle playing. +static void maw_attack_update(Entity_NPC& npc) +{ + npc.UpdateControllerMovement(false); + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) maw_spit(npc); + if (!npc_anim_is_done(npc)) return; + } + npc.state = NPC_STATE_MOVE; + npc_anim_loop(npc.sprite, "Idle"); +} + +// 00510ae0 The Maw's AI: it drifts toward its target and spits at it in range, a homing shot for the psychic one. +// The red one only chases, faster, and bursts into four shots as it dies. +void npc_maw_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return maw_init(npc); + + npc.pos = g_game->room->GetClampedPositionImpl(npc.pos, MAW_MARGIN_TOP, 0, MAW_MARGIN_BOTTOM, 0); + if (Random() % MAW_SPLAT_ODDS == 0) npc.MakeSplat(random_unit() * MAW_SPLAT_RANGE + MAW_SPLAT_SIZE); + + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + if (npc.controllerID != -1) toward = npc.GetControllerInput(0); + if (npc.state == NPC_STATE_MOVE) maw_drift(npc, toward); + else if (npc.state == NPC_STATE_ATTACK) maw_attack_update(npc); + + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + npc.friction *= MAW_FRICTION; + if (!npc.isDead || npc.variant != MAW_RED || npc.HasEntityFlags(FLAG_SHRINK)) return; + + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(RED_BURST_SPEED, 0), PROJECTILES_PLUS, params); + npc.PlaySound(SOUND_SHAKEY_KID_ROAR, 1, 2, false, 1); +} diff --git a/src/npc_movable_tnt.cpp b/src/npc_movable_tnt.cpp new file mode 100644 index 0000000..348109e --- /dev/null +++ b/src/npc_movable_tnt.cpp @@ -0,0 +1,125 @@ +#include "npc_basement.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_effect_combat.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "item_pool.h" + +// A pushable TNT barrel: each hit takes 1 (2 one time in three, 4 from an explosion) down to its last point, then it +// blows up for 100 within 75, leaving a crater and wood chips. It stays as a husk unless it rides a minecart. +constexpr uint64_t FLAG_TNT_INERT = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | + FLAG_NO_DEATH_TRIGGER | FLAG_NO_SPIKE_DAMAGE | FLAG_NO_FLASH_ON_DAMAGE; +constexpr int TNT_DEPTH = 100; +constexpr float TNT_LAST_POINT = 1; +constexpr float TNT_HIT = 1; +constexpr float TNT_HARD_HIT = 2; +constexpr float TNT_BLAST_HIT = 4; +constexpr uint32_t TNT_HARD_HIT_ODDS = 3; +constexpr float TNT_BLAST_DAMAGE = 100; +constexpr float TNT_BLAST_RADIUS = 75; +constexpr int TNT_CHIPS_MIN = 2; +constexpr uint32_t TNT_CHIPS_RANGE = 3; +constexpr float TNT_CHIP_SPEED_MIN = 2; +constexpr float TNT_CHIP_SPEED_RANGE = 4; +constexpr float TNT_HUSK_HEALTH = 0.5f; +constexpr float TNT_HUSK_FRICTION = 0.3f; +constexpr float TNT_FULL = 3; +constexpr float TNT_CRACKED = 2; +constexpr float TNT_FRICTION = 0.8f; +constexpr int TNT_COUNTER_FLOOR = -4; + +// One barrel in a hundred drops a Burnt Penny or a Match Stick (whichever is left in the trinket pool). +constexpr uint32_t TNT_TRINKET_ODDS = 100; + +// Takes a trinket out of the trinket pool and drops it, when it is still there to take. Whether it did. +static bool tnt_trinket_drop(Entity_NPC& npc, int trinket) +{ + std::vector& pool = g_game->itemPool.trinketPoolItems; + if ((int)pool.size() <= trinket || !pool[trinket].isAvailable || !pool[trinket].isInPool) return false; + + pool[trinket].isAvailable = false; + g_game->itemPool.numAvailableTrinkets--; + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(npc.pos, nullptr, 1); + g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .subType = trinket, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = Random()}); + return true; +} + +// The blast: an explosion effect and crater, 100 damage within 75 (counted as TNT), wood chips, and maybe a trinket. +static void tnt_explode(Entity_NPC& npc) +{ + g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_BOMB_EXPLOSION, + .seed = Random()}); + bomb_crater_spawn(npc.pos, &npc, 1); + explosion_damage({.position = npc.pos, + .source = &npc, + .damageFlags = DAMAGE_EXPLOSION | DAMAGE_TNT, + .damage = TNT_BLAST_DAMAGE, + .radius = TNT_BLAST_RADIUS, + .isLineCheck = false}); + + float speed = random_unit() * TNT_CHIP_SPEED_RANGE + TNT_CHIP_SPEED_MIN; + int count = (int)(Random() % TNT_CHIPS_RANGE) + TNT_CHIPS_MIN; + game_particles_spawn({.position = npc.pos, .speed = speed, .count = count, .variant = EFFECT_WOOD_PARTICLE}); + Entity_Pickup::GetRandomPickupVelocity(npc.pos, nullptr, 1); + if (npc.dropRNG.Next() % TNT_TRINKET_ODDS != 0) return; + + if (npc.dropRNG.RandomInt(2) == 0 && tnt_trinket_drop(npc, TRINKET_BURNT_PENNY)) return; + tnt_trinket_drop(npc, TRINKET_MATCH_STICK); +} + +// 006d6690 The Movable TNT's AI: hits wear it down and its last one blows it up. Its look shows how worn it is, and the +// husk left behind does nothing but get pushed about. +void npc_movable_tnt_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_TNT_INERT; + npc.state = npc.health > TNT_LAST_POINT ? NPC_STATE_IDLE : NPC_STATE_SPECIAL; + if (!npc.minecart) npc.renderZOffset = TNT_DEPTH; + } + if (npc.pendingDamage > 0) + { + float hit = Random() % TNT_HARD_HIT_ODDS == 0 ? TNT_HARD_HIT : TNT_HIT; + if (npc.pendingDamageFlags & DAMAGE_EXPLOSION) hit = TNT_BLAST_HIT; + npc.health = std::max(npc.health - hit, TNT_LAST_POINT); + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + } + if (npc.isDead || npc.health <= TNT_LAST_POINT) + { + if (npc.state != NPC_STATE_SPECIAL) tnt_explode(npc); + if (npc.minecart) npc.Remove(); + else + { + npc.isDead = false; + npc.state = NPC_STATE_SPECIAL; + npc.health = TNT_HUSK_HEALTH; + } + } + + if (npc.state == NPC_STATE_SPECIAL) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.sprite.Play("Blown"); + npc.friction *= TNT_HUSK_FRICTION; + return; + } + if (npc.state != NPC_STATE_IDLE) return; + + if (npc.health > TNT_FULL) npc.sprite.Play("Idle"); + else if (npc.health > TNT_CRACKED) npc.sprite.Play("IdleMedium"); + else if (npc.health > TNT_LAST_POINT) npc.sprite.Play("ReadyToExplode"); + npc.friction *= TNT_FRICTION; + if (npc.i1 > TNT_COUNTER_FLOOR) npc.i1--; +} diff --git a/src/npc_mushroom.cpp b/src/npc_mushroom.cpp new file mode 100644 index 0000000..2035170 --- /dev/null +++ b/src/npc_mushroom.cpp @@ -0,0 +1,128 @@ +#include "npc_caves.h" +#include "sfx_manager.h" +#include "game.h" + +// The Mushroom hides under its cap (taking a quarter of any hit) for 30 to 150 frames, then pops out to spit a plus or +// a cross of shots, stays out 30 to 90 frames and hides again. It stays rooted to its spot. +constexpr int MUSHROOM_PHASE_FRAMES = 30; +constexpr int MUSHROOM_HIDE_PHASES = 5; +constexpr int MUSHROOM_OUT_PHASES = 3; +constexpr float MUSHROOM_HIDDEN_DAMAGE = 0.25f; +constexpr float MUSHROOM_CONTROLLED_RANGE = 1000; +constexpr int MUSHROOM_RANGE_FRAMES = 7; +constexpr int CONTROLLER_ACTION_CROSS = 9; +constexpr float MUSHROOM_INPUT_DEADZONE = 0.1f; +constexpr float MUSHROOM_AIM_OFFSET = 360 + 22.5f; +constexpr float MUSHROOM_AIM_STEP = 45; +constexpr float MUSHROOM_SHOT_SPEED = 7; +constexpr float MUSHROOM_FRICTION = 0.8f; +constexpr int SOUND_MUSHROOM_HIDE = 38; +constexpr float MUSHROOM_HIDE_VOLUME = 0.5f; + +// How long it stays hidden or out: its controller's 30 frames, else a random number of 30 frame phases. +static int mushroom_phase_frames(Entity_NPC& npc, int phases) +{ + if (npc.controllerID != -1) return MUSHROOM_PHASE_FRAMES; + return (int)(Random() % (uint32_t)phases + 1) * MUSHROOM_PHASE_FRAMES; +} + +// Whether its controller wants it to act: aiming at a target or pressing the shot. +static bool mushroom_is_commanded(Entity_NPC& npc) +{ + return npc.IsTargetInAttackRange(MUSHROOM_CONTROLLED_RANGE, MUSHROOM_RANGE_FRAMES, false) || + npc.IsControllerActionPressed(CONTROLLER_ACTION_CROSS); +} + +// Hidden: it settles under its cap, then blocks until its time is up and pops out with a plus or a cross at random +// (its controller picks). +static void mushroom_hidden_update(Entity_NPC& npc) +{ + if (npc.i1 == 0) + { + npc.sprite.Play("Hide"); + if (npc_anim_is_done(npc)) npc.i1++; + return; + } + npc.sprite.Play("Blocking"); + npc.stateFrame -= npc_ticks_get(npc); + if (npc.stateFrame > 0) return; + if (npc.controllerID != -1 && !mushroom_is_commanded(npc)) return; + + npc.state = (int)(Random() & 1) | NPC_STATE_ATTACK; + if (npc.controllerID == -1) return; + npc.state = NPC_STATE_ATTACK + (npc.IsControllerActionPressed(CONTROLLER_ACTION_CROSS) ? 1 : 0); + npc.UpdateControllerMovement(true); +} + +// Out: it spits a plus (a cross in the second attack state, or as its controller's aim leans diagonal), then stays +// out. +static void mushroom_reveal_update(Entity_NPC& npc) +{ + if (npc.controllerID == -1) npc.controllerMovement = {}; + else + { + Vector input = npc.GetControllerMovementInput(MUSHROOM_INPUT_DEADZONE); + if (!vector_is_zero(input)) npc.controllerMovement = input; + } + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) + { + float degrees = vector_angle(npc.controllerMovement); + npc.state = ((int)((degrees + MUSHROOM_AIM_OFFSET) / MUSHROOM_AIM_STEP) & 1) + NPC_STATE_ATTACK; + } + + npc.sprite.Play("Reveal"); + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + ProjectileParams params; + ProjectilesMode mode = npc.state == NPC_STATE_ATTACK2 ? PROJECTILES_CROSS : PROJECTILES_PLUS; + npc.FireProjectiles(npc.pos, vector_make(MUSHROOM_SHOT_SPEED, 0), mode, params); + } + if (!npc_anim_is_done(npc)) return; + } + npc.state = NPC_STATE_SPECIAL; + npc.stateFrame = mushroom_phase_frames(npc, MUSHROOM_OUT_PHASES); +} + +// Revealed: it stays out (its controller holding it while commanding), sighs as its time runs out, and hides again. +static void mushroom_revealed_update(Entity_NPC& npc) +{ + if (npc.stateFrame > 0) + { + npc.sprite.Play("Revealed"); + npc.stateFrame -= npc_ticks_get(npc); + if (npc.stateFrame > 0) return; + if (npc.controllerID != -1 && mushroom_is_commanded(npc)) npc.stateFrame = 1; + if (npc.stateFrame < 1) npc.PlaySound(SOUND_MUSHROOM_HIDE, MUSHROOM_HIDE_VOLUME, 2, false, 1); + return; + } + npc.sprite.Play("Hide"); + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_IDLE; + npc.stateFrame = mushroom_phase_frames(npc, MUSHROOM_HIDE_PHASES); +} + +// 00542be0 The Mushroom's AI: it hides under its cap, shrugging off most of a hit, and pops out now and then to spit a +// plus or a cross of shots. It never leaves its spot. +void npc_mushroom_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = mushroom_phase_frames(npc, MUSHROOM_HIDE_PHASES); + npc.targetPosition = npc.pos; + return; + } + if (npc.pendingDamage > 0 && npc.state == NPC_STATE_IDLE) + for (DamageEvent& event : npc.damageEvents) event.damage *= MUSHROOM_HIDDEN_DAMAGE; + + if (npc.state == NPC_STATE_IDLE) mushroom_hidden_update(npc); + else if (npc.state == NPC_STATE_ATTACK || npc.state == NPC_STATE_ATTACK2) mushroom_reveal_update(npc); + else if (npc.state == NPC_STATE_SPECIAL) mushroom_revealed_update(npc); + + npc.friction *= MUSHROOM_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_portal.cpp b/src/npc_portal.cpp new file mode 100644 index 0000000..5fc272d --- /dev/null +++ b/src/npc_portal.cpp @@ -0,0 +1,188 @@ +#include "npc_basement.h" +#include "deathmatch_manager.h" +#include "entity_config.h" +#include "game.h" +#include "grid_entity_trap_door.h" +#include "level.h" +#include "manager.h" +#include "room.h" + +// The Portal hangs 30 up and summons a stage's enemy every 90 to 149 frames while fewer than three of its own live +// (rechecking every 60 to 89), 1 to 5 times before it closes. Outside the chapters (the Blue Womb, the Dark Room and +// past it, but the Void) it closes at once. +constexpr int PORTAL_LIL = 1; +constexpr float PORTAL_HEIGHT = -30; +constexpr int PORTAL_DEPTH = 40; +constexpr int PORTAL_FIRST_WAIT = 15; +constexpr uint32_t PORTAL_SUMMONS = 5; +constexpr int PORTAL_KIN_CAP = 3; +constexpr uint32_t PORTAL_SUMMON_WAIT = 60; +constexpr int PORTAL_SUMMON_WAIT_MIN = 90; +constexpr uint32_t PORTAL_CROWDED_WAIT = 30; +constexpr int PORTAL_CROWDED_WAIT_MIN = 60; +constexpr int PORTAL_SUMMON_COLOR_FRAMES = 50; +constexpr int PORTAL_SUMMON_COLOR_PRIORITY = 20; +constexpr float PORTAL_FRICTION = 0.7f; +constexpr float PORTAL_RIPPLE_AMPLITUDE = 0.03f; +constexpr float PORTAL_RIPPLE_SPEED = 0.015f; +constexpr int PORTAL_RIPPLE_FRAMES = 10; +constexpr ColorMod PORTAL_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6117647f, 0.27450982f, 0.73333335f}}; +constexpr ColorMod PORTAL_SUMMON_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The enemies a Portal summons, seven per chapter: the Basement, Caves, Depths, Womb, Cathedral (and anything past it), +// Sheol, Downpour and Dross. +constexpr int PORTAL_CHOICES = 7; +constexpr int PORTAL_GROUP_BASEMENT = 0; +constexpr int PORTAL_GROUP_CAVES = 1; +constexpr int PORTAL_GROUP_DEPTHS = 2; +constexpr int PORTAL_GROUP_WOMB = 3; +constexpr int PORTAL_GROUP_CATHEDRAL = 4; +constexpr int PORTAL_GROUP_SHEOL = 5; +constexpr int PORTAL_GROUP_DOWNPOUR = 6; +constexpr int PORTAL_GROUP_DROSS = 7; +constexpr std::array PORTAL_ENEMIES = { + 10, 217, 85, 244, 16, 29, 18, 25, 61, 26, 234, 258, 208, 23, 24, 41, 34, 227, 212, + 229, 32, 32, 15, 58, 56, 59, 55, 204, 38, 55, 86, 90, 260, 219, 86, 259, 252, 225, + 55, 278, 258, 55, 10, 810, 814, 813, 817, 15, 806, 10, 810, 870, 813, 817, 872, 806}; +constexpr int ENTITY_SWARMER = 260; +constexpr int SWARMER_PORTAL_VARIANT = 10; + +// The stage's chapter group of summons. The Void's rooms count as the chapter their layout comes from. +static int portal_group_get() +{ + Game& game = *g_game; + bool isAlt = game.stageType != STAGETYPE_ORIGINAL; + int stage = game.stage; + if (stage == STAGE_VOID) + { + int layout = game.room->GetRoomConfigStage(); + if (layout >= STAGE_ID_BASEMENT && layout <= STAGE_ID_BURNING_BASEMENT) stage = STAGE_BASEMENT_I; + else if (layout >= STAGE_ID_CAVES && layout <= STAGE_ID_FLOODED_CAVES) stage = STAGE_CAVES_I; + else if (layout >= STAGE_ID_DEPTHS && layout <= STAGE_ID_DANK_DEPTHS) stage = STAGE_DEPTHS_I; + else if (layout >= STAGE_ID_WOMB && layout <= STAGE_ID_SCARRED_WOMB) stage = STAGE_WOMB_I; + else if (layout == STAGE_ID_CATHEDRAL || layout == STAGE_ID_SHEOL) + { + isAlt = layout == STAGE_ID_CATHEDRAL; + stage = STAGE_SHEOL; + } + } + + // Greed mode counts one floor per chapter, Sheol its fifth. + if (game.IsGreedMode()) + { + switch (stage) + { + case STAGE_BASEMENT_I: return PORTAL_GROUP_BASEMENT; + case STAGE_BASEMENT_II: return PORTAL_GROUP_CAVES; + case STAGE_CAVES_I: return PORTAL_GROUP_DEPTHS; + case STAGE_CAVES_II: return PORTAL_GROUP_WOMB; + case STAGE_GREED_SHEOL: return PORTAL_GROUP_SHEOL; + default: return PORTAL_GROUP_CATHEDRAL; + } + } + switch (stage) + { + case STAGE_BASEMENT_I: + case STAGE_BASEMENT_II: + if (game.stageType == STAGETYPE_REPENTANCE) return PORTAL_GROUP_DOWNPOUR; + if (game.stageType == STAGETYPE_REPENTANCE_B) return PORTAL_GROUP_DROSS; + return PORTAL_GROUP_BASEMENT; + case STAGE_CAVES_I: + case STAGE_CAVES_II: return PORTAL_GROUP_CAVES; + case STAGE_DEPTHS_I: + case STAGE_DEPTHS_II: return PORTAL_GROUP_DEPTHS; + case STAGE_WOMB_I: + case STAGE_WOMB_II: return PORTAL_GROUP_WOMB; + case STAGE_SHEOL: return isAlt ? PORTAL_GROUP_CATHEDRAL : PORTAL_GROUP_SHEOL; + default: return PORTAL_GROUP_CATHEDRAL; + } +} + +// The enemies alive that this Portal summoned. +static int portal_kin_count(Entity_NPC& npc) +{ + int count = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isRival = g_game->deathmatchManager.state >= DEATHMATCH_INTRO && entity->type == ENTITY_PLAYER; + bool isEnemy = entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY; + if ((isRival || isEnemy) && entity->spawnerEntity.get() == &npc) count++; + } + return count; +} + +// A summoned enemy from the chapter's seven, a few in their own variant, sharing the Portal's champion color and charm. +static void portal_summon(Entity_NPC& npc) +{ + int group = portal_group_get(); + int type = PORTAL_ENEMIES[npc.dropRNG.RandomInt(PORTAL_CHOICES) + group * PORTAL_CHOICES]; + int variant = 0; + if (type == ENTITY_LEECH && group == PORTAL_GROUP_CATHEDRAL) variant = 2; + else if (type == ENTITY_LEECH && group == PORTAL_GROUP_SHEOL) variant = 1; + else if (type == ENTITY_FATTY) variant = 1; + else if (type == ENTITY_SWARMER) variant = SWARMER_PORTAL_VARIANT; + else if (type == ENTITY_DEATHS_HEAD) variant = npc.HasEntityFlags(FLAG_CHARM) ? 1 : 0; + + auto* enemy = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = type, .variant = variant, .seed = npc.dropRNG.Next()})); + EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(type, variant, 0); + if (config && config->isCanBeChampion) + { + enemy->isChampion = npc.isChampion; + enemy->championColorIdx = npc.championColorIdx; + } + enemy->LoadEntityConfig(); + enemy->health = std::min(enemy->health, enemy->maxHitPoints); + if (npc.HasEntityFlags(FLAG_CHARM)) enemy->AddCharmed(EntityRef(), -1, false, false); + enemy->SetColor(PORTAL_SUMMON_COLOR, PORTAL_SUMMON_COLOR_FRAMES, PORTAL_SUMMON_COLOR_PRIORITY, true, true); + enemy->Update(); + + npc.PlaySound(SOUND_DEATH_BURST_LARGE, 1, 2, false, 1); + npc.i1--; + shockwave_make(vector_add(npc.pos, npc.posOffset), PORTAL_RIPPLE_AMPLITUDE, PORTAL_RIPPLE_SPEED, + PORTAL_RIPPLE_FRAMES); +} + +// 00543720 The Portal's AI: it hovers in place, summoning an enemy of the floor's chapter while fewer than three of its +// summons live, and closes after its last. The Lil Portal is not written yet. +void npc_portal_update(Entity_NPC& npc) +{ + if (npc.variant == PORTAL_LIL) return reconstruction_missing("NpcAI::ENTITY_PORTAL 00543720: the Lil Portal"); + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.targetPosition = npc.pos; + npc.AddEntityFlags(FLAG_NO_PLAYER_CONTROL); + npc.posOffset = vector_make(0, PORTAL_HEIGHT); + npc.renderZOffset = PORTAL_DEPTH; + npc.splatColor = PORTAL_SPLAT; + npc.i2 = PORTAL_FIRST_WAIT; + npc.i1 = (int)(npc.dropRNG.Next() % PORTAL_SUMMONS) + 1; + } + int stage = g_game->stage; + if (stage == STAGE_BLUE_WOMB || (stage >= STAGE_DARK_ROOM && stage != STAGE_VOID)) npc.Remove(); + + if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Idle"); + if (npc.i2 < 1) + { + bool isRoomy = portal_kin_count(npc) < PORTAL_KIN_CAP; + if (isRoomy) npc.state = NPC_STATE_ATTACK; + npc.i2 = isRoomy ? (int)(Random() % PORTAL_SUMMON_WAIT) + PORTAL_SUMMON_WAIT_MIN + : (int)(Random() % PORTAL_CROWDED_WAIT) + PORTAL_CROWDED_WAIT_MIN; + } + } + if (npc.state == NPC_STATE_ATTACK) + { + portal_summon(npc); + npc.state = NPC_STATE_IDLE; + } + + if (npc.i2 > 0) npc.i2 -= npc_ticks_get(npc); + if (npc.i1 < 1) npc.Remove(); + npc.pos = npc.targetPosition; + npc.friction *= PORTAL_FRICTION; +} diff --git a/src/npc_ring_fly.cpp b/src/npc_ring_fly.cpp new file mode 100644 index 0000000..705cc82 --- /dev/null +++ b/src/npc_ring_fly.cpp @@ -0,0 +1,111 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "score_sheet.h" + +// A ring of flies circles its leader's spot 40 to 70 out, breathing by 0.5 a frame, turning with the ring's speed. The +// leader's spot drifts at 2 toward its target (2.5 along its controller's input). +constexpr float RING_FLY_RADIUS_MIN = 40; +constexpr float RING_FLY_RADIUS_MAX = 70; +constexpr float RING_FLY_BREATH = 0.5f; +constexpr float RING_FLY_TURN = 0.09424778f; +constexpr float RING_FLY_DRIFT = 2; +constexpr float RING_FLY_STEER = 2.5f; +constexpr float RING_FLY_SNAP_SQUARED = 100; +constexpr float RING_FLY_SPEED = 6; +constexpr float RING_FLY_REGEN = 4; + +// Lord of the Flies takes a fly as a blue fly of its own. Whether it did. +bool npc_fly_beelzebub_take(Entity_NPC& npc) +{ + Entity_Player* beelzebub = g_game->playerManager.GetRandomPlayer(npc.initSeed); + if (!beelzebub || npc.isDead) return false; + + g_game->scoreSheet.AddKilledEnemy(npc); + npc.Remove(); + beelzebub->AddBlueFlies(1, npc.pos, nullptr); + return true; +} + +// The leader moves the ring's spot, breathes its radius and turns it, by the ring's average speed. +static void ring_fly_lead(Entity_NPC& npc, const Vector& toward, float ringSpeed) +{ + Vector drift = npc.controllerID == -1 ? vector_scale(vector_normalized(toward), RING_FLY_DRIFT) + : vector_scale(npc.GetControllerInput(0), RING_FLY_STEER); + npc.targetPosition = vector_add(npc.targetPosition, vector_scale(drift, npc.speedMultiplier)); + + if (npc.i1 == 0) + { + npc.v1.y -= RING_FLY_BREATH; + if (npc.v1.y < RING_FLY_RADIUS_MIN) npc.i1 = 1; + } + else + { + npc.v1.y += RING_FLY_BREATH; + if (npc.v1.y > RING_FLY_RADIUS_MAX) npc.i1 = 0; + } + + npc.v2.x -= ringSpeed * RING_FLY_TURN; + while (npc.v2.x < -PI_F) npc.v2.x += PI_F * 2; +} + +// 0053bae0 The ring of flies' AI: Lord of the Flies takes it and Skatole tames it. The flies of a ring share the first +// one's spot and take their places evenly around it, the leader drifting toward the target. +void npc_ring_fly_update(Entity_NPC& npc) +{ + if (npc_fly_beelzebub_take(npc)) return; + if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK) && !npc.IsFriendly()) + { + npc.Morph(ENTITY_FLY, 0, 0, -1); + npc.v2 = {}; + npc.v1 = {}; + return; + } + + std::vector ring = entity_query(ENTITY_RING_OF_FLIES, -1); + if (!npc.parent && !ring.empty()) npc.parent = ring.front(); + if (npc.subtype == 1 && npc.health > npc.maxHitPoints) + npc.health = std::max(npc.health - RING_FLY_REGEN, npc.maxHitPoints); + + if (npc.state == NPC_STATE_INIT) + { + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.targetPosition = npc.parent.get() == &npc ? npc.pos : npc.parent->targetPosition; + npc.i1 = 1; + npc.v1.y = RING_FLY_RADIUS_MIN; + npc.state = NPC_STATE_MOVE; + return; + } + if (npc.state != NPC_STATE_MOVE) return; + + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Fly"); + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + + int ringSize = 0; + int slot = 0; + float ringSpeed = 0; + for (Entity* fly : ring) + { + if (fly == &npc) slot = ringSize; + if (fly->parent.get() != npc.parent.get()) continue; + ringSpeed += fly->speedMultiplier; + ringSize++; + } + if (ringSize > 0) ringSpeed /= (float)ringSize; + + if (npc.parent.get() == &npc) ring_fly_lead(npc, toward, ringSpeed); + else if (npc.parent) + { + npc.targetPosition = npc.parent->targetPosition; + npc.v1.y = npc.ParentNPC()->v1.y; + npc.v2.x = npc.ParentNPC()->v2.x; + } + + npc.v1.x = (float)slot * PI_F * 2 / (float)ringSize; + float angle = npc.v1.x + npc.v2.x; + Vector place = vector_make(std::cos(angle) * npc.v1.y, std::sin(angle) * npc.v1.y); + Vector step = vector_sub(vector_add(npc.targetPosition, place), npc.pos); + if (vector_length_squared(step) > RING_FLY_SNAP_SQUARED) + step = vector_scale(vector_normalized(step), RING_FLY_SPEED); + npc.velocity = step; +} diff --git a/src/npc_round_worm.cpp b/src/npc_round_worm.cpp new file mode 100644 index 0000000..8576dbf --- /dev/null +++ b/src/npc_round_worm.cpp @@ -0,0 +1,513 @@ +#include "npc_caves.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "room_grid.h" +#include "sfx_manager.h" + +// The worm kin this AI runs (Round worms, Tube worms and their tainted forms, Night crawler, Roundy, Ulcer), the +// tainted Round worm's head and its body segments. +constexpr int ROUND_WORM_TUBE = 1; +constexpr int ROUND_WORM_TAINTED = 2; +constexpr int ROUND_WORM_TAINTED_TUBE = 3; +constexpr int ROUND_WORM_HEAD = 0; +constexpr int ROUND_WORM_SEGMENT = 1; +constexpr int ROUND_WORM_SEGMENTS = 5; + +// Underground, a worm surfaces somewhere 60 to 310 around the room's center, 100 to 1000 from the nearest player. +constexpr float ROUND_WORM_SURFACE_MIN = 60; +constexpr float ROUND_WORM_SURFACE_RANGE = 250; +constexpr float ROUND_WORM_PLAYER_NEAR_SQUARED = 10000; +constexpr float ROUND_WORM_PLAYER_FAR_SQUARED = 1e6f; +constexpr float ROUND_WORM_MARGIN = 20; +constexpr int ROUND_WORM_SPOT_TRIES = 10; +constexpr int ROUND_WORM_FAR_TRIES = 2; +constexpr float ROUND_WORM_FALLBACK_DISTANCE = 26; +constexpr float ROUND_WORM_JITTER = 15; +constexpr int ROUND_WORM_TAINTED_REST = 45; + +// The tainted head lays its body 20 to 100 around itself. +constexpr float ROUND_WORM_SEGMENT_MIN = 20; +constexpr float ROUND_WORM_SEGMENT_RANGE = 80; +constexpr float ROUND_WORM_SEGMENT_MARGIN = 10; + +// A player steering a worm surfaces it near its target or after 90 frames, hurting it by 3.5 when stuck past 120. +constexpr float ROUND_WORM_CONTROL_SPEED = 3; +constexpr float ROUND_WORM_CONTROL_RANGE = 1000; +constexpr int ROUND_WORM_CONTROL_FRAMES = 90; +constexpr int ROUND_WORM_CONTROL_STUCK = 120; +constexpr float ROUND_WORM_CONTROL_RADIUS = 80; +constexpr float ROUND_WORM_CONTROL_SHIFT = 30; +constexpr float ROUND_WORM_STUCK_DAMAGE = 3.5f; +constexpr int ROUND_WORM_DAMAGE_COUNTDOWN = 30; +constexpr float ROUND_WORM_CHARGE_BAR_START = 90; + +// Its shot: at 10 where the target heads within 10 frames, short of the wall it would reach. +constexpr float ROUND_WORM_SHOT_SPEED = 10; +constexpr float ROUND_WORM_LEAD = 10; +constexpr float ROUND_WORM_LEAD_MIN_SQUARED = 100; +constexpr float ROUND_WORM_WALL_GAP = 8; +constexpr float ROUND_WORM_TAINTED_SHOT_SCALE = 2; +constexpr float NIGHT_CRAWLER_SHOT_SPEED = 10; +constexpr float NIGHT_CRAWLER_SHOT_ORBIT = 5; + +// A Tube worm spits 10 lobbed shots one per frame (the tainted one a single big one), around where its target heads. +constexpr int TUBE_WORM_SHOTS = 10; +constexpr float TUBE_WORM_SPREAD = 30; +constexpr float TUBE_WORM_TAINTED_SPREAD = 80; +constexpr float TUBE_WORM_LEAD = 0.2f; +constexpr float TUBE_WORM_MARGIN = 4; +constexpr float TUBE_WORM_SHOT_SHARE = 0.025f; +constexpr float TUBE_WORM_HEIGHT = 25; +constexpr float TUBE_WORM_FALL_RANGE = 8; +constexpr float TUBE_WORM_FALL = -56; +constexpr float TUBE_WORM_FALL_ACCEL = 1.5f; +constexpr float TUBE_WORM_SCALE_MIN = 0.5f; +constexpr float TUBE_WORM_TAINTED_SCALE = 1.6f; +constexpr int TUBE_WORM_GUSH_EVERY = 6; +constexpr float TUBE_WORM_GUSH_HEIGHT = -30; +constexpr float TUBE_WORM_GUSH_RISE = -2; +constexpr float TUBE_WORM_GUSH_SCALE_MIN = 0.8f; +constexpr float TUBE_WORM_GUSH_SCALE_RANGE = 0.4f; +constexpr int TUBE_WORM_GUSH_Z = 100; +constexpr float TUBE_WORM_GUSH_TURN = 360; + +// Roundy's shockwave as it surfaces, and its slow, big, exploding lob. The Ulcer lobs at 8 or spawns a Dart fly. +constexpr float ROUNDY_TRAJECTORY = 10; +constexpr float ROUNDY_FALL_ACCEL = -0.3f; +constexpr float ROUNDY_FALL_SHARE = 0.7f; +constexpr float ROUNDY_FALL = -13; +constexpr float ROUNDY_HEIGHT = -20; +constexpr float ROUNDY_SHOT_SCALE = 1.6f; +constexpr float ROUNDY_SHOT_SLOW = 0.55f; +constexpr float ROUNDY_WAVE_RADIUS = 50; +constexpr int ROUNDY_WAVE_FRAMES = 5; +constexpr float ULCER_TRAJECTORY = 8; +constexpr uint32_t ULCER_FLY_ODDS = 75; +constexpr uint32_t ULCER_FLY_ROLL = 100; +constexpr int ULCER_ENEMY_CAP = 7; +constexpr ColorMod ROUND_WORM_GREEN = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; +constexpr uint64_t FLAG_ROUND_WORM_CALM = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// 007f0b40 Room::GetLaserTarget: where a beam from a position along a direction first meets a pit, block or wall. +Vector room_laser_target_get(const Vector& position, const Vector& direction) +{ + Room& room = *g_game->room; + Vector end = vector_add(position, vector_scale(direction, 10000)); + Vector delta = vector_sub(end, position); + Vector hit = position; + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + int stepX = delta.x > 0 ? 1 : -1; + int stepY = delta.y > 0 ? 1 : -1; + float travelled = 0; + if (vector_is_zero(delta)) return end; + + while (true) + { + uint32_t collision = room.GetGridCollision(room.GetGridIndexByTile(column, row)); + if (collision >= COLLISION_OBJECT && collision <= COLLISION_WALL_EXCEPT_PLAYER) break; + + float edgeX = (float)column * GRID_CELL_SIZE + GRID_ORIGIN_X + (float)stepX * GRID_CELL_SIZE / 2; + float edgeY = (float)row * GRID_CELL_SIZE + GRID_ORIGIN_Y + (float)stepY * GRID_CELL_SIZE / 2; + float toX = delta.x == 0 ? INFINITY : (edgeX - hit.x) / delta.x; + float toY = delta.y == 0 ? INFINITY : (edgeY - hit.y) / delta.y; + if (toY <= toX) row += stepY; + else column += stepX; + travelled += std::min(toX, toY); + hit = vector_add(position, vector_scale(delta, travelled)); + if (travelled >= 1) return end; + } + return hit; +} + +// A free spot near a position, off the active entities. +static Vector round_worm_free_spot(const Vector& position) +{ + return room_free_pickup_position_find({.position = position, .isAvoidActiveEntities = true}); +} + +// A spot nudged up to 15 in a random direction. +static Vector round_worm_jitter(const Vector& position) +{ + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit() * ROUND_WORM_JITTER; + return vector_add(position, vector_scale(vector_make(std::cos(angle), std::sin(angle)), reach)); +} + +// A spot a random reach (min, plus up to range) in a random direction from a center, kept a margin in the room. +static Vector round_worm_spot_around(const Vector& center, float min, float range, float margin) +{ + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit() * range + min; + Vector spot = vector_add(center, vector_scale(vector_make(std::cos(angle), std::sin(angle)), reach)); + return g_game->room->GetClampedPosition(spot, margin); +} + +static float round_worm_player_distance_squared(const Vector& spot) +{ + return vector_length_squared(vector_sub(spot, game_nearest_player(spot)->pos)); +} + +// Before its update: Roundy ignores its own kind's shots and the tainted Tube worm the enemies' fire and blasts. The +// tainted Round worm's head shares the worst health and the hardest hit with its body, which dies with it. +static void round_worm_pre_update(Entity_NPC& npc) +{ + if (npc.type == ENTITY_ROUNDY && npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if (!(event.source.flags & ENTITY_REF_CHARMED) && + (event.source.type == npc.type || event.source.spawnerType == npc.type)) + event.damage = 0; + if (npc.type != ENTITY_ROUND_WORM) return; + + if (npc.variant == ROUND_WORM_TAINTED_TUBE && npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + { + bool isEnemyBlast = event.damageFlags & (DAMAGE_FIRE | DAMAGE_EXPLOSION) && + !(event.source.flags & ENTITY_REF_FRIENDLY) && event.source.type != ENTITY_PLAYER && + event.source.spawnerType != ENTITY_PLAYER && + event.source.spawnerType != ENTITY_FAMILIAR; + if (isEnemyBlast && !(event.damageFlags & DAMAGE_TNT)) event.damage = 0; + } + if (npc.variant != ROUND_WORM_TAINTED) return; + + if (npc.subtype == ROUND_WORM_SEGMENT) + { + Entity* root = npc.GetLastParent(); + if (!root->IsType(npc.type, ROUND_WORM_TAINTED, ROUND_WORM_HEAD)) npc.Kill(EntityRef()); + } + if (npc.subtype == ROUND_WORM_HEAD) + { + float lowestHealth = 1e10f; + float hardestHit = 0; + for (Entity* segment = &npc; segment; segment = segment->child) + { + lowestHealth = std::min(lowestHealth, segment->health); + hardestHit = std::max(hardestHit, segment->pendingDamage); + } + for (Entity* segment = &npc; segment; segment = segment->child) + { + segment->health = lowestHealth + hardestHit; + segment->TakeDamage(hardestHit, DAMAGE_INVINCIBLE, EntityRef(), ROUND_WORM_DAMAGE_COUNTDOWN); + } + } + if (!npc.isDead) return; + + for (Entity* segment = npc.GetLastParent(); segment; segment = segment->child) segment->Kill(EntityRef()); +} + +// The tainted Round worm's head lays its body: five segments 20 to 100 around it, each linked to the last. +static void round_worm_body_lay(Entity_NPC& npc) +{ + Room& room = *g_game->room; + room_grid_path_mark(room, room.GetGridIndex(npc.pos), GRID_PATH_FREED); + + Entity_NPC* previous = &npc; + for (int i = 0; i < ROUND_WORM_SEGMENTS; i++) + { + Vector spot = round_worm_spot_around(npc.pos, ROUND_WORM_SEGMENT_MIN, ROUND_WORM_SEGMENT_RANGE, + ROUND_WORM_SEGMENT_MARGIN); + spot = round_worm_jitter(round_worm_free_spot(spot)); + Entity* segment = g_game->Spawn({.position = spot, + .subType = ROUND_WORM_SEGMENT, + .type = npc.type, + .variant = npc.variant, + .seed = Random()}); + segment->parent = previous; + previous->child = segment; + segment->Update(); + room_grid_path_mark(room, room.GetGridIndex(segment->pos), GRID_PATH_FREED); + previous = static_cast(segment); + } +} + +// Underground and steered by a player: it surfaces near its target, or after 90 frames, unless a player or a block +// stands on it and no free spot lies within 30, which hurts it past 120 frames. +static void round_worm_steered_dig(Entity_NPC& npc) +{ + npc.i2 += npc_ticks_get(npc); + npc.pathfinder.FindGridPath({}, ROUND_WORM_CONTROL_SPEED, 0, DIRECT_PATH_FAR); + if (!npc.IsTargetInAttackRange(ROUND_WORM_CONTROL_RANGE, 7, false) && npc.i2 < ROUND_WORM_CONTROL_FRAMES) return; + + if (room_grid_collision_at(npc.pos) != 0 || npc.IsPlayerInRadius(npc.pos, ROUND_WORM_CONTROL_RADIUS)) + { + Vector spot = round_worm_free_spot(npc.pos); + if (vector_length(vector_sub(npc.pos, spot)) >= ROUND_WORM_CONTROL_SHIFT) + { + if (npc.i2 < ROUND_WORM_CONTROL_STUCK) return; + npc.i2 = ROUND_WORM_CONTROL_FRAMES; + npc.TakeDamage(ROUND_WORM_STUCK_DAMAGE, 0, EntityRef(), ROUND_WORM_DAMAGE_COUNTDOWN); + return; + } + npc.pos = spot; + } + npc.targetPosition = npc.pos; +} + +// Underground: once its wait runs out it picks a spot around the room's center, taken one time in two when it is +// neither too near nor too far from the nearest player. It surfaces once it has one. +static void round_worm_dig_update(Entity_NPC& npc) +{ + if (npc.IsType(ENTITY_ROUND_WORM, ROUND_WORM_TAINTED, ROUND_WORM_SEGMENT)) return; + + if (npc.controllerID != -1) round_worm_steered_dig(npc); + else if (npc.stateFrame < 1) + { + Room& room = *g_game->room; + Vector center = vector_scale(vector_add(room.topLeftPos, room.bottomRightPos), 0.5f); + Vector direction = random_direction(); + float reach = random_unit() * ROUND_WORM_SURFACE_RANGE + ROUND_WORM_SURFACE_MIN; + Vector spot = room.GetClampedPosition(vector_add(center, vector_scale(direction, reach)), ROUND_WORM_MARGIN); + spot = round_worm_free_spot(spot); + float distance = round_worm_player_distance_squared(spot); + bool isTaken = (Random() & 1) == 0; + if (isTaken && distance > ROUND_WORM_PLAYER_NEAR_SQUARED && distance < ROUND_WORM_PLAYER_FAR_SQUARED) + { + npc.targetPosition = spot; + npc.pos = spot; + } + } + + if (npc.stateFrame > 0) npc.stateFrame -= npc_ticks_get(npc); + if (vector_is_zero(npc.targetPosition)) return; + + npc.state = NPC_STATE_ATTACK; + npc.i1 = 0; + npc.isVisible = true; + npc.UpdateDirtColor(true); + npc.i2 = 0; +} + +// A Tube worm's lobbed shot around where its target heads, with a gush of blood every sixth one. +static void tube_worm_shoot(Entity_NPC& npc) +{ + npc.i1--; + bool isTainted = npc.variant == ROUND_WORM_TAINTED_TUBE; + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, TUBE_WORM_LEAD * distance)); + lead = g_game->room->GetClampedPosition(lead, TUBE_WORM_MARGIN); + Vector direction = random_direction(); + float spread = random_unit() * (isTainted ? TUBE_WORM_TAINTED_SPREAD : TUBE_WORM_SPREAD); + Vector aim = vector_add(lead, vector_scale(direction, spread)); + if (npc.controllerID != -1) aim = npc.GetAimTargetPosition(); + + ProjectileParams params; + params.heightModifier = random_unit() * TUBE_WORM_HEIGHT; + params.fallingSpeedModifier = random_unit() * TUBE_WORM_FALL_RANGE + TUBE_WORM_FALL; + params.fallingAccelModifier = TUBE_WORM_FALL_ACCEL; + params.scale = random_unit() + TUBE_WORM_SCALE_MIN; + if (isTainted) + { + params.bulletFlags = PROJECTILE_EXPLODE; + params.scale = TUBE_WORM_TAINTED_SCALE; + params.color = ROUND_WORM_GREEN; + blood_explosion_spawn(2, npc.pos, vector_make(0, TUBE_WORM_GUSH_HEIGHT), params.color, + vector_make(0, random_unit() * TUBE_WORM_GUSH_RISE)); + } + npc.FireProjectiles(npc.pos, vector_scale(vector_sub(aim, npc.pos), TUBE_WORM_SHOT_SHARE), PROJECTILES_SINGLE, + params); + if (npc.i1 % TUBE_WORM_GUSH_EVERY != 0 || isTainted) return; + + Entity* gush = blood_explosion_spawn(1, npc.pos, vector_make(0, TUBE_WORM_GUSH_HEIGHT), COLOR_DEFAULT, + vector_make(0, random_unit() * TUBE_WORM_GUSH_RISE)); + gush->sprite.rotation = random_unit() * TUBE_WORM_GUSH_TURN; + float scale = random_unit() * TUBE_WORM_GUSH_SCALE_RANGE + TUBE_WORM_GUSH_SCALE_MIN; + gush->renderZOffset = TUBE_WORM_GUSH_Z; + gush->sprite.scale = vector_make(scale, scale); +} + +// The tainted Round worm's head sends its next segment up: a spot 60 to 310 around it, 100 from the nearest player (and +// within 1000 after the first two tries), else just beside it. +static void round_worm_segment_raise(Entity_NPC& npc) +{ + Entity_NPC* segment = npc.ChildNPC(); + Vector spot{}; + bool isFound = false; + for (int i = 0; i < ROUND_WORM_SPOT_TRIES && !isFound; i++) + { + spot = round_worm_spot_around(npc.pos, ROUND_WORM_SURFACE_MIN, ROUND_WORM_SURFACE_RANGE, ROUND_WORM_MARGIN); + spot = round_worm_jitter(round_worm_free_spot(spot)); + float distance = round_worm_player_distance_squared(spot); + isFound = distance > ROUND_WORM_PLAYER_NEAR_SQUARED && + (i < ROUND_WORM_FAR_TRIES || distance < ROUND_WORM_PLAYER_FAR_SQUARED); + } + if (!isFound) spot = vector_add(npc.pos, vector_scale(random_direction(), ROUND_WORM_FALLBACK_DISTANCE)); + + segment->targetPosition = spot; + segment->pos = spot; + segment->state = NPC_STATE_ATTACK; + segment->isVisible = true; + segment->UpdateDirtColor(true); + segment->i2 = 0; +} + +// Where a worm aims: where its target will be in 10 frames, short of the wall it would reach, or its aim target. +static Vector round_worm_aim_get(Entity_NPC& npc) +{ + Entity* target = npc.GetPlayerTarget(); + Vector lead = vector_scale(target->velocity, ROUND_WORM_LEAD); + if (vector_length_squared(lead) > ROUND_WORM_LEAD_MIN_SQUARED) + { + Vector wall = room_laser_target_get(target->pos, lead); + float room = vector_length(vector_sub(target->pos, wall)) - ROUND_WORM_WALL_GAP; + float length = vector_length(lead); + if (room < length) lead = vector_scale(lead, room / length); + } + + Vector aim = g_game->room->GetClampedPosition(vector_add(target->pos, lead), ROUND_WORM_MARGIN); + return npc.controllerID != -1 ? npc.GetAimTargetPosition() : aim; +} + +// A worm's shot as it surfaces, by kind: the Night crawler's orbiting plus, Roundy's exploding lob, the Ulcer's lob or +// Dart fly, the tainted head's bursting shot, or a plain one when it sees its target. +static void round_worm_shoot(Entity_NPC& npc) +{ + Vector aim = round_worm_aim_get(npc); + Vector lobTarget = npc.controllerID != -1 ? aim : npc.GetPlayerTarget()->pos; + bool isHead = npc.IsType(ENTITY_ROUND_WORM, ROUND_WORM_TAINTED, ROUND_WORM_HEAD); + bool isPlain = npc.type != ENTITY_NIGHT_CRAWLER && npc.type != ENTITY_ROUNDY && npc.type != ENTITY_ULCER && !isHead; + if (npc.HasEntityFlags(FLAG_ROUND_WORM_CALM)) return; + + bool isUnseen = npc.controllerID == -1 && !g_game->room->camera->IsPosVisible(npc.pos); + if (npc.type == ENTITY_ULCER && isUnseen) return; + if (isPlain && npc.controllerID == -1 && !room_check_line(npc.pos, aim, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD)) + return; + + ProjectileParams params; + if (npc.type == ENTITY_NIGHT_CRAWLER) + { + params.bulletFlags |= PROJECTILE_ORBIT_CW; + params.targetPosition = npc.pos; + npc.FireProjectiles(npc.pos, vector_make(NIGHT_CRAWLER_SHOT_SPEED, NIGHT_CRAWLER_SHOT_ORBIT), PROJECTILES_PLUS, + params); + } + else if (npc.type == ENTITY_ROUNDY) + { + Entity_Projectile* shot = npc.FireBossProjectiles(1, lobTarget, ROUNDY_TRAJECTORY, params); + shot->projectileFlags |= PROJECTILE_EXPLODE; + shot->fallingAccel += ROUNDY_FALL_ACCEL; + shot->scale = ROUNDY_SHOT_SCALE; + shot->fallingSpeed = shot->fallingSpeed * ROUNDY_FALL_SHARE + ROUNDY_FALL; + shot->height += ROUNDY_HEIGHT; + shot->velocity = vector_scale(shot->velocity, ROUNDY_SHOT_SLOW); + shot->SetColor(ROUND_WORM_GREEN, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + else if (npc.type == ENTITY_ULCER) + { + bool isClear = room_check_line(npc.pos, aim, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); + bool isFlyRolled = Random() % ULCER_FLY_ROLL < ULCER_FLY_ODDS; + if ((isFlyRolled || !isClear) && npc.GetAliveEnemyCount() < ULCER_ENEMY_CAP) + { + Entity* fly = + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_DART_FLY, .seed = Random()}); + fly->ClearEntityFlags(FLAG_APPEAR); + } + else npc.FireBossProjectiles(1, lobTarget, ULCER_TRAJECTORY, params)->scale = 1; + } + else + { + if (isHead) + { + params.bulletFlags = PROJECTILE_BURST8; + params.scale = ROUND_WORM_TAINTED_SHOT_SCALE; + } + Vector toward = vector_sub(aim, npc.pos); + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(toward), ROUND_WORM_SHOT_SPEED), PROJECTILES_SINGLE, + params); + } + npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); +} + +// Surfacing: it digs out, Tube worms spitting their burst (and diving back unseen), the others one shot, the tainted +// head raising its next segment. Roundy sends a shockwave as it breaks the ground. It digs back in once done. +static void round_worm_surface_update(Entity_NPC& npc) +{ + npc.SpawnControlTarget(0, -1); + npc.sprite.Play("DigOut"); + npc.entityCollisionClass = ENTCOLL_ALL; + + if (npc.variant == ROUND_WORM_TUBE || npc.variant == ROUND_WORM_TAINTED_TUBE) + { + bool isHidden = npc.controllerID == -1 && !g_game->room->camera->IsPosVisible(npc.pos); + if (npc.sprite.IsEventTriggered("PreShoot") && isHidden) npc.state = NPC_STATE_JUMP; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.i1 = npc.variant == ROUND_WORM_TAINTED_TUBE ? 1 : TUBE_WORM_SHOTS; + npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); + } + if (npc.i1 > 0) tube_worm_shoot(npc); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_JUMP; + } + else + { + bool isTainted = npc.IsType(ENTITY_ROUND_WORM, ROUND_WORM_TAINTED, -1); + if (isTainted && npc.child && npc.sprite.IsEventTriggered("Next")) round_worm_segment_raise(npc); + if (npc.sprite.IsEventTriggered("Shoot")) round_worm_shoot(npc); + } + + if (npc.type == ENTITY_ROUNDY && npc.sprite.animState.animFrame == 0) + { + Entity_Effect* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_SHOCKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->minRadius = npc.size; + wave->maxRadius = ROUNDY_WAVE_RADIUS; + wave->timeout = ROUNDY_WAVE_FRAMES; + wave->lifespan = ROUNDY_WAVE_FRAMES; + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, false, 1); + } + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_JUMP; + if (npc.type == ENTITY_ROUND_WORM && npc.variant == ROUND_WORM_TAINTED) npc.stateFrame = ROUND_WORM_TAINTED_REST; +} + +// 0053e4a0 The worms' AI: Round and Tube worms, Night crawler, Roundy and Ulcer dig in, wander underground and surface +// elsewhere to shoot. The tainted Round worm's head drags five segments sharing its health. +void npc_round_worm_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return round_worm_pre_update(npc); + if (npc.isDead) + { + npc.velocity = {}; + return; + } + npc.UpdateChargeBar(ROUND_WORM_CHARGE_BAR_START, 0, (float)npc.i2, true); + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_JUMP; + npc.targetPosition = npc.pos; + npc.UpdateDirtColor(true); + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + if (npc.IsType(ENTITY_ROUND_WORM, ROUND_WORM_TAINTED, ROUND_WORM_HEAD)) round_worm_body_lay(npc); + return; + } + if (npc.state == NPC_STATE_JUMP) + { + npc.sprite.Play("DigIn"); + if (npc_anim_is_done(npc)) + { + if (npc.pendingDamage < npc.health) + { + npc.state = NPC_STATE_MOVE; + npc.targetPosition = {}; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + } + else + { + npc.state = NPC_STATE_ATTACK; + npc.i1 = 0; + } + } + } + else if (npc.state == NPC_STATE_MOVE) round_worm_dig_update(npc); + else if (npc.state == NPC_STATE_ATTACK) round_worm_surface_update(npc); + + if (!vector_is_zero(npc.targetPosition)) npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.friction *= 0.8f; +} diff --git a/src/npc_skinny.cpp b/src/npc_skinny.cpp new file mode 100644 index 0000000..6a578d0 --- /dev/null +++ b/src/npc_skinny.cpp @@ -0,0 +1,385 @@ +#include "npc_caves.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" +#include + +// The Skinny family's variants (the Rotty and the Crispy) and the Bony family (the Holy Bony and the Black Bony). +constexpr int SKINNY_ROTTY = 1; +constexpr int SKINNY_CRISPY = 2; +constexpr int BONY_HOLY = 1; +constexpr uint64_t FLAG_SKINNY_SCARED = FLAG_FEAR | FLAG_SHRINK; +constexpr uint64_t FLAG_BONY_CALM = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// A Skinny groans now and then, chases at 0.5 and trails a small red creep every 7 frames. +constexpr int SKINNY_GROAN_FRAMES = 20; +constexpr uint32_t SKINNY_GROAN_ODDS = 3; +constexpr float SKINNY_GROAN_VOLUME = 0.8f; +constexpr int SKINNY_GROAN_DELAY = 120; +constexpr float SKINNY_SPEED = 0.5f; +constexpr float SKINNY_WALK_THRESHOLD = 0.1f; +constexpr float SKINNY_EVADE_FRICTION = 0.8f; +constexpr int SKINNY_CREEP_FRAMES = 7; +constexpr float SKINNY_CREEP_SCALE = 0.5f; +constexpr float SKINNY_CREEP_SPRITE_SCALE = 0.1f; +constexpr int SKINNY_CREEP_TIMEOUT = 30; +constexpr float SKINNY_FRICTION = 0.8f; +constexpr float ROTTY_FLY_SPEED = 2; + +// A Crispy burns from 90% of its health down to 40%, burning 1 a second, faster, darker, bouncier and smokier. +constexpr float CRISPY_BURN_START = 0.9f; +constexpr float CRISPY_BURN_END = 0.4f; +constexpr float CRISPY_ANGRY = 0.5f; +constexpr float CRISPY_SPEED_MIN = 0.6f; +constexpr float CRISPY_SPEED_RANGE = 0.5f; +constexpr float CRISPY_PUSH = 0.65f; +constexpr float CRISPY_LEAD = 10; +constexpr float CRISPY_EMBER_ODDS = 0.2f; +constexpr float CRISPY_EMBER_RISE = -15; +constexpr float CRISPY_EMBER_SPREAD = 16; +constexpr float CRISPY_EMBER_FALL = -1.6f; +constexpr float CRISPY_EMBER_FALL_MIN = -0.8f; +constexpr float CRISPY_EMBER_DRIFT = 0.4f; +constexpr float CRISPY_RED_DARKEN = 0.9f; +constexpr float CRISPY_DARKEN = 0.8f; +constexpr uint32_t CRISPY_SPLAT_ODDS = 5; +constexpr float CRISPY_SPLAT_MIN = 0.4f; +constexpr float CRISPY_SPLAT_RANGE = 0.4f; +constexpr int CRISPY_BURN_FRAMES = 30; +constexpr float CRISPY_BURN_DAMAGE = 1; +constexpr float CRISPY_BOUNCY = 0.3f; +constexpr float CRISPY_FRICTION = 0.8f; +constexpr float CRISPY_FRICTION_RANGE = 0.15f; + +// A Bony walks the grid's axes at 1.25 and throws a bone at 10 when its target lines up within 200. The Holy Bony's +// arcs to its aim, setting a blue fire. The Black Bony's look dark, throw three times, and it explodes as it dies. +constexpr float BONY_SPEED = 1.25f; +constexpr int BONY_GROAN_FRAMES = 30; +constexpr int BONY_AIM_FRAMES = 3; +constexpr float BONY_AIM_LEAD = 16; +constexpr float BONY_MARGIN = 20; +constexpr float BONY_LINE_WIDTH = 20; +constexpr float BONY_RANGE = 200; +constexpr float BONY_CONTROL_RANGE = 1000; +constexpr float BONY_AIM_RANGE = 160; +constexpr float BONY_SHOT_SPEED = 10; +constexpr float BONY_ARC_MIN = 20; +constexpr float BONY_ARC_MAX = 240; +constexpr float BONY_ARC_STEP = 10; +constexpr float BONY_ARC_DECAY = 0.9f; +constexpr float BONY_ARC_SCALE = -9.491221f; +constexpr float BONY_ARC_FLOOR = 0.01f; +constexpr float BONY_ARC_LIFT = 18; +constexpr float BONY_ARC_DROP = 11; +constexpr float BONY_ARC_JITTER_MIN = 0.8f; +constexpr float BONY_ARC_JITTER = 0.4f; +constexpr int BLACK_BONY_THROWS = 2; +constexpr float BONY_ATTACK_FRICTION = 0.3f; +constexpr float BLACK_BONY_BLAST_DAMAGE = 40; +constexpr float BLACK_BONY_BLAST_RADIUS = 60; +constexpr ColorMod BLACK_BONY_SPLAT = {{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod BLACK_BONY_BONE = {{0.4f, 0.4f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The way a Crispy has burnt so far, from 0 at 90% of its health to 1 at 40%. +static float crispy_burn_get(Entity_NPC& npc) +{ + float start = npc.maxHitPoints * CRISPY_BURN_END; + float end = npc.maxHitPoints * CRISPY_BURN_START; + if (start == end) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + return 1 - std::clamp((npc.health - start) / (end - start), 0.0f, 1.0f); +} + +// A Crispy chasing: straight at where its target heads when it sees it, around the blocks otherwise, shedding embers +// and darkening splats as it burns. +static void crispy_chase(Entity_NPC& npc, float burn) +{ + if (npc.IsFrame(SKINNY_GROAN_FRAMES, npc.index) && Random() % SKINNY_GROAN_ODDS == 0) + npc.PlaySound(SOUND_ANGRY_GURGLE, SKINNY_GROAN_VOLUME, SKINNY_GROAN_DELAY, false, 1); + + Entity* target = npc.GetPlayerTarget(); + Vector aim = npc.CalcTargetPosition(0); + Vector lead = vector_sub(vector_add(aim, vector_scale(target->velocity, CRISPY_LEAD)), npc.pos); + Vector push{}; + if (npc.controllerID != -1) push = npc.GetControllerInput(0); + else if (room_check_line(npc.pos, aim, LINE_MODE_GROUND, 0)) push = vector_normalized(lead); + else + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), burn * CRISPY_SPEED_RANGE + CRISPY_SPEED_MIN, + GRID_PATH_FREED, DIRECT_PATH_FAR); + npc.velocity = vector_add(npc.velocity, vector_scale(push, CRISPY_PUSH * npc.speedMultiplier)); + + if (random_unit() < burn * CRISPY_EMBER_ODDS) + { + float rise = CRISPY_EMBER_RISE - random_unit() * -CRISPY_EMBER_RISE; + float x = random_unit() * CRISPY_EMBER_SPREAD - CRISPY_EMBER_SPREAD / 2 + npc.pos.x; + float fall = random_unit() * CRISPY_EMBER_FALL + CRISPY_EMBER_FALL_MIN; + float drift = random_unit() * CRISPY_EMBER_DRIFT - CRISPY_EMBER_DRIFT / 2; + g_game->Spawn({.position = vector_make(x, npc.pos.y + rise), + .velocity = vector_make(drift, fall), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_EMBER_PARTICLE, + .seed = Random()}); + } + npc.AnimWalkFrame("WalkHori", "WalkVert", SKINNY_WALK_THRESHOLD); + + float green = 1 - burn * CRISPY_DARKEN; + npc.splatColor = {{1 - burn * CRISPY_RED_DARKEN, green, green, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + if (npc.IsFrame(2, npc.index) && Random() % CRISPY_SPLAT_ODDS == 0) + npc.MakeSplat(random_unit() * CRISPY_SPLAT_RANGE + CRISPY_SPLAT_MIN) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// 0054a350 The Crispy's AI: it burns down, its head angry below half health, chasing faster and darker, hurting itself +// by 1 a second and bouncing off the walls once well burnt. +static void crispy_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc_overlay_loop(npc.sprite, "Head"); + return; + } + + float burn = crispy_burn_get(npc); + if (npc.health < npc.maxHitPoints * CRISPY_ANGRY) + { + if (!npc.sprite.overlayAnimState.is_playing("")) npc_overlay_loop(npc.sprite, "HeadAngry"); + else if (npc.sprite.overlayAnimState.animData->name == "Head") npc_overlay_loop(npc.sprite, "HeadTransition"); + } + if (npc.state == NPC_STATE_MOVE) crispy_chase(npc, burn); + + if (npc.IsFrame(CRISPY_BURN_FRAMES, npc.initSeed % CRISPY_BURN_FRAMES)) + npc.TakeDamage(CRISPY_BURN_DAMAGE, 0, EntityRef(), CRISPY_BURN_FRAMES); + npc.sprite.GetLayer(1)->color._tint[3] = 1 - burn; + LayerState* body = npc.sprite.GetLayer(0); + float green = 1 - burn * CRISPY_DARKEN; + body->color._tint[3] = 1; + body->color._tint[0] = 1 - burn * CRISPY_RED_DARKEN; + body->color._tint[1] = green; + body->color._tint[2] = green; + + if (burn > CRISPY_BOUNCY && npc.isCollidesWithGrid) + npc.velocity = vector_scale(vector_normalized(npc.velocity), vector_length(npc.gridCollisionVelocity)); + npc.friction *= burn * CRISPY_FRICTION_RANGE + CRISPY_FRICTION; +} + +// A Skinny or Rotty: it groans, chases its target around the blocks (or runs from it when scared), and trails creep. +static void skinny_walk(Entity_NPC& npc) +{ + if (npc.IsFrame(SKINNY_GROAN_FRAMES, npc.index) && Random() % SKINNY_GROAN_ODDS == 0 && + npc.IsHostileTo(npc.GetPlayerTarget())) + npc.PlaySound(npc.variant == 0 ? (int)SOUND_ANGRY_GURGLE : (int)SOUND_ZOMBIE_WALKER_KID, SKINNY_GROAN_VOLUME, + SKINNY_GROAN_DELAY, false, 1); + + if (!npc.HasEntityFlags(FLAG_SKINNY_SCARED) || npc.controllerID != -1) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), SKINNY_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= SKINNY_EVADE_FRICTION; + } + npc.AnimWalkFrame("WalkHori", "WalkVert", SKINNY_WALK_THRESHOLD); + if (!npc.IsFrame(SKINNY_CREEP_FRAMES, npc.index) || npc.HasEntityFlags(FLAG_SHRINK)) return; + + Entity_Effect* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()})); + creep->scale = SKINNY_CREEP_SCALE; + creep->timeout = SKINNY_CREEP_TIMEOUT; + creep->sprite.scale = vector_make(SKINNY_CREEP_SPRITE_SCALE, SKINNY_CREEP_SPRITE_SCALE); + creep->lifespan = SKINNY_CREEP_TIMEOUT; +} + +// A Bony winds up its throw toward a direction: sideways when it leans that way, else up or down. +static void bony_attack_start(Entity_NPC& npc, const Vector& toward) +{ + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + if (std::abs(toward.y) >= std::abs(toward.x)) return npc.sprite.Play(toward.y <= 0 ? "AttackUp" : "AttackDown"); + + bool isHoly = npc.IsType(ENTITY_BONY, BONY_HOLY, -1); + npc.sprite.Play(isHoly ? (toward.x < 0 ? "AttackLeft" : "AttackRight") : "AttackHori"); + npc.sprite.isFlipX = !isHoly && toward.x < 0; +} + +// Whether an uncontrolled Bony's target lines up with its cell (where it will be in a moment, within 200). +static bool bony_target_lines_up(Entity_NPC& npc, Vector& lead) +{ + if (!npc.IsFrame(BONY_AIM_FRAMES, npc.index) || npc.spawnerType == ENTITY_HORNFEL || + npc.HasEntityFlags(FLAG_BONY_CALM) || (npc.IsFriendly() && npc.GetPlayerTarget()->type == ENTITY_PLAYER)) + return false; + + Room& room = *g_game->room; + Entity* target = npc.GetPlayerTarget(); + Vector targetPos = target->pos; + Vector targetVelocity = npc.GetPlayerTarget()->velocity; + lead = room.GetClampedPosition(vector_add(targetPos, vector_scale(targetVelocity, random_unit() * BONY_AIM_LEAD)), + BONY_MARGIN); + Vector cell = room.GetGridPosition(npc.pathfinder.gridIndex); + Vector gap = vector_sub(cell, lead); + if (std::abs(gap.x) >= BONY_LINE_WIDTH && std::abs(gap.y) >= BONY_LINE_WIDTH) return false; + return vector_length(gap) < BONY_RANGE && room_check_line(cell, lead, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); +} + +// A Bony walking the grid's axes, throwing once its target lines up (or its player aims). +static void bony_walk(Entity_NPC& npc) +{ + if (npc.IsFrame(BONY_GROAN_FRAMES, npc.index) && Random() % SKINNY_GROAN_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, SKINNY_GROAN_VOLUME, SKINNY_GROAN_DELAY, false, 1); + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(npc.pos), GRID_PATH_FREED); + npc.pathfinder.UpdateGridIndex(); + npc.pathfinder.MoveRandomlyAxisAligned(BONY_SPEED, STATUS_OBEYED); + + Vector velocity = npc.velocity; + if (vector_length_squared(velocity) < 1) npc.sprite.SetFrame("WalkDown", 0); + else if (std::abs(velocity.x) <= std::abs(velocity.y)) npc.sprite.Play(velocity.y <= 0 ? "WalkUp" : "WalkDown"); + else if (npc.IsType(ENTITY_BONY, BONY_HOLY, -1)) + { + npc.sprite.Play(velocity.x < 0 ? "WalkLeft" : "WalkRight"); + npc.sprite.isFlipX = false; + } + else + { + npc.sprite.Play("WalkHori"); + npc.sprite.isFlipX = velocity.x < 0; + } + + if (npc.controllerID == -1) + { + Vector lead; + if (bony_target_lines_up(npc, lead)) bony_attack_start(npc, vector_sub(lead, npc.pos)); + return; + } + if (npc.HasEntityFlags(FLAG_BONY_CALM)) return; + if (!npc.IsTargetInAttackRange(BONY_CONTROL_RANGE, 7, false) && + (!npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) || + vector_is_zero(vector_sub(npc.GetAimTargetPosition(), npc.pos)))) + return; + + npc.SpawnControlTarget(0, BONY_AIM_RANGE); + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + npc.UpdateControllerMovement(true); + Vector aim = vector_sub(npc.GetAimTargetPosition(), npc.pos); + bony_attack_start(npc, vector_is_zero(aim) ? npc.controllerMovement : aim); +} + +// A Bony's bone at 10 toward its target (or where its player steers). The Holy Bony arcs it down onto its aim. +static void bony_throw(Entity_NPC& npc) +{ + Vector toward = npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement) + ? npc.controllerMovement + : vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + Vector velocity = vector_resized(toward, BONY_SHOT_SPEED); + + ProjectileParams params; + params.variant = PROJECTILE_BONE; + if (npc.type == ENTITY_BLACK_BONY) params.color = BLACK_BONY_BONE; + else if (npc.IsType(ENTITY_BONY, BONY_HOLY, -1)) + { + float distance = vector_length(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + Vector aim = npc.GetAimTargetPosition(); + if (!vector_is_zero(vector_sub(aim, npc.pos))) + distance = std::clamp(vector_length(vector_sub(npc.pos, aim)), BONY_ARC_MIN, BONY_ARC_MAX); + float frames = distance / BONY_ARC_STEP; + float reach = std::max((std::pow(BONY_ARC_DECAY, frames) - 1) * BONY_ARC_SCALE, BONY_ARC_FLOOR); + params.bulletFlags = PROJECTILE_BLUE_FIRE_SPAWN; + params.fallingAccelModifier = 1; + params.fallingSpeedModifier = (random_unit() * BONY_ARC_JITTER + BONY_ARC_JITTER_MIN) * + ((BONY_ARC_LIFT - (frames - reach) * BONY_ARC_DROP) / reach); + } + npc.PlaySound(SOUND_SCAMPER, 1, 2, false, 1); + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); +} + +// A Bony's throw: the bone at its event, then back to walking (the Black Bony throws the animation thrice). +static void bony_attack_update(Entity_NPC& npc) +{ + npc.SpawnControlTarget(0, BONY_AIM_RANGE); + Vector aim = vector_sub(npc.GetAimTargetPosition(), npc.pos); + if (!vector_is_zero(aim)) npc.controllerMovement = vector_normalized(aim); + + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) bony_throw(npc); + if (npc_anim_is_done(npc)) + { + if (npc.type == ENTITY_BLACK_BONY && npc.stateFrame < BLACK_BONY_THROWS) + { + npc_anim_restart(npc.sprite, npc.sprite.GetAnimation()); + npc.stateFrame++; + } + else npc.state = NPC_STATE_MOVE; + } + npc.friction *= BONY_ATTACK_FRICTION; +} + +// A dying Rotty gets back up as a Bony one time in two, else lets out one or two attack flies. The Black Bony blows up. +static void skinny_death(Entity_NPC& npc) +{ + if (npc.IsType(ENTITY_SKINNY, SKINNY_ROTTY, -1)) + { + if ((Random() & 1) == 0) + { + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.Morph(ENTITY_BONY, 0, 0, -1); + npc.health = npc.maxHitPoints; + npc.isDead = false; + return; + } + if (npc.championRegenCount != 0) return; + + Vector velocity = vector_scale(random_direction(), ROTTY_FLY_SPEED); + Entity* fly = g_game->Spawn( + {.position = npc.pos, .velocity = velocity, .spawner = &npc, .type = ENTITY_ATTACKFLY, .seed = Random()}); + fly->ClearEntityFlags(FLAG_APPEAR); + if ((Random() & 1) != 0) return; + + fly = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(velocity, -1), + .spawner = &npc, + .type = ENTITY_ATTACKFLY, + .seed = Random()}); + fly->ClearEntityFlags(FLAG_APPEAR); + return; + } + if (npc.type != ENTITY_BLACK_BONY || npc.HasEntityFlags(FLAG_SHRINK)) return; + + explosion_damage( + {.position = npc.pos, .source = &npc, .damage = BLACK_BONY_BLAST_DAMAGE, .radius = BLACK_BONY_BLAST_RADIUS}); + bomb_crater_spawn(npc.pos, nullptr, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); +} + +// 00538b70 The Skinny and Bony families' AI: Skinny and Rotty chase with their heads on, trailing creep, and the Rotty +// gets back up as a Bony. Bonies walk the grid's axes and throw bones along them, the Black Bony exploding as it dies. +void npc_skinny_update(Entity_NPC& npc) +{ + if (npc.IsType(ENTITY_SKINNY, SKINNY_CRISPY, -1)) return crispy_update(npc); + + int state = npc.state; + if (state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + if (npc.type == ENTITY_SKINNY) npc.sprite.PlayOverlay("Head"); + if (npc.type != ENTITY_BONY && npc.type != ENTITY_BLACK_BONY) return; + + npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + if (npc.type == ENTITY_BLACK_BONY) npc.splatColor = BLACK_BONY_SPLAT; + if (!npc.IsType(ENTITY_BONY, BONY_HOLY, -1)) return; + + npc.sprite.isOverlayRenderFirst = true; + if (!npc.sprite.SetOverlayAnimation("Glow", SWITCH_KEEP_FRAME)) return; + + npc.sprite.overlayAnimState.Rewind(); + npc.sprite.overlayAnimState.isPlaying = true; + return; + } + + if (state == NPC_STATE_MOVE && npc.type == ENTITY_SKINNY) skinny_walk(npc); + else if (state == NPC_STATE_MOVE) bony_walk(npc); + else if (state == NPC_STATE_ATTACK) bony_attack_update(npc); + + if (npc.isDead) skinny_death(npc); + npc.friction *= SKINNY_FRICTION; +} diff --git a/src/npc_sub_horf.cpp b/src/npc_sub_horf.cpp new file mode 100644 index 0000000..9bc67bf --- /dev/null +++ b/src/npc_sub_horf.cpp @@ -0,0 +1,176 @@ +#include "npc_caves.h" +#include "backdrop.h" +#include "game.h" +#include "level.h" +#include "room.h" +#include "sfx_manager.h" +#include + +// The Sub Horf spins in place as it drifts, spitting along its facing. Its tainted variant chases its target instead, +// shooting bigger, slower arcs. A hit knocks it away at 8 or more. +constexpr int SUB_HORF_TAINTED = 1; +constexpr float SUB_HORF_KNOCKBACK = 8; +constexpr float SUB_HORF_STILL_SQUARED = 1e-6f; +constexpr int SUB_HORF_KNOCKED_FRAMES = 15; +constexpr int SUB_HORF_SHAKE_FRAMES = 12; +constexpr uint32_t SUB_HORF_GRUNT_ODDS = 3; +constexpr int SUB_HORF_GRUNT_DELAY = 10; +constexpr float SUB_HORF_TAINTED_PITCH = 0.85f; +constexpr float SUB_HORF_FACING_OFFSET = 90; +constexpr float SUB_HORF_HALF_TURN = 180; +constexpr float SUB_HORF_FULL_TURN = 360; + +// The tainted one pushes at 0.2 toward its target, turning its facing 0.4 of the way. +constexpr float SUB_HORF_CHASE_PUSH = 0.2f; +constexpr float SUB_HORF_CHASE_TURN = 0.4f; +constexpr float SUB_HORF_CHASE_FRICTION = 0.9f; + +// The plain one spins by twice its speed, shooting at 10 more often the faster it goes, and bleeds while fast. +constexpr float SUB_HORF_STEER_PUSH = 0.2f; +constexpr float SUB_HORF_STEER_DAMP = 0.97f; +constexpr float SUB_HORF_SPIN = 2; +constexpr float SUB_HORF_MOVING = 1; +constexpr float SUB_HORF_STOPPED = 0.01f; +constexpr float SUB_HORF_SHOT_REACH = 20; +constexpr float SUB_HORF_TAINTED_SHOT_REACH = 5; +constexpr float SUB_HORF_SHOT_SPEED = 10; +constexpr float SUB_HORF_SHOT_SPEED_SHARE = 0.7f; +constexpr float SUB_HORF_TAINTED_FALL_ACCEL = -0.1f; +constexpr float SUB_HORF_TAINTED_SHOT_SCALE = 1.4f; +constexpr float SUB_HORF_FRICTION = 0.97f; +constexpr float SUB_HORF_SPLAT_SPEED = 2; +constexpr int SUB_HORF_SPLAT_FRAMES = 7; +constexpr float SUB_HORF_SPLAT_MIN = 0.1f; +constexpr float SUB_HORF_SPLAT_RANGE = 0.3f; + +// An angle in degrees brought within -180 to 180. +static float sub_horf_angle_wrap(float angle) +{ + if (std::abs(angle) > SUB_HORF_FULL_TURN) angle = std::fmod(angle, SUB_HORF_FULL_TURN); + if (angle > SUB_HORF_HALF_TURN) return angle - SUB_HORF_FULL_TURN; + if (angle < -SUB_HORF_HALF_TURN) return angle + SUB_HORF_FULL_TURN; + return angle; +} + +// A hit knocks it straight away from the last attacker's position (a random way when on it), at 8 or more. +static void sub_horf_knockback(Entity_NPC& npc) +{ + if (!npc.damageEvents.empty()) + npc.velocity = vector_normalized(vector_sub(npc.pos, npc.damageEvents.back().source.position)); + if (vector_length_squared(npc.velocity) < SUB_HORF_STILL_SQUARED) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + npc.velocity = vector_make(std::cos(angle), std::sin(angle)); + } + float speed = vector_length(npc.velocity); + if (speed < SUB_HORF_KNOCKBACK && speed > 0) npc.velocity = vector_scale(npc.velocity, SUB_HORF_KNOCKBACK / speed); + npc.stateFrame = SUB_HORF_KNOCKED_FRAMES; +} + +// The tainted one pushes toward its target (where its player steers), turning to face its push. +static void sub_horf_chase(Entity_NPC& npc, const Vector& facing) +{ + Vector toward = npc.controllerID != -1 ? npc.GetControllerInput(0) : vector_sub(npc.CalcTargetPosition(0), npc.pos); + float distance = vector_length(toward); + if (distance > 0) + { + Vector push = vector_scale(toward, SUB_HORF_CHASE_PUSH / distance); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(push, npc.speedMultiplier / npc.friction)); + Vector turned = vector_add(facing, vector_scale(push, SUB_HORF_CHASE_TURN)); + npc.v1.x = vector_angle(turned) - SUB_HORF_FACING_OFFSET; + } + if (vector_length(npc.velocity) > SUB_HORF_KNOCKBACK) npc.stateFrame = SUB_HORF_KNOCKED_FRAMES; + npc.friction *= SUB_HORF_CHASE_FRICTION; +} + +// The plain one (or the tainted one while knocked about) spins with its speed and spits along its facing, more often +// the faster it goes: tears in flooded stages, puke in the Dross. +static void sub_horf_spin(Entity_NPC& npc, const Vector& facing, int shotVariant) +{ + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerInput(0); + if (!vector_is_zero(input)) + { + float cap = std::max(vector_length(npc.velocity) / SUB_HORF_STEER_DAMP, 1.0f); + npc.velocity = vector_add(npc.velocity, vector_scale(input, SUB_HORF_STEER_PUSH * npc.speedMultiplier)); + float speed = vector_length(npc.velocity); + if (speed > cap && speed > 0) npc.velocity = vector_scale(npc.velocity, cap / speed); + } + } + float speed = vector_length(npc.velocity); + float spin = speed * SUB_HORF_SPIN; + if (npc.velocity.x < 0) spin = -spin; + npc.v1.x = sub_horf_angle_wrap(spin + npc.v1.x); + + if (speed >= SUB_HORF_MOVING) npc.stateFrame = SUB_HORF_KNOCKED_FRAMES; + else if (npc.stateFrame > 0) npc.stateFrame -= npc_ticks_get(npc); + if (speed <= SUB_HORF_STOPPED) npc.i1 = 0; + else + { + float reach = npc.variant == SUB_HORF_TAINTED ? SUB_HORF_TAINTED_SHOT_REACH : SUB_HORF_SHOT_REACH; + int interval = std::max((int)(reach / speed), 1); + if (npc.i1 > interval * 2) + { + ProjectileParams params; + params.variant = shotVariant; + params.velocityMulti = SUB_HORF_SHOT_SPEED_SHARE; + if (npc.variant == SUB_HORF_TAINTED) + { + params.fallingAccelModifier = SUB_HORF_TAINTED_FALL_ACCEL; + params.scale = SUB_HORF_TAINTED_SHOT_SCALE; + } + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(facing), SUB_HORF_SHOT_SPEED), + PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_TEARS_FIRE, 1, 2, false, 1); + npc.i1 = 0; + } + npc.i1++; + } + npc.friction *= SUB_HORF_FRICTION; +} + +// 0055fb60 The Sub Horf's AI: knocked away by hits, it spins as it drifts, its shake frame showing its facing, and +// spits along it. The tainted one chases its target. Outside flooded stages it bleeds while moving fast. +void npc_sub_horf_update(Entity_NPC& npc) +{ + Vector facing = vector_from_angle(npc.v1.x + SUB_HORF_FACING_OFFSET); + uint32_t stage = Level::GetStageID(); + int backdrop = g_game->room->backdropType; + bool isFlooded = backdrop == BACKDROP_DOWNPOUR || backdrop == BACKDROP_FLOODED_CAVES || + stage == STAGE_ID_DOWNPOUR || stage == STAGE_ID_DROSS; + int shotVariant = !isFlooded ? PROJECTILE_NORMAL : stage == STAGE_ID_DROSS ? PROJECTILE_PUKE : PROJECTILE_TEAR; + if (npc.pendingDamage > 0) sub_horf_knockback(npc); + + int state = npc.state; + if (state == NPC_STATE_INIT) + { + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + npc.state = NPC_STATE_SPECIAL; + npc.v1.x = 0; + return; + } + if (state == NPC_STATE_SPECIAL) + { + npc.sprite.Play("AppearEnd"); + if (npc_anim_is_done(npc) || npc.pendingDamage > 0) npc.state = NPC_STATE_IDLE; + return; + } + if (state != NPC_STATE_IDLE) return; + + float turn = sub_horf_angle_wrap(npc.v1.x - SUB_HORF_HALF_TURN); + int frame = std::max((int)std::floor((turn + SUB_HORF_HALF_TURN) * SUB_HORF_SHAKE_FRAMES / SUB_HORF_FULL_TURN), 0); + char shake[8]; + std::snprintf(shake, sizeof(shake), "Shake%02d", frame % SUB_HORF_SHAKE_FRAMES); + npc.sprite.Play(shake); + if (npc.pendingDamage > 0 && Random() % SUB_HORF_GRUNT_ODDS == 0) + npc.PlaySound(SOUND_SHAKEY_KID_ROAR, 1, SUB_HORF_GRUNT_DELAY, false, + npc.variant == SUB_HORF_TAINTED ? SUB_HORF_TAINTED_PITCH : 1); + + if (npc.variant == SUB_HORF_TAINTED && npc.stateFrame < 1) sub_horf_chase(npc, facing); + else sub_horf_spin(npc, facing, shotVariant); + + bool isBleeding = vector_length(npc.velocity) > SUB_HORF_SPLAT_SPEED && npc.IsFrame(SUB_HORF_SPLAT_FRAMES, 0); + if (!isFlooded && isBleeding) npc.MakeSplat(random_unit() * SUB_HORF_SPLAT_RANGE + SUB_HORF_SPLAT_MIN); +} diff --git a/src/npc_swarm.cpp b/src/npc_swarm.cpp new file mode 100644 index 0000000..ed9639c --- /dev/null +++ b/src/npc_swarm.cpp @@ -0,0 +1,133 @@ +#include "npc_basement.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "room_grid.h" + +// A Swarm is a leader and four flies spawned 10 around it, circling the leader's spot as it drifts toward the target at +// 5 a frame (6 along its player's input). They push each other apart within 50, and leaders' spots within 100. +constexpr int SWARM_FLY_COUNT = 4; +constexpr float SWARM_SPREAD = 10; +constexpr float SWARM_DRIFT = 5; +constexpr float SWARM_STEER = 6; +constexpr float SWARM_TURN = 5; +constexpr float SWARM_PHASE = 25; +constexpr float SWARM_WOBBLE = 0.8f; +constexpr float SWARM_PULL = 0.03f; +constexpr float SWARM_CROWD = 50; +constexpr float SWARM_CROWD_PUSH = 0.75f; +constexpr float SWARM_SPOT_CROWD = 100; +constexpr float SWARM_SPOT_PUSH = 0.5f; +constexpr float SWARM_FRICTION = 0.8f; + +// Pushes away from a point, the harder the nearer within a reach. Nothing on the point. +static Vector swarm_push_get(const Vector& away, float reach, float strength) +{ + float distance = vector_length(away); + if (distance <= 0) return away; + return vector_scale(away, (1 - distance / reach) * strength / distance); +} + +// The leader's spot drifts toward its target (along its player's input when controlled). +static void swarm_spot_drift(Entity_NPC& npc) +{ + Vector drift = npc.controllerID == -1 ? vector_resized(vector_sub(npc.CalcTargetPosition(0), npc.pos), SWARM_DRIFT) + : vector_scale(npc.GetControllerInput(0), SWARM_STEER); + npc.targetPosition = vector_add(npc.targetPosition, vector_scale(drift, npc.speedMultiplier)); +} + +// A dying leader hands its swarm to its first fly, the others following that one. +static void swarm_leader_pass(Entity_NPC& npc) +{ + Entity_NPC* leader = nullptr; + for (Entity* fly : entity_query(npc.type, npc.variant)) + { + if (fly == &npc || fly->parent.get() != &npc) continue; + fly->parent = leader; + if (!leader) leader = static_cast(fly); + } + if (!leader) return; + + leader->targetPosition = npc.targetPosition; + if (npc.controllerID != -1) npc.TransferControl(leader); +} + +// Flying: pulled toward its leader's spot with a circling wobble, pushing the enemies near it apart. +static void swarm_fly(Entity_NPC& npc) +{ + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, npc.speedMultiplier)); + Vector spot = npc.targetPosition; + if (!npc.parent) swarm_spot_drift(npc); + else spot = npc.parent->targetPosition; + + float sign = (npc.index & 1) == 0 ? 1 : -1; + float angle = ((float)(g_game->frameCount - npc.spawnFrame) * sign * SWARM_TURN + (float)npc.index * SWARM_PHASE) * + DEGREES_TO_RADIANS; + float wobble = random_unit() * SWARM_WOBBLE; + npc.v1 = vector_make((spot.x - npc.pos.x) * SWARM_PULL + std::cos(angle) * wobble, + (spot.y - npc.pos.y) * SWARM_PULL + wobble * std::sin(angle)); + + EntityList_EL nearby = entity_query_radius(npc.pos, SWARM_CROWD, QUERY_ENEMIES); + for (Entity* other : nearby) + { + if (other->index < npc.index) continue; + Vector push = swarm_push_get(vector_sub(npc.pos, other->pos), SWARM_CROWD, SWARM_CROWD_PUSH); + npc.velocity = vector_add(npc.velocity, vector_scale(push, npc.speedMultiplier)); + other->velocity = vector_sub(other->velocity, push); + } + if (!npc.parent) + for (Entity* other : nearby) + { + if (other->parent) continue; + Vector away = vector_sub(npc.targetPosition, other->targetPosition); + if (vector_length_squared(away) >= SWARM_SPOT_CROWD * SWARM_SPOT_CROWD) continue; + npc.targetPosition = + vector_add(npc.targetPosition, swarm_push_get(away, SWARM_SPOT_CROWD, SWARM_SPOT_PUSH)); + } + npc.friction *= SWARM_FRICTION; +} + +// 00540df0 The Swarm's AI: a leader spawns four flies that circle its spot as it drifts toward its target. Lord of the +// Flies takes them and Skatole tames them, and a dying leader passes the swarm on. +void npc_swarm_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + for (int i = 0; i < SWARM_FLY_COUNT && !npc.parent; i++) + { + uint32_t seed = npc.dropRNG.Next(); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector spot = + vector_make(std::cos(angle) * SWARM_SPREAD + npc.pos.x, std::sin(angle) * SWARM_SPREAD + npc.pos.y); + Entity* fly = g_game->Spawn({.position = spot, + .spawner = &npc, + .subType = npc.subtype, + .type = npc.type, + .variant = npc.variant, + .seed = seed}); + fly->parent = &npc; + fly->Update(); + } + npc.targetPosition = npc.pos; + } + if (npc.controllerID != -1 && npc.parent) npc.TransferControl(npc.ParentNPC()); + if (g_game->playerManager.GetRandomPlayer(npc.initSeed) && !npc.isDead) npc.entityCollisionClass = ENTCOLL_NONE; + if (npc_fly_beelzebub_take(npc)) return; + if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK) && !npc.IsFriendly()) + { + npc.Morph(ENTITY_FLY, 0, 0, -1); + npc.v2 = {}; + npc.v1 = {}; + return; + } + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + return; + } + + if (npc.HasEntityFlags(FLAG_KNOCKED_BACK)) npc.targetPosition = npc.pos; + if (!npc.parent && npc.isDead) swarm_leader_pass(npc); + if (npc.state == NPC_STATE_MOVE) swarm_fly(npc); + npc_anim_loop(npc.sprite, "Fly"); + npc.sprite.isFlipX = npc.velocity.x > 0; +} diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 8e32635..85dac45 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -43,7 +43,7 @@ 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_BAR_STEP = 10; constexpr float EVADE_GRID_TOP = 120; constexpr float EVADE_SPOT_RANGE_SQUARED = 40000; constexpr float EVADE_PATH_SPEED = 1.079f; @@ -53,6 +53,8 @@ constexpr float EVADE_PATH_SPEED = 1.079f; constexpr uint32_t GRID_PATH_BAND = 1000; constexpr uint32_t GRID_PATH_PIT = 3000; constexpr int GRID_PATH_IMPASSABLE = 950; +constexpr int GRID_PATH_SOLID_CELL = 1000; +constexpr int GRID_PATH_POOP_CELL = 1500; constexpr int GRID_PATH_SLOWING_MAX = 949; constexpr int CRUSH_COST_EASY = 1; constexpr int CRUSH_COST_DANGEROUS = 800; @@ -117,7 +119,7 @@ void PathFinder::Reset() isPathFound = false; gridPathTarget = {}; evadeMovementCountdown = 0; - stuckFrames = 0; + evadeBar = 0; evadeDistance = 0; visitedGridIndices.clear(); direction = PATH_DIRECTION_NONE; @@ -434,18 +436,19 @@ static void evade_spot_try(PathFinder& finder, const Vector& targetPos, const Ve } float bar = reach / EVADE_REACH_SHARE + distance + EVADE_MARGIN + finder.evadeDistance; - bar -= (float)finder.stuckFrames; + bar -= finder.evadeBar; 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; + finder.evadeBar += 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. +// once the evasion runs out. A friendly owner paths to its target instead. evadeBar lowers the bar each candidate +// spot must clear. void PathFinder::EvadeTarget(const Vector& targetPos, StatusMode mode) { if (mode == STATUS_OBEYED && is_entity_friendly()) @@ -470,7 +473,7 @@ void PathFinder::EvadeTarget(const Vector& targetPos, StatusMode mode) if (is_evade_check_frame(*entity, EVADE_FORGET_FRAMES)) visitedGridIndices.clear(); if (evadeMovementCountdown < 1) { - stuckFrames = 0; + evadeBar = 0; evadeDistance *= EVADE_DECAY; MoveRandomly(STATUS_IGNORED); entity->friction *= EVADE_DECAY; @@ -568,10 +571,35 @@ void PathFinder::update_chase_movement() reconstruction_missing("PathFinder::update_chase_movement 007e6b90"); } -// 007e7070 -bool PathFinder::HasPathToPos(const Vector&, bool) +// 007e7070 Whether the owner can walk to a position: a flood from its cell over the walkable cells (and poop, when +// asked) reaches the owner's cell within half the room's cells. An owner standing in a solid cell cannot. +bool PathFinder::HasPathToPos(const Vector& position, bool isIgnorePoop) { - reconstruction_missing("PathFinder::HasPathToPos 007e7070"); + Room& room = *g_game->room; + int start = room.GetGridIndex(entity->pos); + if (start >= 0 && room.gridPaths[start] == GRID_PATH_SOLID_CELL) return false; + + std::array costs = room.gridPaths; + std::queue open; + open.push({room.GetGridIndex(position), 0}); + while (!open.empty()) + { + PathNode node = open.front(); + if (node.cost >= room.gridWidth * room.gridHeight / 2) return false; + open.pop(); + + for (int next : grid_neighbors_get(room, node.gridIndex)) + { + if (next < 0) continue; + bool isWalkable = costs[next] >= 0 && costs[next] < GRID_PATH_IMPASSABLE; + if (!isWalkable && !(isIgnorePoop && costs[next] == GRID_PATH_POOP_CELL)) continue; + + costs[next] = -(node.cost + 1); + if (next == start) return true; + open.push({next, node.cost + 1}); + } + } + return false; } // 007e8010 diff --git a/src/path_finder.h b/src/path_finder.h index d841cda..b2eb8ad 100644 --- a/src/path_finder.h +++ b/src/path_finder.h @@ -55,6 +55,7 @@ struct PathFinder Vector gridPathTarget{}; Vector moveDirection{}; Vector movementTarget{}; + float evadeBar = 0; float evadeDistance = 0; int direction = PATH_DIRECTION_NONE; int directionTimer = 0; @@ -62,7 +63,6 @@ struct PathFinder int gridIndex = -1; int gridIndexDelay = 0; int moveCountdown = 0; - int stuckFrames = 0; int targetGridIndex = -1; bool canCrushRocks = false; bool hasDirectPath = false; diff --git a/src/player_manager.h b/src/player_manager.h index 740aa37..2614f0b 100644 --- a/src/player_manager.h +++ b/src/player_manager.h @@ -87,6 +87,7 @@ public: Entity_Player* SpawnCoPlayerBaby(int babyId); void RemoveCoPlayer(Entity_Player* player); void remove_coplayers_without_device(); + void players_clear(); bool replace_player(Entity_Player* oldPlayer, Entity_Player* newPlayer); void ReviveCoopPlayer(uint32_t index); void revive_player_ghosts(); diff --git a/src/player_stats.cpp b/src/player_stats.cpp new file mode 100644 index 0000000..c216801 --- /dev/null +++ b/src/player_stats.cpp @@ -0,0 +1,42 @@ +#include "player_stats.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include + +// The record of a user, or none. +static OnlineUserStats* user_stats_find(std::vector& users, uint64_t userId) +{ + auto found = std::ranges::find(users, userId, &OnlineUserStats::userId); + return found == users.end() ? nullptr : &*found; +} + +// 004264c0 The user a player counts for in the online stats. Offline no input device is networked, so it is the +// player's controller. +uint64_t player_get_net_user_id(Entity_Player* player) +{ + if (g_manager->netplayManager.is_online()) + reconstruction_missing("player_get_net_user_id 004264c0 (a networked player's user)"); + return (uint32_t)player->controllerIndex; +} + +// 004259b0 Gives a user an empty record unless it has one, or is no user. +void online_stats_add_user(std::vector& users, uint64_t userId) +{ + if (user_stats_find(users, userId) || userId == NET_USER_NONE) return; + users.push_back({.userId = userId}); +} + +// 00425ac0 Adds to a player's stat for the online co-op stats screen, outside the deathmatch and until the stats are +// final. Its lookups (00425a70, 00426560) are user_stats_find. +void Player_stats_add(std::vector& users, int statId, Entity_Player* player, float amount) +{ + Game& game = *g_game; + if (game.deathmatchManager.is_active() || !player) return; + + uint64_t userId = player_get_net_user_id(player); + if (userId == NET_USER_NONE || game.isOnlineStatsFinalized || statId < 0 || statId >= ONLINE_STAT_COUNT) return; + online_stats_add_user(users, userId); + user_stats_find(users, userId)->stats[statId] += amount; +} diff --git a/src/player_stats.h b/src/player_stats.h new file mode 100644 index 0000000..07b62dc --- /dev/null +++ b/src/player_stats.h @@ -0,0 +1,35 @@ +#pragma once + +#include "classes.h" +#include +#include +#include + +// The stat ids the online co-op stats count (Player_stats_add's statId), below this. +constexpr int ONLINE_STAT_COUNT = 22; +constexpr uint64_t NET_USER_NONE = ~0ull; + +// The online co-op stats Player_stats_add counts. +enum OnlineStat : int +{ + ONLINE_STAT_DAMAGE_TAKEN = 3, + ONLINE_STAT_DEAL_DEATHS = 4, + ONLINE_STAT_ESCAPES = 9, + ONLINE_STAT_REVIVES = 12, + ONLINE_STAT_COINS_SPENT = 13, + ONLINE_STAT_FIRES_PUT_OUT = 14, + ONLINE_STAT_PLAYER_DAMAGE_DEALT = 16, + ONLINE_STAT_SECRET_DOORS_BOMBED = 19 +}; + +// One user's tallies in the online co-op stats (the block's 0x68 byte records): who, and each stat's count. +struct OnlineUserStats +{ + std::array stats{}; + uint64_t userId = 0; + bool isJoined = true; +}; + +uint64_t player_get_net_user_id(Entity_Player* player); +void online_stats_add_user(std::vector& users, uint64_t userId); +void Player_stats_add(std::vector& users, int statId, Entity_Player* player, float amount); diff --git a/src/rail_manager.cpp b/src/rail_manager.cpp index 3ca6494..082b318 100644 --- a/src/rail_manager.cpp +++ b/src/rail_manager.cpp @@ -5,8 +5,6 @@ #include "log.h" #include "room.h" -constexpr int BACKDROP_ASHPIT = 46; - // The row and the columns where an L room's walls step in around its missing quarter. constexpr int L_ROW = 7; constexpr int L_LEFT_COLUMN = 13; diff --git a/src/revive_player_menu.cpp b/src/revive_player_menu.cpp index d44602c..a6435ab 100644 --- a/src/revive_player_menu.cpp +++ b/src/revive_player_menu.cpp @@ -22,7 +22,6 @@ constexpr float SELECTOR_BELOW = 65; constexpr float SELECTOR_BELOW_COMPACT = 50; constexpr int CLOSE_FRAMES = 8; constexpr int SOUND_FRAME_DELAY = 2; -constexpr uint32_t ONLINE_STAT_REVIVES = 12; constexpr uint32_t PLAYER_INDEX_NONE = UINT32_MAX; // Whether an action was pressed this frame on one device, by its default bindings. @@ -129,7 +128,7 @@ void RevivePlayerMenu::Update() std::vector& list = players.playerList; auto revived = std::ranges::find(list, players.get_main_player(selectedPlayer)); players.ReviveCoopPlayer(revived == list.end() ? PLAYER_INDEX_NONE : (uint32_t)(revived - list.begin())); - Player_stats_add(&g_game->onlinePlayerStats, ONLINE_STAT_REVIVES, player_by_controller(controllerIndex), 1); + Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_REVIVES, player_by_controller(controllerIndex), 1); menu_sound_play(SOUND_HOLY, SOUND_FRAME_DELAY); } diff --git a/src/room.cpp b/src/room.cpp index 79f2ca7..2d71213 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -95,31 +95,11 @@ constexpr uint32_t GRID_COLLISION_PIT = 1; constexpr uint32_t GRID_COLLISION_SOLID = 3; constexpr uint32_t GRID_COLLISION_WALL = 4; -// The stages, stage ids, backdrops and bosses Init and PlayMusic tell apart. -constexpr int STAGE_HOME = 13; - // A crawlspace's subtypes: Rotgut's two phases and the Beast's arena. constexpr int DUNGEON_GIDEON = 1; constexpr int DUNGEON_ROTGUT = 2; constexpr int DUNGEON_ROTGUT_HEART = 3; constexpr int DUNGEON_BEAST = 4; -constexpr int STAGE_BLUE_WOMB = 9; -constexpr int STAGE_ID_DOWNPOUR = 27; -constexpr int STAGE_ID_DROSS = 28; -constexpr int STAGE_ID_ASHPIT = 30; -constexpr int STAGE_ID_HOME = 35; -constexpr int BACKDROP_FLOODED_CAVES = 6; -constexpr int BACKDROP_SCARRED_WOMB = 12; -constexpr int BACKDROP_DARK_ROOM = 16; -constexpr int BACKDROP_MEGA_SATAN = 18; -constexpr int BACKDROP_MINES = 32; -constexpr int BACKDROP_CORPSE = 34; -constexpr int BACKDROP_PLANETARIUM = 35; -constexpr int BACKDROP_CORPSE3 = 44; -constexpr int BACKDROP_ASHPIT = 46; -constexpr int BACKDROP_CLOSET_B = 53; -constexpr int BACKDROP_MINES_SHAFT = 58; -constexpr int BACKDROP_ASHPIT_SHAFT = 59; constexpr int BOSS_MOM = 6; constexpr int BOSS_ISAAC = 39; constexpr int BOSS_SATAN = 24; @@ -130,43 +110,6 @@ constexpr int BOSS_MOM_MAUSOLEUM = 89; // The backdrops LoadBackdropGraphics picks beyond the stage's own (backdrops.xml ids), and what picks them: rooms off // the map, Home's rooms by subtype, the bosses and stages with their own, and the Void's random ones. -constexpr int BACKDROP_UTERO = 11; -constexpr int BACKDROP_BLUE_WOMB = 13; -constexpr int BACKDROP_SHEOL = 14; -constexpr int BACKDROP_CATHEDRAL = 15; -constexpr int BACKDROP_CHEST = 17; -constexpr int BACKDROP_LIBRARY = 19; -constexpr int BACKDROP_SHOP = 20; -constexpr int BACKDROP_ISAAC = 21; -constexpr int BACKDROP_BARREN = 22; -constexpr int BACKDROP_SECRET = 23; -constexpr int BACKDROP_DICE = 24; -constexpr int BACKDROP_ARCADE = 25; -constexpr int BACKDROP_ERROR_ROOM = 26; -constexpr int BACKDROP_BLUE_WOMB_PASS = 27; -constexpr int BACKDROP_GREED_SHOP = 28; -constexpr int BACKDROP_DUNGEON = 29; -constexpr int BACKDROP_SACRIFICE = 30; -constexpr int BACKDROP_MAUSOLEUM = 33; -constexpr int BACKDROP_DOWNPOUR_ENTRANCE = 36; -constexpr int BACKDROP_MAUSOLEUM_ENTRANCE = 38; -constexpr int BACKDROP_MAUSOLEUM_HEART = 39; -constexpr int BACKDROP_MAUSOLEUM2 = 40; -constexpr int BACKDROP_MAUSOLEUM3 = 41; -constexpr int BACKDROP_MAUSOLEUM4 = 42; -constexpr int BACKDROP_CORPSE2 = 43; -constexpr int BACKDROP_ISAACS_BEDROOM = 49; -constexpr int BACKDROP_HALLWAY = 50; -constexpr int BACKDROP_MOMS_BEDROOM = 51; -constexpr int BACKDROP_CLOSET = 52; -constexpr int BACKDROP_DOGMA = 54; -constexpr int BACKDROP_DUNGEON_GIDEON = 55; -constexpr int BACKDROP_DUNGEON_ROTGUT = 56; -constexpr int BACKDROP_DUNGEON_BEAST = 57; -constexpr int BACKDROP_DARK_CLOSET = 60; -constexpr int BACKDROP_DEATHMATCH = 61; -constexpr int BACKDROP_LIL_PORTAL = 62; -constexpr int BACKDROP_WOMB = 10; constexpr int ROOM_DEATHMATCH_IDX = -19; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int DARK_CLOSET_B_SUBTYPE = 33; @@ -178,17 +121,8 @@ constexpr int HOME_CLOSET_LEFT = 10; constexpr int BOSS_MAUSOLEUM_HEART = 90; constexpr int BOSS_VISAGE = 78; constexpr int BOSS_RAINMAKER = 77; -constexpr int STAGE_DARK_ROOM_CHEST = 11; -constexpr int STAGE_THE_VOID = 12; -constexpr int STAGE_MAUSOLEUM_II = 8; constexpr int STAGE_ID_LAST_CHAPTER = 12; -constexpr int STAGE_ID_SHEOL = 14; -constexpr int STAGE_ID_CHEST = 17; -constexpr int STAGE_ID_ULTRA_GREED = 24; -constexpr int STAGE_ID_ULTRA_GREED_EXIT = 25; -constexpr int STAGE_ID_VOID = 26; constexpr int STAGE_ID_FIRST_ALT = 27; -constexpr int GREED_STAGE_ULTRA_GREED = 6; constexpr int VOID_BACKDROPS = 17; constexpr uint32_t DELETE_THIS_STAGES = 11; constexpr uint32_t DELETE_THIS_STAGE_TYPES = 5; @@ -231,7 +165,6 @@ constexpr int ACHIEVEMENT_BLUE_WOMB = 234; 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 SOUND_ANGEL_DOOR_APPEAR = 23; constexpr int SOUND_DEVIL_DOOR_APPEAR = 320; constexpr int GREED_DEAL_DOOR_SLOT = 4; @@ -1976,7 +1909,7 @@ static int deal_stage_get_unclamped() // The stage a deal door last opened on, up to Home. static int deal_stage_get() { - return std::clamp(deal_stage_get_unclamped(), 0, STAGE_HOME); + return std::clamp(deal_stage_get_unclamped(), 0, (int)STAGE_HOME); } // 007f92b0 The chance the floor's last boss room opens a deal door: a base chance raised by the deal items and @@ -2185,7 +2118,7 @@ static int backdrop_by_stage(Room& room, int& fxStage, int& stageType) } int stageId = RoomConfig::GetStageID(stage, stageType, ROOM_MODE_CURRENT); - if (stage == STAGE_THE_VOID && descriptor.data->stageId != 0) stageId = descriptor.data->stageId; + if (stage == STAGE_VOID && descriptor.data->stageId != 0) stageId = descriptor.data->stageId; if (stageId == STAGE_ID_VOID) { RNG rng = {descriptor.decorationSeed, 1, 21, 20}; @@ -2194,13 +2127,13 @@ static int backdrop_by_stage(Room& room, int& fxStage, int& stageType) if (stageId == STAGE_ID_HOME) return backdrop_home_get(descriptor); int backdropId = game.roomConfig.stages[stageId].backdrop; - bool isGreedBoss = (stageId == STAGE_ID_ULTRA_GREED || stageId == STAGE_ID_ULTRA_GREED_EXIT) && + bool isGreedBoss = (stageId == STAGE_ID_GREED_SHOP || stageId == STAGE_ID_ULTRA_GREED) && descriptor.data->type == ROOM_BOSS && descriptor.listIndex == game.lastBossRoomListIdx; if (isGreedBoss) backdropId = BACKDROP_GREED_SHOP; if (room.roomType == ROOM_TREASURE && descriptor.flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE) return BACKDROP_SHEOL; if (room.roomType == ROOM_BOSS && descriptor.data->subtype == BOSS_MAUSOLEUM_HEART) return BACKDROP_WOMB; - if (backdropId == BACKDROP_MAUSOLEUM && game.IsMausoleumHeartStage()) return BACKDROP_MAUSOLEUM_HEART; + if (backdropId == BACKDROP_MAUSOLEUM && game.IsMausoleumHeartStage()) return BACKDROP_CORPSE_ENTRANCE; return backdropId; } @@ -2258,8 +2191,8 @@ static void void_fx_stage_get(int stageId, int& fxStage, int& stageType) if (is_greed()) { - if (stageId == STAGE_ID_ULTRA_GREED) stage = GREED_STAGE_ULTRA_GREED; - else if (stageId == STAGE_ID_ULTRA_GREED_EXIT) stage = GREED_STAGE_ULTRA_GREED + 1; + if (stageId == STAGE_ID_GREED_SHOP) stage = STAGE_GREED_SHOP; + else if (stageId == STAGE_ID_ULTRA_GREED) stage = STAGE_ULTRA_GREED; else if (stageId < STAGE_ID_FIRST_ALT) { if (stageId > STAGE_ID_LAST_CHAPTER) return; @@ -2284,7 +2217,7 @@ static void void_fx_stage_get(int stageId, int& fxStage, int& stageType) stage = (stageId - STAGE_ID_SHEOL) / 2 + STAGE_BLUE_WOMB + 1; type = (stageId - STAGE_ID_SHEOL) % 2; } - else if (stageId == STAGE_ID_VOID) stage = STAGE_THE_VOID; + else if (stageId == STAGE_ID_VOID) stage = STAGE_VOID; else return; } else @@ -2362,7 +2295,7 @@ void Room::LoadBackdropGraphics() backdrop.rng = {descriptor->decorationSeed, 5, 9, 7}; backdrop.Init((uint32_t)backdropId, false); backdropType = (int)backdrop.backdropId; - if (fxStage == STAGE_THE_VOID) void_fx_stage_get(descriptor->data->stageId, fxStage, stageType); + if (fxStage == STAGE_VOID) void_fx_stage_get(descriptor->data->stageId, fxStage, stageType); bool isNoLayers = roomType == ROOM_DUNGEON || backdropId == BACKDROP_MEGA_SATAN; if (isNoLayers) fxLayers.clear(); @@ -2387,7 +2320,7 @@ bool Room::TrySpawnMegaSatanRoomDoor(bool isForce) if (!isForce) { - bool isStart = game.currentRoomIdx == game.startingRoomIdx && game.stage == STAGE_DARK_ROOM_CHEST && + bool isStart = game.currentRoomIdx == game.startingRoomIdx && game.stage == STAGE_DARK_ROOM && game.currentDimensionIdx == 0; if (!isStart || !is_unlocked(ACHIEVEMENT_MEGA_SATAN)) return false; if (is_challenge_or_daily() && !isMegaSatan) return false; @@ -3098,14 +3031,14 @@ bool Room::TrySpawnTheVoidDoor(bool isForce) ChallengeParam& params = game.GetChallengeParams(); bool isVoidUnlocked = !is_challenge_or_daily() && is_unlocked(ACHIEVEMENT_THE_VOID); - int endStage = params.endStage == STAGE_THE_VOID || isVoidUnlocked ? STAGE_THE_VOID : STAGE_DARK_ROOM_CHEST; + int endStage = params.endStage == STAGE_VOID || isVoidUnlocked ? STAGE_VOID : STAGE_DARK_ROOM; bool isClosed = is_greed(); if (!isClosed && params.isPathTypeSet) { if (params.endStage != 0) endStage = params.endStage; isClosed = params.pathType == PATH_TYPE_HOME; } - if (isClosed || endStage < STAGE_THE_VOID || game.levelStateFlags & 1u << LEVEL_STATE_VOID_DOOR_DISABLED) + if (isClosed || endStage < STAGE_VOID || game.levelStateFlags & 1u << LEVEL_STATE_VOID_DOOR_DISABLED) { game.levelStateFlags |= 1u << LEVEL_STATE_VOID_DOOR_DISABLED; return false; @@ -3137,7 +3070,7 @@ bool Room::TrySpawnBlueWombDoor(bool isFirstTime, bool isIgnoreTime, bool isForc int stage = labyrinth_stage_get(); ChallengeParam& params = game.GetChallengeParams(); bool isAltStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - bool isAllowed = (!params.isPathTypeSet || stage < params.endStage) && stage == STAGE_MAUSOLEUM_II && !isAltStage; + bool isAllowed = (!params.isPathTypeSet || stage < params.endStage) && stage == STAGE_WOMB_II && !isAltStage; if (!isForce && !isAllowed) return false; if (is_door_to(*this, ROOM_BLUE_WOMB_IDX)) return false; if (game.timeCounter > game.blueWombParTime && !isIgnoreTime && !isForce) return false; diff --git a/src/room_clear.cpp b/src/room_clear.cpp index 476e538..eb8f5c6 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -10,7 +10,7 @@ #include "grid_entity_pit.h" #include "item_config.h" #include "item_pool.h" -#include "lua_callbacks.h" +#include "lua_engine.h" #include "manager.h" #include "npc_ai.h" #include "persistent_game_data.h" @@ -32,16 +32,11 @@ constexpr int COLLECTIBLE_GLYPH_OF_BALANCE = 464; constexpr int COLLECTIBLE_BROKEN_SHOVEL_2 = 551; constexpr int COLLECTIBLE_OPTIONS = 670; constexpr int COLLECTIBLE_SWARM = 693; -constexpr int COLLECTIBLE_AZAZELS_RAGE = 699; 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 TRINKET_AAA_BATTERY_CLEAR = 3; -constexpr int TRINKET_RUSTED_KEY = 36; -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_OLD_CAPACITOR = 143; @@ -55,7 +50,6 @@ constexpr int FAMILIAR_BLUE_FLY_CLEAR = 43; constexpr int ENTITY_ETERNALFLY_CLEAR = 96; constexpr int GRID_PATH_TRODDEN = 900; constexpr int BABY_SKIN_WISP = 64; -constexpr int EFFECT_HEART_CLEAR = 49; constexpr int SOUND_DOOR_HEAVY_OPEN = 36; constexpr int SOUND_VAMP_GULP_CLEAR = 157; constexpr int SOUND_VAMP_DOUBLE_CLEAR = 614; @@ -67,9 +61,6 @@ constexpr int EVENT_COUNTER_LAMB_KILLS = 25; constexpr int EVENT_COUNTER_BOSSRUSHS_CLEARED = 111; constexpr int ULTRA_GREED_BOSS = 62; constexpr int BABY_PLUM_BOSS = 84; -constexpr int STAGE_HOME_ID = 35; -constexpr int STAGE_WOMB_2 = 8; -constexpr int STAGE_HOME_END = 13; constexpr int GREED_WAVES = 10; constexpr int ACHIEVEMENT_MONSTROS_LUNG = 13; constexpr int ACHIEVEMENT_LIL_CHUBBY = 14; @@ -89,7 +80,6 @@ struct NoDamageUnlock }; constexpr std::array NO_DAMAGE_UNLOCKS = { {{2, 1, 37, 351}, {4, 3, 38, 365}, {6, 5, 39, 368}, {8, 7, 40, 374}, {11, 11, 83, 0}}}; -constexpr int STAGE_DEPTHS_2 = 6; // The room clear award's generator shifts (5, 9, 7), and Deep Pockets' (2, 21, 9). constexpr uint32_t AWARD_RNG_SHIFT = 35; @@ -173,7 +163,7 @@ constexpr int COLOR_PRIORITY_FULL = 255; static void clear_heart_spawn(Entity_Player& player, int subType) { Entity* heart = g_game->Spawn({.position = player.pos, .subType = subType, .type = ENTITY_EFFECT, - .variant = EFFECT_HEART_CLEAR, .seed = Random()}); + .variant = EFFECT_HEART, .seed = Random()}); heart->sprite.offset = vector_make(0, HEART_EFFECT_RISE_CLEAR); heart->renderDepthOffset = 1; } @@ -225,7 +215,7 @@ void room_spawn_cell_clear(Room& room, int& gridIndex) gridIndex = room.GetGridIndex(free_spot_get(room.GetGridPosition(gridIndex))); RoomConfig_Room* data = room.descriptor->data; - bool isHomeCloset = data && data->type == ROOM_DUNGEON && data->stageId == STAGE_HOME_ID; + bool isHomeCloset = data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME; int column = gridIndex % room.gridWidth; int row = gridIndex / room.gridWidth; for (int x = column - 1; x <= column + 1; x++) @@ -284,7 +274,7 @@ static int trapdoor_index_get(Room& room) static bool is_depths_last_boss() { Game& game = *g_game; - if (game.stage != STAGE_DEPTHS_2 && (game.stage != STAGE_DEPTHS_2 - 1 || !game.filter_curses(CURSE_OF_LABYRINTH))) + if (game.stage != STAGE_DEPTHS_II && (game.stage != STAGE_DEPTHS_II - 1 || !game.filter_curses(CURSE_OF_LABYRINTH))) return false; return game.GetRoomByIdx(game.currentRoomIdx)->listIndex == game.lastBossRoomListIdx; } @@ -792,7 +782,7 @@ static int boss_stage_get() int stage = (int)game.stage; int stageType = (int)game.stageType; if (game.currentRoomIdx == ROOM_EXTRA_BOSS_IDX) Level::boss_count_adjust(stage, stageType); - else if ((game.filter_curses(CURSE_OF_LABYRINTH) && stage < STAGE_WOMB_2) || + else if ((game.filter_curses(CURSE_OF_LABYRINTH) && stage < STAGE_WOMB_II) || game.challenge == CHALLENGE_RED_REDEMPTION) stage++; return stage; @@ -824,10 +814,10 @@ static void boss_award_spawn(Room& room, ClearAward& award) isLastBoss = game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx)->data->type == ROOM_BOSS; if (players.IsCoopPlay() && isLastBoss) players.revive_player_ghosts(); - bool isPlainFloor = stage < STAGE_WOMB_2 && stage != STAGE_DEPTHS_2; - bool isMomsFloor = (stage == STAGE_WOMB_2 || stage == STAGE_DEPTHS_2) && !isLastBoss; + bool isPlainFloor = stage < STAGE_WOMB_II && stage != STAGE_DEPTHS_II; + bool isMomsFloor = (stage == STAGE_WOMB_II || stage == STAGE_DEPTHS_II) && !isLastBoss; bool isBossRush = room.roomType == ROOM_BOSSRUSH || - (game.challenge == CHALLENGE_RED_REDEMPTION && stage < STAGE_WOMB_2); + (game.challenge == CHALLENGE_RED_REDEMPTION && stage < STAGE_WOMB_II); if (isSecretExitBoss) reconstruction_missing("Room::SpawnClearAward 007fb250: the secret exit's bosses (Mom, Mother)"); else if (isPlainFloor || isBossRush) @@ -850,7 +840,7 @@ void room_clear_award_spawn(Room& room) ClearAward award; award.rng = rng_make(room.descriptor->awardSeed, AWARD_RNG_SHIFT); award.reward = Room::GetCenterPos(); - lua_callback_check(MC_PRE_SPAWN_CLEAN_AWARD, "Room::SpawnClearAward 007fb250: MC_PRE_SPAWN_CLEAN_AWARD"); + if (lua_engine_get().PreSpawnCleanAward(award.rng, award.reward)) return; award.trapdoorIndex = trapdoor_index_get(room); award.itemRow = award.reward.y + AWARD_ITEM_DROP; @@ -867,7 +857,7 @@ void room_clear_award_spawn(Room& room) if (room.roomType == ROOM_DEFAULT || (room.roomType == ROOM_BOSS && room.bossId == ULTRA_GREED_BOSS)) reconstruction_missing("Room::SpawnClearAward 007fb250: Greed mode's wave music and Ultra Greed's coins"); } - else if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_HOME_ID) + else if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME) reconstruction_missing("Room::SpawnClearAward 007fb250: Home's ending"); else if (isNormal && !isEmpty) room_award_spawn(room, award); else if (!isNormal) boss_award_spawn(room, award); @@ -904,9 +894,9 @@ void room_clear_trigger(Room& room, ClearSound sound) ChallengeParam& params = game.GetChallengeParams(); bool isPathChallenge = game.challenge == CHALLENGE_BACKASSWARDS || params.pathType == PATH_TYPE_HOME || - params.endStage == STAGE_HOME_END; + params.endStage == STAGE_HOME; int nextStage = (int)game.stage + (game.filter_curses(CURSE_OF_LABYRINTH) ? 1 : 0); - if (isPathChallenge && Room::IsCurrentRoomLastBoss() && nextStage == STAGE_DEPTHS_2) + if (isPathChallenge && Room::IsCurrentRoomLastBoss() && nextStage == STAGE_DEPTHS_II) reconstruction_missing("Room::TriggerClear 008068f0: a path challenge's doors (Room::update_door_targets " "00802670)"); diff --git a/src/room_config.cpp b/src/room_config.cpp index 73bd974..dd93086 100644 --- a/src/room_config.cpp +++ b/src/room_config.cpp @@ -39,17 +39,10 @@ constexpr int CURSE_SLOTS = 9; constexpr uint16_t QUEST_DOOR_VARIANT = 2; constexpr uint32_t GRID_PRESSURE_PLATE = 4500; constexpr int ROOM_TYPE_DEFAULT = 1; -constexpr int STAGE_MINES = 29; -constexpr int STAGE_ASHPIT = 30; constexpr int MINESHAFT_SUBTYPE = 31; -constexpr int STAGE_BURNING_BASEMENT = 3; constexpr int PATCHED_VARIANT_A = 603; constexpr int PATCHED_VARIANT_B = 716; -constexpr uint32_t LEVEL_STAGE_VOID = 12; -constexpr int STAGE_SPECIAL_ROOMS = 0; -constexpr int STAGE_HOME = 35; -constexpr int STAGE_BLUE_WOMB = 13; constexpr int VOID_STAGE_LAST = 17; constexpr int VOID_MAX_DIFFICULTY = 20; constexpr uint32_t GIANT_SHIFT = 17; @@ -493,8 +486,8 @@ void RoomConfig::LoadStageBinary(int stageId, RoomMode mode) bool isPatched = room.variant == PATCHED_VARIANT_A || room.variant == PATCHED_VARIANT_B; bool isMineshaft = room.type == ROOM_TYPE_DEFAULT && room.subtype == MINESHAFT_SUBTYPE; - if (stageId >= 1 && stageId <= STAGE_BURNING_BASEMENT && isPatched) room.flags |= ROOM_FLAG_BASEMENT_PATCHED; - if ((stageId == STAGE_MINES || stageId == STAGE_ASHPIT) && isMineshaft) room.flags |= ROOM_FLAG_MINESHAFT; + if (stageId >= 1 && stageId <= STAGE_ID_BURNING_BASEMENT && isPatched) room.flags |= ROOM_FLAG_BASEMENT_PATCHED; + if ((stageId == STAGE_ID_MINES || stageId == STAGE_ID_ASHPIT) && isMineshaft) room.flags |= ROOM_FLAG_MINESHAFT; } g_manager->modManager.LoadModRooms(stageId, mode); @@ -583,15 +576,15 @@ RoomConfig_Room* RoomConfig::GetRandomRoom(uint32_t seed, WeightReduction reduct if (RoomConfig_Room* room = GetRandomSplitRoom(seed, reduction, query)) return room; std::vector rooms; - bool isVoid = g_game->stage == LEVEL_STAGE_VOID && query.stageId != STAGE_SPECIAL_ROOMS && - query.stageId != STAGE_HOME; + bool isVoid = g_game->stage == STAGE_VOID && query.stageId != STAGE_ID_SPECIAL_ROOMS && + query.stageId != STAGE_ID_HOME; if (isVoid) { RoomQuery chapter = query; chapter.maxDifficulty = VOID_MAX_DIFFICULTY; for (chapter.stageId = 1; chapter.stageId <= VOID_STAGE_LAST; chapter.stageId++) - if (chapter.stageId != STAGE_BLUE_WOMB) std::ranges::copy(GetRooms(chapter), std::back_inserter(rooms)); + if (chapter.stageId != STAGE_ID_BLUE_WOMB) std::ranges::copy(GetRooms(chapter), std::back_inserter(rooms)); } else rooms = GetRooms(query); @@ -860,11 +853,11 @@ int RoomConfig::GetStageID(int levelStage, int stageType, RoomMode mode) if (type == 5) return (int)(stage * 2 + 26); return (int)(type + stage * 3 - 2); } - if (stage == 13) return STAGE_HOME; + if (stage == 13) return STAGE_ID_HOME; if (levelStage > 8) { - if (stage == 9) return type == 4 ? 36 : STAGE_BLUE_WOMB; - if (stage == LEVEL_STAGE_VOID) return 26; + if (stage == 9) return type == 4 ? 36 : STAGE_ID_BLUE_WOMB; + if (stage == STAGE_VOID) return 26; return (int)(type + (stage - 3) * 2); } if (type == 4) return (int)(((stage - 1) & ~1u) + 27); diff --git a/src/room_grid.cpp b/src/room_grid.cpp index b92c42e..54e796a 100644 --- a/src/room_grid.cpp +++ b/src/room_grid.cpp @@ -37,6 +37,9 @@ constexpr int DOOR_RETRIES = 20; constexpr float DOOR_RETRY_STEP = 40; constexpr float DEGREES_FULL_TURN = 360; +// The distance FindFreeTilePosition starts its search from, farther than any cell. +constexpr float FREE_TILE_FAR = 1e6f; + // The grid path a try accepts, by the tries left below which it does: higher as the search runs out. struct PathBand { @@ -206,3 +209,27 @@ bool room_bridge_make(GridEntity* pit, GridEntity* rock) static_cast(pit)->MakeBridge(isRock ? static_cast(rock) : nullptr, 0); return true; } + +// 0081e520 Room::FindFreeTilePosition: the position itself on a free cell, else the center of the nearest free cell, +// taking the first one found within the distance. +Vector room_free_tile_position_find(const Vector& position, float distanceThreshold) +{ + Room& room = *g_game->room; + int cell = room.GetGridIndex(position); + if (room.GetGridCollision(cell) == COLLISION_NONE) return position; + + Vector best = room.GetGridPosition(cell); + float bestDistance = FREE_TILE_FAR; + for (int i = 0; i < room.gridWidth * room.gridHeight; i++) + { + if (i == cell || room.GetGridCollision(i) != COLLISION_NONE) continue; + + Vector at = room.GetGridPosition(i); + float distance = (at.y - position.y) * (at.y - position.y) + (at.x - position.x) * (at.x - position.x); + if (distance >= bestDistance) continue; + best = at; + bestDistance = distance; + if (distance < distanceThreshold * distanceThreshold) break; + } + return best; +} diff --git a/src/room_grid.h b/src/room_grid.h index 36797b9..a513c4b 100644 --- a/src/room_grid.h +++ b/src/room_grid.h @@ -39,5 +39,6 @@ struct GridDestroy EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t partitions); GridEntity* room_grid_entity_at(const Vector& position); Vector room_free_pickup_position_find(const FreeSpotSearch& search); +Vector room_free_tile_position_find(const Vector& position, float distanceThreshold); bool room_grid_destroy(const GridDestroy& destroy); bool room_bridge_make(GridEntity* pit, GridEntity* rock); diff --git a/src/room_lighting.cpp b/src/room_lighting.cpp index 8924efa..c52be3e 100644 --- a/src/room_lighting.cpp +++ b/src/room_lighting.cpp @@ -90,7 +90,6 @@ 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; @@ -111,14 +110,12 @@ enum LightVariant : int 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, diff --git a/src/room_render.cpp b/src/room_render.cpp index 612540e..122cb99 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -98,19 +98,6 @@ constexpr int DOOR_STATE_LIGHT = 4; constexpr int ROOM_IDX_SECRET_EXIT = -10; constexpr int ROOM_IDX_BLUE_WOMB_LIGHT = -9; constexpr int BOSS_MOM_MAUSOLEUM = 89; -constexpr int STAGE_BASEMENT_I = 1; -constexpr int STAGE_BLUE_WOMB = 9; -constexpr int STAGE_HOME = 13; -constexpr int STAGE_ID_HOME = 35; -constexpr int STAGE_ID_CAVES = 4; -constexpr int STAGE_ID_CATACOMBS = 5; -constexpr int STAGE_ID_FLOODED = 6; -constexpr int STAGE_ID_DOWNPOUR = 27; -constexpr int STAGE_ID_DROSS = 28; -constexpr int STAGE_TYPE_WOTL = 1; -constexpr int STAGE_TYPE_AFTERBIRTH = 2; -constexpr int STAGE_TYPE_REPENTANCE = 4; -constexpr int STAGE_TYPE_REPENTANCE_B = 5; constexpr int DIMENSION_MIRROR = 1; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_LIT_DOOR = 1u << 18; @@ -119,15 +106,6 @@ constexpr uint32_t DEBUG_FLAG_GRID_VALUES = 1 << 1; constexpr uint32_t DEBUG_FLAG_ROOM_INFO = 1 << 4; 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_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 Beast's arena draws in passes around the room's: under everything, over the floor, over the entities, last. enum BeastArenaPass { @@ -137,6 +115,49 @@ enum BeastArenaPass BEAST_PASS_FOREGROUND }; +// The caustics band along the walls: its width before scaling, how fast it scrolls along the walls, turns and drifts +// across them, the pit count that fills a flooded room's water, and the Corpse's red water. +constexpr float CAUSTICS_EDGE = 50; +constexpr float CAUSTICS_SCROLL_SPEED = 0.5f; +constexpr float CAUSTICS_TURN_SPEED = 0.01f; +constexpr float CAUSTICS_DRIFT = 0.1f; +constexpr float CAUSTICS_FLOOD_PITS = 30; +constexpr float CORPSE_CAUSTICS_GREEN_BLUE = 0.3f; +constexpr float CAUSTICS_DEGREES_TO_RADIANS = 0.017453292f; + +// -1, 0 or 1 by the sign of a number. +static float sign_get(float value) +{ + return (float)((value > 0) - (value < 0)); +} + +// A room's wall corners for its caustics, clockwise from the bottom of the left wall: a rectangle's four, an L's six +// with the inner corner at the middle of the room's bounds. +static std::vector caustics_corners(RoomShape shape, Vector topLeft, Vector bottomRight) +{ + float left = topLeft.x; + float top = topLeft.y; + float right = bottomRight.x; + float bottom = bottomRight.y; + float midX = (right - left) * 0.5f + left; + float midY = (bottom - top) * 0.5f + top; + auto at = [](float x, float y) { return vector_make(x, y); }; + + switch (shape) + { + case ROOMSHAPE_LTL: + return {at(left, bottom), at(left, midY), at(midX, midY), at(midX, top), at(right, top), at(right, bottom)}; + case ROOMSHAPE_LTR: + return {at(left, bottom), at(left, top), at(midX, top), at(midX, midY), at(right, midY), at(right, bottom)}; + case ROOMSHAPE_LBL: + return {at(left, midY), at(left, top), at(right, top), at(right, bottom), at(midX, bottom), at(midX, midY)}; + case ROOMSHAPE_LBR: + return {at(left, bottom), at(left, top), at(right, top), at(right, midY), at(midX, midY), at(midX, bottom)}; + default: + return {at(left, bottom), at(left, top), at(right, top), at(right, bottom)}; + } +} + // render_water's passes: the caustics over the room's walls, or the water's light in the light overlay. enum WaterPass { @@ -409,19 +430,96 @@ static void shockwaves_radial_render(Room& room, Vector offset) } } -// 00817830 The floor's water caustics over the room, or their light in the light overlay. Backdrops without walls, -// and rooms without water but the flooded stages' water rooms, have none. +// 00817830 The water's caustics in a band along the room's walls, in the room's light color (the Corpse's red) as +// opaque as the room's water. Backdrops without walls, and rooms without water but the flooded stages' water rooms, +// have none. Both passes draw the same, the original ignores which one it is in. static void water_render(Room& room, WaterPass) { int stageId = g_game->GetStageID(); - bool isFloodStage = stageId == STAGE_ID_CAVES || stageId == STAGE_ID_CATACOMBS || stageId == STAGE_ID_FLOODED || + bool isFloodStage = stageId == STAGE_ID_CAVES || stageId == STAGE_ID_CATACOMBS || stageId == STAGE_ID_FLOODED_CAVES || stageId == STAGE_ID_DOWNPOUR || stageId == STAGE_ID_DROSS; bool isFloodRoom = isFloodStage && room.descriptor->pitsCount >= 0 && room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER; if (room.backdrop.configs[room.backdropType].walls == 0) return; if (room.waterAmount <= 0 && !isFloodRoom) return; - reconstruction_missing("Room::render_water 00817830: the caustics"); + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Game& game = *g_game; + float left = room.topLeftPos.x; + float top = room.topLeftPos.y; + float right = room.bottomRightPos.x; + float bottom = room.bottomRightPos.y; + float perimeter = (right - left) * 2 + (bottom - top) * 2; + float textureWidth = roomSurfaces.caustics ? (float)roomSurfaces.caustics->width : 1; + float scale = (float)std::floor(perimeter / textureWidth + 0.5f) * textureWidth / perimeter; + float edge = scale * CAUSTICS_EDGE; + float scroll = (float)game.frameCount * CAUSTICS_SCROLL_SPEED; + float turn = (float)game.frameCount * CAUSTICS_TURN_SPEED * CAUSTICS_DEGREES_TO_RADIANS; + float drift = scroll * CAUSTICS_DRIFT; + KColor light = room.fxLayers.fxParams.lightColor; + bool isCorpse = room.backdropType == BACKDROP_CORPSE3; + ColorMod color = COLOR_DEFAULT; + float alpha = isFloodRoom ? std::clamp((float)room.descriptor->pitsCount / CAUSTICS_FLOOD_PITS, 0.0f, 1.0f) : 0; + + color._tint[0] = isCorpse ? 1 : light._red; + color._tint[1] = isCorpse ? CORPSE_CAUSTICS_GREEN_BLUE : light._green; + color._tint[2] = isCorpse ? CORPSE_CAUSTICS_GREEN_BLUE : light._blue; + if (room.waterAmount > 0) alpha += (1 - alpha) * room.waterAmount; + color._tint[3] = alpha; + graphics.shader_default_set(); + if (!roomSurfaces.caustics) return; + + // The walls' corners, clockwise from the bottom of the left wall. The band runs along each wall from its inner + // edge out to its corners pushed outward by the edge, and the texture unrolls along the walls in that order, a + // whole number of times around the room: once as it is, once turning. + std::vector corners = caustics_corners(room.descriptor->data->shape, room.topLeftPos, room.bottomRightPos); + size_t sideCount = corners.size(); + Vector offset = vector_add(game.screenShakeOffset, room.renderScrollOffset); + float turnCos = std::cos(turn); + float turnSin = std::sin(turn); + auto screen = [&](Vector world) { return vector_add(render_position_get(world, RENDER_SNAPPED), offset); }; + auto turned = [&](float x, float y) { + return vector_make(x * turnCos - y * turnSin + scroll, y * turnCos + x * turnSin); + }; + std::vector sides; + std::vector sources(sideCount * 2); + float along = 0; + + for (size_t side = 0; side < sideCount; side++) + { + Vector start = corners[side]; + Vector end = corners[(side + 1) % sideCount]; + auto outer = [&](size_t corner) { + Vector before = corners[(corner + sideCount - 1) % sideCount]; + Vector at = corners[corner]; + Vector after = corners[(corner + 1) % sideCount]; + float pushX = sign_get(at.y - before.y) + sign_get(after.y - at.y); + float pushY = sign_get(before.x - at.x) + sign_get(at.x - after.x); + return vector_make(at.x + pushX * edge, at.y + pushY * edge); + }; + float length = (std::abs(end.x - start.x) + std::abs(end.y - start.y)) * scale; + + sides.emplace_back(DestinationQuad{screen(outer(side)), screen(outer((side + 1) % sideCount)), screen(start), + screen(end)}, + WHITE); + static_cast(sources[side]) = { + vector_make(scroll + along, drift), vector_make(scroll + along + length, drift), + vector_make(scroll + along, drift + edge), vector_make(scroll + along + length, drift + edge)}; + static_cast(sources[side + sideCount]) = { + turned(along, 0), turned(along + length, 0), turned(along, edge), turned(along + length, edge)}; + along += length; + } + + if (KAGE::Graphics::Shader* shader = graphics.shader_find(COLOR_OFFSET_SHADER)) graphics.currentShader = shader; + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *roomSurfaces.caustics); + for (size_t i = 0; i < sources.size(); i++) + { + sources[i]._coordinateSpace = KAGE::Graphics::COORDINATES_PIXEL; + roomSurfaces.caustics->Render(sources[i], sides[i % sideCount], + kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); + } + graphics.shader_default_set(); } // 00821950 Draws the floor through the water surface. Not reconstructed yet. @@ -719,7 +817,7 @@ void Room::Render() Game& game = *g_game; RenderConfig& render = g_manager->optionsConfig.render; bool isDataminer = temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DATAMINER); - bool isRepentanceStage = game.stageType == STAGE_TYPE_REPENTANCE || game.stageType == STAGE_TYPE_REPENTANCE_B; + bool isRepentanceStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; bool isMirrorWorld = game.currentDimensionIdx == DIMENSION_MIRROR && isRepentanceStage && (game.stage == 2 || (game.stage == 1 && game.GetCurses() & CURSE_OF_LABYRINTH)); bool isUteroSurface = backdropType == BACKDROP_UTERO && render.isWaterOverlayEnabled; @@ -803,7 +901,7 @@ static void grid_light_render(Room& room, GridEntity& grid, Vector offset) bool isFlooded = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER; bool isShaft = room.backdropType == BACKDROP_MINES_SHAFT || room.backdropType == BACKDROP_ASHPIT_SHAFT; bool isFuelFlood = g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && - g_game->GetStageID() == STAGE_ID_FLOODED && room.waterAmount > 0.5f; + g_game->GetStageID() == STAGE_ID_FLOODED_CAVES && room.waterAmount > 0.5f; if (room.backdropType == BACKDROP_MINES ? isFlooded : (isShaft && isFlooded) || isFuelFlood) reconstruction_missing("Room::render_grid_entity_light 0080c810: the lava pits"); return; @@ -857,7 +955,7 @@ static KColor room_light_color(Room& room, KColor shadow) is_pre_ascent_mom_room(room); if (isDarkRoom) darkness = std::min(darkness + DARK_ROOM_DARKNESS, 1.0f); - if (game.stage == STAGE_HOME && game.stageType == STAGE_TYPE_WOTL && !room.IsSacrificeDone()) darkness = 1; + if (game.stage == STAGE_HOME && game.stageType == STAGETYPE_WOTL && !room.IsSacrificeDone()) darkness = 1; darkness = std::max(darkness - game.lightningIntensity, 0.0f); return kcolor_rgba((shadow._red - light._red) * darkness + light._red, (shadow._green - light._green) * darkness + light._green, @@ -880,8 +978,8 @@ float Room::GetLightingAlpha() if (!is_curse_of_darkness()) { alpha = fxLayers.fxParams.shadowAlpha; - bool isAltBasement = game.stageType == STAGE_TYPE_REPENTANCE || game.stageType == STAGE_TYPE_REPENTANCE_B || - game.stageType == STAGE_TYPE_AFTERBIRTH; + bool isAltBasement = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B || + game.stageType == STAGETYPE_AFTERBIRTH; if (game.stage == STAGE_BASEMENT_I && !isAltBasement) alpha *= BASEMENT_SHADOW; } if (players.FirstCollectibleOwner(COLLECTIBLE_NIGHT_LIGHT, LAZARUS_SHARE_CHECK)) alpha *= NIGHT_LIGHT_SHADOW; diff --git a/src/room_special.cpp b/src/room_special.cpp index b094845..169c527 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -17,7 +17,6 @@ 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; @@ -788,7 +787,6 @@ void npc_shopkeeper_update(Entity_NPC& npc) 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; @@ -801,7 +799,6 @@ 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; diff --git a/src/room_state.cpp b/src/room_state.cpp index 601acaf..81d0ae4 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_grid.h" #include "room_special.h" #include #include @@ -19,7 +20,6 @@ // The last frames of a clear's delay that leaving the room still counts the clear in. constexpr int ROOM_CLEAR_DELAY_PENDING = 8; constexpr int GRID_PATH_RESET = 900; -constexpr int STAGE_MAUSOLEUM_II = 8; // The effects, slots and enemies whose saves keep more than the common fields. constexpr int EFFECT_BUTTERFLY = 69; @@ -37,7 +37,11 @@ constexpr int SHOP_ITEM_ID_MAX = 7; constexpr int TEAR_FLAG_WORDS = 4; constexpr int TEAR_FLAG_WORD_BITS = 32; constexpr uint8_t BOMB_NO_PLAYER = 0xff; -constexpr RNG DROP_RNG_SAVED = {0, 4, 3, 17}; + +// The free spot searches for a respawn saved without a place: anything from a random spot, an enemy near the center. +constexpr float UNPLACED_STEP = 40; +constexpr float UNPLACED_ENEMY_STEP = 80; +constexpr float UNPLACED_ENEMY_SCATTER = 20; // The pickups whose save keeps where they were heading rather than where they are. constexpr std::array PICKUPS_SAVING_TARGET = {PICKUP_COLLECTIBLE, PICKUP_BED, PICKUP_BIGCHEST, @@ -296,15 +300,22 @@ static void effect_state_restore(Room& room, Entity_Effect& effect, const Entity } } -// Restores an enemy's health and champion color. One saved without a place would go to a free spot near the center. +// Restores an enemy's health and champion color. One saved without a place goes up to 20 off a free spot near the +// center. static void enemy_state_restore(Entity& entity, const EntitySaveState& state) { if (!entity.IsEnemy() || entity.type == ENTITY_SHOPKEEPER || entity.type == GIDEON_TYPE) return; entity.health = state.floatStorage1; if (state.intStorage4 >= 0) static_cast(entity).MakeChampion(state.initSeed, state.intStorage4, false); - if (state.targetPosition.x == 0 && state.targetPosition.y == 0) - reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520: a saved enemy without a place"); + if (state.targetPosition.x != 0 || state.targetPosition.y != 0) return; + + Vector spot = room_free_pickup_position_find( + {.position = Room::GetCenterPos(), .step = UNPLACED_ENEMY_STEP, .isAvoidActiveEntities = true}); + Vector direction = random_direction(); + float distance = random_unit(); + entity.pos = vector_make(distance * direction.x * UNPLACED_ENEMY_SCATTER + spot.x, + distance * direction.y * UNPLACED_ENEMY_SCATTER + spot.y); } // 007ef420 Gives a respawned entity what its save kept (Entity_Pickup::RestoreState in the dump): its drop seed, grid @@ -312,7 +323,8 @@ static void enemy_state_restore(Entity& entity, const EntitySaveState& state) void entity_state_restore(Room& room, Entity& entity, const EntitySaveState& state) { if (entity.pos.x == 0 && entity.pos.y == 0) - reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520: a saved entity without a place"); + entity.pos = room_free_pickup_position_find( + {.position = room.GetRandomPosition(0), .step = UNPLACED_STEP, .isAvoidActiveEntities = true}); entity.dropRNG = DROP_RNG_SAVED; entity.dropRNG._seed = state.dropSeed; @@ -447,7 +459,7 @@ void Room::RestoreState() } saved.clear(); - bool isOpenedExit = descriptor->gridIndex == ROOM_SECRET_EXIT_IDX && g_game->stage == STAGE_MAUSOLEUM_II && + bool isOpenedExit = descriptor->gridIndex == ROOM_SECRET_EXIT_IDX && g_game->stage == STAGE_WOMB_II && descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; if (isOpenedExit) secret_exit_open(*this); g_pickupIgnoreModifiers--; diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 8f6f85d..98816a8 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -53,7 +53,6 @@ constexpr float SCREEN_CELL_SIZE = 26; constexpr int ROOM_CELLS_ACROSS = 13; constexpr int ROOM_CELLS_DOWN = 7; constexpr int DEATH_CERTIFICATE_DIMENSION = 2; -constexpr int STAGE_ID_HOME = 35; constexpr int DOGMA_ROOM_VARIANT = 1000; constexpr uint32_t BOSS_DOGMA = 99; diff --git a/src/room_update.cpp b/src/room_update.cpp index df31f07..dbf8c52 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -109,16 +109,6 @@ constexpr int SOUND_BOSS_ROAR = 190; constexpr int SOUND_THUNDER = 472; constexpr int SOUND_ALARM = 460; constexpr int PLAYER_THE_FORGOTTEN_B = 35; -constexpr int STAGE_HOME = 13; -constexpr int STAGE_ULTRA_GREED = 7; -constexpr int STAGE_ID_DOWNPOUR = 27; -constexpr int STAGE_ID_DROSS = 28; -constexpr int STAGE_ID_HOME = 35; -constexpr int STAGE_ID_CORPSE = 33; -constexpr int STAGE_TYPE_ORIGINAL = 0; -constexpr int STAGE_TYPE_AFTERBIRTH = 2; -constexpr int STAGE_TYPE_REPENTANCE = 4; -constexpr int STAGE_TYPE_REPENTANCE_B = 5; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int DIMENSION_MIRROR = 1; constexpr int BOSS_THE_BEAST_ROOM = 91; @@ -126,12 +116,6 @@ constexpr int ROOM_IDX_DUNGEON_BEAST = -16; constexpr int GREED_LAST_STAGE = 5; constexpr int GREED_LAST_STAGE_ID = 10; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_MAMA_MEGA = 1u << 14; -constexpr int BACKDROP_DANK_DEPTHS = 9; -constexpr int BACKDROP_ERROR_ROOM = 26; -constexpr int BACKDROP_MINES = 32; -constexpr int BACKDROP_CORPSE = 34; -constexpr int BACKDROP_CORPSE2 = 43; -constexpr int BACKDROP_CORPSE3 = 44; constexpr uint32_t RNG_SHIFT_COUPON_1 = 1; constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; @@ -574,22 +558,22 @@ static void weather_update(Room& room) if (is_greed()) { stage = stage < GREED_LAST_STAGE ? stage * 2 - 1 : stage == GREED_LAST_STAGE ? GREED_LAST_STAGE_ID : 0; - stageType = STAGE_TYPE_ORIGINAL; + stageType = STAGETYPE_ORIGINAL; } bool isCaves = stage == 3 || stage == 4; bool isWomb = stage == 7 || stage == 8; bool isDepths = stage == 5 || stage == 6; bool isBasement = stage == 1 || stage == 2; - bool isRareDrop = ((isCaves || isWomb) && stageType == STAGE_TYPE_ORIGINAL) || - (isDepths && stageType == STAGE_TYPE_AFTERBIRTH); + bool isRareDrop = ((isCaves || isWomb) && stageType == STAGETYPE_ORIGINAL) || + (isDepths && stageType == STAGETYPE_AFTERBIRTH); bool isDrop = (isRareDrop && Random() % DROP_CHANCE_RARE == 0) || - (isCaves && stageType == STAGE_TYPE_AFTERBIRTH && Random() % DROP_CHANCE_WOMB == 0) || - (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); + (isCaves && stageType == STAGETYPE_AFTERBIRTH && Random() % DROP_CHANCE_WOMB == 0) || + (isWomb && stageType == STAGETYPE_AFTERBIRTH && (Random() & 7) == 0) || + (isBasement && stageType == STAGETYPE_REPENTANCE && (Random() & 3) == 0) || + (isBasement && stageType == STAGETYPE_REPENTANCE_B && (Random() & 3) == 0); if (isDrop) weather_drop_spawn(room, EFFECT_WATER_DROPLET); - else if (isBasement && stageType == STAGE_TYPE_AFTERBIRTH && Random() % DROP_CHANCE_DROSS == 0) + else if (isBasement && stageType == STAGETYPE_AFTERBIRTH && Random() % DROP_CHANCE_DROSS == 0) weather_drop_spawn(room, EFFECT_FALLING_EMBER); } diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 06a45c1..4721c7a 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -25,31 +25,95 @@ enum SoundLoop enum SoundId : int { SOUND_BOOK_PAGE_TURN_12 = 8, + SOUND_BOSS_LITE_ROAR = 14, + SOUND_BOSS_SPIT_BLOB_BARF = 16, + SOUND_CHEST_OPEN = 22, SOUND_DEATH_BURST_LARGE = 28, + SOUND_DEATH_REVERSE = 29, SOUND_FART = 37, SOUND_FETUS_LAND = 40, SOUND_FIREDEATH_HISS = 43, + SOUND_COIN_INSERT = 45, SOUND_FORESTBOSS_STOMPS = 48, + SOUND_HELLBOSS_GROUNDPOUND = 52, SOUND_HOLY = 54, SOUND_ISAAC_HURT_GRUNT = 55, + SOUND_CHILD_ANGRY_ROAR = 57, SOUND_DIP_HURT = 60, + SOUND_MEAT_JUMPS = 72, + SOUND_MONSTER_GRUNT_1 = 106, + SOUND_MONSTER_GRUNT_2 = 108, + SOUND_MONSTER_GRUNT_4 = 112, + SOUND_MONSTER_ROAR_0 = 115, + SOUND_MONSTER_ROAR_1 = 116, SOUND_POWERUP1 = 128, SOUND_POWERUP_SPEWER = 132, SOUND_ROCK_CRUMBLE = 137, + SOUND_SHAKEY_KID_ROAR = 146, SOUND_TEAR_IMPACTS = 150, + SOUND_TEARS_FIRE = 153, SOUND_UNLOCK = 156, SOUND_VAMP_GULP = 157, + SOUND_SPIDER_COUGH = 159, + SOUND_ANGRY_GURGLE = 167, SOUND_BATTERYCHARGE = 170, SOUND_BEEP = 171, SOUND_BLOODSHOOT = 178, + SOUND_BOIL_HATCH = 181, + SOUND_BOSS2_BUBBLES = 185, SOUND_ERROR_BUZZ = 187, + SOUND_HEARTIN = 212, + SOUND_HEARTOUT = 213, + SOUND_HELL_PORTAL2 = 215, + SOUND_LEECH = 221, + SOUND_MAGGOTCHARGE = 224, + SOUND_METAL_BLOCKBREAK = 229, SOUND_PLOP = 237, + SOUND_SCAMPER = 249, SOUND_SHELLGAME = 252, SOUND_SPLATTER = 258, + SOUND_SUMMONSOUND = 265, SOUND_THUMBS_DOWN = 267, SOUND_THUMBSUP = 268, + SOUND_HAPPY_RAINBOW = 270, + SOUND_FART_GURG = 301, + SOUND_FAT_WIGGLE = 303, + SOUND_WHISTLE = 315, + SOUND_WORM_SPIT = 318, + SOUND_LITTLE_SPIT = 319, + SOUND_DANGLE_WHISTLE = 413, + SOUND_LITTLE_HORN_COUGH = 414, + SOUND_LITTLE_HORN_GRUNT_1 = 415, + SOUND_LITTLE_HORN_GRUNT_2 = 416, SOUND_GOLD_HEART_DROP = 466, - SOUND_SHINYROCK_SHIMMER = 1014 + SOUND_FLAME_BURST = 483, + SOUND_FREEZE = 496, + SOUND_FREEZE_SHATTER = 498, + SOUND_MOM_AND_DAD_1 = 598, + SOUND_MOM_AND_DAD_2 = 599, + SOUND_MOM_AND_DAD_3 = 600, + SOUND_MOM_AND_DAD_4 = 601, + SOUND_VAMP_DOUBLE = 614, + SOUND_POOP_THROW = 865, + SOUND_GURGLING_ATTACK = 943, + SOUND_LITTLE_HORN_DEATH = 944, + SOUND_LITTLE_HORN_BOMB_DROP = 945, + SOUND_LITTLE_HORN_DIVE = 946, + SOUND_LITTLE_HORN_HOLE_OPEN = 947, + SOUND_LITTLE_HORN_HOLE_EXIT = 948, + SOUND_POOP_DROP = 990, + SOUND_LARRY_JR_DEATH_1 = 999, + SOUND_LARRY_JR_DEATH_2 = 1000, + SOUND_LARRY_JR_ROAR = 1001, + SOUND_HOLLOW_DEATH_1 = 1003, + SOUND_HOLLOW_DEATH_2 = 1004, + SOUND_HOLLOW_ROAR = 1005, + SOUND_MONSTERS_NEXT_DOOR = 1008, + SOUND_IMMACULATE_CONCEPTION = 1010, + SOUND_SHINYROCK_SHIMMER = 1014, + SOUND_BRAIN_MOVE = 1080, + SOUND_POISON_MIND_HURT = 1081, + SOUND_BUTTLICKER_GROWL = 1085 }; // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. diff --git a/src/stage_transition.cpp b/src/stage_transition.cpp index e2ff3fc..32a3263 100644 --- a/src/stage_transition.cpp +++ b/src/stage_transition.cpp @@ -24,10 +24,6 @@ constexpr int EXIT_FRAME_UNSET = 1000; constexpr int MUSIC_FRAME = 2; constexpr int FIRST_ASCENT_STAGE = 1; constexpr int LAST_ASCENT_STAGE = 6; -constexpr int STAGE_SHEOL = 11; -constexpr int STAGE_VOID = 12; -constexpr int STAGE_HOME = 13; -constexpr int STAGE_WOMB_I = 7; constexpr int GRID_COLUMN_OFFSET = 40; constexpr int GRID_ROW_OFFSET = 120; constexpr float GRID_CELL = 40; @@ -311,7 +307,7 @@ static void out_update(StageTransition& transition) { if (!transition.isSameStage) { - if (transition.type == STAGE_TRANSITION_SHEOL) game.SetStage(STAGE_SHEOL, STAGETYPE_ORIGINAL); + if (transition.type == STAGE_TRANSITION_SHEOL) game.SetStage(STAGE_DARK_ROOM, STAGETYPE_ORIGINAL); else if (transition.type == STAGE_TRANSITION_VOID) game.SetStage(STAGE_VOID, STAGETYPE_ORIGINAL); else if (transition.type == STAGE_TRANSITION_HOME) game.SetStage(STAGE_HOME, STAGETYPE_ORIGINAL); else game.SetNextStage(); @@ -381,7 +377,7 @@ static void floor_enter(StageTransition& transition) game.room->Update(); Manager::save_game_state(); game.playerManager.trigger_new_room_effects(); - if (game.challenge == CHALLENGE_BACKASSWARDS && (int)game.stage != STAGE_SHEOL) + if (game.challenge == CHALLENGE_BACKASSWARDS && (int)game.stage != STAGE_DARK_ROOM) { main_players_visit([](Entity_Player& player) { player.isPlayingExtraAnimation = false;