From 8dbeb1bc4a6b90df67ed8031eddd458dd2786b98 Mon Sep 17 00:00:00 2001 From: shweet Date: Sun, 22 Nov 2026 00:33:35 -0500 Subject: [PATCH] Curation round 20: player update, costumes and render, Missing No., the last actives and cards, familiars, Pin, the Frail, Wormwood and the Heretic, Dross to Gehenna, effects and the devil room purchase, champion colours, the quit path, save fields, shared vector helpers --- generated-src/ambush.cpp | 642 --------- generated-src/classes.h | 96 +- generated-src/input_manager.cpp | 38 - generated-src/npc_helper.cpp | 345 ----- generated-src/stubs.cpp | 47 - src/active_items.h | 4 + src/ambush.cpp | 243 ++++ src/ambush.h | 40 + src/anm2.cpp | 32 +- src/anm2.h | 93 ++ src/bomb_explosion.cpp | 2 +- src/boss_ai.h | 18 + src/boss_big_horn.cpp | 10 +- src/boss_brownie.cpp | 2 +- src/boss_chub.cpp | 2 +- src/boss_death.cpp | 18 +- src/boss_gideon.cpp | 2 +- src/boss_heretic.cpp | 988 +++++++++++++ src/boss_hush.cpp | 2 +- src/boss_isaac.cpp | 2 +- src/boss_little_horn.cpp | 3 +- src/boss_mask_of_infamy.cpp | 4 +- src/boss_monstro.cpp | 175 ++- src/boss_pin.cpp | 925 ++++++++++++ src/boss_rag_man.cpp | 6 +- src/boss_wormwood.cpp | 912 ++++++++++++ src/camera.cpp | 5 - src/entity.cpp | 14 +- src/entity.h | 11 + src/entity_bomb.h | 1 + src/entity_collision.cpp | 14 - src/entity_combat.cpp | 13 +- src/entity_effect.cpp | 73 +- src/entity_effect.h | 49 +- src/entity_effect_alt.cpp | 2 +- src/entity_effect_ambient.cpp | 321 +++-- src/entity_effect_blast.cpp | 732 ++++++++++ src/entity_effect_boss.cpp | 86 +- src/entity_effect_combat.cpp | 18 - src/entity_effect_floor.cpp | 81 ++ src/entity_effect_hazard.cpp | 80 +- src/entity_effect_items.cpp | 194 ++- src/entity_effect_mother.cpp | 300 ++++ src/entity_effect_portal.cpp | 279 ++++ src/entity_effect_shots.cpp | 535 +++++++ src/entity_effect_souls.cpp | 945 ++++++++++++ src/entity_factory.cpp | 1 - src/entity_familiar.cpp | 148 +- src/entity_familiar.h | 59 +- src/entity_knife.cpp | 8 - src/entity_knife_hits.cpp | 13 +- src/entity_npc.cpp | 228 ++- src/entity_npc.h | 8 +- src/entity_npc_boss.cpp | 6 +- src/entity_npc_champion.cpp | 2 +- src/entity_npc_render.cpp | 62 +- src/entity_npc_rewards.cpp | 276 +++- src/entity_pickup.cpp | 157 +- src/entity_pickup_shop.cpp | 20 +- src/entity_player.cpp | 108 +- src/entity_player.h | 71 +- src/entity_player_actives_afterbirth.cpp | 628 ++++++++ src/entity_player_actives_grid.cpp | 479 +++++++ src/entity_player_actives_rebirth.cpp | 17 +- src/entity_player_actives_repentance.cpp | 189 ++- src/entity_player_cards.cpp | 114 ++ src/entity_player_costumes.cpp | 202 ++- src/entity_player_damage.cpp | 22 +- src/entity_player_death.cpp | 13 +- src/entity_player_evaluate.cpp | 62 +- src/entity_player_frame.cpp | 324 +++-- src/entity_player_health.cpp | 32 + src/entity_player_hits.cpp | 1 - src/entity_player_items.cpp | 94 +- src/entity_player_missing.cpp | 16 - src/entity_player_room.cpp | 7 +- src/entity_player_tears.cpp | 1 - src/entity_player_update.cpp | 883 ++++++++++++ src/entity_player_weapons.cpp | 69 +- src/entity_projectile.cpp | 44 +- src/entity_projectile.h | 1 + src/entity_status.cpp | 22 + src/entity_tear.cpp | 18 +- src/entity_tear_flags.cpp | 17 +- src/familiar_ai.cpp | 47 +- src/familiar_body.cpp | 232 +++ src/familiar_collision.cpp | 47 +- src/familiar_dip.cpp | 315 +++- src/familiar_follow.cpp | 94 +- src/familiar_gello.cpp | 33 +- src/familiar_missing.cpp | 78 - src/familiar_shoot.cpp | 17 +- src/familiar_sprinkler.cpp | 182 +++ src/familiar_update.cpp | 1202 ++++++++++++++++ src/familiar_variants.cpp | 1670 ++++++++++++++++++++++ src/familiar_variants.h | 51 + src/fx_layers.cpp | 2 - src/game.cpp | 30 +- src/game.h | 3 + src/game_restore.cpp | 39 +- src/game_save.cpp | 17 +- src/game_state.cpp | 4 +- src/game_state_player.h | 9 +- src/grid_entity_door.cpp | 3 +- src/grid_entity_poop.cpp | 2 +- src/grid_entity_stairs.cpp | 90 +- src/grid_entity_stairs.h | 9 + src/grid_entity_trap_door.cpp | 23 +- src/grid_entity_trap_door.h | 1 + src/hud.cpp | 4 +- src/item_overlay.h | 1 + src/level.cpp | 42 +- src/lua_api_game.cpp | 2 - src/lua_api_room.cpp | 6 +- src/lua_api_vector.cpp | 8 - src/lua_callbacks.cpp | 13 + src/lua_engine.h | 1 + src/main.cpp | 2 +- src/manager.cpp | 28 + src/manager.h | 1 + src/menu_character.cpp | 1 - src/menu_daily_challenge.cpp | 25 +- src/menu_manager.cpp | 11 +- src/menu_manager.h | 1 - src/music_manager.h | 3 + src/nightmare_scene.cpp | 2 - src/npc_ai.cpp | 8 +- src/npc_ai.h | 71 - src/npc_boil.cpp | 4 +- src/npc_boom_fly.cpp | 2 +- src/npc_brain.cpp | 6 +- src/npc_caves.h | 7 - src/npc_deep_gaper.cpp | 13 +- src/npc_faceless.cpp | 350 +++++ src/npc_fly.cpp | 20 +- src/npc_gaper.cpp | 13 +- src/npc_gusher.cpp | 1 - src/npc_guts.cpp | 2 +- src/npc_hive.cpp | 20 +- src/npc_hush.cpp | 2 +- src/npc_maggot.cpp | 19 +- src/npc_one_tooth.cpp | 4 +- src/npc_poky.cpp | 2 +- src/npc_vis.cpp | 2 +- src/path_finder.cpp | 71 +- src/persistent_game_data.h | 7 +- src/platform.cpp | 4 +- src/player_manager.cpp | 6 +- src/pocket_items.h | 1 + src/room.cpp | 13 +- src/room.h | 4 + src/room_clear.cpp | 1 - src/room_config.h | 2 + src/room_grid.cpp | 68 + src/room_grid.h | 3 + src/room_lighting.cpp | 12 +- src/room_render.cpp | 23 +- src/room_render.h | 1 - src/room_special.h | 1 - src/room_transition.cpp | 2 - src/room_update.cpp | 50 +- src/seeds.h | 9 + src/sfx_manager.h | 40 +- src/tainted_characters.cpp | 4 +- src/weapon.cpp | 16 +- src/weapon_monstros_lung.cpp | 4 +- src/weapon_rockets.cpp | 15 +- src/weapon_rockets.h | 1 + 168 files changed, 15682 insertions(+), 2399 deletions(-) delete mode 100644 generated-src/ambush.cpp create mode 100644 src/ambush.cpp create mode 100644 src/ambush.h create mode 100644 src/boss_heretic.cpp create mode 100644 src/boss_pin.cpp create mode 100644 src/boss_wormwood.cpp create mode 100644 src/entity_effect_blast.cpp create mode 100644 src/entity_effect_mother.cpp create mode 100644 src/entity_effect_portal.cpp create mode 100644 src/entity_effect_shots.cpp create mode 100644 src/entity_effect_souls.cpp create mode 100644 src/entity_player_actives_afterbirth.cpp create mode 100644 src/entity_player_actives_grid.cpp create mode 100644 src/entity_player_update.cpp create mode 100644 src/familiar_body.cpp create mode 100644 src/familiar_sprinkler.cpp create mode 100644 src/familiar_update.cpp create mode 100644 src/familiar_variants.cpp create mode 100644 src/familiar_variants.h create mode 100644 src/npc_faceless.cpp diff --git a/generated-src/ambush.cpp b/generated-src/ambush.cpp deleted file mode 100644 index c7b2b14..0000000 --- a/generated-src/ambush.cpp +++ /dev/null @@ -1,642 +0,0 @@ -#include "classes.h" - -// 008332e0 -void Ambush::shuffle_waves() -{ - int iVar1; - code *pcVar2; - uint32_t seed; - uint32_t swapIndex; - uint32_t remainingCount; - uint32_t local_1c; - int waveOffset; - int waveIndex; - uint32_t swapTmp; - uint32_t *temp_161c0439608; - - if (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) != this) { - msvc::vector>::assign - (*GHIDRA_CAST(this),*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))),local_1c); - } - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 4)); - seed = 0; - if (iVar1 != 0) { - seed = *GHIDRA_CAST((iVar1 + 0x5c)); - } - iVar1 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - remainingCount = (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) - iVar1) / 0xc; - waveIndex = remainingCount - 1; - if (0 < waveIndex) { - waveOffset = waveIndex * 0xc; - do { - if (seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar2 = (code *)swi(3); - (*pcVar2)(); - return; - } - seed = seed >> 1 ^ seed; - seed = seed << 5 ^ seed; - seed = seed >> 0x13 ^ seed; - swapIndex = 0; - if (remainingCount != 0) { - swapIndex = seed % remainingCount; - } - temp_161c0439608 = GHIDRA_CAST((iVar1 + swapIndex * 0xc)); - if (GHIDRA_CAST((iVar1 + waveOffset)) != temp_161c0439608) { - swapTmp = *GHIDRA_CAST((iVar1 + waveOffset)); - *GHIDRA_CAST((waveOffset + iVar1)) = *temp_161c0439608; - *temp_161c0439608 = swapTmp; - swapTmp = *GHIDRA_CAST((waveOffset + 4 + iVar1)); - *GHIDRA_CAST((waveOffset + 4 + iVar1)) = temp_161c0439608[1]; - temp_161c0439608[1] = swapTmp; - swapTmp = *GHIDRA_CAST((waveOffset + 8 + iVar1)); - *GHIDRA_CAST((waveOffset + 8 + iVar1)) = temp_161c0439608[2]; - temp_161c0439608[2] = swapTmp; - } - waveIndex = waveIndex + -1; - waveOffset = waveOffset + -0xc; - remainingCount = remainingCount - 1; - } while (0 < waveIndex); - } - return; -} - -// 00833420 -void Ambush::StartChallenge() -{ - void *pvVar1; - Entity_Player *doorStopOwner; - int targetRoomType; - uint32_t doorSlot; - uint32_t uVar3; - Game *game; - int doorOffset; - int currentRoomType; - GridEntity_Door *door; - int targetRoomType; - - if (((*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 4)) + 0x44)) >> 3 & 1) == 0) && (this->_isActive == 0) - ) { - this->_isActive = 1; - *GHIDRA_CAST((this + 1)) = 0x1e; - this->_currentWave = 0; - shuffle_waves(this); - doorStopOwner = PlayerManager::FirstTrinketOwner(&g_game->_playerManager,0x7c); - if (doorStopOwner == GHIDRA_CAST(0x0)) { - targetRoomType = 0; - } - else { - targetRoomType = Entity_Player::GetTrinketMultiplier(doorStopOwner,0x7c); - } - doorOffset = 0x724; - doorSlot = 0; - game = g_game; - do { - doorSlot = doorSlot + 1; - if (doorSlot < 9) { - pvVar1 = game->_room; - door = *GHIDRA_CAST((doorOffset + GHIDRA_INT(pvVar1))); - if (((door != GHIDRA_CAST(0x0)) && - ((game->_enterDoor != door->_slot || - (((targetRoomType < 2 || (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 8)) != 0x11)) && - ((targetRoomType < 3 || (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 8)) != 0xb)))))))) && - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((door)) + 0xc)))) != 1)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((door)) + 0xc)))) = 1; - GridEntity_Door::UpdateAnimation(door); - currentRoomType = door->_currentRoomType; - if (((((currentRoomType == 7) || - (targetRoomType = door->_targetRoomType, targetRoomType == 7)) || - (currentRoomType == 8)) || ((targetRoomType == 8 || (currentRoomType == 0x1d)))) || - (game = g_game, targetRoomType == 0x1d)) { - (GHIDRA_CAST(((door->_openAnimation)._buf)))->msvc::string::assign(s_Open,4); - game = g_game; - } - } - } - doorOffset = doorOffset + 4; - } while (doorOffset < 0x744); - (GHIDRA_CAST((GHIDRA_CAST(&g_manager->_musicManager))))->Music::Play((*GHIDRA_CAST((GHIDRA_CAST(game->_room) + 8)) == 0x11) + 0x26, - (g_manager->_optionsConfig)._musicVolume); - game = g_game; - targetRoomType = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 4)); - uVar3 = 0; - if (targetRoomType != 0) { - uVar3 = *GHIDRA_CAST((targetRoomType + 0x5c)); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = uVar3; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) = 5; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0xc)))) = 9; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x10)))) = 7; - targetRoomType = *GHIDRA_CAST((GHIDRA_CAST(game->_room) + 4)); - uVar3 = 0; - if (targetRoomType != 0) { - uVar3 = *GHIDRA_CAST((targetRoomType + 0x5c)); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))) = uVar3; - this[1]._maxWaves = 7; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1c)))) = 0x11; - *GHIDRA_CAST(&this[1]._isActive) = 0x15; - } - return; -} - -// 00833600 -void Ambush::SpawnWave() -{ - code *pcVar1; - int iVar2; - uint32_t uVar3; - uint64_t *pickedEntry; - uint32_t uVar4; - uint32_t *playerSlot; - int gridX; - Entity *entryType; - void *pvVar5; - uint32_t *puVar6; - short *spawnEntry; - PlayerManager *playerManager; - uint32_t local_90; - Vector local_8c; - int local_84; - uint32_t *entries; - uint32_t *entriesEnd; - uint32_t *local_78; - Vector local_74; - uint32_t *entriesCapacity; - Entity *local_68; - uint32_t local_64; - uint32_t *local_60; - Room *room; - uint32_t *local_58; - Game *local_54; - uint32_t newEntry; - uint64_t uStack_4c; - uint32_t uStack_44; - uint64_t entry; - uint32_t local_38; - int difficultyTable [5]; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - int local_14; - Manager *manager; - uint16_t variant; - - local_14 = 0xffffffff; - puStack_18 = &LAB_00b021dd; - local_1c = ExceptionList; - puStack_20 = GHIDRA_CAST((difficultyTable + 0xc)); - difficultyTable[4] = __security_cookie ^ GHIDRA_UINT((difficultyTable + 9)); - ExceptionList = &local_1c; - difficultyTable[0] = 1; - difficultyTable[1] = 5; - difficultyTable[2] = 10; - difficultyTable[3] = 0xf; - local_54 = g_game; - room = g_game->_room; - iVar2 = this->_currentWave - GHIDRA_UINT((g_game->_difficulty != 1)); - if (3 < iVar2) { - iVar2 = 3; - } - local_84 = difficultyTable[iVar2]; - if (g_game->_challenge == 0x2c) { - uVar3 = Level::GetRoomStageType(GHIDRA_CAST(g_game),g_game->_currentRoomIdx); - local_58 = GHIDRA_CAST(RoomConfig)::GetStageID(local_54->_stage,uVar3,-1); - local_54 = g_game; - } - else if (g_game->_currentDimensionIdx == 2) { - local_58 = GHIDRA_CAST(&DAT_00000023); - } - else { - local_58 = GHIDRA_CAST(RoomConfig)::GetStageID(g_game->_stage,g_game->_stageType,-1); - } - local_8c.y = (float)(0xb - GHIDRA_UINT((*GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((room)) + 0x4)))) + 0x10)) + 0x10)) != 1)) - ); - puVar6 = GHIDRA_CAST(0x0); - local_60 = GHIDRA_CAST(0x0); - entries = GHIDRA_CAST(0x0); - entriesEnd = GHIDRA_CAST(0x0); - entriesCapacity = GHIDRA_CAST(0x0); - local_78 = GHIDRA_CAST(0x0); - local_14 = 0; - local_64 = 0; - local_68 = GHIDRA_CAST(0x3e8); - do { - if (local_60 != puVar6) { -LAB_00833972: - local_58 = local_60 + 1; - do { - puVar6 = local_58; - local_68 = GHIDRA_CAST(local_58[-1]); - local_8c.x = (float)(GHIDRA_INT(local_68) % room->_gridWidth) * 40.0 + 40.0; - local_8c.y = (float)(GHIDRA_INT(local_68) / room->_gridWidth) * 40.0 + 120.0; - Room::FindFreeTilePosition(room,&local_74,&local_8c,0.0); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (*puVar6 - 10 < 0x3de) { - if (uVar3 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar3 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - puVar6 = local_58; - uVar3 = uVar3 >> ((uint8_t)this[1]._maxWaves & 0x1f) ^ uVar3; - uVar3 = uVar3 << ((uint8_t)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1c)))) & 0x1f) ^ uVar3; - uVar3 = uVar3 >> ((uint8_t)*GHIDRA_CAST(&this[1]._isActive) & 0x1f) ^ uVar3; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))) = uVar3; - variant = (uint16_t)local_58[1]; - iVar2 = spawn_enemy_spawner_effect - (*local_58,variant,&local_74,variant,0, - *GHIDRA_CAST((GHIDRA_CAST(local_58) + 6)),uVar3,variant,local_68); - local_54 = g_game; - if ((((g_game != GHIDRA_CAST(0x0)) && (1 < *GHIDRA_CAST(&g_game->_deathmatchManager))) && - (*puVar6 == 1)) || (*puVar6 - 10 < 0x3de)) { - *GHIDRA_CAST((iVar2 + 0x16c)) = *GHIDRA_CAST((iVar2 + 0x16c)) | 0x80; - *GHIDRA_CAST((iVar2 + 0x168)) = *GHIDRA_CAST((iVar2 + 0x168)); - } - } - else { - if (uVar3 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - local_54 = g_game; - if (uVar3 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - puVar6 = local_58; - uVar3 = uVar3 >> ((uint8_t)this[1]._maxWaves & 0x1f) ^ uVar3; - uVar3 = uVar3 << ((uint8_t)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1c)))) & 0x1f) ^ uVar3; - uVar3 = uVar3 >> ((uint8_t)*GHIDRA_CAST(&this[1]._isActive) & 0x1f) ^ uVar3; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))) = uVar3; - local_68 = Game::Spawn(local_54,*local_58,GHIDRA_UINT((uint16_t)local_58[1]),&local_74, - &g_vectorZero,GHIDRA_CAST(0x0),GHIDRA_UINT(*GHIDRA_CAST((GHIDRA_CAST(local_58) + 6))), - uVar3); - if (local_68->_type == 1000) { - (**(code **)(*GHIDRA_CAST(local_68) + 0xc))(); - } - local_68->_spawnGridIndex = puVar6[-1]; - local_54 = g_game; - } - local_58 = puVar6 + 4; - } while (puVar6 + 3 != entriesEnd); -LAB_00833b32: - manager = g_manager; - local_64 = 0x367; - seed_fart_sound_override(GHIDRA_CAST(&local_64)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(local_64,1.0,2,0,1.0,0.0); - uVar3 = 0; - playerManager = &g_game->_playerManager; - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - GHIDRA_INT((playerManager->_playerList)._begin) - >> 2 != 0) { - do { - pvVar5 = (playerManager->_playerList)._end; - if (GHIDRA_INT(pvVar5) - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("PlayerManager::GetPlayer() : There are no players! \n")); - pvVar5 = (playerManager->_playerList)._end; - } - playerSlot = (playerManager->_playerList)._begin; - if (uVar3 < GHIDRA_UINT((GHIDRA_INT(pvVar5) - GHIDRA_INT(playerSlot) >> 2))) { - playerSlot = playerSlot + uVar3; - } - Entity_Player::spawn_locusts(GHIDRA_CAST(*playerSlot)); - uVar3 = uVar3 + 1; - playerManager = &g_game->_playerManager; - } while (uVar3 < GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((playerManager->_playerList)._begin) >> 2))); - } - if (local_60 != GHIDRA_CAST(0x0)) { - uVar3 = GHIDRA_INT(entriesCapacity) - GHIDRA_INT(local_60) & 0xfffffff0; - puVar6 = local_60; - if (0xfff < uVar3) { - puVar6 = GHIDRA_CAST(local_60[-1]); - uVar3 = uVar3 + 0x23; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(local_60) + (-4 - GHIDRA_INT(puVar6))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(puVar6,uVar3); - } - ExceptionList = local_1c; - return; - } - local_54 = GHIDRA_CAST(&local_54->_roomConfig); - local_90 = 0; - local_74.y = (float)Room::GetRoomShape(room); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar3 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar3 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar3 = uVar3 >> ((uint8_t)this[1]._maxWaves & 0x1f) ^ uVar3; - uVar3 = uVar3 << ((uint8_t)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1c)))) & 0x1f) ^ uVar3; - uVar3 = uVar3 >> ((uint8_t)*GHIDRA_CAST(&this[1]._isActive) & 0x1f) ^ uVar3; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))) = uVar3; - local_54 = GHIDRA_CAST(RoomConfig)::GetRandomRoom - (GHIDRA_CAST(local_54),uVar3,1,GHIDRA_INT(local_58),0xb,GHIDRA_INT(local_74.y),0 - ,-1,local_84,local_84,&local_90,GHIDRA_UINT(local_8c.y),-1); - if (local_54 == GHIDRA_CAST(0x0)) { - if (local_58 == GHIDRA_CAST(0x0)) { - KAGE_LogMessage(0x10,GHIDRA_CAST("No enemy wave found for ambush (difficulty: %d)\n")); - goto LAB_008337d3; - } - local_58 = GHIDRA_CAST(0x0); - } - else { -LAB_008337d3: - local_74.y = 0.0; - if (*GHIDRA_CAST((GHIDRA_CAST(local_54) + 0x44)) != 0) { - local_60 = GHIDRA_CAST(0x0); - do { - spawnEntry = GHIDRA_CAST((GHIDRA_INT(*(void **)(GHIDRA_CAST(local_54) + 0x40)) + GHIDRA_INT(local_60))); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar3 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar3 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar3 = uVar3 >> ((uint8_t)this[1]._maxWaves & 0x1f) ^ uVar3; - uVar3 = uVar3 << ((uint8_t)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1c)))) & 0x1f) ^ uVar3; - uVar3 = uVar3 >> ((uint8_t)*GHIDRA_CAST(&this[1]._isActive) & 0x1f) ^ uVar3; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))) = uVar3; - pickedEntry = (GHIDRA_CAST((spawnEntry)))->Spawn::PickEntry((float)((double)GHIDRA_INT(uVar3) + - __uint_to_double_fixup[-(GHIDRA_INT(uVar3) >> 0x1f)]) * - 2.3283062e-10); - entry = *pickedEntry; - local_38 = *GHIDRA_CAST((pickedEntry + 1)); - iVar2 = spawnEntry[1] + 1; - gridX = *spawnEntry + 1; - if ((((gridX < 0) || (room->_gridWidth <= gridX)) || (iVar2 < 0)) || - (room->_gridHeight <= iVar2)) { - uVar3 = 0xffffffff; - } - else { - uVar3 = room->_gridWidth * iVar2 + gridX; - } - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar4 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))); - if (uVar4 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar4 = uVar4 >> ((uint8_t)this[1]._maxWaves & 0x1f) ^ uVar4; - uVar4 = uVar4 << ((uint8_t)*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1c)))) & 0x1f) ^ uVar4; - uVar4 = uVar4 >> ((uint8_t)*GHIDRA_CAST(&this[1]._isActive) & 0x1f) ^ uVar4; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x14)))) = uVar4; - Room::TransformEntry(room,&entry,uVar3,uVar4); - if (&(*GHIDRA_CAST((GHIDRA_CAST(&((GHIDRA_CAST(entry))[-1])) + 0x40f))) < GHIDRA_CAST(0x3e7)) { - entryType = GHIDRA_CAST(entry); - if (GHIDRA_CAST(entry) == GHIDRA_CAST(0x3e7)) { - entryType = local_68; - } - entry = CONCAT44((*GHIDRA_CAST((GHIDRA_CAST(&(entry)) + 0x4))),entryType); - uStack_4c = entry; - uStack_44 = local_38; - newEntry = uVar3; - if (entriesEnd == entriesCapacity) { - msvc::vector::_Emplace_reallocate(entriesEnd,&newEntry); - entriesCapacity = local_78; - } - else { - *entriesEnd = uVar3; - entriesEnd[1] = GHIDRA_UINT(entryType); - entriesEnd[2] = (*GHIDRA_CAST((GHIDRA_CAST(&(entry)) + 0x4))); - entriesEnd[3] = local_38; - entriesEnd = entriesEnd + 4; - } - } - local_74.y = (float)(GHIDRA_INT(local_74.y) + 1); - local_60 = GHIDRA_CAST((GHIDRA_INT(local_60) + 0x10)); - } while (GHIDRA_UINT(local_74.y) < GHIDRA_UINT((uint16_t)*GHIDRA_CAST((GHIDRA_CAST(local_54) + 0x44)))); - local_60 = entries; - puVar6 = entriesEnd; - } - } - local_64 = local_64 + 1; - if (9 < local_64) { - local_54 = g_game; - if (local_60 == puVar6) goto LAB_00833b32; - goto LAB_00833972; - } - local_54 = g_game; - } while( true ); -} - -// 00833c40 -void Ambush::SpawnBossrushWave() -{ - int iVar1; - Manager *pMVar2; - uint32_t uVar3; - uint32_t *playerSlot; - int iVar4; - void *pvVar5; - int iVar6; - PlayerManager *playerManager; - Vector leftCopyPos; - Vector rightCopyPos; - Vector bodySpawnPos; - Vector headSpawnPos; - uint32_t local_38; - int local_20 [4]; - void *local_10; - uint8_t *puStack_c; - int local_8; - - puStack_c = &LAB_00b0221d; - local_10 = ExceptionList; - uVar3 = __security_cookie ^ GHIDRA_UINT((local_20 + 7)); - ExceptionList = &local_10; - iVar6 = 0; - local_8 = 0; - if (0 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x1c))))) { - do { - iVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - iVar1 = iVar4 >> 0x1f; - if (iVar4 / 0xc + iVar1 == iVar1) break; - msvc::vector<12byte>::insert_range - (0,*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) + -0xc)), - *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) + -8)),local_38); - msvc::vector<12byte>::_Tidy(uVar3); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) + -0xc; - iVar6 = iVar6 + 1; - } while (iVar6 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x1c))))); - } - local_20[0] = 0; - KAGE_LogMessage(0x10,GHIDRA_CAST("Wave has no entries!")); - pMVar2 = g_manager; - local_20[0] = 0x367; - seed_fart_sound_override(local_20); - (GHIDRA_CAST((&pMVar2->_sfxManager)))->SoundEffects::Play(local_20[0],1.0,2,0,1.0,0.0); - uVar3 = 0; - playerManager = &g_game->_playerManager; - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 - != 0) { - do { - pvVar5 = (playerManager->_playerList)._end; - if (GHIDRA_INT(pvVar5) - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("PlayerManager::GetPlayer() : There are no players! \n")); - pvVar5 = (playerManager->_playerList)._end; - } - playerSlot = (playerManager->_playerList)._begin; - if (uVar3 < GHIDRA_UINT((GHIDRA_INT(pvVar5) - GHIDRA_INT(playerSlot) >> 2))) { - playerSlot = playerSlot + uVar3; - } - Entity_Player::spawn_locusts(GHIDRA_CAST(*playerSlot)); - uVar3 = uVar3 + 1; - playerManager = &g_game->_playerManager; - } while (uVar3 < GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((playerManager->_playerList)._begin) >> 2))); - } - ExceptionList = local_10; - return; -} - -// 00834350 -void Ambush::Update() -{ - int iVar1; - int iVar2; - Entity_Player *player; - int iVar3; - int iVar4; - int iVar5; - uint32_t playerIndex; - void *local_1c; - int tempEffect [3]; - uint32_t local_c; - void *collectibles; - Game *game; - Manager *manager; - uint32_t *roomFlags; - - game = g_game; - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 8)); - if (iVar1 == 0x11) { - iVar3 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - iVar4 = this->_maxWaves; - iVar2 = iVar3 >> 0x1f; - if (iVar3 / 0xc + iVar2 == iVar2) { - this->_maxWaves = this->_currentWave; - } - } - else { - iVar4 = (*GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 4)) + 0x10)) + 0x10)) != 1) + 2; - } - iVar2 = *GHIDRA_CAST((this + 1)); - if (0 < iVar2) { - local_1c = game->_room; - iVar5 = *GHIDRA_CAST((GHIDRA_CAST(local_1c) + 0x12c4)) + *GHIDRA_CAST((GHIDRA_CAST(local_1c) + 0x12c0)); - iVar3 = 0; - if (0 < iVar5) { - iVar3 = iVar5; - } - if ((iVar3 != 0) || (iVar1 == 0x11)) { - iVar5 = *GHIDRA_CAST((GHIDRA_CAST(local_1c) + 0x12cc)) + *GHIDRA_CAST((GHIDRA_CAST(local_1c) + 0x12c8)); - iVar3 = 0; - if (0 < iVar5) { - iVar3 = iVar5; - } - if (0 < iVar3) { - return; - } - if (iVar1 != 0x11) { - return; - } - } - if (((iVar2 == 0x1e) && (0 < this->_currentWave)) && (this->_currentWave < iVar4)) { - PlayerManager::trigger_room_clear(&g_game->_playerManager); - if (iVar1 == 0x11) { - PlayerManager::trigger_room_clear(&g_game->_playerManager); - } - playerIndex = 0; - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((g_game->_playerManager)._playerList._begin) >> 2 != 0) { - do { - player = Game::GetPlayer(g_game,playerIndex); - collectibles = (g_manager->_itemConfig)._collectibles._begin; - if ((0x898 < GHIDRA_INT((GHIDRA_INT((g_manager->_itemConfig)._collectibles._end) - GHIDRA_INT(collectibles) & - 0xfffffffcU))) && - (iVar1 = *GHIDRA_CAST((GHIDRA_CAST(collectibles) + 0x898)), iVar1 != 0)) { - tempEffect[2] = *GHIDRA_CAST((iVar1 + 0x78)); - tempEffect[1] = 0; - local_c = 0; - tempEffect[0] = iVar1; - TemporaryEffects::RemoveEffect(&player->_temporaryeffects,tempEffect,1); - } - playerIndex = playerIndex + 1; - } while (playerIndex < - GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((g_game->_playerManager)._playerList._begin) >> 2))); - } - (GHIDRA_CAST((GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))))))->RNG::Next(); - iVar2 = *GHIDRA_CAST((this + 1)); - } - *GHIDRA_CAST((this + 1)) = iVar2 + -1; - return; - } - if (iVar4 <= this->_currentWave) { - this->_isActive = 0; - roomFlags = GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(game->_room) + 4)) + 0x44)); - *roomFlags = *roomFlags | 8; - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(game->_room) + 4)); - if ((iVar4 == 0) || (*GHIDRA_CAST((iVar4 + 0x10)) == 0)) { - iVar2 = 1; - } - else { - iVar2 = *GHIDRA_CAST((*GHIDRA_CAST((iVar4 + 0x10)) + 0x48)); - } - ScoreSheet::add_cleared_room - (GHIDRA_CAST(&game->_scoreSheet),*GHIDRA_CAST((GHIDRA_CAST(game->_room) + 8)),iVar2,1, - (uint8_t)(*GHIDRA_CAST((iVar4 + 0x44)) >> 10) & 1); - iVar4 = 0x5c; - if (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 8)) == 0x11) { - iVar4 = 0x28; - } - MusicManager::Crossfade(&g_manager->_musicManager,iVar4,0.08); - if (0x25 < (GHIDRA_INT((g_manager->_musicManager)._entries._end) - - GHIDRA_INT((g_manager->_musicManager)._entries._begin)) / 0x60) { - (g_manager->_musicManager)._queuedMusicID = 0x25; - } - Room::SpawnClearAward(g_game->_room); - PlayerManager::trigger_room_clear(&g_game->_playerManager); - if (iVar1 == 0x11) { - PlayerManager::trigger_room_clear(&g_game->_playerManager); - } - manager = g_manager; - local_1c = (void *)0x24; - roomFlags = GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 4)) + 0x44)); - *roomFlags = *roomFlags | 1; - seed_fart_sound_override(GHIDRA_CAST(&local_1c)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_1c),1.0,2,0,1.0,0.0); - return; - } - *GHIDRA_CAST((this + 1)) = 0x1e; - this->_currentWave = this->_currentWave + 1; - if (iVar1 == 0x11) { - SpawnBossrushWave(this); - return; - } - SpawnWave(this); - return; -} diff --git a/generated-src/classes.h b/generated-src/classes.h index 4ccfd6f..0a452b5 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -151,6 +151,7 @@ struct BossPool; struct BossPoolState; struct BossPool_Entry; struct BossPool_Pool; +struct BossRushEntry; struct BrimstoneShot; struct BufferedStream; struct ButterBeanFart; @@ -395,7 +396,9 @@ struct LayerAnimation; struct LayerData; struct LayerState; struct Leaderboard; +struct LeechThrow; struct LeftFire; +struct LerpRange; struct Level; struct LevelGenerator; struct LevelGenerator_Room; @@ -510,6 +513,7 @@ struct PlayerHUDPocketItem; struct PlayerHUDTrinket; struct PlayerManager; struct PlayerProceduralItems; +struct PlayerTrail; struct PngWriter; struct PocketItem; struct PocketItemConfig; @@ -634,6 +638,7 @@ struct TexelQuery; struct TextMeasure; struct TexturePtr; struct Thread; +struct TrailFrame; struct TrailPoint; struct TrinketPoolItem; struct TypeDescriptor; @@ -961,36 +966,6 @@ struct AfterbirthPersistentGameData { }; -struct std_vector { - void * _begin; - void * _end; - void * _capacity; -}; -LAYOUT32(offsetof(std_vector, _begin) == 0x0); -LAYOUT32(offsetof(std_vector, _end) == 0x4); -LAYOUT32(offsetof(std_vector, _capacity) == 0x8); -LAYOUT32(sizeof(std_vector) == 0xc); - -struct Ambush { - void shuffle_waves(); // 008332e0 - void StartChallenge(); // 00833420 - void SpawnWave(); // 00833600 - void SpawnBossrushWave(); // 00833c40 - void Update(); // 00834350 - - uint8_t _pad_0x0[0xc]; - std_vector _bossRushWaves; - int _maxWaves; - uint8_t _pad_0x1c[0x4]; - bool _isActive; - uint8_t _pad_0x21[0x3]; - int _currentWave; -}; -LAYOUT32(offsetof(Ambush, _bossRushWaves) == 0xc); -LAYOUT32(offsetof(Ambush, _maxWaves) == 0x18); -LAYOUT32(offsetof(Ambush, _isActive) == 0x20); -LAYOUT32(offsetof(Ambush, _currentWave) == 0x24); - struct BitSet128 { static BitSet128 * operator_and(BitSet128 *outResult, BitSet128 *a, BitSet128 *b); // 00417170 uint8_t IsNonZero(); // 004171b0 @@ -1609,13 +1584,6 @@ struct Weapon { } -struct IsaacsBodyData { - virtual ~IsaacsBodyData(); // 0060d530 slot 0 ::FUN_0060d530 - - uint8_t _pad_0x4[0x574]; -}; -LAYOUT32(sizeof(IsaacsBodyData) == 0x578); - struct Item { uint8_t IsCollectible(); // 005b14e0 uint8_t HasTags(uint64_t tags); // 005b1500 @@ -3629,13 +3597,6 @@ struct PersistentGameDataWriter { }; -struct PickupGhostData { - virtual ~PickupGhostData(); // 005d23a0 slot 0 ::FUN_005d23a0 - - uint8_t _pad_0x4[0x454]; -}; -LAYOUT32(sizeof(PickupGhostData) == 0x458); - struct PillEffect { uint8_t IsAvailable(); // 00730b20 }; @@ -3815,6 +3776,16 @@ struct SimpleString { }; +struct std_vector { + void * _begin; + void * _end; + void * _capacity; +}; +LAYOUT32(offsetof(std_vector, _begin) == 0x0); +LAYOUT32(offsetof(std_vector, _end) == 0x4); +LAYOUT32(offsetof(std_vector, _capacity) == 0x8); +LAYOUT32(sizeof(std_vector) == 0xc); + struct SoundEffects { void Play(int ID, float Volume, int FrameDelay, uint8_t Loop, float Pitch, float Pan); // 0092dc30 void ClearVolumeModifier(); // 0092e430 @@ -5824,8 +5795,6 @@ void FUN_004aae30(char param_1); // 004aae30 void FUN_004aae50(char param_1); // 004aae50 int FUN_004aae70(); // 004aae70 void FUN_004b3950(); // 004b3950 -void FUN_004b3d50(); // 004b3d50 -void FUN_004b3f10(); // 004b3f10 void FUN_004b6b20(int *param_1, int param_2, int param_3); // 004b6b20 void FUN_004b6ce0(int param_1, int param_2, int param_3); // 004b6ce0 uint32_t FUN_004b6d70(uint32_t param_1); // 004b6d70 @@ -5932,8 +5901,6 @@ int FUN_005accb0(); // 005accb0 int FUN_005accf0(); // 005accf0 int FUN_005acd10(); // 005acd10 void FUN_005ad1c0(); // 005ad1c0 -uint32_t position_is_over_pit(); // 005ae0b0 -bool FUN_005ae1d0(); // 005ae1d0 void FUN_005b1490(uint32_t param_1, uint32_t param_2); // 005b1490 void FUN_005b1560(); // 005b1560 void FUN_005b15a0(uint32_t param_1); // 005b15a0 @@ -6042,8 +6009,6 @@ void FUN_005cd840(uint32_t param_1); // 005cd840 void FUN_005cd850(); // 005cd850 void FUN_005cd8c0(uint8_t param_1); // 005cd8c0 void FUN_005cda90(); // 005cda90 -void FUN_005d2300(); // 005d2300 -void FUN_005d23a0(uint8_t param_1); // 005d23a0 void FUN_00607540(); // 00607540 void room_perimeter_to_position(float *param_1, float *param_2); // 0060ac70 void FUN_0060c350(); // 0060c350 @@ -6104,10 +6069,8 @@ bool FUN_0060d1c0(uint32_t param_1); // 0060d1c0 uint32_t FUN_0060d1e0(); // 0060d1e0 void FUN_0060d1f0(uint32_t param_1); // 0060d1f0 void FUN_0060d400(); // 0060d400 -void FUN_0060d530(uint8_t param_1); // 0060d530 void FUN_0060d5e0(uint8_t param_1); // 0060d5e0 uint32_t FUN_0060dae0(); // 0060dae0 -void FUN_0062c8a0(); // 0062c8a0 void FUN_0062e0e0(int param_1); // 0062e0e0 void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3); // 00631a00 void familiar_wisp_pick_tear_color(RNG *rng, int *outVariant, BitSet128 *outFlags); // 00633990 @@ -6116,9 +6079,6 @@ void FUN_006395e0(Vector *param_1, int *param_2, int param_3, int param_4, int p void FUN_0063b240(); // 0063b240 void FUN_0063c060(int param_1); // 0063c060 void FUN_0063e180(); // 0063e180 -void FUN_00640050(); // 00640050 -void FUN_006401d0(); // 006401d0 -void FUN_006403f0(); // 006403f0 void FUN_006431b0(); // 006431b0 void anm2_apply_gfx_overrides(std_string *gfxSpec, std_string *unusedString, ANM2 *anm2); // 0064aab0 void FUN_0064b6a0(); // 0064b6a0 @@ -6197,7 +6157,6 @@ uint8_t string_to_bool(void *self); // 0067f600 void ResolveRelativePath(uint8_t *anmPath, uint8_t *relPath, uint8_t *outPath); // 0067f670 void ExtractAngleBracketText(); // 0067fdf0 void FUN_00680060(size_t param_1); // 00680060 -void FUN_00682260(); // 00682260 void shader_stack_push(int shaderIndex); // 00682280 void FUN_00682350(); // 00682350 uint32_t checksum_stream(void *stream, int offset, int trailingSize); // 00683580 @@ -6413,7 +6372,6 @@ void FUN_007008b0(int *param_1); // 007008b0 void FUN_00703140(); // 00703140 void FUN_00704b50(); // 00704b50 void FUN_007068f0(int param_1); // 007068f0 -void r_key_timer_callback(); // 00707ad0 Entity * spawn_chain_lightning(Vector *position, BitSet128 tearFlags, Entity *spawner, float damage); // 00707e10 uint32_t FUN_00708350(); // 00708350 void FUN_00708380(); // 00708380 @@ -6768,7 +6726,6 @@ void FUN_008370b0(); // 008370b0 uint32_t FUN_00837610(); // 00837610 void FUN_00837660(uint32_t param_1); // 00837660 int FUN_00839070(); // 00839070 -void FUN_008391a0(); // 008391a0 void sprite_member_at_0xc_destroy(void *self); // 00839300 void list_anm2_state_assign(int *param_1); // 00839380 void FUN_00839830(); // 00839830 @@ -6789,7 +6746,6 @@ void FUN_0083c480(); // 0083c480 void item_pool_icons_render(void *iconLayer, Vector *position, KColor *color); // 0083d8c0 char * FUN_00840510(); // 00840510 std_string * int_to_string(std_string *outString, int value); // 00840540 -void FUN_0084a870(float *param_1); // 0084a870 void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4); // 0084abc0 void FUN_0084bba0(); // 0084bba0 void FUN_0084bbc0(uint32_t *param_1); // 0084bbc0 @@ -6895,7 +6851,6 @@ uint32_t Catch_00863d4e(); // 00863d4e uint32_t Catch_008641bb(); // 008641bb 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 uint32_t Catch_0086504e(); // 0086504e uint32_t Catch_0086512e(); // 0086512e @@ -20809,28 +20764,19 @@ namespace AudioPacketQueue { void destroyAllAudioPackets(); // 00aadc80 } namespace FamiliarAI { -void bobs_brain(Entity_Familiar *familiar); // 00616770 void gb_bug(Entity_Familiar *familiar); // 00618b00 void variant_53(Entity_Familiar *familiar); // 006196e0 void variant_66(Entity_Familiar *familiar); // 0061c3f0 -void punching_bag(Entity_Familiar *familiar); // 0061c910 void lil_haunt(Entity_Familiar *familiar, int unused); // 0061d030 -void lost_fly(Entity_Familiar *familiar); // 0062e9c0 void bumbo(Entity_Familiar *familiar); // 0062f7f0 -void spider_mod(Entity_Familiar *familiar); // 00630c90 -void sprinkler(Entity_Familiar *familiar); // 00635390 -void mystery_egg(Entity_Familiar *familiar); // 00638170 void lil_spewer(Entity_Familiar *familiar); // 006384a0 Entity_Knife * sprinkler_spawn_knife(Entity_Familiar *familiar); // 0063b070 void tinytoma(Entity_Familiar *familiar); // 00642cb0 void variant_204(Entity_Familiar *familiar); // 00644780 -void lost_soul(Entity_Familiar *familiar); // 00645bc0 void lil_dumpy(Entity_Familiar *familiar); // 006468a0 void apollyons_best_friend(Entity_Familiar *familiar); // 00647320 int worm_friend(Entity_Familiar *familiar); // 0064bfa0 void star_of_bethlehem(Entity_Familiar *familiar); // 0064d5f0 -void cube_baby(Entity_Familiar *familiar); // 0064f860 -void blood_puppy(Entity_Familiar *familiar); // 0064fd40 void vanishing_twin(Entity_Familiar *familiar); // 00650610 } namespace FamiliarHelper { @@ -20843,7 +20789,6 @@ void SwapANM2(ANM2 *left, ANM2 *right); // 00407ae0 ItemConfig * GetItemConfig(); // 0042ca00 int Random(int Max); // 0067f010 Vector * GetRandomPickupVelocity(Vector *outVelocity, Vector *position, uint32_t pickupVelType, RNG *rng); // 006ee440 -void Shutdown(); // 009ab700 } namespace ItemInfo { uint8_t is_collectible_seen(int param_1); // 0083d760 @@ -20887,7 +20832,6 @@ void ENTITY_BEAST_ultra_war(Entity_NPC *npc); // 0044c070 void ENTITY_BEAST_ultra_war_fire_burst(Entity_NPC *npc); // 0044ee60 void ENTITY_BEAST_ultra_war_bomb(Entity_NPC *npc); // 0044f2b0 void ENTITY_LIL_BLUB(Entity_NPC *npc); // 00450da0 -void ENTITY_PIN(Entity_NPC *npc); // 00476860 void ENTITY_BUMBINO(Entity_NPC *npc); // 00499de0 void ENTITY_CHIMERA_head_update(Entity_NPC *npc); // 0049cd90 void ENTITY_CHIMERA_body(Entity_NPC *npc); // 0049d130 @@ -20899,7 +20843,6 @@ void ENTITY_DOGMA(Entity_NPC *npc); // 004aafa0 void ENTITY_DOGMA_angel(Entity_NPC *npc); // 004ae4d0 Vector * ENTITY_DOGMA_angel_baby(Entity_NPC *npc); // 004b0200 void ENTITY_DOGMA_tv(Entity_NPC *npc); // 004b0a30 -void ENTITY_HERETIC(Entity_NPC *npc); // 004b43c0 void ENTITY_HORNFEL_DOOR(Entity_NPC *npc); // 004bb9b0 void ENTITY_HORNY_BOYS(Entity_NPC *npc); // 004bd2a0 void ENTITY_MATRIARCH(Entity_NPC *npc); // 004c59d0 @@ -20920,7 +20863,6 @@ void ENTITY_WHIPPER(Entity_NPC *npc); // 004e5170 void ENTITY_GRUDGE(Entity_NPC *npc); // 004e6570 uint32_t ENTITY_BISHOP(Entity_NPC *npc); // 004e7ea0 uint8_t * ENTITY_BABY_BEGOTTEN(Entity_NPC *npc); // 004e8380 -void ENTITY_EXORCIST(Entity_NPC *npc); // 004ec240 void ENTITY_REVENANT(Entity_NPC *npc); // 004ecc10 void ENTITY_CULTIST(Entity_NPC *npc); // 004ed840 void ENTITY_CLICKETY_CLACK(Entity_NPC *npc); // 004efb90 @@ -20930,7 +20872,6 @@ void ENTITY_BALL_AND_CHAIN(Entity_NPC *npc); // 004f4730 void ENTITY_POOFER(Entity_NPC *npc); // 004f64e0 void ENTITY_MOCKULUS(Entity_NPC *npc); // 004f76f0 void ENTITY_MORNINGSTAR(Entity_NPC *npc); // 004f7e60 -void ENTITY_FACELESS(Entity_NPC *npc); // 004faad0 void ENTITY_DANNY(Entity_NPC *npc); // 004fbd10 void ENTITY_GYRO(Entity_NPC *npc); // 004ff620 void ENTITY_BOUNCER(Entity_NPC *npc); // 00501f30 @@ -21005,10 +20946,6 @@ void ENTITY_VISAGE(Entity_NPC *npc); // 005a7b20 void ENTITY_VISAGE_mask(Entity_NPC *npc); // 005ab4d0 void ENTITY_VISAGE_chain(Entity_NPC *npc); // 005ad250 void ENTITY_VISAGE_plasma(Entity_NPC *npc); // 005ad8a0 -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 } namespace OnlinePlayerInfo { void render_items(float *param_1); // 008d4940 @@ -21034,9 +20971,6 @@ uint32_t _seekPage(int param_1, char param_2); // 00a8e1b0 namespace _Entity { int GetAncestorField(uint32_t param_1); // 006b7d20 } -namespace _Entity_Player { -uint32_t SpawnTrinketRandomPickup(); // 007dc2d0 -} namespace _NpcHelper { uint32_t spider_load_graphics(uint8_t *param_1); // 006baa70 } diff --git a/generated-src/input_manager.cpp b/generated-src/input_manager.cpp index c8939e2..5eb277c 100644 --- a/generated-src/input_manager.cpp +++ b/generated-src/input_manager.cpp @@ -124,41 +124,3 @@ int InputManager::FirstLocalDeviceID() ); return -1; } - -// 009562d0 -float InputManager::GetActionValue(int action, int controllerIndex, Entity *entity, int unused) -{ - char isNetplayHandled; - uint32_t in_ECX; - int iVar1; - uint32_t deviceIndex; - long double value; - Manager *manager; - int requestedAction; - - requestedAction = action; - manager = g_manager; - if (((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((g_manager)) + 0x8)))) != 2) || (g_luaEngine == (void *)0x0)) || - (isNetplayHandled = FUN_00864d80(entity,in_ECX,action,&action), isNetplayHandled == '\0')) { - iVar1 = manager->_netplayManager; - if ((iVar1 != *GHIDRA_CAST((manager + 1))) && (controllerIndex == -1)) { - deviceIndex = 0; - if (*GHIDRA_CAST((manager + 1)) - iVar1 >> 2 != 0) { - do { - action = *GHIDRA_CAST((**GHIDRA_CAST((iVar1 + deviceIndex * 4)) + 0x38)); - value = (long double)(*(code *)action)(requestedAction); - if ((float)value != 0.0) { - return (float)value; - } - deviceIndex = deviceIndex + 1; - iVar1 = manager->_netplayManager; - } while (deviceIndex < GHIDRA_UINT((*GHIDRA_CAST((manager + 1)) - iVar1 >> 2))); - } - return 0.0; - } - entity = GHIDRA_CAST(requestedAction); - action = 0; - (**(code **)(PTR_vftable_00c57b18 + 0x74))(controllerIndex,FUN_00a20ab0,&entity,&action,0); - } - return (float)action; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index fa2c232..64fb976 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -469,333 +469,6 @@ LAB_004a2fed: return; } -// 004b3af0 -Entity * NpcHelper::heretic_spawn_afterimage(Entity_NPC *npc) -{ - uint8_t bVar1; - Entity *afterimage; - uint8_t *afterimageAnimChar; - uint32_t uVar2; - LayerState *afterimageLayer; - LayerState *npcLayer; - uint8_t *****animNameData; - uint8_t *****animNameChar; - bool isLess; - uint32_t local_38; - uint8_t *****animName [4]; - uint32_t animNameSize; - uint32_t animNameCapacity; - uint32_t securityCookie; - void *local_10; - uint8_t *puStack_c; - uint8_t ****local_8; - uint32_t flagsHi; - void *npcAnimData; - - local_8 = GHIDRA_CAST(0xffffffff); - puStack_c = &LAB_00af32ed; - local_10 = ExceptionList; - securityCookie = __security_cookie ^ GHIDRA_UINT((animName + 10)); - ExceptionList = &local_10; - afterimage = Game::Spawn(g_game,0x389,0,&npc->_pos,&npc->_velocity,GHIDRA_CAST(npc), - (npc->_state == 0xb) + 1,npc->_initSeed); - flagsHi = *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)); - *GHIDRA_CAST(&afterimage->_flags) = GHIDRA_INT(npc->_flags); - *GHIDRA_CAST((GHIDRA_INT(&afterimage->_flags) + 4)) = flagsHi; - FUN_004b6b20((afterimage->_colorParams)._begin,(npc->_colorParams)._begin,(npc->_colorParams)._end - ,local_38); - flagsHi = *GHIDRA_CAST((GHIDRA_INT(&afterimage->_flags) + 4)); - *GHIDRA_CAST(&afterimage->_flags) = GHIDRA_UINT(afterimage->_flags) | 0x11; - afterimage->_isInvicible = 1; - *GHIDRA_CAST((GHIDRA_INT(&afterimage->_flags) + 4)) = flagsHi; - npcAnimData = (npc->_sprite)._animState._animData; - if (npcAnimData == (void *)0x0) { - animNameCapacity = 0xf; - animNameSize = 0; - animName[0] = GHIDRA_CAST(0x0); - } - else { - (GHIDRA_CAST((GHIDRA_CAST(animName))))->msvc::string::string(npcAnimData); - } - local_8 = GHIDRA_CAST(0x0); - animNameData = GHIDRA_CAST(animName); - if (0xf < animNameCapacity) { - animNameData = animName[0]; - } - afterimageAnimChar = (afterimage->_sprite)._animState._animData; - if (afterimageAnimChar != GHIDRA_CAST(0x0)) { - if (0xf < *GHIDRA_CAST((afterimageAnimChar + 0x14))) { - afterimageAnimChar = *GHIDRA_CAST(afterimageAnimChar); - } - animNameChar = animNameData; - do { - bVar1 = *afterimageAnimChar; - isLess = bVar1 < *GHIDRA_CAST(animNameChar); - if (bVar1 != *GHIDRA_CAST(animNameChar)) { -LAB_004b3c27: - uVar2 = -GHIDRA_UINT(isLess) | 1; - goto LAB_004b3c2c; - } - if (bVar1 == 0) break; - bVar1 = afterimageAnimChar[1]; - isLess = bVar1 < *GHIDRA_CAST((GHIDRA_CAST(animNameChar) + 1)); - if (bVar1 != *GHIDRA_CAST((GHIDRA_CAST(animNameChar) + 1))) goto LAB_004b3c27; - afterimageAnimChar = afterimageAnimChar + 2; - animNameChar = GHIDRA_CAST((GHIDRA_INT(animNameChar) + 2)); - } while (bVar1 != 0); - uVar2 = 0; -LAB_004b3c2c: - if ((uVar2 == 0) && - ((*GHIDRA_CAST((GHIDRA_INT((afterimage->_sprite)._animState._animData) + 0x34)) == '\0' || - ((afterimage->_sprite)._animState._isPlaying != 0)))) goto LAB_004b3c68; - } - bVar1 = ANM2::SetAnimation(&afterimage->_sprite,GHIDRA_CAST(animNameData),1); - if (bVar1 != 0) { - AnimationState::Rewind(&(afterimage->_sprite)._animState); - (afterimage->_sprite)._animState._isPlaying = 1; - } -LAB_004b3c68: - local_8 = GHIDRA_CAST(0xffffffff); - if (0xf < animNameCapacity) { - uVar2 = animNameCapacity + 1; - animNameData = animName[0]; - if (0xfff < uVar2) { - animNameData = GHIDRA_CAST(animName[0][-1]); - uVar2 = animNameCapacity + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(animName[0]) + (-4 - GHIDRA_INT(animNameData))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(animNameData,uVar2); - } - animNameSize = 0; - animNameCapacity = 0xf; - animName[0] = GHIDRA_CAST((GHIDRA_UINT(animName[0]) & 0xffffff00)); - if ((afterimage->_sprite)._animState._animData != (void *)0x0) { - AnimationState::SetFrameFloat - (&(afterimage->_sprite)._animState,(npc->_sprite)._animState._animFrame); - } - afterimageLayer = ANM2::GetLayer(&afterimage->_sprite,GHIDRA_CAST(0x0)); - npcLayer = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x0)); - (afterimageLayer->_color)._tint[3] = (npcLayer->_color)._tint[3]; - afterimage->_entityGridCollisionClass = 0; - afterimage->_entityCollisionClass = 0; - afterimage[2]._preInterpolatePos.x = 1.82169e-44; - *GHIDRA_CAST((GHIDRA_INT(&afterimage[2]._health) + 2)) = - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileCooldown) + 2)); - *GHIDRA_CAST((afterimage + 1)) = 0; - afterimage->_health = 0.0; - afterimage->_maxHitPoints = 0.0; - (**(code **)(*GHIDRA_CAST(afterimage) + 0xc))(); - ExceptionList = local_10; - return afterimage; -} - -// 004b3ec0 -int NpcHelper::heretic_count_out_fires() -{ - int *entityIt; - int outFireCount; - int remaining; - int entity; - - outFireCount = 0; - remaining = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1264)); - if (remaining != 0) { - entityIt = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x125c)); - do { - entity = *entityIt; - if (((*GHIDRA_CAST((entity + 0x28)) == 0x21) && (*GHIDRA_CAST((entity + 0x2c)) == 3)) && - (*GHIDRA_CAST((entity + 0x380)) <= 1.5 && *GHIDRA_CAST((entity + 0x380)) != 1.5)) { - outFireCount = outFireCount + 1; - } - entityIt = entityIt + 1; - remaining = remaining + -1; - } while (remaining != 0); - } - return outFireCount; -} - -// 004b40d0 -void NpcHelper::heretic_choose_attack(Entity_NPC *npc) -{ - RNG rng; - Entity_NPC *pEVar1; - uint32_t uVar2; - uint32_t outcomeCount; - void *pvVar3; - uint32_t *outcomesCursor; - float halfHealth; - uint64_t uStack_44; - uint32_t uStack_3c; - uint32_t *local_38; - Entity_NPC *npcLocal; - void *outcomes; - uint32_t *outcomesEnd; - uint32_t *outcomesCapacityEnd; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - int *weight; - - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - puStack_18 = &LAB_00af332d; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - ExceptionList = &local_1c; - outcomes = (void *)0x0; - outcomesEnd = GHIDRA_CAST(0x0); - outcomesCapacityEnd = GHIDRA_CAST(0x0); - local_14 = 0; - npcLocal = npc; - local_38 = GHIDRA_CAST(heretic_count_out_fires()); - pvVar3 = (void *)0x0; - outcomesCursor = GHIDRA_CAST(0x0); - if (*GHIDRA_CAST((GHIDRA_INT(&npcLocal->_projectileDelay) + 1)) < '\x01') { - uStack_44 = CONCAT44(0xe,(uint32_t)uStack_44); - uStack_3c = 10; - msvc::vector<8byte>::_Emplace_reallocate(0,GHIDRA_INT(&uStack_44) + 4); - pvVar3 = outcomes; - outcomesCursor = outcomesEnd; - } - if (*GHIDRA_CAST((GHIDRA_INT(&npcLocal->_projectileDelay) + 2)) < '\x01') { - uVar2 = 0; - outcomeCount = GHIDRA_INT(outcomesCursor) - GHIDRA_INT(pvVar3) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar3) + uVar2 * 8)) == 9) { - weight = GHIDRA_CAST((GHIDRA_INT(pvVar3) + uVar2 * 8 + 4)); - *weight = *weight + 10; - if (*weight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(pvVar3) + uVar2 * 8 + 4)) = 0; - } - goto LAB_004b41d2; - } - uVar2 = uVar2 + 1; - } while (uVar2 < outcomeCount); - } - uStack_44 = CONCAT44(9,(uint32_t)uStack_44); - uStack_3c = 10; - if (outcomesCursor == outcomesCapacityEnd) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesCursor,GHIDRA_INT(&uStack_44) + 4); - pvVar3 = outcomes; - outcomesCursor = outcomesEnd; - } - else { - *outcomesCursor = 9; - outcomesCursor[1] = 10; - outcomesCursor = outcomesCursor + 2; - outcomesEnd = outcomesCursor; - } - } -LAB_004b41d2: - if (*GHIDRA_CAST((GHIDRA_INT(&npcLocal->_projectileDelay) + 3)) < '\x01') { - if (GHIDRA_CAST(0x2) < local_38) { - uVar2 = 0; - outcomeCount = GHIDRA_INT(outcomesCursor) - GHIDRA_INT(pvVar3) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar3) + uVar2 * 8)) == 7) { - weight = GHIDRA_CAST((GHIDRA_INT(pvVar3) + uVar2 * 8 + 4)); - *weight = *weight + 10; - if (*weight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(pvVar3) + uVar2 * 8 + 4)) = 0; - } - goto LAB_004b4249; - } - uVar2 = uVar2 + 1; - } while (uVar2 < outcomeCount); - } - uStack_44 = CONCAT44(7,(uint32_t)uStack_44); - uStack_3c = 10; - if (outcomesCursor == outcomesCapacityEnd) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesCursor,GHIDRA_INT(&uStack_44) + 4); - pvVar3 = outcomes; - outcomesCursor = outcomesEnd; - } - else { - *outcomesCursor = 7; - outcomesCursor[1] = 10; - outcomesEnd = outcomesCursor + 2; - outcomesCursor = outcomesEnd; - } - } - } -LAB_004b4249: - uVar2 = 0; - outcomeCount = GHIDRA_INT(outcomesCursor) - GHIDRA_INT(pvVar3) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar3) + uVar2 * 8)) == 3) { - weight = GHIDRA_CAST((GHIDRA_INT(pvVar3) + uVar2 * 8 + 4)); - *weight = *weight + 1; - if (*weight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(pvVar3) + uVar2 * 8 + 4)) = 0; - } - goto LAB_004b42a6; - } - uVar2 = uVar2 + 1; - } while (uVar2 < outcomeCount); - } - uStack_44 = CONCAT44(3,(uint32_t)uStack_44); - uStack_3c = 1; - if (outcomesCursor == outcomesCapacityEnd) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesCursor,GHIDRA_INT(&uStack_44) + 4); - } - else { - *outcomesCursor = 3; - outcomesCursor[1] = 1; - outcomesEnd = outcomesCursor + 2; - } -LAB_004b42a6: - uVar2 = Random(); - uStack_44 = 0x900000005; - uStack_3c = 7; - rng._shift1 = 5; - rng._seed = uVar2 | 1; - rng._shift2 = 9; - rng._shift3 = 7; - uVar2 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&outcomes),rng); - pEVar1 = npcLocal; - if (uVar2 == 3) { - *GHIDRA_CAST((GHIDRA_INT(&npcLocal->_stateFrame) + 2)) = 0; - } - else { - *GHIDRA_CAST(&npcLocal->_stateFrame) = 0xffff; - npcLocal->_state = uVar2; - if (uVar2 == 7) { - Entity_NPC::ClearDequeRefs(npcLocal); - if (pEVar1->_child != 0) { - local_38 = &pEVar1->_child; - msvc::multiset::erase(&local_38); - } - halfHealth = pEVar1->_maxHitPoints * 0.5; - pEVar1->_child = 0; - *GHIDRA_CAST(&pEVar1->_projectileCooldown) = - (pEVar1->_health <= halfHealth && halfHealth != pEVar1->_health) + '\x05'; - } - *GHIDRA_CAST((GHIDRA_INT(&pEVar1->_projectileCooldown) + 1)) = 0; - } - if (outcomes != (void *)0x0) { - uVar2 = GHIDRA_INT(outcomesCapacityEnd) - GHIDRA_INT(outcomes) & 0xfffffff8; - pvVar3 = outcomes; - if (0xfff < uVar2) { - pvVar3 = *(void **)(GHIDRA_CAST(outcomes) + -4); - uVar2 = uVar2 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(outcomes) + (-4 - GHIDRA_INT(pvVar3))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar3,uVar2); - } - ExceptionList = local_1c; - return; -} - // 004b70c0 void NpcHelper::hornfel_spawn_doors() { @@ -7537,24 +7210,6 @@ LAB_005adfbb: return 1; } -// 005ae140 -Entity * NpcHelper::wormwood_spawn_splash(Entity_NPC *npc) -{ - uint32_t seed; - Entity *splash; - int soundId; - Manager *manager; - - seed = Random(); - splash = Game::Spawn(g_game,1000,0x84,&npc->_pos,&g_vectorZero,GHIDRA_CAST(0x0),0,seed); - (**(code **)(*GHIDRA_CAST(splash) + 0xc))(); - manager = g_manager; - soundId = 0x1da; - seed_fart_sound_override(&soundId); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(soundId,1.0,10,0,1.0,0.0); - return splash; -} - // 006be7e0 uint8_t NpcHelper::is_target_valid(Entity *target) { diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 3638b7c..b18ce2e 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8222,11 +8222,6 @@ uint32_t register0x0000001e{}; AbyssLocustData::~AbyssLocustData() { generated_stub("AbyssLocustData::~AbyssLocustData 0060d5e0"); } uint8_t AfterbirthPersistentGameData::check_header(void *stream) { generated_stub("AfterbirthPersistentGameData::check_header 0041d670"); } -void Ambush::shuffle_waves() { generated_stub("Ambush::shuffle_waves 008332e0"); } -void Ambush::StartChallenge() { generated_stub("Ambush::StartChallenge 00833420"); } -void Ambush::SpawnWave() { generated_stub("Ambush::SpawnWave 00833600"); } -void Ambush::SpawnBossrushWave() { generated_stub("Ambush::SpawnBossrushWave 00833c40"); } -void Ambush::Update() { generated_stub("Ambush::Update 00834350"); } BitSet128 * BitSet128::operator_and(BitSet128 *outResult, BitSet128 *a, BitSet128 *b) { generated_stub("BitSet128::operator_and 00417170"); } uint8_t BitSet128::IsNonZero() { generated_stub("BitSet128::IsNonZero 004171b0"); } BitSet128 * BitSet128::operator__(BitSet128 *other) { generated_stub("BitSet128::operator__ 00435bf0"); } @@ -8383,10 +8378,8 @@ void GlitchedItemSet::recalculate() { generated_stub("GlitchedItemSet::recalcula void HallucinationOverlay::Render(Vector *offset) { generated_stub("HallucinationOverlay::Render 00839550"); } void * InputManager::GetDeviceByPlayerEntity(Entity_Player *player) { generated_stub("InputManager::GetDeviceByPlayerEntity 0090ac70"); } int InputManager::FirstLocalDeviceID() { generated_stub("InputManager::FirstLocalDeviceID 0090aeb0"); } -float InputManager::GetActionValue(int action, int controllerIndex, Entity *entity, int unused) { generated_stub("InputManager::GetActionValue 009562d0"); } void InviteFriendsMenu::load_graphics() { generated_stub("InviteFriendsMenu::load_graphics 009c4100"); } void InviteFriendsMenu::Render() { generated_stub("InviteFriendsMenu::Render 009c51e0"); } -IsaacsBodyData::~IsaacsBodyData() { generated_stub("IsaacsBodyData::~IsaacsBodyData 0060d530"); } KAGE::CommandQueue::~CommandQueue() { generated_stub("KAGE::CommandQueue::~CommandQueue 00a28d30"); } KAGE::EosFriendManager::~EosFriendManager() { generated_stub("KAGE::EosFriendManager::~EosFriendManager 00a7e440"); } KAGE::ManagerBase::~ManagerBase() { generated_stub("KAGE::ManagerBase::~ManagerBase 00a61a80"); } @@ -9224,9 +9217,6 @@ int * NpcHelper::chub_nearest_segment(int *param_1, int param_2) { generated_stu void NpcHelper::chimera_charge_begin(Entity_NPC *npc, Vector *target, float speed) { generated_stub("NpcHelper::chimera_charge_begin 0049f870"); } Vector * NpcHelper::colostomia_pick_target(Entity_NPC *npc, Vector *outTarget, uint8_t *isPlayerPos) { generated_stub("NpcHelper::colostomia_pick_target 004a2940"); } void NpcHelper::colostomia_pick_dive_target(Entity_NPC *npc) { generated_stub("NpcHelper::colostomia_pick_dive_target 004a2ce0"); } -Entity * NpcHelper::heretic_spawn_afterimage(Entity_NPC *npc) { generated_stub("NpcHelper::heretic_spawn_afterimage 004b3af0"); } -int NpcHelper::heretic_count_out_fires() { generated_stub("NpcHelper::heretic_count_out_fires 004b3ec0"); } -void NpcHelper::heretic_choose_attack(Entity_NPC *npc) { generated_stub("NpcHelper::heretic_choose_attack 004b40d0"); } void NpcHelper::hornfel_spawn_doors() { generated_stub("NpcHelper::hornfel_spawn_doors 004b70c0"); } void NpcHelper::hornfel_remove_doors() { generated_stub("NpcHelper::hornfel_remove_doors 004b78f0"); } void NpcHelper::hornfel_charge(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_charge 004b7e30"); } @@ -9286,7 +9276,6 @@ void NpcHelper::visage_pick_target_position(Entity_NPC *npc) { generated_stub("N void NpcHelper::visage_start_charge(Entity_NPC *npc) { generated_stub("NpcHelper::visage_start_charge 005ab180"); } void NpcHelper::visage_chain_solve(Entity_NPC *npc, uint8_t isInterpolate) { generated_stub("NpcHelper::visage_chain_solve 005acd30"); } uint8_t NpcHelper::visage_handle_collision(Entity_NPC *npc, Entity *collider, int unused) { generated_stub("NpcHelper::visage_handle_collision 005add40"); } -Entity * NpcHelper::wormwood_spawn_splash(Entity_NPC *npc) { generated_stub("NpcHelper::wormwood_spawn_splash 005ae140"); } uint8_t NpcHelper::is_target_valid(Entity *target) { generated_stub("NpcHelper::is_target_valid 006be7e0"); } void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } void OnlineChat::render(Vector *position, uint8_t isInputLine, uint8_t isCursorVisible, float alpha) { generated_stub("OnlineChat::render 0091d2b0"); } @@ -9299,7 +9288,6 @@ void OnlineChatMessage::constructor() { generated_stub("OnlineChatMessage::const void PersistentGameDataReader::read(PersistentGameData *data) { generated_stub("PersistentGameDataReader::read 0091adf0"); } void * PersistentGameDataWriter::compress(uint32_t *outSize) { generated_stub("PersistentGameDataWriter::compress 0091acc0"); } void PersistentGameDataWriter::write(PersistentGameData *data, void *header) { generated_stub("PersistentGameDataWriter::write 0091b130"); } -PickupGhostData::~PickupGhostData() { generated_stub("PickupGhostData::~PickupGhostData 005d23a0"); } void PngWriter::write_end() { generated_stub("PngWriter::write_end 009e8d40"); } void PngWriter::write_info() { generated_stub("PngWriter::write_info 009e8ee0"); } uint8_t ProceduralEffect::roll_trigger_target(uint32_t *outTarget, float *outChance, RNG *rng) { generated_stub("ProceduralEffect::roll_trigger_target 009e0700"); } @@ -9887,7 +9875,6 @@ bool FUN_004567d0() { generated_stub("FUN_004567d0 004567d0"); } void FUN_00456820() { generated_stub("FUN_00456820 00456820"); } void FUN_00456830(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4) { generated_stub("FUN_00456830 00456830"); } int FUN_00456880() { generated_stub("FUN_00456880 00456880"); } -void NpcAI::ENTITY_PIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PIN 00476860"); } void FUN_00479d50(uint32_t *param_1) { generated_stub("FUN_00479d50 00479d50"); } void FUN_00498f80() { generated_stub("FUN_00498f80 00498f80"); } void _range_to_span(uint32_t *param_1) { generated_stub("_range_to_span 00499270"); } @@ -9929,9 +9916,6 @@ void NpcAI::ENTITY_DOGMA_angel(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ Vector * NpcAI::ENTITY_DOGMA_angel_baby(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_angel_baby 004b0200"); } void NpcAI::ENTITY_DOGMA_tv(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_tv 004b0a30"); } void FUN_004b3950() { generated_stub("FUN_004b3950 004b3950"); } -void FUN_004b3d50() { generated_stub("FUN_004b3d50 004b3d50"); } -void FUN_004b3f10() { generated_stub("FUN_004b3f10 004b3f10"); } -void NpcAI::ENTITY_HERETIC(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HERETIC 004b43c0"); } void FUN_004b6b20(int *param_1, int param_2, int param_3) { generated_stub("FUN_004b6b20 004b6b20"); } void FUN_004b6ce0(int param_1, int param_2, int param_3) { generated_stub("FUN_004b6ce0 004b6ce0"); } uint32_t FUN_004b6d70(uint32_t param_1) { generated_stub("FUN_004b6d70 004b6d70"); } @@ -9994,7 +9978,6 @@ void NpcAI::ENTITY_WHIPPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WHIP void NpcAI::ENTITY_GRUDGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GRUDGE 004e6570"); } uint32_t NpcAI::ENTITY_BISHOP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BISHOP 004e7ea0"); } uint8_t * NpcAI::ENTITY_BABY_BEGOTTEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY_BEGOTTEN 004e8380"); } -void NpcAI::ENTITY_EXORCIST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EXORCIST 004ec240"); } void NpcAI::ENTITY_REVENANT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_REVENANT 004ecc10"); } void NpcAI::ENTITY_CULTIST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CULTIST 004ed840"); } void NpcAI::ENTITY_CLICKETY_CLACK(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLICKETY_CLACK 004efb90"); } @@ -10010,7 +9993,6 @@ uint8_t str_ne(std_string *a, uint8_t *b) { generated_stub("str_ne 004f84a0"); } void rng_pair_init(void *self) { generated_stub("rng_pair_init 004f88a0"); } uint32_t FUN_004f88e0() { generated_stub("FUN_004f88e0 004f88e0"); } uint32_t FUN_004f8930() { generated_stub("FUN_004f8930 004f8930"); } -void NpcAI::ENTITY_FACELESS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FACELESS 004faad0"); } void NpcAI::ENTITY_DANNY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DANNY 004fbd10"); } void NpcAI::ENTITY_GYRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GYRO 004ff620"); } void NpcAI::ENTITY_BOUNCER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOUNCER 00501f30"); } @@ -10144,12 +10126,6 @@ int FUN_005acd10() { generated_stub("FUN_005acd10 005acd10"); } void FUN_005ad1c0() { generated_stub("FUN_005ad1c0 005ad1c0"); } void NpcAI::ENTITY_VISAGE_chain(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE_chain 005ad250"); } void NpcAI::ENTITY_VISAGE_plasma(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE_plasma 005ad8a0"); } -uint32_t position_is_over_pit() { generated_stub("position_is_over_pit 005ae0b0"); } -bool FUN_005ae1d0() { generated_stub("FUN_005ae1d0 005ae1d0"); } -void NpcAI::ENTITY_WORMWOOD_pick_pit(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WORMWOOD_pick_pit 005ae230"); } -void NpcAI::ENTITY_WORMWOOD_segment_follow(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WORMWOOD_segment_follow 005ae840"); } -void NpcAI::wormwood_pick_emerge_position(Entity_NPC *npc) { generated_stub("NpcAI::wormwood_pick_emerge_position 005aef20"); } -void NpcAI::ENTITY_WORMWOOD_main(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WORMWOOD_main 005af800"); } void FUN_005b1490(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_005b1490 005b1490"); } void FUN_005b1560() { generated_stub("FUN_005b1560 005b1560"); } void FUN_005b15a0(uint32_t param_1) { generated_stub("FUN_005b15a0 005b15a0"); } @@ -10258,8 +10234,6 @@ void FUN_005cd840(uint32_t param_1) { generated_stub("FUN_005cd840 005cd840"); } void FUN_005cd850() { generated_stub("FUN_005cd850 005cd850"); } void FUN_005cd8c0(uint8_t param_1) { generated_stub("FUN_005cd8c0 005cd8c0"); } void FUN_005cda90() { generated_stub("FUN_005cda90 005cda90"); } -void FUN_005d2300() { generated_stub("FUN_005d2300 005d2300"); } -void FUN_005d23a0(uint8_t param_1) { generated_stub("FUN_005d23a0 005d23a0"); } void FUN_00607540() { generated_stub("FUN_00607540 00607540"); } void room_perimeter_to_position(float *param_1, float *param_2) { generated_stub("room_perimeter_to_position 0060ac70"); } void FUN_0060c350() { generated_stub("FUN_0060c350 0060c350"); } @@ -10320,24 +10294,16 @@ bool FUN_0060d1c0(uint32_t param_1) { generated_stub("FUN_0060d1c0 0060d1c0"); } uint32_t FUN_0060d1e0() { generated_stub("FUN_0060d1e0 0060d1e0"); } void FUN_0060d1f0(uint32_t param_1) { generated_stub("FUN_0060d1f0 0060d1f0"); } void FUN_0060d400() { generated_stub("FUN_0060d400 0060d400"); } -void FUN_0060d530(uint8_t param_1) { generated_stub("FUN_0060d530 0060d530"); } void FUN_0060d5e0(uint8_t param_1) { generated_stub("FUN_0060d5e0 0060d5e0"); } uint32_t FUN_0060dae0() { generated_stub("FUN_0060dae0 0060dae0"); } -void FamiliarAI::bobs_brain(Entity_Familiar *familiar) { generated_stub("FamiliarAI::bobs_brain 00616770"); } void FamiliarAI::gb_bug(Entity_Familiar *familiar) { generated_stub("FamiliarAI::gb_bug 00618b00"); } void FamiliarAI::variant_53(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_53 006196e0"); } void FamiliarAI::variant_66(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_66 0061c3f0"); } -void FamiliarAI::punching_bag(Entity_Familiar *familiar) { generated_stub("FamiliarAI::punching_bag 0061c910"); } void FamiliarAI::lil_haunt(Entity_Familiar *familiar, int unused) { generated_stub("FamiliarAI::lil_haunt 0061d030"); } -void FUN_0062c8a0() { generated_stub("FUN_0062c8a0 0062c8a0"); } void FUN_0062e0e0(int param_1) { generated_stub("FUN_0062e0e0 0062e0e0"); } -void FamiliarAI::lost_fly(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lost_fly 0062e9c0"); } void FamiliarAI::bumbo(Entity_Familiar *familiar) { generated_stub("FamiliarAI::bumbo 0062f7f0"); } -void FamiliarAI::spider_mod(Entity_Familiar *familiar) { generated_stub("FamiliarAI::spider_mod 00630c90"); } void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3) { generated_stub("FUN_00631a00 00631a00"); } void familiar_wisp_pick_tear_color(RNG *rng, int *outVariant, BitSet128 *outFlags) { generated_stub("familiar_wisp_pick_tear_color 00633990"); } -void FamiliarAI::sprinkler(Entity_Familiar *familiar) { generated_stub("FamiliarAI::sprinkler 00635390"); } -void FamiliarAI::mystery_egg(Entity_Familiar *familiar) { generated_stub("FamiliarAI::mystery_egg 00638170"); } void FamiliarAI::lil_spewer(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lil_spewer 006384a0"); } void FUN_00638e20() { generated_stub("FUN_00638e20 00638e20"); } void FUN_006395e0(Vector *param_1, int *param_2, int param_3, int param_4, int param_5, float param_6, int param_7, int param_8, Entity *param_9, int param_10) { generated_stub("FUN_006395e0 006395e0"); } @@ -10347,13 +10313,9 @@ void FUN_0063b240() { generated_stub("FUN_0063b240 0063b240"); } void FUN_0063c060(int param_1) { generated_stub("FUN_0063c060 0063c060"); } void FamiliarHelper::fly_head_pathfind_move(Entity_Familiar *familiar) { generated_stub("FamiliarHelper::fly_head_pathfind_move 0063d570"); } void FUN_0063e180() { generated_stub("FUN_0063e180 0063e180"); } -void FUN_00640050() { generated_stub("FUN_00640050 00640050"); } -void FUN_006401d0() { generated_stub("FUN_006401d0 006401d0"); } -void FUN_006403f0() { generated_stub("FUN_006403f0 006403f0"); } void FamiliarAI::tinytoma(Entity_Familiar *familiar) { generated_stub("FamiliarAI::tinytoma 00642cb0"); } void FUN_006431b0() { generated_stub("FUN_006431b0 006431b0"); } void FamiliarAI::variant_204(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_204 00644780"); } -void FamiliarAI::lost_soul(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lost_soul 00645bc0"); } void FamiliarAI::lil_dumpy(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lil_dumpy 006468a0"); } void FamiliarAI::apollyons_best_friend(Entity_Familiar *familiar) { generated_stub("FamiliarAI::apollyons_best_friend 00647320"); } void anm2_apply_gfx_overrides(std_string *gfxSpec, std_string *unusedString, ANM2 *anm2) { generated_stub("anm2_apply_gfx_overrides 0064aab0"); } @@ -10364,8 +10326,6 @@ int level_get_room_neighbors(uint32_t roomIndex, uint32_t *outNeighbors) { gener int star_of_bethlehem_get_target_room() { generated_stub("star_of_bethlehem_get_target_room 0064d370"); } void FUN_0064d570(uint32_t param_1) { generated_stub("FUN_0064d570 0064d570"); } void FamiliarAI::star_of_bethlehem(Entity_Familiar *familiar) { generated_stub("FamiliarAI::star_of_bethlehem 0064d5f0"); } -void FamiliarAI::cube_baby(Entity_Familiar *familiar) { generated_stub("FamiliarAI::cube_baby 0064f860"); } -void FamiliarAI::blood_puppy(Entity_Familiar *familiar) { generated_stub("FamiliarAI::blood_puppy 0064fd40"); } void FamiliarAI::vanishing_twin(Entity_Familiar *familiar) { generated_stub("FamiliarAI::vanishing_twin 00650610"); } int apply_forgotten_lullaby(void *self, int fireDelay) { generated_stub("apply_forgotten_lullaby 00651810"); } int FUN_006518d0(uint32_t param_1) { generated_stub("FUN_006518d0 006518d0"); } @@ -10439,7 +10399,6 @@ uint8_t string_to_bool(void *self) { generated_stub("string_to_bool 0067f600"); void ResolveRelativePath(uint8_t *anmPath, uint8_t *relPath, uint8_t *outPath) { generated_stub("ResolveRelativePath 0067f670"); } void ExtractAngleBracketText() { generated_stub("ExtractAngleBracketText 0067fdf0"); } void FUN_00680060(size_t param_1) { generated_stub("FUN_00680060 00680060"); } -void FUN_00682260() { generated_stub("FUN_00682260 00682260"); } void shader_stack_push(int shaderIndex) { generated_stub("shader_stack_push 00682280"); } void FUN_00682350() { generated_stub("FUN_00682350 00682350"); } uint32_t checksum_stream(void *stream, int offset, int trailingSize) { generated_stub("checksum_stream 00683580"); } @@ -10659,7 +10618,6 @@ void FUN_007008b0(int *param_1) { generated_stub("FUN_007008b0 007008b0"); } void FUN_00703140() { generated_stub("FUN_00703140 00703140"); } void FUN_00704b50() { generated_stub("FUN_00704b50 00704b50"); } void FUN_007068f0(int param_1) { generated_stub("FUN_007068f0 007068f0"); } -void r_key_timer_callback() { generated_stub("r_key_timer_callback 00707ad0"); } Entity * spawn_chain_lightning(Vector *position, BitSet128 tearFlags, Entity *spawner, float damage) { generated_stub("spawn_chain_lightning 00707e10"); } uint32_t FUN_00708350() { generated_stub("FUN_00708350 00708350"); } void FUN_00708380() { generated_stub("FUN_00708380 00708380"); } @@ -10862,7 +10820,6 @@ uint32_t FUN_007da770() { generated_stub("FUN_007da770 007da770"); } uint32_t FUN_007dac30() { generated_stub("FUN_007dac30 007dac30"); } void FUN_007dad80() { generated_stub("FUN_007dad80 007dad80"); } int FUN_007dafb0() { generated_stub("FUN_007dafb0 007dafb0"); } -uint32_t _Entity_Player::SpawnTrinketRandomPickup() { generated_stub("_Entity_Player::SpawnTrinketRandomPickup 007dc2d0"); } void FUN_007dc610() { generated_stub("FUN_007dc610 007dc610"); } void FUN_007dc620(uint32_t *param_1) { generated_stub("FUN_007dc620 007dc620"); } void FUN_007dc650() { generated_stub("FUN_007dc650 007dc650"); } @@ -11016,7 +10973,6 @@ void FUN_008370b0() { generated_stub("FUN_008370b0 008370b0"); } uint32_t FUN_00837610() { generated_stub("FUN_00837610 00837610"); } void FUN_00837660(uint32_t param_1) { generated_stub("FUN_00837660 00837660"); } int FUN_00839070() { generated_stub("FUN_00839070 00839070"); } -void FUN_008391a0() { generated_stub("FUN_008391a0 008391a0"); } void sprite_member_at_0xc_destroy(void *self) { generated_stub("sprite_member_at_0xc_destroy 00839300"); } void list_anm2_state_assign(int *param_1) { generated_stub("list_anm2_state_assign 00839380"); } void FUN_00839830() { generated_stub("FUN_00839830 00839830"); } @@ -11043,7 +10999,6 @@ void ItemInfo::render_popup_callback(int param_1, uint32_t param_2) { generated_ void ItemInfo::render_line(uint8_t *param_1, Vector *param_2, int param_3) { generated_stub("ItemInfo::render_line 008404a0"); } char * FUN_00840510() { generated_stub("FUN_00840510 00840510"); } std_string * int_to_string(std_string *outString, int value) { generated_stub("int_to_string 00840540"); } -void FUN_0084a870(float *param_1) { generated_stub("FUN_0084a870 0084a870"); } void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4) { generated_stub("FUN_0084abc0 0084abc0"); } void FUN_0084bba0() { generated_stub("FUN_0084bba0 0084bba0"); } void FUN_0084bbc0(uint32_t *param_1) { generated_stub("FUN_0084bbc0 0084bbc0"); } @@ -11150,7 +11105,6 @@ uint32_t Catch_00863d4e() { generated_stub("Catch_00863d4e 00863d4e"); } uint32_t Catch_008641bb() { generated_stub("Catch_008641bb 008641bb"); } 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"); } uint32_t Catch_0086504e() { generated_stub("Catch_0086504e 0086504e"); } uint32_t Catch_0086512e() { generated_stub("Catch_0086512e 0086512e"); } @@ -13256,7 +13210,6 @@ void FUN_009a8a40() { generated_stub("FUN_009a8a40 009a8a40"); } void _player_hud_set_heart_anim_state(int param_1) { generated_stub("_player_hud_set_heart_anim_state 009a90b0"); } void move_directory_files() { generated_stub("move_directory_files 009a90e0"); } uint8_t delete_directory_recursive(uint8_t *path) { generated_stub("delete_directory_recursive 009a9250"); } -void Isaac::Shutdown() { generated_stub("Isaac::Shutdown 009ab700"); } void resources_mount_language() { generated_stub("resources_mount_language 009ab970"); } void FUN_009abd50() { generated_stub("FUN_009abd50 009abd50"); } void FUN_009ad470() { generated_stub("FUN_009ad470 009ad470"); } diff --git a/src/active_items.h b/src/active_items.h index 039f5de..392f4d5 100644 --- a/src/active_items.h +++ b/src/active_items.h @@ -115,10 +115,14 @@ bool is_item_target(Entity* entity, Entity_Player& player); void battery_effect_spawn(Entity_Player& player); void rebirth_item_effect_run(ItemUse& use); void repentance_item_effect_run(ItemUse& use); +void afterbirth_item_effect_run(ItemUse& use); +void d12_use(ItemUse& use); +void deeper_use(ItemUse& use); void active_missing_report(ItemUse& use); bool input_is_action_pressed(ButtonAction action, int controllerIndex, Entity* entity); bool input_is_action_triggered(ButtonAction action, int controllerIndex, Entity* entity); +float input_action_value_get(ButtonAction action, int controllerIndex, Entity* entity); bool is_active_usable(Entity_Player& player, int item, int slot); ChargeType active_charge_type(Entity_Player& player, int slot); bool is_active_slot_kept(Entity_Player& player, int slot); diff --git a/src/ambush.cpp b/src/ambush.cpp new file mode 100644 index 0000000..9bc37cc --- /dev/null +++ b/src/ambush.cpp @@ -0,0 +1,243 @@ +#include "ambush.h" +#include "entity_effect.h" +#include "entity_factory.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "log.h" +#include "manager.h" +#include "music_manager.h" +#include "npc_alt.h" +#include "platform.h" +#include "room_config.h" +#include "room_descriptor.h" +#include "room.h" +#include "room_clear.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include +#include + +// A wave's difficulty by wave (one later on Hard), the room subtypes of normal and boss waves, how often a wave is +// drawn again (the special rooms' stage the second time) before none is called, and the Death Certificate's +// dimension, whose waves come from Home. A layout entry of type 999 is an effect. +constexpr std::array AMBUSH_WAVE_DIFFICULTY = {1, 5, 10, 15}; +constexpr int WAVE_SUBTYPE_NORMAL = 10; +constexpr int WAVE_SUBTYPE_BOSS = 11; +constexpr int AMBUSH_WAVE_TRIES = 10; +constexpr int AMBUSH_HOME_DIMENSION = 2; +constexpr uint32_t WAVE_ENTRY_EFFECT = 999; + +// A challenge's three waves (two for bosses), 30 frames between them, and Door Stop's multiplier that keeps the +// entrance open. +constexpr int WAVES_NORMAL = 3; +constexpr int WAVES_BOSS = 2; +constexpr int WAVE_COUNTDOWN = 30; +constexpr int DOOR_STOP_BOSSRUSH = 2; +constexpr int DOOR_STOP_CHALLENGE = 3; + +// 008332e0 Copies the Boss Rush's waves and shuffles them by the room's spawn seed, drawing from the back. +// The original stops the game on a zero seed. Here the waves stay unshuffled. +void Ambush::shuffle_waves() +{ + RoomDescriptor* descriptor = g_game->room->descriptor; + uint32_t seed = descriptor ? descriptor->spawnSeed : 0; + + wavesLeft = bossRushWaves; + for (size_t left = wavesLeft.size(); left > 1 && seed != 0; left--) + { + seed ^= seed >> 1; + seed ^= seed << 5; + seed ^= seed >> 19; + std::swap(wavesLeft[left - 1], wavesLeft[seed % left]); + } +} + +// 00833420 Starts the room's fight unless it is done or running: the doors shut (Door Stop's doubled or tripled +// trinket keeps the entrance open), the secret doors take the plain open animation, its music plays and both RNGs +// are seeded from the room. +void Ambush::StartChallenge() +{ + Game& game = *g_game; + Room& room = *game.room; + if ((room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CHALLENGE_DONE) || isActive) return; + + isActive = true; + countdown = WAVE_COUNTDOWN; + currentWave = 0; + shuffle_waves(); + + Entity_Player* doorStopOwner = game.playerManager.FirstTrinketOwner(TRINKET_DOOR_STOP); + int doorStop = doorStopOwner ? doorStopOwner->GetTrinketMultiplier(TRINKET_DOOR_STOP) : 0; + bool isEntranceKept = (doorStop >= DOOR_STOP_BOSSRUSH && room.roomType == ROOM_BOSSRUSH) || + (doorStop >= DOOR_STOP_CHALLENGE && room.roomType == ROOM_CHALLENGE); + for (GridEntity_Door* door : room.doors) + { + if (!door || (game.enterDoor == door->slot && isEntranceKept) || door->state == DOOR_STATE_CLOSED) continue; + + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + for (int type : {door->currentRoomType, door->targetRoomType}) + { + bool isSecret = type == ROOM_SECRET || type == ROOM_SUPERSECRET || type == ROOM_ULTRASECRET; + if (isSecret) door->openAnimation = "Open"; + } + } + int music = room.roomType == ROOM_BOSSRUSH ? MUSIC_BOSS_RUSH : MUSIC_CHALLENGE_FIGHT; + g_manager->musicManager.Play(music, g_manager->optionsConfig.musicVolume); + + uint32_t seed = room.descriptor ? room.descriptor->spawnSeed : 0; + bossRushRng = {seed, 5, 9, 7}; + waveRng = {seed, 7, 17, 21}; +} + +// The challenge wave's layout entries by cell: up to ten draws of a challenge room of the wave's difficulty and the +// room's shape, falling back once to the special rooms' stage, each spawn picking one entry, transformed as the room +// would. +static std::vector> wave_entries_pick(Ambush& ambush) +{ + Game& game = *g_game; + Room& room = *game.room; + int difficultyIndex = ambush.currentWave - (game.difficulty != DIFFICULTY_HARD ? 1 : 0); + int difficulty = AMBUSH_WAVE_DIFFICULTY[std::clamp(difficultyIndex, 0, (int)AMBUSH_WAVE_DIFFICULTY.size() - 1)]; + int stageId = STAGE_ID_HOME; + if (game.challenge == CHALLENGE_RED_REDEMPTION) + stageId = RoomConfig::GetStageID(game.stage, game.GetRoomStageType(game.currentRoomIdx), ROOM_MODE_CURRENT); + else if (game.currentDimensionIdx != AMBUSH_HOME_DIMENSION) + stageId = RoomConfig::GetStageID(game.stage, game.stageType, ROOM_MODE_CURRENT); + bool isBossWave = room.descriptor->data->subtype == CHALLENGE_SUBTYPE_BOSS; + + std::vector> entries; + for (int tries = 0; entries.empty() && tries < AMBUSH_WAVE_TRIES; tries++) + { + RoomQuery query = {.shape = (RoomShape)room.GetRoomShape(), + .maxDifficulty = difficulty, + .minDifficulty = difficulty, + .stageId = stageId, + .subtype = isBossWave ? WAVE_SUBTYPE_BOSS : WAVE_SUBTYPE_NORMAL, + .type = ROOM_CHALLENGE}; + RoomConfig_Room* wave = game.roomConfig.GetRandomRoom(ambush.waveRng.Next(), WEIGHT_REDUCE, query); + if (!wave) + { + if (stageId == STAGE_ID_SPECIAL_ROOMS) + log_printf(LOG_ASSERT, "No enemy wave found for ambush (difficulty: %d)\n", difficulty); + stageId = STAGE_ID_SPECIAL_ROOMS; + continue; + } + + for (RoomSpawn& spawn : wave->spawns) + { + RoomEntry entry = *spawn.PickEntry(ambush.waveRng.RandomFloat()); + int column = spawn.x + 1; + int row = spawn.y + 1; + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cell = isInside ? row * room.gridWidth + column : -1; + room_entry_transform(room, entry, cell, ambush.waveRng.Next()); + if (entry.type < 1 || entry.type > WAVE_ENTRY_EFFECT) continue; + if (entry.type == WAVE_ENTRY_EFFECT) entry.type = ENTITY_EFFECT; + entries.push_back({cell, entry}); + } + } + return entries; +} + +// 00833600 Calls a challenge wave: its enemies rise from pentagrams on free cells near where the layout places them +// (anything else appears at once), with the summon's sound, and every player's locusts come out. +// The original crashes when the fallback stage has no wave either. Here it draws again. +void Ambush::SpawnWave() +{ + Game& game = *g_game; + Room& room = *game.room; + + for (auto& [cell, entry] : wave_entries_pick(*this)) + { + Vector free = room_free_tile_position_find(room.GetGridPosition(cell), 0); + uint32_t seed = waveRng.Next(); + EntitySpawn spawn = {.position = free, + .subType = entry.subtype, + .type = (int)entry.type, + .variant = entry.variant, + .seed = seed}; + + if (entry.type >= ENTITY_FIRST_ENEMY && entry.type < ENTITY_EFFECT) + { + pentagram_spawn(spawn, cell)->AddEntityFlags(FLAG_AMBUSH); + continue; + } + Entity* spawned = game.Spawn(spawn); + if (spawned->type == ENTITY_EFFECT) spawned->Update(); + spawned->spawnGridIndex = cell; + } + int sound = SOUND_SUMMON_PENTA; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + for (Entity_Player* player : game.playerManager.playerList) player->spawn_locusts(); +} + +// 00833c40 Calls a Boss Rush wave. +void Ambush::SpawnBossrushWave() +{ + reconstruction_missing("Ambush::SpawnBossrushWave 00833c40"); +} + +// 00834350 Runs the fight: 30 frames after a wave's enemies (the Boss Rush's bosses) are gone the next is called, the +// first of those frames counting as a room clear (twice in the Boss Rush) that ends Broken Shovel's stomps. Once +// every wave is beaten the room is done and cleared: its score, its music fades out to the outro, its reward drops +// and the doors open with their sound. A challenge has three waves (two for a boss challenge), the Boss Rush as many +// as ambush.xml says. +void Ambush::Update() +{ + Game& game = *g_game; + Room& room = *game.room; + RoomDescriptor& descriptor = *room.descriptor; + bool isBossRush = room.roomType == ROOM_BOSSRUSH; + int waves = maxWaves; + if (isBossRush && wavesLeft.empty()) maxWaves = currentWave; + if (!isBossRush) waves = descriptor.data->subtype == CHALLENGE_SUBTYPE_BOSS ? WAVES_BOSS : WAVES_NORMAL; + + if (countdown > 0) + { + if (room.GetAliveEnemiesCount() != 0 || isBossRush) + { + if (room.GetAliveBossesCount() > 0 || !isBossRush) return; + } + if (countdown == WAVE_COUNTDOWN && currentWave > 0 && currentWave < waves) + { + game.playerManager.trigger_room_clear(); + if (isBossRush) game.playerManager.trigger_room_clear(); + ItemConfig_Item* shovel = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BROKEN_SHOVEL_1); + for (Entity_Player* player : game.playerManager.playerList) + if (shovel) player->temporaryEffects.RemoveEffect(shovel, 1); + bossRushRng.Next(); + } + countdown--; + return; + } + + if (currentWave >= waves) + { + isActive = false; + descriptor.flags |= ROOM_DESCRIPTOR_FLAG_CHALLENGE_DONE; + game.scoreSheet.add_cleared_room({.clearCount = 1, + .shape = descriptor.data ? descriptor.data->shape : ROOMSHAPE_1x1, + .type = room.roomType, + .isRedRoom = (descriptor.flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM) != 0}); + MusicManager& music = g_manager->musicManager; + music.Crossfade(isBossRush ? MUSIC_JINGLE_BOSS_RUSH_OUTRO : MUSIC_JINGLE_CHALLENGE_OUTRO, MUSIC_FADE_RATE); + if (music.tracks.size() > MUSIC_BOSS_OVER) music.queuedMusicId = MUSIC_BOSS_OVER; + room_clear_award_spawn(room); + game.playerManager.trigger_room_clear(); + if (isBossRush) game.playerManager.trigger_room_clear(); + descriptor.flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; + + int sound = SOUND_DOOR_HEAVY_OPEN; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + return; + } + + countdown = WAVE_COUNTDOWN; + currentWave++; + isBossRush ? SpawnBossrushWave() : SpawnWave(); +} diff --git a/src/ambush.h b/src/ambush.h new file mode 100644 index 0000000..9a3f8af --- /dev/null +++ b/src/ambush.h @@ -0,0 +1,40 @@ +#pragma once + +#include "classes.h" +#include + +// A boss a Boss Rush spawn slot holds (ambush.xml): its type and variant, and the segments of a segmented boss. +struct BossRushEntry +{ + int chunks = 1; + int type = 0; + int variant = 0; +}; + +// A spawn slot's bosses, one of which a wave draws. +using BossRushWave = std::vector; + +// The original's copies, assignment and destruction are the defaults. +// A challenge room's or the boss rush's fight (Game::ambush, REPENTOGON's Ambush): StartChallenge shuts the doors and +// shuffles the boss rush's waves, then Update calls a wave 30 frames after the last one is beaten until all are, and +// clears the room with its reward. Each wave is drawn and placed by waveRng, the challenge's subtype picking normal +// or boss waves. ambush.xml gives the Boss Rush its spawn slots, its wave count (maxWaves) and the slots each wave +// takes (bossesPerWave). +struct Ambush +{ + std::vector bossRushWaves; + std::vector wavesLeft; + RNG bossRushRng{}; + RNG waveRng{}; + int bossesPerWave = 0; + int countdown = 0; + int currentWave = 0; + int maxWaves = 0; + bool isActive = false; + + void shuffle_waves(); + void StartChallenge(); + void SpawnWave(); + void SpawnBossrushWave(); + void Update(); +}; diff --git a/src/anm2.cpp b/src/anm2.cpp index 859b210..13af098 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -16,6 +16,16 @@ #include #include +// 00a15640 A value's place between inMin and inMax carried between outMin and outMax, logging an empty range. +float lerp_range(float value, const LerpRange& range) +{ + if (range.inMin == range.inMax) + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + float t = (value - range.inMin) / (range.inMax - range.inMin); + if (range.isClamped) t = std::clamp(t, 0.0f, 1.0f); + return (range.outMax - range.outMin) * t + range.outMin; +} + using simdjson::dom::array; using simdjson::dom::element; using simdjson::dom::object; @@ -35,6 +45,10 @@ constexpr std::string_view SHADOW_LAYER_NAME = "shadow"; constexpr std::string_view APPEAR_ANIMATION = "Appear"; constexpr std::string_view IDLE_ANIMATION = "Idle"; constexpr std::string_view CHAMPION_COLOR_UNIFORM = "ChampionColor"; +constexpr std::string_view COLOR_OFFSET_SHADER = "ColorOffset"; +constexpr std::string_view COLOR_OFFSET_CHAMPION_SHADER = "ColorOffsetChampion"; +constexpr std::string_view COLOR_OFFSET_DOGMA_SHADER = "ColorOffsetDogma"; +constexpr std::string_view COLOR_OFFSET_GOLD_SHADER = "ColorOffsetGold"; // Delirium's forms swap a boss's or monster's spritesheets for the ones under DELIRIUM_FORMS_FOLDER. constexpr int DELIRIUM_TYPE = 412; @@ -1208,6 +1222,21 @@ static KAGE::Graphics::BlendMode layer_blend_get(const LayerState& layer) (Factor)mode[BLEND_RGB_DEST], (Factor)mode[BLEND_ALPHA_SOURCE], (Factor)mode[BLEND_ALPHA_DEST]}; } +// 00682260 Makes the shader a layer's render flags ask for current, when it is loaded. +// A layer keeping its shader sets none and returns false. +static bool layer_shader_select(unsigned int flags) +{ + std::string_view name = COLOR_OFFSET_SHADER; + if (flags & ANIM_RENDER_COLOROFFSET_CHAMPION) name = COLOR_OFFSET_CHAMPION_SHADER; + else if (flags & ANIM_RENDER_STATIC) name = COLOR_OFFSET_DOGMA_SHADER; + else if (flags & ANIM_RENDER_GOLDEN) name = COLOR_OFFSET_GOLD_SHADER; + else if (flags & ANIM_RENDER_SHADER_KEPT) return false; + + KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.shader_find(name); + if (shader) KAGE::Graphics::manager.currentShader = shader; + return true; +} + // 00409120 Draws one keyframe of a layer track with the layer's spritesheet, colour, blending and shader. // The original reads past the sprite's layers for a track keying a missing layer. Here it draws nothing. void AnimationLayer::RenderFrame(const SpriteDraw& draw, int frameIndex, const ANM2& animation) const @@ -1245,8 +1274,7 @@ void AnimationLayer::RenderFrame(const SpriteDraw& draw, int frameIndex, const A tint._blue = color._tint[2]; tint._alpha = color._tint[3]; tint._unk = 0; - if (isChampion || isShimmering || !(flags & ANIM_RENDER_SHADER_KEPT)) - apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *layer.spriteSheet); + if (layer_shader_select(flags)) apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *layer.spriteSheet); if (isChampion) KAGE::Graphics::manager.currentShader->set_uniform(CHAMPION_COLOR_UNIFORM, KAGE::Graphics::UNIFORM_VEC4, &animation.championColor); diff --git a/src/anm2.h b/src/anm2.h index 819a8a0..22eac20 100644 --- a/src/anm2.h +++ b/src/anm2.h @@ -2,6 +2,7 @@ #include "classes.h" #include +#include #include #include #include @@ -100,6 +101,98 @@ inline Vector vector_make(float x, float y) return vector; } +// Vector math, Vector's own methods written as free functions. +constexpr float PI_F = 3.1415927f; +constexpr float DEGREES_TO_RADIANS = 0.017453292f; +constexpr float RADIANS_TO_DEGREES = 57.295776f; + +inline Vector vector_add(Vector a, Vector b) +{ + return vector_make(a.x + b.x, a.y + b.y); +} + +inline Vector vector_sub(Vector a, Vector b) +{ + return vector_make(a.x - b.x, a.y - b.y); +} + +inline Vector vector_scale(Vector v, float scale) +{ + return vector_make(v.x * scale, v.y * scale); +} + +inline float vector_dot(Vector a, Vector b) +{ + return a.x * b.x + a.y * b.y; +} + +inline float vector_length_squared(Vector v) +{ + return v.x * v.x + v.y * v.y; +} + +inline float vector_length(Vector v) +{ + return std::sqrt(v.x * v.x + v.y * v.y); +} + +inline bool vector_is_zero(Vector v) +{ + return v.x == 0 && v.y == 0; +} + +// Vector::Normalized: a unit vector along v, or v when it has no length. +inline Vector vector_normalized(Vector v) +{ + float length = vector_length(v); + return length > 0 ? vector_scale(v, 1 / length) : v; +} + +// Vector::Resized: v at a length, or v when it has none. +inline Vector vector_resized(Vector v, float length) +{ + float current = vector_length(v); + return current > 0 ? vector_scale(v, length / current) : v; +} + +// Vector::FromAngle 00a10350: the unit vector at an angle in degrees. +inline Vector vector_from_angle(float degrees) +{ + return vector_make(std::cos(degrees * DEGREES_TO_RADIANS), std::sin(degrees * DEGREES_TO_RADIANS)); +} + +// Vector::GetAngleDegrees 00a10390: a vector's angle in degrees. +inline float vector_angle(Vector v) +{ + return std::atan2(v.y, v.x) * RADIANS_TO_DEGREES; +} + +// Math::timescale_factor 00684cb0: how much of a per-tick factor is left over a step of timeScale ticks. +inline float timescale_factor(float factor, float timeScale) +{ + return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale); +} + +// A value's place in one range carried onto another (assert_lerp_range's arguments), held inside it when clamped. +struct LerpRange +{ + float inMin = 0; + float inMax = 1; + float outMin = 0; + float outMax = 1; + bool isClamped = true; +}; + +float lerp_range(float value, const LerpRange& range); + +// Vector::Rotated: v turned by an angle in degrees. +inline Vector vector_rotated(Vector v, float degrees) +{ + float cosine = std::cos(degrees * DEGREES_TO_RADIANS); + float sine = std::sin(degrees * DEGREES_TO_RADIANS); + return vector_make(v.x * cosine - v.y * sine, v.x * sine + v.y * cosine); +} + // The name prefix of a light pass layer. constexpr char LIGHT_LAYER_PREFIX = '*'; diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index 4b33956..4d5326a 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -277,7 +277,7 @@ void explosion_tear_flag_effects(const Explosion& explosion) } // 008207a0 Digs Mom's Shovel up when a bomb goes off in the first floor's start room while its quest is on. -static void shovel_quest_dig() +void shovel_quest_dig() { Game& game = *g_game; bool isQuestRoom = game.stage == 1 && (game.levelStateFlags & 1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED) && diff --git a/src/boss_ai.h b/src/boss_ai.h index 4c61d80..5e7dc36 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -115,6 +115,19 @@ Entity_Effect* following_effect_spawn(Entity& parent, const FollowingEffect& eff Entity_Player* game_random_player(Game& game, Vector position, float radius); std::string npc_sheet_path_get(Entity_NPC& npc, const std::string& path); + +// A leech thrown up out of the floor (Entity_NPC::ThrowLeech's arguments): from where to which spot, by what, the +// height it starts at, and whether it is a big one. +struct LeechThrow +{ + Vector position{}; + Vector target{}; + Entity* spawner = nullptr; + float height = 0; + bool isBig = false; +}; + +Entity_NPC* leech_throw(const LeechThrow& thrown); bool players_is_falling(); // A hurt dealt around a spot (Game::DamageRadius's arguments): its tear effects, where and from what, its flags and @@ -174,6 +187,9 @@ void boss_gemini_update(Entity_NPC& npc); void boss_gurdy_update(Entity_NPC& npc); void boss_gurdy_jr_update(Entity_NPC& npc); void boss_haunt_update(Entity_NPC& npc); +void boss_heretic_update(Entity_NPC& npc); +void npc_faceless_update(Entity_NPC& npc); +void npc_exorcist_update(Entity_NPC& npc); void boss_headless_horseman_update(Entity_NPC& npc); void boss_larry_jr_update(Entity_NPC& npc); void boss_little_horn_update(Entity_NPC& npc); @@ -183,6 +199,7 @@ void boss_mask_of_infamy_update(Entity_NPC& npc); void boss_mega_fatty_update(Entity_NPC& npc); void boss_mega_maw_update(Entity_NPC& npc); void boss_mom_update(Entity_NPC& npc); +void boss_pin_update(Entity_NPC& npc); void boss_mr_fred_update(Entity_NPC& npc); void boss_moms_heart_update(Entity_NPC& npc); void boss_moms_heart_death_shots(Entity_NPC& npc); @@ -192,6 +209,7 @@ void boss_pestilence_update(Entity_NPC& npc); void boss_polycephalus_update(Entity_NPC& npc); void boss_war_update(Entity_NPC& npc); void boss_widow_update(Entity_NPC& npc); +void boss_wormwood_update(Entity_NPC& npc); void boss_satan_update(Entity_NPC& npc); void boss_fallen_update(Entity_NPC& npc); void boss_music_crossfade(); diff --git a/src/boss_big_horn.cpp b/src/boss_big_horn.cpp index 812e8c3..a0658c2 100644 --- a/src/boss_big_horn.cpp +++ b/src/boss_big_horn.cpp @@ -226,14 +226,6 @@ void water_drops_spawn(const Vector& position, Vector radii, float speed) } } -// 009be990 NpcHelper::big_horn_is_any_hole_busy Whether a player is falling into a hole or down one. -static bool is_hole_busy() -{ - for (Entity_Player* player : g_game->playerManager.playerList) - if (player->pitfallState != PITFALL_NONE && player->pitfallState != PITFALL_CLIMBING) return true; - return false; -} - // Whether a position lies in a hole, its size stretched by its size multiplier. static bool is_in_hole(const Entity& hole, const Vector& position) { @@ -1099,7 +1091,7 @@ static void hole_helper_keep(Entity_NPC& npc) void boss_big_horn_update(Entity_NPC& npc) { int ticks = npc_ticks_get(npc); - bool isBusy = is_hole_busy(); + bool isBusy = players_is_falling(); hole_helper_keep(npc); if (npc.variant == BIG_HORN_HAND) diff --git a/src/boss_brownie.cpp b/src/boss_brownie.cpp index 876dc6f..afb2f34 100644 --- a/src/boss_brownie.cpp +++ b/src/boss_brownie.cpp @@ -464,7 +464,7 @@ static void brownie_steer(Entity_NPC& npc, BrownieFrame& frame) Vector pulled = vector_add(npc.velocity, vector_scale(vector_normalized(toward), speed * BROWNIE_STEER)); pulled = vector_add(pulled, vector_scale(vector_normalized(npc.velocity), speed * BROWNIE_STEER)); Vector wanted = vector_resized(pulled, speed); - float keep = npc_friction_scaled(BROWNIE_STEER_KEEP, npc.speedMultiplier); + float keep = timescale_factor(BROWNIE_STEER_KEEP, npc.speedMultiplier); npc.velocity = vector_add(vector_scale(vector_sub(wanted, npc.velocity), 1 - keep), npc.velocity); if (npc.state == BROWNIE_DASH || npc.state == BROWNIE_FAST_CHASE) diff --git a/src/boss_chub.cpp b/src/boss_chub.cpp index 20df22e..63ce9a6 100644 --- a/src/boss_chub.cpp +++ b/src/boss_chub.cpp @@ -625,7 +625,7 @@ void boss_chub_update(Entity_NPC& npc) npc.scale = health * CHAD_SCALE_HEALTH + CHAD_SCALE_BASE; float size = npc.scale * npc.shrinkStatus1; npc.sprite.scale = vector_make(size, size); - npc.velocity.x *= npc_friction_scaled(CHAD_DRAG_BASE - health * CHAD_DRAG_HEALTH, npc.speedMultiplier); + npc.velocity.x *= timescale_factor(CHAD_DRAG_BASE - health * CHAD_DRAG_HEALTH, npc.speedMultiplier); } if (npc.isDead) chub_death(npc); diff --git a/src/boss_death.cpp b/src/boss_death.cpp index 308b764..566482d 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -47,7 +47,6 @@ constexpr int MINIBOSS_ID_LIMIT = 16; constexpr int EFFECT_POOF04 = 17; constexpr int EFFECT_BLOOD_GUSH = 42; -constexpr int EFFECT_LARGE_BLOOD_EXPLOSION = 77; constexpr int COLLECTIBLE_QUARTER = 74; constexpr int COLLECTIBLE_FOREVER_ALONE = 128; @@ -440,7 +439,7 @@ static void boss_death_rewards(Room& room, Entity_NPC& boss, RNG& rng, bool isGr boss_log("deathspawn_boss, color idx %d\n", boss.bosscoloridx); int music = g_manager->musicManager.currentMusicId; bool isBossMusic = music == MUSIC_BOSS || music == MUSIC_BOSS2 || music == MUSIC_BOSS3; - if ((roomType == ROOM_BOSS || roomType == ROOM_ANGEL || isBossMusic) && !game.ambush._isActive && + if ((roomType == ROOM_BOSS || roomType == ROOM_ANGEL || isBossMusic) && !game.ambush.isActive && (!game.IsGreedMode() || roomType != ROOM_DEFAULT)) victory_jingle_play(room, true); @@ -582,6 +581,7 @@ static void miniboss_death_rewards(Room& room, Entity_NPC& boss, RNG& rng, bool // 007fec00 A boss leaving for good: counts it off the room's bosses (once, never a friendly one or one that does not // count), and the last one gives the room's rewards, a miniboss's or a boss's, then moves the room's death seed on. +// In a challenge or the Boss Rush the rewards are drawn from the fight's seed instead, and the room's stays. // Big Horn's holes never count. Uriel's and Gabriel's key pieces are not reconstructed yet. void Room::TriggerBossDeath(Entity_NPC& boss) { @@ -599,18 +599,20 @@ void Room::TriggerBossDeath(Entity_NPC& boss) bossesRemaining--; if (bossesRemaining <= 0) { - if (game.ambush._isActive) reconstruction_missing("Room::TriggerBossDeath 007fec00: an ambush's death seed"); - - RNG rng = rng_make(DEATH_RNG_SHIFTS, descriptor->bossDeathSeed); + bool isAmbush = game.ambush.isActive; + RNG rng = rng_make(DEATH_RNG_SHIFTS, isAmbush ? game.ambush.bossRushRng._seed : descriptor->bossDeathSeed); bool isMiniboss = (boss.type >= ENTITY_SLOTH && boss.type <= ENTITY_PRIDE) || (boss.type == ENTITY_FALLEN && boss.variant == VARIANT_KRAMPUS) || (boss.type == ENTITY_BABY && boss.variant == VARIANT_ULTRA_PRIDE); if (isMiniboss) miniboss_death_rewards(*this, boss, rng, isGreedWave); else boss_death_rewards(*this, boss, rng, isGreedWave); - RNG seedRng; - seedRng.game_constructor(descriptor->bossDeathSeed, DEATH_SEED_SHIFT_INDEX); - descriptor->bossDeathSeed = seedRng.Next(); + if (!isAmbush) + { + RNG seedRng; + seedRng.game_constructor(descriptor->bossDeathSeed, DEATH_SEED_SHIFT_INDEX); + descriptor->bossDeathSeed = seedRng.Next(); + } } bool isAngel = boss.type == ENTITY_URIEL || boss.type == ENTITY_GABRIEL; diff --git a/src/boss_gideon.cpp b/src/boss_gideon.cpp index 85d917b..51e5456 100644 --- a/src/boss_gideon.cpp +++ b/src/boss_gideon.cpp @@ -5,6 +5,7 @@ #include "entity_laser.h" #include "entity_player.h" #include "grid_entity.h" +#include "grid_entity_stairs.h" #include "loot_list.h" #include "manager.h" #include "music_manager.h" @@ -120,7 +121,6 @@ constexpr float DEATH_DUST_SPEED = 5; constexpr float DEATH_EXPLOSION_SCALE = 2; constexpr int GIDEON_DEATH_SHAKE = 14; constexpr int GIDEON_ROCK_PARTICLE_SUBTYPE = 7; -constexpr int STAIRS_GIDEON = 1; constexpr int STAIRS_PATH = 900; // The waves: challenge rooms of subtype 12 of the stage (else the special rooms), harder each wave (1, 5, 5, 10, 10 diff --git a/src/boss_heretic.cpp b/src/boss_heretic.cpp new file mode 100644 index 0000000..3233218 --- /dev/null +++ b/src/boss_heretic.cpp @@ -0,0 +1,988 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "loot_list.h" +#include "npc_fireplace.h" +#include "path_finder.h" +#include +#include + +// The Heretic's states: its summoning, hidden while its Exorcists live, fading back, pointing at the put out fires to +// light them, its beams through them, its dash off screen and charges across it (and their afterimages), the arcing +// shots and dive bomb, and the end of its death. +constexpr int HERETIC_IDLE = NPC_STATE_IDLE; +constexpr int HERETIC_HIDDEN = NPC_STATE_MOVE; +constexpr int HERETIC_REAPPEARING = NPC_STATE_SUICIDE; +constexpr int HERETIC_SUMMONING = NPC_STATE_JUMP; +constexpr int HERETIC_POINTING = NPC_STATE_STOMP; +constexpr int HERETIC_BEAMS = NPC_STATE_ATTACK; +constexpr int HERETIC_EXITING = NPC_STATE_ATTACK2; +constexpr int HERETIC_CHARGING = NPC_STATE_ATTACK3; +constexpr int HERETIC_DASHING = NPC_STATE_ATTACK4; +constexpr int HERETIC_CHARGE_END = NPC_STATE_ATTACK5; +constexpr int HERETIC_AFTERIMAGE = NPC_STATE_SUMMON; +constexpr int HERETIC_LOBBING = NPC_STATE_SUMMON2; +constexpr int HERETIC_DIVEBOMB = NPC_STATE_SUMMON3; +constexpr int HERETIC_EXPLODING = 100; +constexpr int HERETIC_BOSS_ID = 81; + +// Its byte counters: projectileCooldown holds the fires to light, the attack's repeats and the side it charges from, +// projectileDelay the cooldowns of the lobs, the dash and the beams, counted down every 10 frames. +constexpr int COUNT_FIRES = 0; +constexpr int COUNT_REPEATS = 1; +constexpr int COUNT_SIDE = 2; +constexpr int COOLDOWN_LOBS = 1; +constexpr int COOLDOWN_DASH = 2; +constexpr int COOLDOWN_BEAMS = 3; +constexpr int COOLDOWN_COUNT = 4; +constexpr int COOLDOWN_STEP = 10; +constexpr int LOB_COOLDOWN = 30; +constexpr int DASH_COOLDOWN = 9; +constexpr int HERETIC_BEAMS_COOLDOWN = 12; + +// Its idle wait, and the attacks' weights. +constexpr int HERETIC_IDLE_WAIT = 60; +constexpr int IDLE_WAIT_HURT = 30; +constexpr int ATTACK_WEIGHT = 10; +constexpr int IDLE_WEIGHT = 1; +constexpr int BEAMS_MIN_OUT_FIRES = 3; +constexpr int FIRES_TO_LIGHT = 5; +constexpr float HERETIC_FADE_STEP = 0.04f; +constexpr float HIDDEN_ALPHA = 0.4f; +constexpr float FRICTION = 0.8f; +constexpr float HERETIC_FIRE_OUT_HEALTH = 1.5f; +constexpr int FIRE_LIT_STATE = NPC_STATE_ATTACK2; + +// The pentagram the Exorcists summon at, as five points about the Heretic. +constexpr std::array, 5> PENTAGRAM_POINTS = { + {{72.30769f, -55.38462f}, {-72.30769f, -55.38462f}, {-120, 13.846154f}, {0, 61.538464f}, {120, 13.846154f}}}; +constexpr int HERETIC_EXORCIST_VARIANT = 1; +constexpr int EXORCIST_SUMMONING = NPC_STATE_SPECIAL; +constexpr int EXORCIST_WAKE_MIN = 1; +constexpr int EXORCIST_WAKE_RANGE = 15; + +// Pointing at a fire: it picks the one far from the last lit, on a line across the player's path, not under a player. +constexpr float POINT_SCORE_RANDOM = 500; +constexpr float POINT_NEAR_PLAYER_SQUARED = 30; +constexpr float POINT_NEAR_PLAYER_PENALTY = -1000; +constexpr float POINT_TURN_PENALTY = 400; +constexpr float POINT_BEST_START = -1e10f; +constexpr float HERETIC_QUARTER_TURN = 1.5707964f; +constexpr int POINT_HURT_FIRES = 3; +constexpr float POINT_FRAME_FAST = 5; +constexpr float POINT_FRAME_SLOW = 3; + +// The beams run from fire to fire, the last one on to the wall. +constexpr int HERETIC_BEAM_FRAMES = 40; +constexpr float HERETIC_BEAM_HEIGHT = -35; +constexpr float LONE_BEAM_HEIGHT = -20; +constexpr float LONE_BEAM_ANGLE = 90; +constexpr float HERETIC_BEAM_DEPTH = 1000; +constexpr ColorMod BEAM_COLOR = {{1, 1, 1, 1}, {0.8f, 0.1f, 1, 1}, {0.18f, 0, 0.22f}}; + +// The dash off the screen and the charges across it. +constexpr float EXIT_RAMP = 15; +constexpr float EXIT_ACCEL = 2.4f; +constexpr float EXIT_ACCEL_MIN = 0.1f; +constexpr float OFF_ROOM_MARGIN = -80; +constexpr float CHARGE_EDGE = 80; +constexpr float HERETIC_CHARGE_LEAD = 0.08f; +constexpr float CHARGE_EDGE_MARGIN = 10; +constexpr float CHARGE_SPEED_START = 10; +constexpr float CHARGE_PUSH = 6; +constexpr float CHARGE_STEER = 0.3f; +constexpr float CHARGE_STEER_MIN = 15; +constexpr float CHARGE_FADE = 0.08f; +constexpr float CHARGE_FADE_FAST = 0.16f; +constexpr float CHARGE_STOP = 120; +constexpr int CHARGES_FAST_FADE = 5; +constexpr int CHARGES_MAX = 4; +constexpr int CHARGES_DASH_LAST = 4; +constexpr int DASH_ODDS = 3; +constexpr float DASH_FADE_IN = 0.12f; +constexpr float DASH_ALPHA = 0.5f; +constexpr float DASH_FADE_OUT = 0.06f; +constexpr int DASH_VISIBLE_FRAMES = 10; +constexpr int HERETIC_DASH_FRAMES = 30; +constexpr float BRAKE_PUSH = 6.5f; +constexpr float BRAKE_DRIFT = 0.3f; +constexpr int BRAKE_FRAMES = 10; +constexpr int BRAKE_SHAKE = 8; +constexpr float AFTERIMAGE_PUSH = 6; +constexpr float AFTERIMAGE_ACCEL_MIN = 0.5f; +constexpr int AFTERIMAGE_OF_DASH = 2; + +// The lobs: six arcing fireballs aimed at the player's spot, marked by a target, then the dive bomb onto the player +// (within 300) that rings it with fire. +constexpr int LOBS = 6; +constexpr float LOB_HEIGHT = 25; +constexpr float LOB_SCALE = 2; +constexpr float LOB_FALL_ACCEL = 1.5f; +constexpr float LOB_FALL_SPEED = -60; +constexpr ColorMod LOB_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.2f, 0.3f, 1}}; +constexpr float LOB_LIFT = -5; +constexpr float LOB_SPEED_START = 3; +constexpr float LOB_SPEED_STEP = 4; +constexpr float LOB_DRAG = 0.9f; +constexpr float LOB_DRAG_SCALE = -9.491221f; +constexpr float LOB_TIME_MIN = 0.01f; +constexpr float LOB_ACCEL_SCALE = 10; +constexpr float LOB_STEP_SHRINK = -0.5f; +constexpr float LOB_STEP_MIN = 0.06125f; +constexpr int LOB_TRIES = 20; +constexpr int LOB_TARGET_SUBTYPE = 10; +constexpr float LOB_POOF_HEIGHT = -25; +constexpr float LOB_POOF_DEPTH = 4; +constexpr ColorMod HERETIC_PURPLE = {{0.8f, 0.3f, 1, 1}, {0, 0, 0, 0}, {0.15f, 0, 0.2f}}; +constexpr float DIVE_REACH = 300; +constexpr float DIVE_MARGIN = 10; +constexpr int DIVE_START = 18; +constexpr float DIVE_ACCEL = 0.011f; +constexpr float DIVE_FRICTION = 0.5f; +constexpr int DIVE_HIDE_FRAME = 32; +constexpr int DIVE_SHAKE = 12; +constexpr ColorMod DIVE_POOF_COLOR = {{0.62f, 0.62f, 0.62f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int FLAME_SOUND_DELAY = 45; +constexpr int DIVE_FLAMES = 8; +constexpr float DIVE_FLAME_STEP = 45; +constexpr float DIVE_LANDED_FRICTION = 0.4f; +constexpr int DIVE_RUMBLE_SHAKE = 4; + +// Its death: four flames at its feet, or in its long death, purple explosions about it and two flames at a time. +constexpr int DEATH_FLAMES = 4; +constexpr float DEATH_FLAME_STEP = 90; +constexpr float DEATH_FLAME_OFFSET = 27.692308f; +constexpr float EXPLOSION_SPREAD = 80; +constexpr ColorMod EXPLOSION_COLOR = {{1, 1, 1, 1}, {0.8f, 0.2f, 1, 1}, {0, 0, 0}}; +constexpr float HERETIC_EXPLOSION_DAMAGE = 40; +constexpr float HERETIC_EXPLOSION_RADIUS = 60; +constexpr int EXPLOSION_SHAKE = 8; +constexpr int HERETIC_DEATH_SHAKE = 40; +constexpr int DEATH_FLAME_EVERY = 2; +constexpr int DEATH_FLAME_PAIR = 2; +constexpr float HERETIC_FULL_TURN = 360; + +// The byte counters packed into the NPC's ints. +static int byte_get(int value, int index) +{ + return (int8_t)((uint32_t)value >> (index * 8)); +} + +static void byte_set(int& value, int index, int byte) +{ + uint32_t mask = 0xffu << (index * 8); + value = (int)(((uint32_t)value & ~mask) | ((uint32_t)(uint8_t)byte << (index * 8))); +} + +// stateFrame holds the attack's timer in its low half and the idle wait in its high half. +static int timer_get(const Entity_NPC& npc) +{ + return (short)npc.stateFrame; +} + +static void timer_set(Entity_NPC& npc, int timer) +{ + npc.stateFrame = (int)(((uint32_t)npc.stateFrame & 0xffff0000u) | (uint16_t)timer); +} + +static int idle_get(const Entity_NPC& npc) +{ + return (short)((uint32_t)npc.stateFrame >> 16); +} + +static void idle_set(Entity_NPC& npc, int idle) +{ + npc.stateFrame = (int)(((uint32_t)(uint16_t)idle << 16) | ((uint32_t)npc.stateFrame & 0xffffu)); +} + +static bool is_hurt(const Entity_NPC& npc) +{ + float half = npc.maxHitPoints * 0.5f; + return npc.health < half; +} + +static bool is_anim_done(const Entity_NPC& npc) +{ + return !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; +} + +static float side_sign(const Entity_NPC& npc) +{ + return byte_get(npc.projectileCooldown, COUNT_SIDE) == 0 ? -1.0f : 1.0f; +} + +// A purple flame at the Heretic's feet, turned to an angle. +static void flame_spawn(Entity_NPC& npc, const Vector& position, float rotation) +{ + auto* flame = static_cast(g_game->Spawn({.position = position, + .spawner = &npc, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_FIRE_WAVE, + .seed = Random()})); + flame->parent = &npc; + flame->rotation = rotation; +} + +// 004b3ec0 The purple fires put out. +static std::vector fires_out_get() +{ + std::vector fires; + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_FIREPLACE && entity->variant == FIRE_PURPLE && + entity->health < HERETIC_FIRE_OUT_HEALTH) + fires.push_back(entity); + return fires; +} + +// 004b3f10 Its five Exorcists rise at the points of its pentagram, kept in its deque. +static void exorcists_summon(Entity_NPC& npc) +{ + npc.ClearDequeRefs(); + for (int i = 0; i < (int)PENTAGRAM_POINTS.size(); i++) + { + Vector point = vector_make(PENTAGRAM_POINTS[i][0] + npc.pos.x, PENTAGRAM_POINTS[i][1] + npc.pos.y); + auto* exorcist = static_cast(g_game->Spawn({.position = point, + .spawner = &npc, + .subType = i + 1, + .type = ENTITY_EXORCIST, + .variant = HERETIC_EXORCIST_VARIANT, + .seed = Random()})); + exorcist->ClearEntityFlags(FLAG_APPEAR); + exorcist->Update(); + exorcist->state = EXORCIST_SUMMONING; + exorcist->targetPosition = point; + exorcist->sprite.overlayAnimState.SetAnimationData(nullptr); + exorcist->Update(); + npc.entityDeque.emplace_back(); + npc.entityDeque.back() = exorcist; + } +} + +// 004b40d0 Its next move after idling: lobs, the dash and the beams when off cooldown (the beams with three fires +// out), or more idling. +static void attack_pick(Entity_NPC& npc) +{ + int firesOut = (int)fires_out_get().size(); + WeightedOutcomePicker picker; + if (byte_get(npc.projectileDelay, COOLDOWN_LOBS) < 1) picker.AddOutcomeWeight(HERETIC_LOBBING, ATTACK_WEIGHT); + if (byte_get(npc.projectileDelay, COOLDOWN_DASH) < 1) picker.AddOutcomeWeight(HERETIC_EXITING, ATTACK_WEIGHT); + if (byte_get(npc.projectileDelay, COOLDOWN_BEAMS) < 1 && firesOut >= BEAMS_MIN_OUT_FIRES) + picker.AddOutcomeWeight(HERETIC_POINTING, ATTACK_WEIGHT); + picker.AddOutcomeWeight(HERETIC_IDLE, IDLE_WEIGHT); + + int picked = picker.PickOutcome({Random() | 1, 5, 9, 7}); + if (picked == HERETIC_IDLE) return idle_set(npc, 0); + + timer_set(npc, -1); + npc.state = picked; + if (picked == HERETIC_POINTING) + { + npc.ClearDequeRefs(); + npc.child = nullptr; + byte_set(npc.projectileCooldown, COUNT_FIRES, FIRES_TO_LIGHT + (is_hurt(npc) ? 1 : 0)); + } + byte_set(npc.projectileCooldown, COUNT_REPEATS, 0); +} + +// 004b3d50 A charge starts at the far edge level with where the player will be, from the side it left by. One in +// three of the late charges of a hurt Heretic is a dash. +static void charge_start(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Entity* player = npc.GetPlayerTarget(); + byte_set(npc.projectileCooldown, COUNT_REPEATS, byte_get(npc.projectileCooldown, COUNT_REPEATS) + 1); + bool isFromLeft = byte_get(npc.projectileCooldown, COUNT_SIDE) == 0; + npc.state = HERETIC_CHARGING; + npc.pos.x = isFromLeft ? room.bottomRightPos.x + CHARGE_EDGE : room.topLeftPos.x - CHARGE_EDGE; + npc.pos.y = player->pos.y; + + float distance = vector_length(vector_sub(npc.pos, player->pos)); + float y = distance * HERETIC_CHARGE_LEAD * player->velocity.y + player->pos.y; + y = std::max(y, room.topLeftPos.y + CHARGE_EDGE_MARGIN); + npc.pos.y = std::min(y, room.bottomRightPos.y - CHARGE_EDGE_MARGIN); + npc.velocity = vector_make(isFromLeft ? -CHARGE_SPEED_START : CHARGE_SPEED_START, 0); + npc.entityCollisionClass = ENTCOLL_ALL; + + bool isLate = byte_get(npc.projectileCooldown, COUNT_REPEATS) == CHARGES_DASH_LAST && is_hurt(npc); + if (isLate && Random() % DASH_ODDS == 0) + { + timer_set(npc, 0); + npc.state = HERETIC_DASHING; + npc.entityCollisionClass = ENTCOLL_NONE; + return; + } + timer_set(npc, 0); +} + +// 004b3af0 A fading copy of it left behind as it charges or dashes on. +static void afterimage_spawn(Entity_NPC& npc) +{ + auto* image = + static_cast(g_game->Spawn({.position = npc.pos, + .velocity = npc.velocity, + .spawner = &npc, + .subType = npc.state == HERETIC_DASHING ? AFTERIMAGE_OF_DASH : 1, + .type = ENTITY_HERETIC, + .seed = npc.initSeed})); + image->flags = npc.flags; + image->colorParams = npc.colorParams; + image->AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + image->isInvincible = true; + if (npc.sprite.animState.animData) image->sprite.Play(npc.sprite.GetAnimation()); + if (image->sprite.animState.animData) image->sprite.animState.SetFrameFloat(npc.sprite.animState.animFrame); + image->sprite.GetLayer(0)->color._tint[3] = npc.sprite.GetLayer(0)->color._tint[3]; + image->entityGridCollisionClass = GRIDCOLL_NONE; + image->entityCollisionClass = ENTCOLL_NONE; + image->state = HERETIC_AFTERIMAGE; + byte_set(image->projectileCooldown, COUNT_SIDE, byte_get(npc.projectileCooldown, COUNT_SIDE)); + timer_set(*image, 0); + image->health = 0; + image->maxHitPoints = 0; + image->Update(); +} + +// Its intro: in its own boss room it hides behind its pentagram and summons the Exorcists. +static void heretic_init(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.state = HERETIC_IDLE; + if (room.roomType == ROOM_BOSS && room.bossId == HERETIC_BOSS_ID && npc.spawnGridIndex >= 0) + { + npc.isVisible = false; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.isInvincible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + exorcists_summon(npc); + g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HERETIC_PENTAGRAM, .seed = Random()}); + npc.shadowSize = 0; + npc.targetPosition = npc.pos; + npc.state = HERETIC_SUMMONING; + } + npc.projectileDelay = 0; + npc.aiCallFlags |= AI_CALL_PRE_UPDATE; +} + +// The summoning: it shows itself, roars and wakes its Exorcists one by one, then hides. +static void summoning_update(Entity_NPC& npc) +{ + npc.isVisible = true; + npc.sprite.Play("Summoning"); + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_GHOST_ROAR, 1, 2, false, 1); + for (size_t i = 0; i < npc.entityDeque.size(); i++) + { + Entity* linked = npc.entityDeque[i]; + bool isVersusPlayer = g_game->deathmatchManager.is_active() && linked && linked->type == ENTITY_PLAYER; + if (linked && (isVersusPlayer || Entity::is_enemy_type(linked->type))) + static_cast(linked)->stateFrame = + (int)(Random() % EXORCIST_WAKE_RANGE) + EXORCIST_WAKE_MIN; + } + } + if (!is_anim_done(npc)) return; + + npc.state = HERETIC_HIDDEN; + npc.targetPosition = vector_make(0, 0); +} + +// Pointing: it picks the next put out fire, points at it and lights it, until it has lit enough or none are out. +static Entity* fire_pick(Entity_NPC& npc) +{ + std::vector fires = fires_out_get(); + Vector chainEnd = npc.pos; + Vector chainHeading{}; + size_t count = npc.entityDeque.size(); + if (count > 0) + { + chainEnd = npc.entityDeque[count - 1]->pos; + chainHeading = count == 1 ? vector_sub(npc.entityDeque[0]->pos, npc.pos) + : vector_sub(npc.entityDeque[count - 1]->pos, npc.entityDeque[count - 2]->pos); + } + Vector toPlayer = vector_sub(npc.GetPlayerTarget()->pos, chainEnd); + if (fires.empty()) return nullptr; + + float cosine = std::cos(HERETIC_QUARTER_TURN); + float sine = std::sin(HERETIC_QUARTER_TURN); + Entity* best = nullptr; + float bestScore = POINT_BEST_START; + for (Entity* fire : fires) + { + Entity_Player* nearest = game_nearest_player(fire->pos); + Vector fromPlayer = vector_sub(fire->pos, nearest->pos); + float penalty = fromPlayer.y * fromPlayer.y + fromPlayer.x * fromPlayer.x <= POINT_NEAR_PLAYER_SQUARED + ? POINT_NEAR_PLAYER_PENALTY + : 0; + Vector fromEnd = vector_sub(chainEnd, fire->pos); + float score = std::sqrt(fromEnd.y * fromEnd.y + fromEnd.x * fromEnd.x); + score = score + (random_unit() * POINT_SCORE_RANDOM - POINT_SCORE_RANDOM / 2 + penalty); + + Vector toFire = vector_sub(fire->pos, chainEnd); + Vector heading = vector_normalized(toFire); + float across = + (heading.x * sine + heading.y * cosine) * toPlayer.y + (heading.x * cosine - heading.y * sine) * toPlayer.x; + score -= std::abs(across); + if (!vector_is_zero(chainHeading)) + score -= + std::abs(vector_dot(vector_normalized(chainHeading), vector_normalized(toFire))) * POINT_TURN_PENALTY; + if (score <= bestScore) continue; + + best = fire; + bestScore = score; + } + return best; +} + +static void pointing_update(Entity_NPC& npc) +{ + if (npc.child && npc.child->type != ENTITY_FIREPLACE) npc.child = nullptr; + if (!npc.child && !npc.sprite.WasEventTriggered("Shoot")) + { + Entity* fire = fire_pick(npc); + if (!fire) + { + if (npc.entityDeque.empty()) + { + idle_set(npc, 0); + npc.state = HERETIC_IDLE; + } + else npc.state = HERETIC_BEAMS; + return; + } + + npc.child = fire; + Vector toFire = vector_sub(fire->pos, npc.pos); + std::string_view anim = std::abs(toFire.x) <= std::abs(toFire.y) ? "PointDown" + : toFire.x >= 0 ? "PointRight" + : "PointLeft"; + npc.sprite.Play(anim, PLAY_FORCED); + bool isFast = npc.entityDeque.size() >= POINT_HURT_FIRES || + (is_hurt(npc) && byte_get(npc.projectileCooldown, COUNT_REPEATS) > 0); + bool isSlow = is_hurt(npc) && !isFast; + if ((isFast || isSlow) && npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat(isFast ? POINT_FRAME_FAST : POINT_FRAME_SLOW); + } + + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + auto* fire = static_cast(npc.child.get()); + if (fire && fire->type == ENTITY_FIREPLACE) + { + fire->state = FIRE_LIT_STATE; + fire->Update(); + npc.entityDeque.emplace_back(); + npc.entityDeque.back() = fire; + } + npc.child = nullptr; + } + if (npc.sprite.animState.isPlaying) return; + } + + if ((int)npc.entityDeque.size() < (uint8_t)byte_get(npc.projectileCooldown, COUNT_FIRES) && + !fires_out_get().empty()) + return npc.sprite.Play("Idle"); + npc.state = HERETIC_BEAMS; +} + +// The beams: from it through each lit fire in turn, the fires going out as the beams pass, the last beam on to the +// wall. Without fires one beam goes straight down. +static void beams_update(Entity_NPC& npc) +{ + npc.sprite.Play("Attack1"); + if (vector_is_zero(npc.targetPosition)) npc.targetPosition = npc.pos; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_GHOST_ROAR, 1, 2, false, 1); + Vector from = npc.pos; + Entity_Laser* beam = nullptr; + for (size_t i = 0; i < npc.entityDeque.size(); i++) + { + Entity* fire = npc.entityDeque[i]; + bool isVersusPlayer = g_game->deathmatchManager.is_active() && fire && fire->type == ENTITY_PLAYER; + if (!fire || !(isVersusPlayer || Entity::is_enemy_type(fire->type)) || + fire->health < HERETIC_FIRE_OUT_HEALTH) + continue; + + Vector toFire = vector_sub(fire->pos, from); + fire->isDead = true; + fire->Update(); + beam = Entity_Laser::ShootAngle({.position = from, + .posOffset = vector_make(0, HERETIC_BEAM_HEIGHT), + .source = &npc, + .angleDegrees = std::atan2(toFire.y, toFire.x) * RADIANS_TO_DEGREES, + .timeout = HERETIC_BEAM_FRAMES, + .variant = 1}); + beam->maxDistance = std::sqrt(toFire.y * toFire.y + toFire.x * toFire.x); + beam->SetColor(BEAM_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + beam->renderDepthOffset = HERETIC_BEAM_DEPTH; + from = fire->pos; + } + if (beam) beam->maxDistance = 0; + else + { + Entity_Laser* lone = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = vector_make(0, LONE_BEAM_HEIGHT), + .source = &npc, + .angleDegrees = LONE_BEAM_ANGLE, + .timeout = HERETIC_BEAM_FRAMES, + .variant = 1}); + lone->SetColor(BEAM_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + } + if (!is_anim_done(npc)) return; + + int repeats = byte_get(npc.projectileCooldown, COUNT_REPEATS) + 1; + byte_set(npc.projectileCooldown, COUNT_REPEATS, repeats); + npc.ClearDequeRefs(); + if (!is_hurt(npc) || repeats != 1) + { + npc.targetPosition = vector_make(0, 0); + byte_set(npc.projectileDelay, COOLDOWN_BEAMS, HERETIC_BEAMS_COOLDOWN); + idle_set(npc, 0); + npc.state = HERETIC_IDLE; + return; + } + npc.state = HERETIC_POINTING; +} + +// Its dash off the screen to the nearer side, fading as it speeds up, then the first charge. +static void exiting_update(Entity_NPC& npc, float& alpha, int ticks) +{ + if (timer_get(npc) == -1) + { + float middle = (g_game->room->bottomRightPos.x + g_game->room->topLeftPos.x) * 0.5f; + byte_set(npc.projectileCooldown, COUNT_SIDE, npc.pos.x >= middle ? 1 : 0); + } + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.sprite.Play(byte_get(npc.projectileCooldown, COUNT_SIDE) == 0 ? "ExitLeft" : "ExitRight"); + float sm = npc.speedMultiplier; + alpha = std::max(alpha - sm * HERETIC_FADE_STEP, 0.0f); + if (alpha < 0.5f) npc.entityCollisionClass = ENTCOLL_NONE; + + float ramp = std::min(std::max((float)timer_get(npc) / EXIT_RAMP, 0.0f), 1.0f); + float accel = ramp * ramp * EXIT_ACCEL + EXIT_ACCEL_MIN; + npc.velocity = vector_make(side_sign(npc) * accel * sm + npc.velocity.x, accel * 0 * sm + npc.velocity.y); + if (alpha <= 0 && !g_game->room->IsPositionInRoom(npc.pos, OFF_ROOM_MARGIN)) + { + npc.SetCollisionDamage(2); + byte_set(npc.projectileCooldown, COUNT_REPEATS, 0); + charge_start(npc); + } + timer_set(npc, timer_get(npc) + ticks); +} + +// A charge across the room at the player's height, fading in, braking near the player. +static void charging_update(Entity_NPC& npc, float& alpha) +{ + Vector player = npc.GetPlayerTarget()->pos; + bool isLeftward = byte_get(npc.projectileCooldown, COUNT_SIDE) == 0; + npc.sprite.Play(isLeftward ? "ChargeLeft" : "ChargeRight"); + float sm = npc.speedMultiplier; + float pushX = (isLeftward ? -1.0f : 1.0f) * CHARGE_PUSH * sm + npc.velocity.x; + npc.velocity = vector_make(pushX, sm * 0 + npc.velocity.y); + if (std::abs(player.y - npc.pos.y) > CHARGE_STEER_MIN) + { + float steer = player.y <= npc.pos.y ? -CHARGE_STEER : CHARGE_STEER; + npc.velocity = vector_make(npc.speedMultiplier * 0 + pushX, steer * npc.speedMultiplier + npc.velocity.y); + } + + float fade = byte_get(npc.projectileCooldown, COUNT_REPEATS) == CHARGES_FAST_FADE ? CHARGE_FADE_FAST : CHARGE_FADE; + alpha = std::min(fade * npc.speedMultiplier + alpha, 1.0f); + bool isPast = isLeftward ? npc.pos.x < player.x + CHARGE_STOP : npc.pos.x > player.x - CHARGE_STOP; + if (!isPast) return; + + npc.sprite.Play(isLeftward ? "ChargeEndLeft" : "ChargeEndRight"); + npc.state = HERETIC_CHARGE_END; + timer_set(npc, 0); +} + +// A dash: it fades half in, then out again leaving an afterimage, and charges from the other side. +static void dashing_update(Entity_NPC& npc, float& alpha, int ticks) +{ + npc.GetPlayerTarget(); + npc.sprite.Play(byte_get(npc.projectileCooldown, COUNT_SIDE) == 0 ? "ChargeLeft" : "ChargeRight"); + float sm = npc.speedMultiplier; + npc.velocity = vector_make(side_sign(npc) * CHARGE_PUSH * sm + npc.velocity.x, sm * 0 + npc.velocity.y); + + int timer = timer_get(npc); + if (timer <= DASH_VISIBLE_FRAMES) + { + timer_set(npc, ticks + timer); + alpha = std::min(npc.speedMultiplier * DASH_FADE_IN + alpha, DASH_ALPHA); + return; + } + alpha = std::max(alpha - npc.speedMultiplier * DASH_FADE_OUT, 0.0f); + if (timer > HERETIC_DASH_FRAMES) + { + afterimage_spawn(npc); + byte_set(npc.projectileCooldown, COUNT_SIDE, 1 - byte_get(npc.projectileCooldown, COUNT_SIDE)); + charge_start(npc); + timer = timer_get(npc); + } + timer_set(npc, ticks + timer); +} + +// The brake at the end of a charge: it slams to a stop, then charges again from the other side, or after four +// finishes and idles. +static void charge_end_update(Entity_NPC& npc, float& alpha, int ticks) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_GHOST_SHOOT, 1, 2, false, 1); + game_shake_screen(BRAKE_SHAKE); + } + float sign = side_sign(npc); + float sm = npc.speedMultiplier; + if (!npc.sprite.WasEventTriggered("Shoot")) + { + npc.velocity = vector_make(sign * BRAKE_PUSH * sm + npc.velocity.x, sm * 0 + npc.velocity.y); + return; + } + + alpha = 1; + timer_set(npc, timer_get(npc) + ticks); + npc.velocity = vector_make(sign * BRAKE_DRIFT * sm + npc.velocity.x, sm * 0 + npc.velocity.y); + if (timer_get(npc) <= BRAKE_FRAMES) return; + + if (byte_get(npc.projectileCooldown, COUNT_REPEATS) < CHARGES_MAX) + { + afterimage_spawn(npc); + byte_set(npc.projectileCooldown, COUNT_SIDE, 1 - byte_get(npc.projectileCooldown, COUNT_SIDE)); + return charge_start(npc); + } + npc.sprite.Play(byte_get(npc.projectileCooldown, COUNT_SIDE) == 0 ? "ChargeFinishLeft" : "ChargeFinishRight"); + byte_set(npc.projectileCooldown, COUNT_REPEATS, 0); + idle_set(npc, 0); + npc.state = HERETIC_IDLE; + byte_set(npc.projectileDelay, COOLDOWN_DASH, DASH_COOLDOWN); + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.SetCollisionDamage(1); +} + +// An afterimage drifts on, fading, and goes once off the screen. +static void afterimage_update(Entity_NPC& npc, float& alpha, int ticks) +{ + float sm = npc.speedMultiplier; + if (npc.subtype == AFTERIMAGE_OF_DASH) + npc.velocity = vector_make(side_sign(npc) * AFTERIMAGE_PUSH * sm + npc.velocity.x, sm * 0 + npc.velocity.y); + else + { + alpha = std::max(alpha - sm * HERETIC_FADE_STEP, 0.0f); + float ramp = std::min(std::max((float)timer_get(npc) / EXIT_RAMP, 0.0f), 1.0f); + float accel = ramp * ramp + ramp * ramp + AFTERIMAGE_ACCEL_MIN; + npc.velocity = vector_make(accel * side_sign(npc) * sm + npc.velocity.x, accel * 0 * sm + npc.velocity.y); + } + if (alpha <= 0 && !g_game->room->IsPositionInRoom(npc.pos, OFF_ROOM_MARGIN)) npc.Remove(); + timer_set(npc, timer_get(npc) + ticks); +} + +// The speed a lob needs to land on its spot: tried from 3 up by halving steps until its fall lands near -60. +struct LobArc +{ + float fallingSpeed = 0; + float speed = 0; +}; + +static LobArc lob_arc_solve(Entity_Projectile& shot, float distance) +{ + float lift = LOB_LIFT - shot.height; + float accel = shot.fallingAccel * LOB_ACCEL_SCALE + 1; + LobArc arc{.speed = LOB_SPEED_START}; + float step = LOB_SPEED_STEP; + for (int i = 0; i < LOB_TRIES; i++) + { + float time = distance / arc.speed; + float drag = std::max((std::pow(LOB_DRAG, time) - 1) * LOB_DRAG_SCALE, LOB_TIME_MIN); + arc.fallingSpeed = (lift - (time - drag) * accel) / drag; + bool isPast = + (step > 0 && arc.fallingSpeed > LOB_FALL_SPEED) || (step < 0 && arc.fallingSpeed < LOB_FALL_SPEED); + if (isPast) + { + step *= LOB_STEP_SHRINK; + if (std::abs(step) < LOB_STEP_MIN) break; + } + arc.speed += step; + } + return arc; +} + +// The lobs: a big fireball arcing onto the player's spot, marked by a target, six times, then the dive bomb. +static void lobbing_update(Entity_NPC& npc) +{ + npc.sprite.Play("Attack2"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + int repeats = byte_get(npc.projectileCooldown, COUNT_REPEATS); + npc.PlaySound(((~repeats) & 1) ? SOUND_MONSTER_GRUNT_2 : SOUND_MONSTER_GRUNT_1, 1, 2, false, 1); + Vector target = npc.GetPlayerTarget()->pos; + ProjectileParams params; + params.heightModifier += LOB_HEIGHT; + params.scale = LOB_SCALE; + params.fallingAccelModifier = LOB_FALL_ACCEL; + params.fallingSpeedModifier = LOB_FALL_SPEED; + params.color = LOB_COLOR; + params.bulletFlags |= PROJECTILE_EXPLODE; + if (Entity_Projectile* shot = npc.fire_projectiles(npc.pos, vector_make(0, 0), PROJECTILES_SINGLE, params)) + { + Vector toTarget = vector_sub(target, npc.pos); + LobArc arc = lob_arc_solve(*shot, std::sqrt(toTarget.y * toTarget.y + toTarget.x * toTarget.x)); + shot->velocity = vector_resized(toTarget, arc.speed); + shot->fallingSpeed = arc.fallingSpeed; + Entity* marker = g_game->Spawn({.position = target, + .subType = LOB_TARGET_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_OCCULT_TARGET, + .seed = Random()}); + marker->parent = shot; + marker->sprite.color = COLOR_DEFAULT; + marker->Update(); + } + Entity* poof = g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BULLET_POOF, .seed = Random()}); + poof->sprite.offset = vector_make(0, LOB_POOF_HEIGHT); + poof->renderDepthOffset = LOB_POOF_DEPTH; + poof->SetColor(HERETIC_PURPLE, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + if (!is_anim_done(npc)) return; + + int repeats = byte_get(npc.projectileCooldown, COUNT_REPEATS); + if (repeats != LOBS) + { + byte_set(npc.projectileCooldown, COUNT_REPEATS, repeats + 1); + return npc.sprite.Play("Attack2", PLAY_FORCED); + } + + Vector target = npc.GetPlayerTarget()->pos; + Vector toTarget = vector_sub(target, npc.pos); + if (std::sqrt(toTarget.y * toTarget.y + toTarget.x * toTarget.x) > DIVE_REACH) + target = vector_add(vector_scale(vector_normalized(toTarget), DIVE_REACH), npc.pos); + npc.v2 = g_game->room->GetClampedPositionImpl(target, DIVE_MARGIN, DIVE_MARGIN, DIVE_MARGIN, DIVE_MARGIN); + npc.v1.x = 0; + npc.sprite.Play("Divebomb"); + npc.state = HERETIC_DIVEBOMB; + timer_set(npc, 0); +} + +// The dive bomb: it swoops onto its spot and lands in a ring of eight flames. +static void divebomb_update(Entity_NPC& npc, float friction, int ticks) +{ + if (!vector_is_zero(npc.v2) && timer_get(npc) > DIVE_START) + { + npc.friction = friction * DIVE_FRICTION; + npc.v1.x = std::min(std::max(npc.speedMultiplier * DIVE_ACCEL + npc.v1.x, 0.0f), 1.0f); + float pullY = (npc.v2.y - npc.pos.y) * npc.v1.x; + npc.velocity = vector_make((npc.v2.x - npc.pos.x) * npc.v1.x / npc.friction, pullY / npc.friction); + } + if (timer_get(npc) > DIVE_HIDE_FRAME && !npc.sprite.WasEventTriggered("Shoot")) + npc.entityCollisionClass = ENTCOLL_NONE; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + game_shake_screen(DIVE_SHAKE); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + npc.MakeGroundPoofAtSelf(DIVE_POOF_COLOR, 1); + npc.PlaySound(SOUND_FLAME_BURST, 1, FLAME_SOUND_DELAY, false, 1); + for (int i = 0; i < DIVE_FLAMES; i++) flame_spawn(npc, npc.pos, (float)i * DIVE_FLAME_STEP); + npc.v2 = vector_make(0, 0); + } + if (npc.sprite.WasEventTriggered("Shoot")) npc.friction *= DIVE_LANDED_FRICTION; + if (npc.sprite.IsEventTriggered("Sound")) + { + game_shake_screen(DIVE_RUMBLE_SHAKE); + npc.PlaySound(SOUND_FORTUNE_COOKIE, 1, 2, false, 1); + } + if (is_anim_done(npc)) + { + byte_set(npc.projectileCooldown, COUNT_REPEATS, 0); + idle_set(npc, 0); + npc.state = HERETIC_IDLE; + byte_set(npc.projectileDelay, COOLDOWN_LOBS, LOB_COOLDOWN); + } + timer_set(npc, timer_get(npc) + ticks); +} + +// Its long death: purple explosions about it hurting what is near, the boss death on its Sound event, then flames. +static void exploding_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector heading = random_direction(); + float reach = random_unit(); + Vector spot = vector_make(reach * heading.x * EXPLOSION_SPREAD + npc.pos.x, + reach * heading.y * EXPLOSION_SPREAD + npc.pos.y); + Entity* blast = g_game->Spawn( + {.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + blast->sprite.color = EXPLOSION_COLOR; + blast->Update(); + explosion_damage({.position = spot, + .source = &npc, + .damage = HERETIC_EXPLOSION_DAMAGE, + .radius = HERETIC_EXPLOSION_RADIUS, + .isLineCheck = false}); + game_shake_screen(EXPLOSION_SHAKE); + } + if (npc.sprite.IsEventTriggered("Sound")) + { + g_game->room->TriggerBossDeath(npc); + game_shake_screen(HERETIC_DEATH_SHAKE); + } + if (npc.sprite.WasEventTriggered("Sound") && npc.GetIntervalTicks(DEATH_FLAME_EVERY, 0) != 0) + { + npc.PlaySound(SOUND_FLAME_BURST, 1, FLAME_SOUND_DELAY, false, 1); + for (int i = 0; i < DEATH_FLAME_PAIR; i++) + { + auto* flame = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_FIRE_WAVE, + .seed = Random()})); + flame->parent = &npc; + flame->rotation = random_unit() * HERETIC_FULL_TURN; + } + } + if (is_anim_done(npc)) npc.Remove(); +} + +// Before its update: fire and blasts not set off by a player do not hurt it, and once its Death animation ends four +// flames rise where it fell. +static void heretic_pre_update(Entity_NPC& npc) +{ + if (npc.pendingDamage > 0 && (npc.pendingDamageFlags & DAMAGE_FIRE)) + { + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + for (DamageEvent& event : npc.damageEvents) + { + if ((event.damageFlags & (DAMAGE_FIRE | DAMAGE_EXPLOSION)) && event.source.spawnerType != ENTITY_PLAYER) + { + event.damage = 0; + event.damageFlags = 0; + } + npc.pendingDamage += event.damage; + npc.pendingDamageFlags |= event.damageFlags; + } + } + bool isDeathDone = npc.state == NPC_STATE_DEATH && npc.sprite.GetAnimation() == "Death" && is_anim_done(npc); + if (!isDeathDone) return; + + npc_sound_play(SOUND_FLAME_BURST, 1, FLAME_SOUND_DELAY, champion_pitch_get(npc)); + for (int i = 0; i < DEATH_FLAMES; i++) + flame_spawn(npc, vector_make(npc.pos.x + DEATH_FLAME_OFFSET, npc.pos.y + 0), (float)i * DEATH_FLAME_STEP); +} + +// 004b43c0 The Heretic: hidden behind its pentagram while its Exorcists live, it then points at put out fires to +// light them and beams through them, dashes off screen to charge across the room, and lobs fireballs before a dive +// bomb ringed with flames. +void boss_heretic_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return heretic_pre_update(npc); + + float alpha = npc.sprite.GetLayer(0)->color._tint[3]; + float friction = npc.friction * FRICTION; + npc.friction = friction; + int ticks = npc_ticks_get(npc); + switch (npc.state) + { + case NPC_STATE_INIT: + heretic_init(npc); + break; + case HERETIC_IDLE: + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + if (is_anim_done(npc)) npc.sprite.Play("Idle"); + idle_set(npc, idle_get(npc) + ticks); + if (idle_get(npc) > (is_hurt(npc) ? IDLE_WAIT_HURT : HERETIC_IDLE_WAIT)) attack_pick(npc); + break; + case HERETIC_HIDDEN: + { + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + alpha = std::max(alpha - npc.speedMultiplier * HERETIC_FADE_STEP, HIDDEN_ALPHA); + npc.sprite.Play("IdleInvis"); + bool isGuarded = std::ranges::any_of(npc.entityDeque, [](const EntityPtr& linked) { return linked.get(); }); + if (isGuarded) break; + npc.ClearDequeRefs(); + npc.state = HERETIC_REAPPEARING; + break; + } + case HERETIC_REAPPEARING: + alpha = std::min(npc.speedMultiplier * HERETIC_FADE_STEP + alpha, 1.0f); + npc.sprite.Play("InvisEnd"); + if (!is_anim_done(npc)) break; + alpha = 1; + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.isInvincible = false; + npc.state = HERETIC_IDLE; + npc.sprite.Play("Idle"); + break; + case HERETIC_SUMMONING: + summoning_update(npc); + break; + case HERETIC_POINTING: + pointing_update(npc); + break; + case HERETIC_BEAMS: + beams_update(npc); + break; + case HERETIC_EXITING: + exiting_update(npc, alpha, ticks); + break; + case HERETIC_CHARGING: + charging_update(npc, alpha); + break; + case HERETIC_DASHING: + dashing_update(npc, alpha, ticks); + break; + case HERETIC_CHARGE_END: + charge_end_update(npc, alpha, ticks); + break; + case HERETIC_AFTERIMAGE: + afterimage_update(npc, alpha, ticks); + npc.sprite.GetLayer(0)->color._tint[3] = alpha; + if (npc.sprite.shadowLayerIndex >= 0) + npc.sprite.GetLayer(npc.sprite.shadowLayerIndex)->color._tint[3] = alpha; + return; + case HERETIC_LOBBING: + lobbing_update(npc); + break; + case HERETIC_DIVEBOMB: + divebomb_update(npc, friction, ticks); + break; + case HERETIC_EXPLODING: + exploding_update(npc); + break; + } + + int steps = npc.GetIntervalTicks(COOLDOWN_STEP, 0); + if (steps > 0) + for (int i = 0; i < COOLDOWN_COUNT; i++) + { + int cooldown = byte_get(npc.projectileDelay, i); + if (cooldown > 0) byte_set(npc.projectileDelay, i, cooldown <= steps ? 0 : cooldown - steps); + } + npc.sprite.GetLayer(0)->color._tint[3] = alpha; + if (npc.sprite.shadowLayerIndex >= 0) npc.sprite.GetLayer(npc.sprite.shadowLayerIndex)->color._tint[3] = alpha; + if (!vector_is_zero(npc.targetPosition)) + npc.velocity = vector_make((npc.targetPosition.x - npc.pos.x) / npc.friction, + (npc.targetPosition.y - npc.pos.y) / npc.friction); + if (!npc.isDead) return; + + for (size_t i = 0; i < npc.entityDeque.size(); i++) + { + Entity* fire = npc.entityDeque[i]; + if (!fire || fire->type != ENTITY_FIREPLACE || fire->health < HERETIC_FIRE_OUT_HEALTH) continue; + fire->isDead = true; + fire->Update(); + } +} diff --git a/src/boss_hush.cpp b/src/boss_hush.cpp index ed282c6..38c172f 100644 --- a/src/boss_hush.cpp +++ b/src/boss_hush.cpp @@ -458,7 +458,7 @@ static int phase_update(Entity_NPC& npc) { Entity_Player* nearest = game_nearest_player(npc.pos); if (vector_length(vector_sub(npc.pos, nearest->pos)) <= RESTLESS_REACH) - npc.v1.x *= npc_friction_scaled(RESTLESS_CALM, npc.speedMultiplier); + npc.v1.x *= timescale_factor(RESTLESS_CALM, npc.speedMultiplier); else npc.v1.x += npc.speedMultiplier / RESTLESS_RATE; float healthLeft = npc.health / npc.maxHitPoints; diff --git a/src/boss_isaac.cpp b/src/boss_isaac.cpp index 23ca14b..a88d682 100644 --- a/src/boss_isaac.cpp +++ b/src/boss_isaac.cpp @@ -1269,7 +1269,7 @@ void npc_isaac_fly_update(Entity_NPC& npc) Vector step = vector_sub(npc.targetPosition, npc.pos); if (vector_length(step) > speed) step = vector_resized(step, speed); - float ease = 1 - npc_friction_scaled(ISAAC_ORBIT_EASE, npc.speedMultiplier); + float ease = 1 - timescale_factor(ISAAC_ORBIT_EASE, npc.speedMultiplier); npc.velocity = vector_make(npc.velocity.x + (step.x - npc.velocity.x) * ease, npc.velocity.y + (step.y - npc.velocity.y) * ease); npc.entityGridCollisionClass = GRIDCOLL_NONE; diff --git a/src/boss_little_horn.cpp b/src/boss_little_horn.cpp index ea34633..8eb7b06 100644 --- a/src/boss_little_horn.cpp +++ b/src/boss_little_horn.cpp @@ -24,7 +24,6 @@ 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; @@ -98,7 +97,7 @@ constexpr uint64_t DRAWN_TO_TARGET = FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | F bool players_is_falling() { for (Entity_Player* player : g_game->playerManager.playerList) - if (player->pitfallState != 0 && player->pitfallState != PITFALL_DONE) return true; + if (player->pitfallState != PITFALL_NONE && player->pitfallState != PITFALL_CLIMBING) return true; return false; } diff --git a/src/boss_mask_of_infamy.cpp b/src/boss_mask_of_infamy.cpp index 09263cc..70c9a04 100644 --- a/src/boss_mask_of_infamy.cpp +++ b/src/boss_mask_of_infamy.cpp @@ -271,6 +271,6 @@ void boss_mask_of_infamy_update(Entity_NPC& npc) npc.pathfinder.MoveRandomlyAxisAligned(npc.state == MASK_ANGRY ? MASK_ANGRY_WANDER_SPEED : MASK_WANDER_SPEED, STATUS_OBEYED); - npc.velocity.x *= npc_friction_scaled(MASK_DRAG_X, npc.speedMultiplier); - npc.velocity.y *= npc_friction_scaled(MASK_DRAG_Y, npc.speedMultiplier); + npc.velocity.x *= timescale_factor(MASK_DRAG_X, npc.speedMultiplier); + npc.velocity.y *= timescale_factor(MASK_DRAG_Y, npc.speedMultiplier); } diff --git a/src/boss_monstro.cpp b/src/boss_monstro.cpp index f4e0077..78b7ca0 100644 --- a/src/boss_monstro.cpp +++ b/src/boss_monstro.cpp @@ -1,7 +1,9 @@ #include "boss_ai.h" +#include "active_items.h" #include "entity_laser.h" #include "entity_projectile.h" #include "grid_entity_trap_door.h" +#include "menu_manager.h" #include "npc_caves.h" #include "room_descriptor.h" #include "room_grid.h" @@ -95,9 +97,58 @@ constexpr ColorMod GISH_SHOT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0 constexpr ColorMod GISH_SPLAT_COLOR = tint_color_make(0.02f, 0.05f, 0.05f, 1); constexpr ColorMod GISH_POOF_COLOR = {{3, 3, 3, 1}, {0.03f, 0.03f, 0.03f, 1}, {0, 0, 0}}; +// A player's Monstro: input past half a push is kept as its heading (v1) and aim (v2), it hops toward a spot 250 along +// its heading, and the bomb, item, pill or drop action jumps (also within a hop's first 4 frames). +constexpr float CONTROL_HELD = 0.5f; +constexpr float CONTROL_REACH = 250; +constexpr float CONTROL_SPIT_REACH = 100; +constexpr float CONTROL_TAR_REACH = 70; +constexpr float CONTROL_HOP_JUMP_FRAMES = 4; +constexpr float CONTROL_HOP_SHARE = 0.6f; +constexpr float CONTROL_HOP_BASE = 0.4f; +constexpr float CONTROL_STOMP_SHARE = 1.1999999f; +constexpr float CONTROL_STOMP_BASE = 0.1f; +constexpr float CONTROL_STOMP_STILL = 1.3f; + constexpr ColorMod HOP_DUST_COLOR = {{0.8f, 0.8f, 0.8f, 0.7f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod SPIT_CLOUD_COLOR = {{1, 1, 1, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +// What the controlling player holds: its walking and shooting (each at most 1 long) and whether it jumps. +struct MonstroControl +{ + Vector fire{}; + Vector move{}; + bool isJumpPressed = false; +}; + +// The controlling player's input, read action by action without the seeds' or the mirror world's changes, kept as the +// heading and aim past half a push. Where it heads to: 250 along its heading, inside the room. +static MonstroControl monstro_control_read(Entity_NPC& npc, Vector& target) +{ + auto axes = [&npc](ButtonAction leftAction) { + float left = input_action_value_get(leftAction, npc.controllerID, &npc); + float right = input_action_value_get((ButtonAction)(leftAction + 1), npc.controllerID, &npc); + float up = input_action_value_get((ButtonAction)(leftAction + 2), npc.controllerID, &npc); + float down = input_action_value_get((ButtonAction)(leftAction + 3), npc.controllerID, &npc); + Vector input = vector_make(right - left, down - up); + float length = vector_length(input); + return length > 1 && length > 0 ? vector_scale(input, 1 / length) : input; + }; + MonstroControl control; + control.move = axes(ACTION_LEFT); + control.fire = axes(ACTION_SHOOT_LEFT); + control.isJumpPressed = input_is_action_pressed(ACTION_ITEM, npc.controllerID, &npc) || + input_is_action_pressed(ACTION_BOMB, npc.controllerID, &npc) || + input_is_action_pressed(ACTION_PILL_CARD, npc.controllerID, &npc) || + npc.IsControllerActionPressed(ACTION_DROP); + + if (vector_length(control.move) > CONTROL_HELD) npc.v1 = control.move; + if (vector_length(control.fire) > CONTROL_HELD) npc.v2 = control.fire; + Vector heading = vector_add(vector_scale(npc.v1, CONTROL_REACH), npc.pos); + target = g_game->room->GetClampedPositionImpl(heading, npc.size, npc.size, npc.size, npc.size); + return control; +} + static bool is_monstro2(const Entity_NPC& npc) { return npc.type == ENTITY_MONSTRO2 && npc.variant == 0; @@ -188,9 +239,9 @@ static int attack_roll(Entity_NPC& npc) return attack; } -// The idle pose rolls the next attack, only hops for a calm Delirium form. Monstro II's spit shows a tracer where its -// laser will fire. -static void monstro_idle(Entity_NPC& npc) +// The idle pose rolls the next attack, only hops for a calm Delirium form. A player's Monstro jumps, spits or hops as +// it is told, or waits. Monstro II's spit shows a tracer where its laser will fire. +static void monstro_idle(Entity_NPC& npc, const MonstroControl* control) { if (npc.sprite.SetAnimation("Walk", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) { @@ -203,6 +254,13 @@ static void monstro_idle(Entity_NPC& npc) int attack = attack_roll(npc); if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) attack = MONSTRO_HOP; npc.i2 = attack; + if (control) + { + if (control->isJumpPressed) attack = MONSTRO_JUMP; + else if (vector_length(control->fire) > CONTROL_HELD) attack = MONSTRO_SPIT; + else if (vector_length(control->move) > CONTROL_HELD) attack = MONSTRO_HOP; + else return; + } switch (attack) { @@ -219,7 +277,7 @@ static void monstro_idle(Entity_NPC& npc) npc.state = NPC_STATE_ATTACK; npc_anim_restart(npc.sprite, "Taunt"); - npc.sprite.isFlipX = npc.pos.x - npc.GetPlayerTarget()->pos.x < 0; + npc.sprite.isFlipX = control ? npc.v2.x >= 0 : npc.pos.x - npc.GetPlayerTarget()->pos.x < 0; if (!is_monstro2(npc)) return; following_effect_spawn( @@ -242,10 +300,25 @@ static void suckers_crush(Entity_NPC& npc) } // A hop toward its target's cell: pulled there while airborne (harder for the quick one), dust where it lands, and -// once the hop ends, another one time in two, else back to idle. -static void monstro_hop(Entity_NPC& npc, const Vector& target) +// once the hop ends, another one time in two, else back to idle. A player's Monstro hops straight at its heading's +// spot, steered by its walking, turns a hop's first frames into a jump, and hops again while walking. +static void monstro_hop(Entity_NPC& npc, const Vector& target, const MonstroControl* control) { - if (vector_is_zero(npc.targetPosition)) target_cell_set(npc, target); + bool isEarly = !npc.sprite.animState.animData || npc.sprite.animState.animFrame < CONTROL_HOP_JUMP_FRAMES; + if (control && isEarly && control->isJumpPressed) + { + npc.state = NPC_STATE_JUMP; + npc.PlaySound(SOUND_BOSS_LITE_ROAR, 1, 2, false, 1); + npc_anim_restart(npc.sprite, "JumpUp"); + gish_sound_play(npc, SOUND_GISH_JUMP_HIGH); + if (is_quick(npc)) npc.sprite.playbackSpeed = QUICK_PLAYBACK; + return; + } + if (vector_is_zero(npc.targetPosition)) + { + target_cell_set(npc, target); + if (control) npc.targetPosition = target; + } if (vector_is_zero(npc.targetPosition)) { npc.friction *= MONSTRO_LANDED_FRICTION; @@ -278,6 +351,13 @@ static void monstro_hop(Entity_NPC& npc, const Vector& target) { Vector toward = vector_sub(npc.targetPosition, npc.pos); float distance = vector_length(toward); + if (control && isJumped) + { + float along = std::max(vector_dot(control->move, vector_normalized(npc.velocity)), 0.0f); + float share = std::abs(along * along * along) * CONTROL_HOP_SHARE + CONTROL_HOP_BASE; + if (vector_is_zero(npc.velocity)) share = 1; + toward = vector_scale(vector_scale(control->move, share), distance); + } if (distance == 0) distance = HOP_MIN_DISTANCE; float pull = MONSTRO_HOP_PULL / distance * (is_quick(npc) ? QUICK_HOP_PULL : 1); if (npc.friction != 0) @@ -293,7 +373,8 @@ static void monstro_hop(Entity_NPC& npc, const Vector& target) } npc.targetPosition = {}; - if (Random() & 1) + bool isHopAgain = control ? vector_length(control->move) >= CONTROL_HELD && !control->isJumpPressed : Random() & 1; + if (isHopAgain) { npc.PlaySound(SOUND_BOSS_LITE_ROAR, REHOP_VOLUME, 2, false, 1); npc_anim_restart(npc.sprite, "Walk"); @@ -415,9 +496,21 @@ static void stomp_shoot(Entity_NPC& npc) npc.FireProjectiles(npc.pos, vector_make(MONSTRO_STOMP_RING_SPEED, 0), PROJECTILES_EIGHT, params); } +// A player steers its Monstro's fall by its walking, harder along its flight (1.3 from a standstill). +static void monstro_stomp_steer(Entity_NPC& npc, const MonstroControl& control) +{ + float along = std::abs(vector_dot(control.move, vector_normalized(npc.velocity))); + float strength = along * CONTROL_STOMP_SHARE + CONTROL_STOMP_BASE; + if (vector_is_zero(npc.velocity)) strength = CONTROL_STOMP_STILL; + Vector heading = vector_normalized(control.move); + if (npc.friction == 0) return; + npc.velocity.x = npc.speedMultiplier * strength * heading.x / npc.friction + npc.velocity.x; + npc.velocity.y = npc.speedMultiplier * strength * heading.y / npc.friction + npc.velocity.y; +} + // The fall onto its target's cell (a drop-in lands where the target is heading from): steered there in the air, then // the landing shakes the ground, poofs blood (tar for Gish) and fires. Type 43 jumps twice in a row before it rests. -static void monstro_stomp(Entity_NPC& npc, Vector target) +static void monstro_stomp(Entity_NPC& npc, Vector target, const MonstroControl* control) { if (vector_is_zero(npc.targetPosition)) { @@ -436,9 +529,13 @@ static void monstro_stomp(Entity_NPC& npc, Vector target) { npc.entityCollisionClass = ENTCOLL_NONE; npc.entityGridCollisionClass = GRIDCOLL_WALLS; - Vector toward = vector_sub(npc.targetPosition, npc.pos); - Vector pull = vector_add(vector_scale(toward, JUMP_PULL), vector_scale(vector_normalized(toward), JUMP_PUSH)); - npc_push(npc, pull); + if (control) monstro_stomp_steer(npc, *control); + else + { + Vector toward = vector_sub(npc.targetPosition, npc.pos); + Vector push = vector_scale(vector_normalized(toward), JUMP_PUSH); + npc_push(npc, vector_add(vector_scale(toward, JUMP_PULL), push)); + } } if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) @@ -472,9 +569,17 @@ static void monstro_stomp(Entity_NPC& npc, Vector target) if (is_quick(npc)) npc.sprite.playbackSpeed = QUICK_PLAYBACK; } +// The way Monstro II's laser fires: the way it faces, or along its player's aim. +static float monstro_laser_angle(Entity_NPC& npc, const MonstroControl* control) +{ + if (control) return vector_angle(npc.v2); + return npc.sprite.isFlipX ? LASER_RIGHT_DEGREES : LASER_LEFT_DEGREES; +} + // The spit on Shoot: Monstro lobs 13 shots at its target with a blood cloud from its mouth, Monstro II fires its -// laser the way it faces, Gish lobs one big tar shot. Then idle once the taunt ends. -static void monstro_spit(Entity_NPC& npc) +// laser the way it faces, Gish lobs one big tar shot. A player's Monstro turns to and fires along its aim. Then idle +// once the taunt ends. +static void monstro_spit(Entity_NPC& npc, const MonstroControl* control) { if (!npc.sprite.animState.animData) { @@ -484,29 +589,32 @@ static void monstro_spit(Entity_NPC& npc) if (npc.sprite.IsEventTriggered("Shoot")) { + if (control) npc.sprite.isFlipX = npc.v2.x >= 0; + auto aim = [&npc, control](float reach) { + return control ? vector_add(vector_scale(npc.v2, reach), npc.pos) : npc.GetPlayerTarget()->pos; + }; if (npc.type == ENTITY_MONSTRO) { npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); - npc.FireBossProjectiles(SPIT_SHOTS, npc.GetPlayerTarget()->pos, 0, ProjectileParams()); + npc.FireBossProjectiles(SPIT_SHOTS, aim(CONTROL_SPIT_REACH), 0, ProjectileParams()); Entity_Effect* cloud = npc.MakeBloodCloud(npc.pos, SPIT_CLOUD_COLOR, SPIT_CLOUD_SCALE); cloud->posOffset = vector_make(0, SPIT_CLOUD_HEIGHT); } else if (is_monstro2(npc)) { - Entity_Laser* laser = - Entity_Laser::ShootAngle({.position = npc.pos, - .posOffset = vector_make(0, MONSTRO_LASER_HEIGHT), - .source = &npc, - .angleDegrees = npc.sprite.isFlipX ? LASER_RIGHT_DEGREES : LASER_LEFT_DEGREES, - .timeout = MONSTRO_LASER_TIMEOUT, - .variant = LASER_THICK_RED}); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = vector_make(0, MONSTRO_LASER_HEIGHT), + .source = &npc, + .angleDegrees = monstro_laser_angle(npc, control), + .timeout = MONSTRO_LASER_TIMEOUT, + .variant = LASER_THICK_RED}); laser->renderDepthOffset = LASER_DEPTH; laser->Update(); } else if (is_gish(npc)) { Entity_Projectile* shot = - npc.FireBossProjectiles(1, npc.GetPlayerTarget()->pos, GISH_SHOT_ARC, ProjectileParams()); + npc.FireBossProjectiles(1, aim(CONTROL_TAR_REACH), GISH_SHOT_ARC, ProjectileParams()); shot->projectileFlags |= PROJECTILE_EXPLODE | PROJECTILE_GOO; shot->fallingAccel -= GISH_SHOT_ACCEL; shot->scale = GISH_SHOT_SCALE; @@ -519,14 +627,19 @@ static void monstro_spit(Entity_NPC& npc) } // 0046c0a0 NpcAI::ENTITY_MONSTRO: Monstro, Monstro II and Gish hop after their target, spit (Monstro II fires a laser -// when in line), or jump off screen and stomp down. Type 43 jumps twice in a row, freeing Suckers or Clots. A Monstro -// a player controls is not reconstructed yet. +// when in line), or jump off screen and stomp down. Type 43 jumps twice in a row, freeing Suckers or Clots. A player +// may control it. void boss_monstro_update(Entity_NPC& npc) { - if (npc.controllerID != -1) reconstruction_missing("NpcAI::ENTITY_MONSTRO 0046c0a0: a controlled Monstro"); - npc.friction *= MONSTRO_FRICTION; Vector target = npc.CalcTargetPosition(0); + MonstroControl control; + MonstroControl* controlled = nullptr; + if (npc.controllerID != -1) + { + control = monstro_control_read(npc, target); + controlled = &control; + } suckers_crush(npc); switch (npc.state) @@ -534,14 +647,14 @@ void boss_monstro_update(Entity_NPC& npc) case NPC_STATE_INIT: return monstro_init(npc); case NPC_STATE_IDLE: - return monstro_idle(npc); + return monstro_idle(npc, controlled); case NPC_STATE_MOVE: - return monstro_hop(npc, target); + return monstro_hop(npc, target, controlled); case NPC_STATE_JUMP: return monstro_jump(npc); case NPC_STATE_STOMP: - return monstro_stomp(npc, target); + return monstro_stomp(npc, target, controlled); case NPC_STATE_ATTACK: - return monstro_spit(npc); + return monstro_spit(npc, controlled); } } diff --git a/src/boss_pin.cpp b/src/boss_pin.cpp new file mode 100644 index 0000000..27abf8c --- /dev/null +++ b/src/boss_pin.cpp @@ -0,0 +1,925 @@ +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include +#include + +// Pin's kinds, by variant: Pin, Scolex and the Frail run here, Wormwood has its own AI. +enum PinVariant +{ + PIN_PIN, + PIN_SCOLEX, + PIN_FRAIL, + PIN_WORMWOOD +}; + +// Pin's states: underground, rising through the air, and its attacks. The Frail's second phase also sweeps a beam +// (ATTACK) or fires bursts of beams (ATTACK3). +constexpr int PIN_BURIED = NPC_STATE_IDLE; +constexpr int PIN_JUMPING = NPC_STATE_MOVE; +constexpr int PIN_SPITTING = NPC_STATE_ATTACK; +constexpr int PIN_ROARING = NPC_STATE_ATTACK2; +constexpr int PIN_BEAMS = NPC_STATE_ATTACK3; +constexpr int PIN_ATTACK_DIVE = 10; +constexpr int PIN_POPPED_UP = 4; + +// The segments each kind grows behind its head, Scolex's thick and thin ones, and the delay (in trail points) each +// body segment follows its head by. +constexpr int PIN_SEGMENTS = 6; +constexpr int SCOLEX_SEGMENTS = 9; +constexpr int SCOLEX_THIN_FIRST = 4; +constexpr int SCOLEX_THICK = 7; +constexpr float SCOLEX_THICK_SIZE = 1.5f; +constexpr float SCOLEX_THIN_SIZE = 0.7f; +constexpr std::array PIN_DELAYS = {0, 0, 2, 4, 6, 8}; +constexpr std::array SCOLEX_DELAYS = {0, 0, 3, 6, 10, 14, 18, 21, 23}; +constexpr int SCOLEX_SHIELDING_SEGMENTS = 2; +constexpr float SCOLEX_SHIELD_SLACK = 0.0001f; +constexpr int TAIL_DEPTH_BELOW = 1000; +constexpr int RENDER_DEPTH_STEP = 5; +constexpr int HEALTH_SYNC_COUNTDOWN = 30; + +// The trail the head leaves: a point every 3 of motion or while buried, the newest 30 kept once it passes 60. +constexpr float PIN_TRAIL_STEP = 3; +constexpr size_t PIN_TRAIL_MAX = 60; +constexpr size_t TRAIL_KEPT = 30; + +// The jump out of the ground: its speeds, the lift it starts with, gravity, and the depth it buries at again. +constexpr float JUMP_SPEED = 8; +constexpr float FRAIL_JUMP_FAST = 10; +constexpr float FRAIL_JUMP_SLOW = 6; +constexpr float JUMP_LIFT = -2; +constexpr float JUMP_LIFT_PER_DISTANCE = 0.02f; +constexpr float GRAVITY = 0.4f; +constexpr float BURIED_DEPTH = 16; +constexpr float SURFACE_DEPTH = 8; +constexpr float RISING_DEPTH = 6; +constexpr float SPAWN_DEPTH = 26; +constexpr float PIN_SPIT_HEIGHT = -20; +constexpr int DIVE_SOUND_DELAY = 10; + +// Underground it circles the player at 250 and is pulled toward the room's middle, rising once it lags 15 behind. +constexpr float UNDERGROUND_FRICTION = 0.95f; +constexpr float PLAYER_ORBIT = 250; +constexpr float PLAYER_ORBIT_PULL = 0.003f; +constexpr float CENTER_PULL_MAX = 200; +constexpr float CENTER_PULL = 0.002f; +constexpr float RISE_LAG = 15; +constexpr float RISE_LAG_PER_DISTANCE = 20; +constexpr float RISE_MIN_DISTANCE = 100; + +// The attacks: when they fire, the spit's and the Frail's rings' shots, and the big lobbed shot. +constexpr int ROAR_FIRE_FRAME = 20; +constexpr int FRAIL_ROAR_FIRE_FRAME = 47; +constexpr int SPIT_FIRE_FRAME = 46; +constexpr int SCOLEX_SPIT_LAST_FRAME = 48; +constexpr int ATTACK_END_FRAME = 105; +constexpr float PIN_SHOT_HEIGHT = -40; +constexpr int FRAIL_RING_SHOTS = 12; +constexpr float FRAIL_RING_SPEED = 7; +constexpr ColorMod FRAIL_RING_COLOR = {{0.3f, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {140 / 255.0f, 140 / 255.0f, 140 / 255.0f}}; +constexpr int ROAR_SHOTS = 15; +constexpr float CUTE_GRUNT_VOLUME = 0.8f; +constexpr float SPIT_RING_LIFT = -20; +constexpr float SPIT_RING_FALL = -0.06f; +constexpr float SPIT_RING_SPEED = 8; +constexpr float SPIT_RING_SHOTS = 6; +constexpr float BIG_SHOT_SPEED = 10; +constexpr float BIG_SHOT_FALL = -0.3f; +constexpr float PIN_BIG_SHOT_SCALE = 1.6f; +constexpr float BIG_SHOT_LIFT_SCALE = 0.7f; +constexpr float BIG_SHOT_LIFT = -13; +constexpr float BIG_SHOT_SLOW = 0.55f; +constexpr int SEGMENT_SPIT_COOLDOWN = 30; +constexpr int SEGMENT_SPITTER = 4; +constexpr float SEGMENT_CROSS_SPEED = 5; + +// The Frail's beams: the tracer warning of them, the sweep after the player and the bursts. +constexpr float PIN_TRACER_HEIGHT = -80; +constexpr ColorMod PIN_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float PIN_TRACER_SCALE = 4; +constexpr int SWEEP_TRACER_FRAMES = 60; +constexpr int BURST_TRACER_FRAMES = 24; +constexpr int SWEEP_FRAMES = 80; +constexpr int BURSTS_FRAMES = 120; +constexpr int SWEEP_START = 20; +constexpr int SWEEP_LASER_FRAMES = 60; +constexpr float SWEEP_TURN = 0.05f; +constexpr float SWEEP_TURN_MIN = 1; +constexpr int BURST_LASER_FRAMES = 20; +constexpr std::array BURST_TRACERS = {110, 60}; +constexpr std::array BURST_LASERS = {100, 50}; +constexpr int GLOW_LATE_FIRST = 90; +constexpr int GLOW_LATE_LAST = 110; +constexpr int GLOW_EARLY_FIRST = 40; +constexpr int GLOW_EARLY_LAST = 60; +constexpr float BEAM_SIDE_OFFSET = 25; +constexpr float BEAM_OFFSET_X = -5; +constexpr float PIN_BEAM_HEIGHT = -70; +constexpr float BEAM_DEPTH_BELOW = 3000; +constexpr float BEAM_DEPTH_ABOVE = -10; +constexpr float SHOOT_ANIM_STEP = 45; +constexpr int SHOOT_ANIM_ANGLES = 360; +constexpr std::array SHOOT_ANIMS = { + "Attack3ShootLeft", "Attack3ShootUpLeft", "Attack3ShootUp", "Attack3ShootUpRight", + "Attack3ShootRight", "Attack3ShootDownRight", "Attack3ShootDown", "Attack3ShootDownLeft"}; + +// The tail's hole closing, by kind. +constexpr int HOLE_CLOSE_FRAME = 15; +constexpr int SCOLEX_HOLE_CLOSE_FRAME = 25; + +// The Frail's second phase: its sheet, a Delirium form's health, and the blood and dust of the change and its death. +constexpr std::string_view FRAIL_PHASE_SHEET = "gfx/Bosses/Afterbirth/Boss_TheFrail2.png"; +constexpr std::string_view PIN_BOSSES_FOLDER = "Bosses"; +constexpr std::string_view DELIRIUM_FOLDER = "Bosses/AfterbirthPlus/DeliriumForms"; +constexpr size_t GFX_FOLDER_SIZE = 4; +constexpr float DELIRIUM_FRAIL_HEALTH = 75; +constexpr int PHASE_GIBS = 6; +constexpr std::array PHASE_GIB_KINDS = {0, 2, 3}; +constexpr int PHASE_GIB_HEAD_ONLY = 3; +constexpr float PHASE_GIB_SPEED_MIN = 2; +constexpr float PHASE_GIB_SPEED_RANGE = 4; +constexpr float PHASE_GIB_LIFT = 0.5f; +constexpr float PHASE_GIB_SPREAD = 0.5f; +constexpr int DEATH_DUST_MIN = 3; +constexpr float PIN_DEATH_DUST_SPEED = 5; +constexpr float DEATH_DUST_SPREAD = 20; +constexpr float DEATH_DUST_SPIN_MIN = 2; +constexpr float DEATH_DUST_SPIN_RANGE = 10; +constexpr int DEATH_DUST_LIFE_MIN = 15; +constexpr int DEATH_DUST_LIFE_RANGE = 15; +constexpr float DEATH_DUST_ALPHA_MIN = 0.2f; +constexpr float DEATH_DUST_ALPHA_RANGE = 0.5f; + +// i2 holds the Frail's phase in its low half and its beam timer in its high half. +static int frail_phase(const Entity_NPC& npc) +{ + return (short)npc.i2; +} + +static int beam_timer(const Entity_NPC& npc) +{ + return (short)(npc.i2 >> 16); +} + +static void beam_timer_set(Entity_NPC& npc, int timer) +{ + npc.i2 = (int)(((uint32_t)(uint16_t)timer << 16) | (uint16_t)npc.i2); +} + +static void frail_phase_advance(Entity_NPC& npc) +{ + npc.i2 = (int)(((uint32_t)npc.i2 & 0xffff0000u) | (uint16_t)(frail_phase(npc) + 1)); +} + +// The chain's ends and the segment's depth below its head. +struct PinChain +{ + Entity_NPC* head = nullptr; + Entity_NPC* tail = nullptr; + int depth = 0; +}; + +static PinChain pin_chain_get(Entity_NPC& npc) +{ + PinChain chain{.head = &npc, .tail = &npc}; + + for (Entity_NPC* link = npc.ParentNPC(); link; link = link->ParentNPC()) + { + chain.head = link; + chain.depth++; + } + for (Entity_NPC* link = npc.ChildNPC(); link; link = link->ChildNPC()) chain.tail = link; + return chain; +} + +// Plays an animation from its start, the way the AI restarts one. +static void anim_restart(Entity_NPC& npc, std::string_view name) +{ + npc.sprite.Play(name, PLAY_FORCED); +} + +static bool is_anim_done(Entity_NPC& npc) +{ + return !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; +} + +// Grows the head's segments, the last one the hole it rises from, and buries the head. +static void pin_init(Entity_NPC& npc) +{ + if (npc.variant == PIN_FRAIL) + { + npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + npc.health *= 0.5f; + npc.maxHitPoints *= 0.5f; + npc.entityDeque.resize(1); + } + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.state = PIN_BURIED; + npc.i1 = 0; + + int segments = npc.variant == PIN_SCOLEX ? SCOLEX_SEGMENTS : PIN_SEGMENTS; + Entity_NPC* last = &npc; + for (int i = 0; i < segments; i++) + { + auto* segment = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_PIN, .variant = npc.variant, .seed = Random()})); + segment->ClearEntityFlags(FLAG_APPEAR); + segment->isVisible = false; + segment->parent = last; + segment->maxHitPoints = npc.maxHitPoints; + segment->health = npc.health; + last->child = segment; + segment->state = PIN_BURIED; + segment->entityCollisionClass = ENTCOLL_NONE; + last = segment; + + if (npc.variant == PIN_SCOLEX && i >= SCOLEX_THIN_FIRST && i < SCOLEX_SEGMENTS - 1) + { + float size = segment->size * (i == SCOLEX_THICK ? SCOLEX_THICK_SIZE : SCOLEX_THIN_SIZE); + segment->SetSize(size, vector_make(-1, -1), -1); + } + if (npc.variant == PIN_FRAIL) segment->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + } + + last->renderZOffset = TAIL_DEPTH_BELOW; + last->sprite.GetLayer(0)->pos = vector_make(0, 0); + last->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); +} + +// The Frail's second phase sheet on every layer drawing from its first sheet, a Delirium form's from its folder. +static void frail_sheet_load(Entity_NPC& npc, Entity_NPC& segment) +{ + for (size_t layer = 0; layer < segment.sprite.layerStates.size(); layer++) + { + const LayerData* data = segment.sprite.layerStates[layer].layerData; + if (!data || data->spriteSheetId != 0) continue; + + std::string path(FRAIL_PHASE_SHEET); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + path.replace(GFX_FOLDER_SIZE, PIN_BOSSES_FOLDER.size(), DELIRIUM_FOLDER); + segment.sprite.ReplaceSpritesheet((int)layer, npc_sheet_path_get(npc, path)); + } + segment.sprite.LoadGraphics(); + segment.sprite.Update(); +} + +// A Frail spawned in its second phase: every segment changes to it at full health, in its boss color. +static void frail_phase_start(Entity_NPC& npc) +{ + for (auto* segment = static_cast(npc.GetLastParent()); segment; segment = segment->ChildNPC()) + { + segment->maxHitPoints = npc.config->baseHP; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) segment->maxHitPoints = DELIRIUM_FRAIL_HEALTH; + frail_phase_advance(*segment); + segment->health = segment->maxHitPoints; + segment->isDead = false; + frail_sheet_load(npc, *segment); + + // The original also reads the boss color one past the end of the list. Here it stays within. + int bossColor = npc.bosscoloridx; + if (bossColor >= 0 && bossColor < (int)npc.config->bossColors.size()) + segment->SetColor(npc.config->bossColors[bossColor].color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } +} + +// The head shares its lowest health with every segment but the hole, as harmless hits. +static void pin_health_share(Entity_NPC& npc, const PinChain& chain) +{ + float lowest = npc.health - npc.pendingDamage; + for (Entity_NPC* link = npc.ChildNPC(); link; link = link->ChildNPC()) lowest = std::min(lowest, link->health); + + for (Entity_NPC* link = &npc; link; link = link->ChildNPC()) + { + bool isDelirium = npc.HasEntityFlags(FLAG_DELIRIUM_FORM); + bool isHurt = isDelirium ? npc.pendingDamage > 0 && link->health - lowest > 0 + : lowest < link->health - link->pendingDamage; + if (isHurt && link != chain.tail) + link->TakeDamage(link->health - lowest, DAMAGE_INVINCIBLE, EntityRef(&npc), HEALTH_SYNC_COUNTDOWN); + } +} + +// Scolex's segments shrug off hits from anything but itself while more than two segments lie behind them. +static void scolex_shield(Entity_NPC& npc, const PinChain& chain) +{ + int behind = 0; + for (Entity_NPC* link = npc.ChildNPC(); link && link != chain.tail; link = link->ChildNPC()) behind++; + if (behind <= SCOLEX_SHIELDING_SEGMENTS) return; + + for (DamageEvent& event : npc.damageEvents) + { + if (event.source.type == npc.type) continue; + npc.pendingDamage -= event.damage + SCOLEX_SHIELD_SLACK; + event.damage = 0; + } +} + +// The tracer that warns of a Frail beam, pointing at an angle. +static Entity_Effect* beam_tracer_spawn(Entity_NPC& npc, float angle, int frames) +{ + return following_effect_spawn(npc, {.offset = vector_make(0, PIN_TRACER_HEIGHT), + .targetPosition = vector_from_angle(angle), + .color = PIN_TRACER_COLOR, + .scale = PIN_TRACER_SCALE, + .timeout = frames}); +} + +// A beam held at the Frail's mouth, drawn behind it while it points down. +static void beam_place(Entity_Laser& laser, float depthAngle) +{ + Direction direction = vector_to_direction(vector_from_angle(laser.angleDegrees)); + float side = direction == DIRECTION_RIGHT ? BEAM_SIDE_OFFSET : direction == DIRECTION_LEFT ? -BEAM_SIDE_OFFSET : 0; + laser.posOffset = vector_make(side + BEAM_OFFSET_X, PIN_BEAM_HEIGHT); + laser.renderDepthOffset = depthAngle >= 0 ? BEAM_DEPTH_BELOW : BEAM_DEPTH_ABOVE; +} + +static Entity_Laser* beam_shoot(Entity_NPC& npc, float angle, int frames) +{ + Entity_Laser* laser = Entity_Laser::ShootAngle( + {.position = npc.pos, .source = &npc, .angleDegrees = angle, .timeout = frames, .variant = 1}); + npc.entityRef = laser; + return laser; +} + +// The sweep: a beam turning after the player at a twentieth of the way each frame, at least a degree. +static void beam_sweep(Entity_NPC& npc, float targetAngle) +{ + auto* laser = static_cast(npc.entityRef.get()); + bool isNew = !laser; + if (isNew) laser = beam_shoot(npc, npc.v2.x, SWEEP_LASER_FRAMES); + + float angle = angle_lerp(laser->angleDegrees, targetAngle, SWEEP_TURN); + float turn = normalize_angle_degrees(angle - laser->angleDegrees); + if (std::abs(turn) < SWEEP_TURN_MIN) + { + float step = std::min(SWEEP_TURN_MIN, std::abs(turn)); + angle = normalize_angle_degrees(laser->angleDegrees + (turn <= 0 ? -step : step)); + } + laser->set_aim_angle(angle); + Entity* tracer = npc.entityDeque.empty() ? nullptr : npc.entityDeque.front().get(); + if (tracer) tracer->targetPosition = vector_from_angle(angle); + + beam_place(*laser, laser->angleDegrees); + if (isNew) laser->Update(); +} + +// The bursts: tracers then beams at the player twice, the eyes glowing around each. +static void beam_bursts(Entity_NPC& npc, int timer) +{ + if (std::ranges::find(BURST_TRACERS, timer) != BURST_TRACERS.end()) + { + npc.v2.x = vector_angle(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + beam_tracer_spawn(npc, npc.v2.x, BURST_TRACER_FRAMES); + } + else if (std::ranges::find(BURST_LASERS, timer) != BURST_LASERS.end()) + { + Entity_Laser* laser = beam_shoot(npc, npc.v2.x, BURST_LASER_FRAMES); + beam_place(*laser, npc.v2.x); + } + + bool isGlowing = (timer >= GLOW_LATE_FIRST && timer <= GLOW_LATE_LAST) || + (timer >= GLOW_EARLY_FIRST && timer <= GLOW_EARLY_LAST); + npc.sprite.GetLayer("Effect1")->isVisible = isGlowing; + npc.sprite.GetLayer("EyesGlow")->isVisible = isGlowing; +} + +// The Frail's beam attacks: it rises, charges, fires its sweep or bursts while turning its head with the beam, then +// sinks again. +static void frail_beams_update(Entity_NPC& npc, const PinChain& chain) +{ + float targetAngle = vector_angle(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + float headAngle = targetAngle; + if (auto* laser = static_cast(npc.entityRef.get())) headAngle = laser->angleDegrees; + + if (npc.stateFrame == 0) + { + npc.sprite.Play("Attack3Start"); + chain.tail->isVisible = false; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.isVisible = true; + npc.shadowSize = 0; + npc.velocity = vector_make(0, 0); + npc.posOffset.y = 0; + } + else if (npc.stateFrame == 2) + { + int timer = beam_timer(npc); + if (npc.state == PIN_SPITTING && timer > SWEEP_START) beam_sweep(npc, targetAngle); + else if (npc.state != PIN_SPITTING) beam_bursts(npc, timer); + + beam_timer_set(npc, beam_timer(npc) - npc_ticks_get(npc)); + if (beam_timer(npc) < 1) + { + npc.stateFrame++; + npc.sprite.Play("Attack3End"); + npc.sprite.GetLayer("Effect1")->isVisible = true; + npc.sprite.GetLayer("EyesGlow")->isVisible = true; + } + } + + if (is_anim_done(npc)) + { + if (npc.stateFrame == 0) + { + npc.sprite.Play("Attack3Charge"); + npc.stateFrame++; + npc.v2.x = vector_angle(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + npc.PlaySound(SOUND_FRAIL_CHARGE, 1, 2, false, 1); + } + else if (npc.stateFrame == 1 || npc.stateFrame == 2) + { + if (npc.stateFrame == 1) + { + beam_timer_set(npc, npc.state == PIN_SPITTING ? SWEEP_FRAMES : BURSTS_FRAMES); + npc.stateFrame = 2; + npc.PlaySound(SOUND_MONSTER_ROAR_2, 1, 2, false, 1); + } + float angle = normalize_angle_degrees(headAngle + SHOOT_ANIM_STEP - SHOOT_ANIM_STEP / 2); + int index = std::clamp((int)(angle + 180), 0, SHOOT_ANIM_ANGLES - 1) / (int)SHOOT_ANIM_STEP; + anim_restart(npc, SHOOT_ANIMS[index]); + } + else + { + npc.state = PIN_BURIED; + npc.targetPosition = npc.CalcTargetPosition(0); + npc.stateFrame = 0; + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + } + } + npc.velocity = vector_make(0, 0); +} + +// The head's trail, newest first: where it is and how high, a point each 3 it moves or each frame it is buried. +static void trail_record(Entity_NPC& npc) +{ + bool isFar = + npc.vectorDeque1.empty() || vector_length(vector_sub(npc.pos, npc.vectorDeque1.front())) > PIN_TRAIL_STEP; + if (isFar || npc.posOffset.y > BURIED_DEPTH) + { + npc.vectorDeque1.push_front(npc.pos); + npc.vectorDeque2.push_front(npc.posOffset); + } + if (npc.vectorDeque1.size() <= PIN_TRAIL_MAX) return; + + npc.vectorDeque1.erase(npc.vectorDeque1.begin() + TRAIL_KEPT, npc.vectorDeque1.end()); + npc.vectorDeque2.erase(npc.vectorDeque2.begin() + TRAIL_KEPT, npc.vectorDeque2.end()); +} + +// Underground it circles the player and drifts to the middle of the room, rising again once it has fallen far enough +// behind its arc. +static void pin_tunnel(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + npc.friction *= UNDERGROUND_FRICTION; + + Vector toPlayer = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + float playerDistance = vector_length(toPlayer); + if (std::abs(playerDistance) > 1) + { + float lag = PLAYER_ORBIT - playerDistance; + npc.AddVelocity_divided(vector_make(-toPlayer.x * lag / playerDistance * PLAYER_ORBIT_PULL, + -toPlayer.y * lag / playerDistance * PLAYER_ORBIT_PULL), + false); + } + + Vector toCenter = vector_sub(Room::GetCenterPos(), npc.pos); + float centerDistance = vector_length(toCenter); + if (std::abs(centerDistance) > 1) + { + float pull = std::min(centerDistance, CENTER_PULL_MAX); + npc.AddVelocity_divided(vector_make(pull * toCenter.x / centerDistance * CENTER_PULL, + pull * toCenter.y / centerDistance * CENTER_PULL), + false); + } + + if (npc.v1.y - playerDistance / RISE_LAG_PER_DISTANCE > RISE_LAG && playerDistance > RISE_MIN_DISTANCE) + { + npc.targetPosition = npc.CalcTargetPosition(0); + npc.state = PIN_BURIED; + } +} + +// The jump: it records its trail, falls under gravity, wiggles through the air and sinks into a new hole where the +// tail waits. +static void pin_jump_update(Entity_NPC& npc, const PinChain& chain) +{ + trail_record(npc); + float depth = npc.posOffset.y; + npc.v1.y += npc.speedMultiplier * GRAVITY; + if (depth >= BURIED_DEPTH) return pin_tunnel(npc); + + npc.entityCollisionClass = ENTCOLL_ALL; + std::string_view anim = npc.velocity.y > 0 ? "HeadWiggle" + : npc.variant == PIN_FRAIL ? "HeadWiggleUp" + : "Body1Wiggle"; + npc.sprite.Play(anim); + npc.posOffset = vector_add(npc.posOffset, vector_scale(npc.v1, npc.speedMultiplier)); + if (npc.posOffset.y <= SURFACE_DEPTH || npc.posOffset.y - npc.v1.y * npc.speedMultiplier >= SURFACE_DEPTH) return; + + chain.tail->pos = vector_add(npc.pos, npc.velocity); + chain.tail->isVisible = true; + chain.tail->stateFrame = 0; + chain.tail->sprite.Play("Ground"); + if (npc.isVisible) + { + npc.PlaySound(SOUND_MAGGOT_ENTER_GROUND, npc.variant == PIN_PIN ? 0.7f : 1, 2, false, 1); + chain.tail->UpdateDirtColor(true); + } + npc.isVisible = false; +} + +// An attack picked as it surfaces: Scolex and the second phase Frail may roar, the second phase Frail fires beams, +// the rest spit. +static void pin_attack_pick(Entity_NPC& npc) +{ + bool isFrailPhase = npc.variant == PIN_FRAIL && frail_phase(npc) == 1; + if ((npc.variant == PIN_SCOLEX || isFrailPhase) && Random() % 2 == 0 && npc.i1 != PIN_ROARING) + { + npc.i1 = PIN_ROARING; + npc.state = PIN_ROARING; + anim_restart(npc, "Attack2"); + } + else if (isFrailPhase) + { + npc.i1 = (int)(Random() % 2) * 2 + PIN_SPITTING; + npc.state = npc.i1; + anim_restart(npc, "Attack3Start"); + if (npc.state == PIN_SPITTING) + { + // The original writes the tracer into an empty deque for a Frail that skipped its start. Here it is + // dropped. + float angle = vector_angle(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + Entity_Effect* tracer = beam_tracer_spawn(npc, angle, SWEEP_TRACER_FRAMES); + if (!npc.entityDeque.empty()) npc.entityDeque.front() = tracer; + } + } + else + { + npc.i1 = PIN_SPITTING; + npc.state = PIN_SPITTING; + npc.sprite.Play("Attack1", PLAY_FORCED); + } + npc.UpdateDirtColor(true); + npc.stateFrame = 0; +} + +// A dive: it bursts out toward its target (the room's middle the first time) with the hole left behind it. +static void pin_dive(Entity_NPC& npc, const PinChain& chain) +{ + if (g_game->frameCount - npc.spawnFrame > DIVE_SOUND_DELAY) + npc.PlaySound(SOUND_MAGGOT_BURST_OUT, npc.variant == PIN_SCOLEX ? 1 : 0.7f, 2, false, 1); + + if (vector_is_zero(npc.targetPosition)) + { + npc.targetPosition = Room::GetCenterPos(); + npc.shadowSize = 0; + npc.posOffset.y = SPAWN_DEPTH; + } + else + { + chain.tail->isVisible = true; + npc.isVisible = true; + npc.shadowSize = npc.config->shadowSize; + npc.posOffset.y = RISING_DEPTH; + npc.i1 = PIN_POPPED_UP; + } + + Vector toTarget = vector_sub(npc.targetPosition, npc.pos); + float distance = vector_length(toTarget); + if (std::abs(distance) > 1) + { + float speed = JUMP_SPEED; + if (npc.variant == PIN_FRAIL) speed = Random() % 2 == 0 ? FRAIL_JUMP_FAST : FRAIL_JUMP_SLOW; + npc.velocity = vector_make(toTarget.x / distance * speed, toTarget.y / distance * speed); + } + npc.state = PIN_JUMPING; + + chain.tail->pos = vector_add(npc.pos, npc.velocity); + chain.tail->sprite.Play("Ground"); + chain.tail->stateFrame = 0; + chain.tail->UpdateDirtColor(true); + npc.vectorDeque1.clear(); + npc.vectorDeque2.clear(); + npc.v1 = vector_make(0, JUMP_LIFT - distance * JUMP_LIFT_PER_DISTANCE); + npc.vectorDeque1.push_front(npc.pos); + npc.vectorDeque2.push_front(npc.posOffset); +} + +// Buried, it either attacks where it surfaced or dives on. A Delirium form in a cleared room only dives. +static void pin_buried_update(Entity_NPC& npc, const PinChain& chain) +{ + bool isPicking = + (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !room_is_clear()) && Random() % 2 == 0 && npc.i1 != PIN_SPITTING; + bool isAttacking = isPicking && npc.i1 != 0 && npc.i1 != PIN_ROARING && npc.i1 != PIN_ATTACK_DIVE; + if (!isAttacking && npc.i1 == PIN_ROARING) + isAttacking = npc.variant == PIN_FRAIL && frail_phase(npc) == 1 && Random() % 5 != 0; + + if (isAttacking) pin_attack_pick(npc); + else pin_dive(npc, chain); +} + +// Its spit and roar shots, on the frame each fires. +static void pin_shots_fire(Entity_NPC& npc) +{ + float pitch = champion_pitch_get(npc); + npc_sound_play(SOUND_BLOODSHOOT, 1, 2, pitch); + if (npc.state == PIN_ROARING) + { + npc_sound_play(SOUND_MONSTER_ROAR_2, 1, 2, pitch); + ProjectileParams params; + params.heightModifier = PIN_SHOT_HEIGHT; + if (npc.variant == PIN_FRAIL) + { + params.bulletFlags |= PROJECTILE_GOO | PROJECTILE_CANT_HIT_PLAYER; + params.color = FRAIL_RING_COLOR; + npc.FireBossProjectiles(FRAIL_RING_SHOTS, vector_make(0, 0), FRAIL_RING_SPEED, params); + } + else npc.FireBossProjectiles(ROAR_SHOTS, npc.GetPlayerTarget()->pos, 0, params); + } + else + { + bool isPin = npc.variant == PIN_PIN; + npc_sound_play(isPin ? SOUND_CUTE_GRUNT : SOUND_BOSS_LITE_HISS, isPin ? CUTE_GRUNT_VOLUME : 1, 2, pitch); + ProjectileParams params; + if (isPin && npc.subtype == 1) + { + Vector mouth = vector_make(npc.pos.x, npc.pos.y + SPIT_RING_LIFT); + params.bulletFlags |= PROJECTILE_ORBIT_CW; + params.fallingAccelModifier = SPIT_RING_FALL; + params.targetPosition = mouth; + npc.FireProjectiles(mouth, vector_make(SPIT_RING_SPEED, SPIT_RING_SHOTS), PROJECTILES_RING, params); + } + else + { + Entity_Projectile* shot = npc.FireBossProjectiles(1, npc.GetPlayerTarget()->pos, BIG_SHOT_SPEED, params); + shot->projectileFlags |= PROJECTILE_EXPLODE; + shot->fallingAccel += BIG_SHOT_FALL; + shot->scale = PIN_BIG_SHOT_SCALE; + shot->fallingSpeed = shot->fallingSpeed * BIG_SHOT_LIFT_SCALE + BIG_SHOT_LIFT; + shot->height += PIN_SHOT_HEIGHT; + shot->velocity = vector_scale(shot->velocity, BIG_SHOT_SLOW); + } + } + npc_sound_play(SOUND_PIN_SPIT, 1, 2, 1); +} + +// Whether this frame of an attack fires: the roar on frame 20 (47 for the Frail), the spit on 46 (to 48 for Scolex). +static bool is_fire_frame(const Entity_NPC& npc, int frame) +{ + if (npc.state == PIN_ROARING) return frame == (npc.variant == PIN_FRAIL ? FRAIL_ROAR_FIRE_FRAME : ROAR_FIRE_FRAME); + if (npc.state != PIN_SPITTING) return false; + if (frame == SPIT_FIRE_FRAME) return true; + return frame > SPIT_FIRE_FRAME && frame <= SCOLEX_SPIT_LAST_FRAME && npc.variant == PIN_SCOLEX; +} + +// Its spit or roar above ground, a frame per tick, sinking back once the animation ends. +static void pin_attack_update(Entity_NPC& npc, const PinChain& chain) +{ + chain.tail->isVisible = false; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.isVisible = true; + npc.shadowSize = 0; + npc.velocity = vector_make(0, 0); + npc.posOffset.y = 0; + + for (int ticks = npc_ticks_get(npc); ticks > 0; ticks--) + { + if (is_fire_frame(npc, npc.stateFrame)) pin_shots_fire(npc); + else if (npc.stateFrame >= ATTACK_END_FRAME) + { + npc.state = PIN_BURIED; + npc.targetPosition = npc.CalcTargetPosition(0); + npc.stateFrame = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + } + else if (is_anim_done(npc)) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + } + npc.stateFrame++; + } +} + +// The head: shares its health, then digs, jumps or attacks. +static void pin_head_update(Entity_NPC& npc, const PinChain& chain) +{ + pin_health_share(npc, chain); + + bool isFrailBeam = npc.variant == PIN_FRAIL && frail_phase(npc) != 0; + if (npc.state == PIN_SPITTING && isFrailBeam) + { + if (frail_phase(npc) == 1) frail_beams_update(npc, chain); + return; + } + if (npc.state == PIN_BEAMS) return frail_beams_update(npc, chain); + if (npc.state == PIN_JUMPING) return pin_jump_update(npc, chain); + if (npc.state == PIN_BURIED) return pin_buried_update(npc, chain); + if (npc.state == PIN_SPITTING || npc.state == PIN_ROARING) pin_attack_update(npc, chain); +} + +// The tail: the hole the head left, closing a while after it and sharing the segment above's health. +static void pin_tail_update(Entity_NPC& npc) +{ + npc.stateFrame++; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + bool isPinHole = npc.stateFrame == HOLE_CLOSE_FRAME && (npc.variant == PIN_PIN || npc.variant == PIN_FRAIL); + if (isPinHole || (npc.stateFrame == SCOLEX_HOLE_CLOSE_FRAME && npc.variant == PIN_SCOLEX)) + { + anim_restart(npc, "HoleClose"); + npc.UpdateDirtColor(true); + } + if (is_anim_done(npc)) npc.isVisible = false; + if (npc.parent) npc.health = npc.parent->health; +} + +// A body segment's wiggle, by kind and place in the chain. +static std::string_view body_anim_get(Entity_NPC& npc, int depth) +{ + if (npc.variant == PIN_PIN) return "Body2Wiggle"; + if (npc.variant == PIN_SCOLEX) + { + if (depth == 2 || depth == 7) return "Body3Wiggle"; + if (depth == SCOLEX_SEGMENTS - 1) return "TailWiggle"; + return depth >= 1 && depth <= 6 ? "Body2Wiggle" : ""; + } + if (npc.variant != PIN_FRAIL || depth < 1 || depth > PIN_SEGMENTS - 1) return ""; + + int place = depth - 1; + if (frail_phase(npc) == 0) return place == 0 || place == 2 ? "Body2Wiggle" : "Body3Wiggle"; + if (place == 1) return "Body2Wiggle"; + if (place == 3) return "Body3Wiggle"; + return place == 4 ? "TailWiggleUp" : "Body1Wiggle"; +} + +// A body segment follows its head's trail some points behind, solid while near the ground. Pin's and the Frail's +// fourth segment spits while high in the air. +static void pin_body_update(Entity_NPC& npc, const PinChain& chain) +{ + if (npc.isVisible) npc.shadowSize = npc.config->shadowSize; + if (chain.head->state != PIN_JUMPING) + { + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + return; + } + + npc.sprite.Play(body_anim_get(npc, chain.depth)); + int delay = npc.variant == PIN_SCOLEX ? SCOLEX_DELAYS[std::min(chain.depth, SCOLEX_SEGMENTS - 1)] + : PIN_DELAYS[std::min(chain.depth, PIN_SEGMENTS - 1)]; + if (delay >= (int)chain.head->vectorDeque1.size()) return; + + npc.pos = chain.head->vectorDeque1[delay]; + npc.velocity = vector_make(0, 0); + npc.posOffset = chain.head->vectorDeque2[delay]; + npc.entityCollisionClass = npc.posOffset.y < BURIED_DEPTH ? ENTCOLL_ALL : ENTCOLL_NONE; + npc.isVisible = npc.posOffset.y < BURIED_DEPTH; + + bool isSpitter = (npc.variant == PIN_PIN || npc.variant == PIN_FRAIL) && chain.depth == SEGMENT_SPITTER; + if (!isSpitter || (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear())) return; + + if (npc.projectileCooldown > 0) npc.projectileCooldown--; + if (Random() % 2 != 0 || npc.posOffset.y >= PIN_SPIT_HEIGHT || npc.projectileCooldown >= 1) return; + + npc.projectileCooldown = SEGMENT_SPIT_COOLDOWN; + ProjectileParams params; + if (npc.variant == PIN_FRAIL && frail_phase(npc) == 1) params.bulletFlags |= PROJECTILE_BURST; + if (npc.variant == PIN_PIN && npc.subtype == 1) + npc.FireProjectiles(npc.pos, vector_make(SPIT_RING_SPEED, SPIT_RING_SHOTS), PROJECTILES_RING, params); + else npc.FireProjectiles(npc.pos, vector_make(SEGMENT_CROSS_SPEED, 0), PROJECTILES_CROSS, params); + npc_sound_play(SOUND_PIN_SPIT, 1, 2, 1); +} + +// The Frail's first phase ends: every segment rises again at full health in its second phase sheet, bursting blood. +static void frail_phase_change(Entity_NPC& npc, const PinChain& chain) +{ + npc.PlaySound(SOUND_DEATH_BURST_LARGE, 1, 2, false, 1); + for (auto* segment = static_cast(npc.GetLastParent()); segment; segment = segment->ChildNPC()) + { + if (!segment->HasEntityFlags(FLAG_DELIRIUM_FORM)) segment->maxHitPoints = npc.config->baseHP; + frail_phase_advance(*segment); + segment->health = segment->maxHitPoints; + segment->isDead = false; + frail_sheet_load(npc, *segment); + segment->damageEvents.clear(); + segment->pendingDamage = 0; + segment->pendingDamageFlags = 0; + + for (int i = 0; i < PHASE_GIBS; i++) + { + float speed = random_unit() * PHASE_GIB_SPEED_RANGE + PHASE_GIB_SPEED_MIN; + int kind = PHASE_GIB_KINDS[Random() % PHASE_GIB_KINDS.size()]; + if (kind == PHASE_GIB_HEAD_ONLY && segment != chain.head) kind = PHASE_GIB_KINDS[Random() % 2]; + uint32_t seed = Random(); + Vector heading = random_direction(); + Vector velocity = vector_make(heading.x * speed, heading.y * PHASE_GIB_LIFT * speed); + Vector place = random_direction(); + Vector position = vector_make(place.x * PHASE_GIB_SPREAD * segment->size + segment->pos.x, + place.y * PHASE_GIB_SPREAD * segment->size + segment->pos.y); + Entity* gib = g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .subType = kind, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = seed}); + gib->splatColor = segment->splatColor; + } + + Entity* burst = g_game->Spawn({.position = segment->pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_LARGE_BLOOD_EXPLOSION, + .seed = Random()}); + burst->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } +} + +// The Frail's second phase ends in faint spinning dust. A Delirium form takes the whole chain with it. +static void frail_death_dust(Entity_NPC& npc, const PinChain& chain) +{ + int clouds = (int)(Random() % 4) + DEATH_DUST_MIN; + for (int i = 0; i < clouds; i++) + { + Vector heading = random_direction(); + Vector velocity = vector_scale(heading, random_unit() * PIN_DEATH_DUST_SPEED); + uint32_t seed = Random(); + Vector place = random_direction(); + Vector position = vector_add(npc.pos, vector_scale(place, random_unit() * DEATH_DUST_SPREAD)); + auto* dust = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + float side = + (dust->pos.y - npc.pos.y) * -velocity.x + (dust->pos.x - npc.pos.x) * velocity.y < 0 ? -1.0f : 1.0f; + dust->rotation = (random_unit() * DEATH_DUST_SPIN_RANGE + DEATH_DUST_SPIN_MIN) * side; + int life = (int)(Random() % DEATH_DUST_LIFE_RANGE) + DEATH_DUST_LIFE_MIN; + dust->timeout = life; + dust->lifespan = life; + ColorMod faint = tint_color_make(1, 1, 1, random_unit() * DEATH_DUST_ALPHA_RANGE + DEATH_DUST_ALPHA_MIN); + dust->SetColor(faint, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->Update(); + + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + for (Entity* link = chain.tail; link; link = link->parent) link->Kill(EntityRef()); + } +} + +// What a dead segment does: the Frail's first death starts its second phase and its second leaves dust, and a +// Delirium form's chain all dies with it. +static void pin_death_update(Entity_NPC& npc, const PinChain& chain) +{ + if (!npc.isDead) return; + if (npc.variant == PIN_FRAIL) + { + if (frail_phase(npc) == 0) frail_phase_change(npc, chain); + else frail_death_dust(npc, chain); + return; + } + if (npc.variant != PIN_PIN && npc.variant != PIN_SCOLEX) return; + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) return; + + for (Entity* link = chain.tail; link; link = link->parent) link->Kill(EntityRef()); +} + +// 00476860 Pin, Scolex and the Frail: a worm that dives through the floor, its body following its trail, rising to +// spit and roar. The Frail changes into a second phase with beams. Wormwood runs its own AI. +void boss_pin_update(Entity_NPC& npc) +{ + if (npc.variant == PIN_WORMWOOD) return boss_wormwood_update(npc); + + PinChain chain = pin_chain_get(npc); + npc.renderZOffset = chain.depth * (npc.velocity.y < 0 ? -RENDER_DEPTH_STEP : RENDER_DEPTH_STEP); + if (npc.state == NPC_STATE_INIT && chain.depth == 0) + { + pin_init(npc); + chain = pin_chain_get(npc); + } + if (npc.subtype == 1 && frail_phase(npc) == 0 && npc.variant == PIN_FRAIL) frail_phase_start(npc); + + if (chain.head == chain.tail) + { + npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.Kill(EntityRef()); + return; + } + if (npc.variant == PIN_SCOLEX && npc.state != PIN_SPITTING) scolex_shield(npc, chain); + + if (&npc == chain.head) pin_head_update(npc, chain); + else if (&npc == chain.tail) pin_tail_update(npc); + else pin_body_update(npc, chain); + + pin_death_update(npc, chain); + if (npc.sprite.IsEventTriggered("Dive")) npc_sound_play(SOUND_PIN_DIVE, 1, 2, 1); + if (npc.sprite.IsEventTriggered("Popup")) npc_sound_play(SOUND_PIN_POPUP, 1, 2, 1); +} diff --git a/src/boss_rag_man.cpp b/src/boss_rag_man.cpp index 70a7ec5..99f3c8d 100644 --- a/src/boss_rag_man.cpp +++ b/src/boss_rag_man.cpp @@ -311,7 +311,7 @@ static void rag_man_headless(Entity_NPC& npc, int heads) if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) { npc.pathfinder.MoveRandomly(STATUS_OBEYED); - npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(RAG_MAN_WANDER_DRAG, npc.speedMultiplier)); + npc.velocity = vector_scale(npc.velocity, timescale_factor(RAG_MAN_WANDER_DRAG, npc.speedMultiplier)); } else { @@ -548,7 +548,7 @@ static void rag_man_head_update(Entity_NPC& npc) Vector steer = vector_add(vector_add(vector_scale(toTarget, speed * HEAD_STEER), npc.velocity), vector_scale(heading, speed * HEAD_STEER)); steer = vector_resized(steer, speed); - float keep = npc_friction_scaled(RAG_MAN_FRICTION, npc.speedMultiplier); + float keep = timescale_factor(RAG_MAN_FRICTION, npc.speedMultiplier); npc.velocity = vector_add(vector_scale(vector_sub(steer, npc.velocity), 1 - keep), npc.velocity); constexpr std::string_view ROLLS[] = {"RollLeft", "RollUp", "RollRight"}; @@ -617,7 +617,7 @@ static void mega_ball_chase(Entity_NPC& npc) { npc.friction *= BALL_FRICTION; Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); - npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(BALL_DRAG, npc.speedMultiplier)); + npc.velocity = vector_scale(npc.velocity, timescale_factor(BALL_DRAG, npc.speedMultiplier)); npc_push(npc, vector_scale(vector_normalized(toTarget), BALL_CHASE)); npc.mass = MEGA_BALL_MASS; if (npc.v2.y > 0) diff --git a/src/boss_wormwood.cpp b/src/boss_wormwood.cpp new file mode 100644 index 0000000..f6b4fb7 --- /dev/null +++ b/src/boss_wormwood.cpp @@ -0,0 +1,912 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "entity_projectile.h" +#include "level.h" +#include "room_grid.h" +#include + +// Wormwood's states: swimming under the floor, up in the air, stunned by a bomb it bit, leaping out of a pit, its +// spit and slam, and its enraged leap across the room. +constexpr int WORMWOOD_SWIMMING = NPC_STATE_IDLE; +constexpr int WORMWOOD_SURFACED = NPC_STATE_MOVE; +constexpr int WORMWOOD_STUNNED = NPC_STATE_SUICIDE; +constexpr int WORMWOOD_LEAPING = NPC_STATE_JUMP; +constexpr int WORMWOOD_SPITTING = NPC_STATE_ATTACK; +constexpr int WORMWOOD_SLAMMING = NPC_STATE_ATTACK2; +constexpr int WORMWOOD_CROSSING = NPC_STATE_SPECIAL; + +// Its head's look (i1): closed, opening, open and stunned. Its temper (i2): calm, enraged under a third of its health, +// and done crossing. +constexpr int HEAD_CLOSED = 0; +constexpr int HEAD_OPENING = 1; +constexpr int HEAD_OPEN = 2; +constexpr int HEAD_STUNNED = 3; +constexpr int TEMPER_ENRAGED = 1; +constexpr int TEMPER_CROSSED = 2; +constexpr float ENRAGE_HEALTH = 0.33f; +constexpr int ENRAGED_SLAMS_MIN = 3; +constexpr float ENRAGED_DAMAGE_TAKEN = 0.2f; + +// The head's animations, front and back. +constexpr std::array HEAD_OPENING_ANIMS = {"HeadFrontWiggleTransition", + "HeadBackWiggleTransition"}; +constexpr std::array HEAD_OPEN_ANIMS = {"HeadFrontWiggleOpen", "HeadBackWiggleOpen"}; +constexpr std::array HEAD_CLOSED_ANIMS = {"HeadFrontWiggleClosed", "HeadBackWiggleClosed"}; +constexpr std::array WORMWOOD_BODY_ANIMS = {"Body1Wiggle", "Body2Wiggle", "Body3Wiggle", + "Body4Wiggle", "Body5Wiggle", "Body6Wiggle"}; +constexpr int SEGMENTS = 6; +constexpr int PIN_WORMWOOD_VARIANT = 3; +constexpr float TAIL_TURN = 0.3f; +constexpr float HEALTH_SHARE_START = 1e10f; +constexpr int HEALTH_SHARE_COUNTDOWN = 30; + +// Its depth (v1.y, its sinking speed in v1.x): 14 deep under the floor, -8 at the top of a leap out of a pit, solid +// from 0 up to 35 above, and a splash crossing the surface faster than 2 a frame. +constexpr float DEPTH_SUBMERGED = 14; +constexpr float DEPTH_LEAP_TOP = -8; +constexpr float DEPTH_SOLID_TOP = -35; +constexpr float SINK_ACCEL = 0.2f; +constexpr float BOUNCE = 0.4f; +constexpr float WORMWOOD_SPLASH_SPEED = 2; +constexpr float WORMWOOD_SPLASH_FRICTION = 0.5f; +constexpr float PIT_PROBE = 10; +constexpr float WORMWOOD_SEGMENT_GAP = 20; +constexpr float WORMWOOD_TRAIL_STEP = 3; +constexpr size_t WORMWOOD_TRAIL_MAX = 60; + +// Swimming: the speeds it steers by, the wobble of its swim and the pits it aims for. +constexpr float SWIM_TURN = 1.6f; +constexpr float SWIM_PIT_TURN = 1.2f; +constexpr float SWIM_SINK_TURN = 5; +constexpr float SWIM_SPEED_UP = 0.22f; +constexpr float CHASE_SPEED_UP = 0.4f; +constexpr float ENRAGED_SPEED_UP = 3; +constexpr float ENRAGED_TURN = 6; +constexpr float WOBBLE_RATE = 0.4f; +constexpr float WOBBLE_DEGREES = 16; +constexpr float WORMWOOD_PIT_REACH = 20; +constexpr float SLAM_REACH = 30; +constexpr float LEAP_SPEED = 8; +constexpr float LEAP_LIFT = -8; +constexpr int PIT_LOST_FRAMES = 30; +constexpr float PIT_SCORE = 500; +constexpr float WORMWOOD_PIT_SCORE_RANDOM = 40; +constexpr float PIT_SCORE_POOL = 100; + +// Surfacing: frames it swims first, the frames it stays up, and how much each hit cuts them. +constexpr int SWIM_FRAMES_MIN = 30; +constexpr int SWIM_FRAMES_RANGE = 30; +constexpr int ENRAGED_SWIM_FRAMES = 60; +constexpr int SPAWN_SWIM_FRAMES = 30; +constexpr int SPIT_DIVE_FRAMES = 15; +constexpr int SLAM_DIVE_FRAMES = 30; +constexpr int LEAP_TIRE_FRAMES = 15; +constexpr int LEAP_FALL_FRAMES = 45; +constexpr int LEAP_LAND_FRAMES = 150; +constexpr float HIT_FRAMES = 2; +constexpr float SWIM_FRICTION = 0.96f; +constexpr float SURFACED_FRICTION = 0.95f; +constexpr float STUNNED_FRICTION = 0.85f; +constexpr float WORMWOOD_ATTACK_FRICTION = 0.4f; +constexpr float STUN_ESCAPE_TURN = 15; +constexpr float STUN_ESCAPE_SPEED = 10; + +// The spit and the slam: thirteen shots led at the player, a slam hurting what stands within 40 and digging a pit. +constexpr int SPIT_SPLASH_FRAME = 2; +constexpr int WORMWOOD_SPIT_SHOTS = 13; +constexpr float WORMWOOD_SPIT_LEAD = 0.02f; +constexpr float SLAM_REACH_HIT = 40; +constexpr float SLAM_ENEMY_DAMAGE = 25; +constexpr float SLAM_PLAYER_DAMAGE = 1; +constexpr float SLAM_PUSH = 15; +constexpr int SLAM_COUNTDOWN = 30; +constexpr int WORMWOOD_SLAM_SHAKE = 8; +constexpr int SLAM_PARTICLES = 4; +constexpr float SLAM_PARTICLE_SPEED = 6; +constexpr int SHOOT_PLUS_SPEED = 10; + +// The enraged crossing: it shakes the room, waits, and bursts out of the wall, scattering dust and three leeches. +constexpr int CROSS_SHAKE = 15; +constexpr int CROSS_WAIT = 30; +constexpr float CROSS_SPEED = 20; +constexpr float CROSS_LIFT = -14; +constexpr float CROSS_RISE = -4; +constexpr int CROSS_LEECHES = 3; +constexpr float CROSS_LEECH_STEP = 80; +constexpr float CROSS_LEECH_SPREAD = 10; +constexpr float CROSS_LEECH_HEIGHT = -8; +constexpr int CROSS_PARTICLES_MIN = 6; +constexpr int CROSS_PARTICLES_RANGE = 5; +constexpr float CROSS_PARTICLE_SPEED = 8; +constexpr int WORMWOOD_DUST_MIN = 3; +constexpr float WORMWOOD_DUST_SPEED = 5; +constexpr float DUST_SPREAD = 20; +constexpr float WORMWOOD_DUST_SPIN_MIN = 2; +constexpr float WORMWOOD_DUST_SPIN_RANGE = 10; +constexpr int WORMWOOD_DUST_LIFE_MIN = 15; +constexpr int DUST_LIFE_RANGE = 15; + +// A leech thrown out of the floor: its rise and the share of the way to its spot it flies each frame. +constexpr float LEECH_RISE = -8; +constexpr float LEECH_FLIGHT = 0.04f; +constexpr int LEECH_STATE_THROWN = NPC_STATE_JUMP; +constexpr float BIG_LEECH_SCALE = 1.25f; + +// The sound of a splash plays after 10 frames. +constexpr int SPLASH_SOUND_DELAY = 10; + +// 005ae1d0 Whether the run is in the Corpse, where Wormwood spits plain shots. +static bool is_corpse() +{ + return g_game->GetStageID() == STAGE_ID_CORPSE; +} + +// The room cell a position rounds to, or -1 outside the room. +static int cell_at(const Vector& position) +{ + Room& room = *g_game->room; + 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); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return -1; + + int index = room.gridWidth * row + column; + return index < ROOM_GRID_CELLS ? index : -1; +} + +static bool is_pit_cell(int index) +{ + GridEntity* grid = index >= 0 && index < ROOM_GRID_CELLS ? g_game->room->gridEntities[index] : nullptr; + return grid && grid->type == GRID_PIT; +} + +// 005ae0b0 Whether a position lies over a pit. +static bool is_over_pit(const Vector& position) +{ + return is_pit_cell(cell_at(position)); +} + +// The pit at a room column and row, none outside the room. +static bool is_pit_tile(int column, int row) +{ + Room& room = *g_game->room; + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return false; + return is_pit_cell(room.gridWidth * row + column); +} + +// 005ae140 A big splash where it breaks the surface. +static void splash_spawn(Entity_NPC& npc) +{ + Entity* splash = + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_SPLASH, .seed = Random()}); + splash->Update(); + npc_sound_play(SOUND_BOSS2_DIVE, 1, SPLASH_SOUND_DELAY, 1); +} + +// 0055c4c0 A leech thrown up out of the floor onto a spot, claiming its cell, the big one twice as tough. +Entity_NPC* leech_throw(const LeechThrow& thrown) +{ + Room& room = *g_game->room; + auto* leech = static_cast(g_game->Spawn({.position = thrown.position, + .spawner = thrown.spawner, + .subType = thrown.isBig ? 1 : 0, + .type = ENTITY_SMALL_LEECH, + .seed = Random()})); + leech->ClearEntityFlags(FLAG_APPEAR); + leech->targetPosition = thrown.target; + + int cell = cell_at(thrown.target); + if (cell >= 0) + { + int claim = room.gridPaths[cell] % GRID_PATH_SOLID; + if (claim < GRID_PATH_FREED) room.gridPaths[cell] += GRID_PATH_FREED - claim; + } + + leech->v1 = vector_make(LEECH_RISE, 0); + leech->state = LEECH_STATE_THROWN; + leech->posOffset.y = thrown.height; + leech->v2 = vector_make((leech->targetPosition.x - leech->pos.x) * LEECH_FLIGHT, + (leech->targetPosition.y - leech->pos.y) * LEECH_FLIGHT); + leech->velocity = leech->v2; + if (!thrown.isBig) return leech; + + leech->maxHitPoints += leech->maxHitPoints; + leech->sprite.scale = vector_make(BIG_LEECH_SCALE, BIG_LEECH_SCALE); + leech->health = leech->maxHitPoints; + return leech; +} + +// 005ae230 The pit it swims for next: the one scoring best on closeness, a little chance and pits on all four sides. +static void pit_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + float bestScore = 0; + int best = -1; + + for (int index = 0; index < room.gridHeight * room.gridWidth; index++) + { + if (!is_pit_cell(index)) continue; + + int column = index % room.gridWidth; + int row = index / room.gridWidth; + Vector cell = + vector_make((float)column * GRID_CELL_SIZE + GRID_ORIGIN_X, (float)row * GRID_CELL_SIZE + GRID_ORIGIN_Y); + float distance = vector_length(vector_sub(npc.pos, cell)); + float score = std::max(PIT_SCORE - distance + random_unit() * WORMWOOD_PIT_SCORE_RANDOM, 0.0f); + bool isPool = is_pit_tile(column - 1, row) && is_pit_tile(column + 1, row) && is_pit_tile(column, row - 1) && + is_pit_tile(column, row + 1); + if (isPool) score += PIT_SCORE_POOL; + if (score <= bestScore) continue; + + best = index; + bestScore = score; + } + if (best >= 0) npc.projectileDelay = best; +} + +// The wobble of its swim, a slow sway of up to 8 degrees either way. +static Vector swim_wobble(Entity_NPC& npc, Vector velocity) +{ + float sway = std::sin((float)(g_game->frameCount - npc.spawnFrame) * WOBBLE_RATE); + float angle = ((sway * 0.5f + 0.5f) * WOBBLE_DEGREES - WOBBLE_DEGREES / 2) * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + return vector_make(cosine * velocity.x - sine * velocity.y, cosine * velocity.y + sine * velocity.x); +} + +// The velocity turned to a heading at a speed. +static void velocity_resize(Entity_NPC& npc, float speed) +{ + npc.velocity = vector_scale(vector_normalized(npc.velocity), speed); +} + +// Swimming to its pit: once over it, it either dives in to spit or leaps out after the player. +static void pit_swim(Entity_NPC& npc, int pit) +{ + float speed = vector_length(npc.velocity) + SWIM_SPEED_UP; + Vector pitPosition = g_game->room->GetGridPosition(pit); + Vector toPit = vector_sub(pitPosition, npc.pos); + if (npc.state == WORMWOOD_SWIMMING && vector_length(toPit) < WORMWOOD_PIT_REACH) + { + if (npc.v2.x > 0 && Random() % 2 == 0) + { + npc.targetPosition = pitPosition; + npc.velocity = vector_make(0, 0); + npc.pos = pitPosition; + npc.projectileDelay = -1; + npc.state = WORMWOOD_SPITTING; + npc.v2.x = 0; + return; + } + + Vector heading = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + npc.v1.x = LEAP_LIFT; + npc.velocity = vector_scale(heading, LEAP_SPEED); + npc.stateFrame = 0; + npc.projectileDelay = -1; + npc.state = WORMWOOD_LEAPING; + npc.v2.x += 1; + return; + } + + Vector heading = vector_normalized(vector_add(toPit, random_direction())); + float sm = npc.speedMultiplier; + npc.velocity = vector_make(heading.x * SWIM_TURN * SWIM_PIT_TURN * sm + npc.velocity.x, + heading.y * SWIM_TURN * SWIM_PIT_TURN * sm + npc.velocity.y); + if (npc.v1.y > 0) + { + Vector turned = vector_make(heading.x * SWIM_SINK_TURN * npc.speedMultiplier + npc.velocity.x, + heading.y * SWIM_SINK_TURN * npc.speedMultiplier + npc.velocity.y); + float turnedLength = vector_length(turned); + npc.velocity = turnedLength > 0 ? vector_scale(turned, vector_length(npc.velocity) / turnedLength) : turned; + } + if (npc.v1.y <= 0) npc.velocity = swim_wobble(npc, npc.velocity); + velocity_resize(npc, speed); +} + +// 005aef20 Steering the head: to its pit when it has one, else after the player, slamming down when close. +static void wormwood_steer(Entity_NPC& npc) +{ + if (npc.subtype != 0) return; + + int pit = npc.projectileDelay; + if (pit >= 0 && is_pit_cell(pit)) return pit_swim(npc, pit); + if (pit >= 0) + { + npc.projectileDelay = -1; + npc.stateFrame = PIT_LOST_FRAMES; + } + + bool isEnraged = npc.i2 == TEMPER_ENRAGED; + float speed = vector_length(npc.velocity) + (isEnraged ? ENRAGED_SPEED_UP : 1) * CHASE_SPEED_UP; + Vector target = isEnraged ? npc.GetPlayerTarget()->pos : npc.CalcTargetPosition(0); + Vector heading = vector_normalized(vector_sub(target, npc.pos)); + float turn = isEnraged ? ENRAGED_TURN : 1; + npc.velocity = vector_make(heading.x * SWIM_TURN * turn * npc.speedMultiplier + npc.velocity.x, + heading.y * SWIM_TURN * turn * npc.speedMultiplier + npc.velocity.y); + if (npc.v1.y <= 0) npc.velocity = swim_wobble(npc, npc.velocity); + velocity_resize(npc, speed); + + if (npc.projectileCooldown <= 0 || vector_length(vector_sub(target, npc.pos)) >= SLAM_REACH) return; + + Room& room = *g_game->room; + Vector cell = room.GetGridPosition(room.GetGridIndex(npc.pos)); + npc.targetPosition = cell; + npc.velocity = vector_make(0, 0); + npc.pos = cell; + npc.state = WORMWOOD_SLAMMING; + npc.projectileCooldown--; +} + +// 005ae490 The head's and body's wiggle: the head opening before it spits a plus of shots, the tail turning after its +// segment. +static void wormwood_animate(Entity_NPC& npc) +{ + if (npc.subtype > SEGMENTS) return; + if (npc.subtype > 0) + { + npc.sprite.Play(WORMWOOD_BODY_ANIMS[npc.subtype - 1]); + if (npc.subtype < SEGMENTS) return; + + Entity& above = *npc.parent; + float dx = above.pos.x + above.posOffset.x - npc.pos.x - npc.posOffset.x; + float dy = above.pos.y + above.posOffset.y - npc.pos.y - npc.posOffset.y; + float angle = normalize_angle_degrees(std::atan2(dy, dx) * RADIANS_TO_DEGREES - npc.sprite.rotation); + npc.sprite.rotation = normalize_angle_degrees(angle * TAIL_TURN + npc.sprite.rotation); + return; + } + + int side = npc.velocity.y < 0 ? 1 : 0; + if (npc.i1 == HEAD_OPEN) return npc.sprite.Play(HEAD_OPEN_ANIMS[side]); + if (npc.i1 != HEAD_OPENING) return npc.sprite.Play(HEAD_CLOSED_ANIMS[side]); + + std::string_view shown = npc.sprite.GetAnimation(); + bool isTurning = + shown == HEAD_OPENING_ANIMS[1] || (shown != HEAD_OPENING_ANIMS[side] && shown == HEAD_OPENING_ANIMS[0]); + float frame = npc.sprite.animState.animData ? npc.sprite.animState.animFrame : -1; + npc.sprite.Play(HEAD_OPENING_ANIMS[side]); + if (isTurning && npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat(frame); + + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + ProjectileParams params; + if (!is_corpse()) params.variant = g_game->GetStageID() != STAGE_ID_DROSS ? PROJECTILE_TEAR : PROJECTILE_PUKE; + npc.FireProjectiles(npc.pos, vector_make(SHOOT_PLUS_SPEED, 0), PROJECTILES_PLUS, params); + } + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) npc.i1 = HEAD_OPEN; +} + +// A segment's place along the trail its leader left, 20 behind it, sinking or rising with it. +static void segment_trail_follow(Entity_NPC& npc, Entity_NPC& leader) +{ + Vector point = leader.pos; + float pointDepth = leader.v1.y; + float walked = 0; + + for (size_t i = 0; i < leader.vectorDeque1.size(); i++) + { + Vector next = leader.vectorDeque1[i]; + float nextDepth = leader.vectorDeque2[i].y; + Vector step = vector_sub(next, point); + float stepDepth = nextDepth - pointDepth; + float length = std::sqrt(step.y * step.y + step.x * step.x + stepDepth * stepDepth); + if (length + walked > WORMWOOD_SEGMENT_GAP) + { + float share = (WORMWOOD_SEGMENT_GAP - walked) / length; + npc.velocity = vector_make((share * step.x + point.x - npc.pos.x) / npc.friction, + (share * step.y + point.y - npc.pos.y) / npc.friction); + npc.v1.x = share * stepDepth + pointDepth - npc.v1.y; + npc.v1.y = npc.v1.x * npc.speedMultiplier + npc.v1.y; + return; + } + walked += length; + point = next; + pointDepth = nextDepth; + } + + Vector toEnd = vector_sub(point, npc.pos); + float endDepth = pointDepth - npc.v1.y; + if (std::sqrt(toEnd.y * toEnd.y + toEnd.x * toEnd.x + endDepth * endDepth) > WORMWOOD_SEGMENT_GAP) + { + npc.velocity = vector_make(toEnd.x / npc.friction, toEnd.y / npc.friction); + npc.v1.x = pointDepth - npc.v1.y; + } + npc.v1.y = npc.v1.x * npc.speedMultiplier + npc.v1.y; +} + +// The head sinks back under or bounces off solid floor at the top of a leap, splashing as it crosses the surface. +static void head_depth_update(Entity_NPC& npc, float depth) +{ + float sink = npc.speedMultiplier * SINK_ACCEL; + float speed = sink + npc.v1.x; + if (speed >= 0 && npc.v1.y >= DEPTH_SUBMERGED) npc.v1 = vector_make(0, DEPTH_SUBMERGED); + else + { + npc.v1.x = speed + sink; + npc.v1.y = speed * npc.speedMultiplier + npc.v1.y; + bool isFalling = depth <= DEPTH_LEAP_TOP && npc.v1.y > DEPTH_LEAP_TOP && npc.v1.x > 0; + bool isOverPit = is_over_pit(vector_make(npc.pos.x - PIT_PROBE, npc.pos.y)) && + is_over_pit(vector_make(npc.pos.x + PIT_PROBE, npc.pos.y)) && + is_over_pit(vector_make(npc.pos.x, npc.pos.y - PIT_PROBE)) && + is_over_pit(vector_make(npc.pos.x, npc.pos.y + PIT_PROBE)); + bool isLanding = isOverPit && (npc.state != WORMWOOD_SURFACED || npc.projectileDelay >= 0); + if (isFalling && !isLanding) + { + npc.v1.x = -npc.v1.x * BOUNCE; + npc.v1.y = DEPTH_LEAP_TOP; + } + } + + if (depth > 0 && npc.v1.y < 0 && npc.v1.y - depth < -WORMWOOD_SPLASH_SPEED) splash_spawn(npc); + else if (depth < 0 && npc.v1.y > 0 && npc.v1.y - depth > -WORMWOOD_SPLASH_SPEED) + { + splash_spawn(npc); + npc.friction *= WORMWOOD_SPLASH_FRICTION; + } +} + +// 005ae840 A segment follows its leader's trail, the head sinks and rises, and each fades with depth, is solid only +// near the surface and leaves its own trail. +static void wormwood_follow(Entity_NPC& npc) +{ + float depth = npc.v1.y; + if (npc.parent) segment_trail_follow(npc, *static_cast(npc.parent.get())); + if (npc.subtype == 0) head_depth_update(npc, depth); + + if (npc.v1.y > 0) + { + npc.sprite.GetLayer(0)->color._tint[3] = 1 - std::min(std::max(npc.v1.y / DEPTH_SUBMERGED, 0.0f), 1.0f); + npc.shadowSize = 0; + } + else + { + npc.sprite.GetLayer(0)->color._tint[3] = 1; + npc.shadowSize = npc.config->shadowSize; + } + bool isSolid = npc.v1.y <= 0 && npc.v1.y >= DEPTH_SOLID_TOP; + npc.entityCollisionClass = isSolid ? ENTCOLL_ALL : ENTCOLL_NONE; + npc.entityGridCollisionClass = isSolid ? GRIDCOLL_NOPITS : GRIDCOLL_WALLS; + + if (!npc.vectorDeque1.empty()) + { + Vector moved = vector_sub(npc.vectorDeque1.front(), npc.pos); + float sunk = npc.vectorDeque2.front().y - npc.v1.y; + if (std::sqrt(moved.y * moved.y + moved.x * moved.x + sunk * sunk) <= WORMWOOD_TRAIL_STEP) return; + } + npc.vectorDeque1.push_front(npc.pos); + npc.vectorDeque2.push_front(vector_make(0, npc.v1.y)); + while (npc.vectorDeque1.size() > WORMWOOD_TRAIL_MAX) + { + npc.vectorDeque1.pop_back(); + npc.vectorDeque2.pop_back(); + } +} + +// Spinning dust thrown from a spot, faint and short lived, turning away from the side it flies to. +struct DustBurst +{ + Vector origin{}; + Vector center{}; + Vector side{}; + Vector velocity{}; +}; + +static void dust_spawn(const DustBurst& burst, uint32_t seed, Vector place) +{ + auto* dust = static_cast(g_game->Spawn({.position = place, + .velocity = burst.velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + float spin = vector_dot(vector_sub(dust->pos, burst.origin), burst.side) < 0 ? -1.0f : 1.0f; + dust->rotation = (random_unit() * WORMWOOD_DUST_SPIN_RANGE + WORMWOOD_DUST_SPIN_MIN) * spin; + int life = (int)(Random() % DUST_LIFE_RANGE) + WORMWOOD_DUST_LIFE_MIN; + dust->timeout = life; + dust->lifespan = life; + dust->Update(); +} + +// The enraged crossing starts: it picks a cell by the wall beside the player, out of a door's way, and the wall there +// crumbles. +static void crossing_start(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.state = WORMWOOD_CROSSING; + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, 1); + game_shake_screen(CROSS_SHAKE); + npc.stateFrame = CROSS_WAIT; + + float centerX = Room::GetCenterPos().x; + int column = npc.GetPlayerTarget()->pos.x <= centerX ? 0 : room.gridWidth - 1; + int row = std::max((int)std::floor((npc.GetPlayerTarget()->pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f), 1); + int lastRow = room.gridHeight - 2; + row = std::min(row, lastRow); + + // The original reads past the room's cells for a cell outside it. Here none is there. + GridEntity* wall = column >= 0 && column < room.gridWidth && row < room.gridHeight + ? room.gridEntities[room.gridWidth * row + column] + : nullptr; + if (wall && wall->type == GRID_DOOR) row = row < 2 || (row != lastRow && Random() % 2 != 0) ? row + 1 : row - 1; + + npc.targetPosition = room.GetGridPosition(room.GetGridIndexByTile(column, row)); + float out = npc.targetPosition.x <= centerX ? 1.0f : -1.0f; + + int clouds = (int)(Random() % 4) + WORMWOOD_DUST_MIN; + for (int i = 0; i < clouds; i++) + { + uint32_t seed = Random(); + float forward = random_unit() * WORMWOOD_DUST_SPEED; + float across = random_unit() * WORMWOOD_DUST_SPEED - WORMWOOD_DUST_SPEED / 2; + Vector velocity = vector_make(out * forward + across * 0.0f, -out * across + forward * 0.0f); + Vector place = vector_add(npc.targetPosition, vector_scale(random_direction(), random_unit() * DUST_SPREAD)); + dust_spawn({.origin = npc.pos, .side = vector_make(0, -out), .velocity = velocity}, seed, place); + } + game_particles_spawn({.position = npc.targetPosition, + .speed = CROSS_PARTICLE_SPEED, + .count = (int)(Random() % CROSS_PARTICLES_RANGE) + CROSS_PARTICLES_MIN, + .variant = EFFECT_ROCK_PARTICLE}); +} + +// It bursts out of the wall across the room, its body with it, scattering dust and leeches. +static void crossing_burst(Entity_NPC& npc) +{ + npc.pos = npc.targetPosition; + npc.v1 = vector_make(CROSS_RISE, CROSS_LIFT); + npc.vectorDeque1.clear(); + npc.vectorDeque2.clear(); + float centerX = Room::GetCenterPos().x; + bool isFromRight = centerX <= npc.targetPosition.x; + npc.velocity = vector_make(isFromRight ? -CROSS_SPEED : CROSS_SPEED, 0); + for (auto* segment = static_cast(npc.child.get()); segment; + segment = static_cast(segment->child.get())) + { + segment->pos = npc.pos; + segment->v1 = npc.v1; + segment->vectorDeque1.clear(); + segment->vectorDeque2.clear(); + } + + for (int subType : {0, 1}) + { + Entity* hole = g_game->Spawn({.position = npc.pos, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_WORMWOOD_HOLE, + .seed = Random()}); + hole->sprite.isFlipX = isFromRight; + hole->Update(); + } + + int clouds = (int)(Random() % 3) + WORMWOOD_DUST_MIN; + for (int i = 0; i < clouds; i++) + { + float across = random_unit() * WORMWOOD_DUST_SPEED - WORMWOOD_DUST_SPEED / 2; + float forward = random_unit() * WORMWOOD_DUST_SPEED; + Vector velocity = vector_make(i != 0 ? -forward : forward, across); + uint32_t seed = Random(); + Vector heading = random_direction(); + float reach = random_unit(); + Vector place = + vector_make(heading.x * DUST_SPREAD * reach + npc.pos.x, heading.y * DUST_SPREAD * reach + npc.pos.y); + dust_spawn({.origin = npc.pos, .side = vector_make(i != 0 ? -1.0f : 1.0f, 0), .velocity = velocity}, seed, + place); + } + + for (int i = 0; i < CROSS_LEECHES; i++) + { + Vector spot = room_free_pickup_position_find({.position = npc.pos, + .step = CROSS_LEECH_STEP, + .isAvoidActiveEntities = true, + .isAllowPits = g_game->room->waterAmount > 0}); + Vector target = vector_add(spot, vector_scale(random_direction(), CROSS_LEECH_SPREAD)); + leech_throw({.position = npc.pos, .target = target, .spawner = &npc, .height = CROSS_LEECH_HEIGHT}); + } + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, 1); + npc_sound_play(SOUND_BOSS2INTRO_PIPES_TURNON, 1, 2, 1); + game_shake_screen(CROSS_SHAKE); + npc.i1 = HEAD_OPEN; + npc.state = WORMWOOD_LEAPING; + npc.stateFrame = 0; + npc.i2 = TEMPER_CROSSED; + wormwood_follow(npc); +} + +// Back to swimming for a while, shorter once enraged. +static void swim_start(Entity_NPC& npc) +{ + if (npc.state == WORMWOOD_SWIMMING) return; + + npc.state = WORMWOOD_SWIMMING; + npc.stateFrame = + npc.i2 == TEMPER_ENRAGED ? ENRAGED_SWIM_FRAMES : (int)(Random() % SWIM_FRAMES_RANGE) + SWIM_FRAMES_MIN; +} + +// Rising out of a pit to attack: still, the head shown in full and drawn toward its spot. +static void attack_hold(Entity_NPC& npc, std::string_view anim) +{ + npc.v1 = vector_make(0, -1); + npc.sprite.Play(anim); + npc.sprite.GetLayer(0)->color._tint[3] = 1; + npc.friction *= WORMWOOD_ATTACK_FRICTION; + npc.velocity = vector_make((npc.targetPosition.x - npc.pos.x) / npc.friction, + (npc.targetPosition.y - npc.pos.y) / npc.friction); +} + +// Sinking again after an attack. +static void attack_end(Entity_NPC& npc, int frames) +{ + splash_spawn(npc); + swim_start(npc); + npc.v1.y = DEPTH_SUBMERGED; + npc.sprite.GetLayer(0)->color._tint[3] = 0; + npc.stateFrame = frames; + npc.entityCollisionClass = ENTCOLL_NONE; +} + +// The spit from a pit: thirteen shots led at the player, puke in Dross, tears elsewhere and plain in the Corpse. +static void spit_update(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + attack_hold(npc, "Attack1"); + if (npc.sprite.GetFrame() == SPIT_SPLASH_FRAME) splash_spawn(npc); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_BOSS_LITE_HISS, 1, 2, 1); + ProjectileParams params; + if (!is_corpse()) params.variant = g_game->GetStageID() != STAGE_ID_DROSS ? PROJECTILE_TEAR : PROJECTILE_PUKE; + Vector target = npc.GetPlayerTarget()->pos; + Entity* player = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(target, npc.pos)); + Vector led = vector_make(player->velocity.x * distance * WORMWOOD_SPIT_LEAD + target.x, + player->velocity.y * distance * WORMWOOD_SPIT_LEAD + target.y); + npc.FireBossProjectiles(WORMWOOD_SPIT_SHOTS, led, 0, params); + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + attack_end(npc, SPIT_DIVE_FRAMES); +} + +// The slam: enemies within 40 take 25 and players 1, all are thrown back, and the floor caves into a pit. +static void slam_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (!npc.sprite.WasEventTriggered("Shoot")) npc.entityCollisionClass = ENTCOLL_NONE; + attack_hold(npc, "Attack2"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + splash_spawn(npc); + for (size_t i = 0; i < room.entityList.updateEL.size(); i++) + { + Entity* entity = room.entityList.updateEL[i]; + bool isNear = vector_length(vector_sub(npc.pos, entity->pos)) < SLAM_REACH_HIT; + bool isOther = !(entity->type == ENTITY_PIN && entity->variant == PIN_WORMWOOD_VARIANT); + if (entity->IsVulnerableEnemy(nullptr) && isOther && isNear) + entity->TakeDamage(SLAM_ENEMY_DAMAGE, 0, EntityRef(), SLAM_COUNTDOWN); + else if (entity->type == ENTITY_PLAYER && isNear) + entity->TakeDamage(SLAM_PLAYER_DAMAGE, 0, EntityRef(&npc), SLAM_COUNTDOWN); + else continue; + npc_push(*entity, vector_scale(vector_normalized(vector_sub(entity->pos, npc.pos)), SLAM_PUSH)); + } + + if (!is_over_pit(npc.pos)) + { + GridEntity* grid = room_grid_entity_at(npc.pos); + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, 1); + game_shake_screen(WORMWOOD_SLAM_SHAKE); + if (grid) grid->Destroy(true, EntityRef(&npc)); + } + if (room_can_spawn_obstacle_at(npc.pos, false)) + { + int cell = room.GetGridIndex(npc.pos); + room.SpawnGridEntity(cell, GRID_PIT, 0, Random(), 0); + GridEntity* pit = cell >= 0 && cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (pit && pit->type == GRID_PIT) pit->PostInit(); + game_particles_spawn({.position = npc.pos, + .speed = SLAM_PARTICLE_SPEED, + .count = SLAM_PARTICLES, + .variant = EFFECT_ROCK_PARTICLE}); + } + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + attack_end(npc, SLAM_DIVE_FRAMES); +} + +// Stunned by a bomb it bit: the bomb goes off in its mouth, then it flees from its body at an angle. +static void stunned_update(Entity_NPC& npc) +{ + npc.friction *= STUNNED_FRICTION; + if (npc.i1 != HEAD_STUNNED) + { + npc.i1 = HEAD_STUNNED; + npc.PlaySound(SOUND_SMB_LARGE_CHEWS_4, 1, 2, false, 1); + npc.sprite.Play(npc.velocity.y < 0 ? "HeadBackStunned" : "HeadFrontStunned"); + } + wormwood_follow(npc); + + if (Entity* bomb = npc.entityRef.get()) + { + bomb->velocity = vector_make(0, 0); + bomb->pos = npc.pos; + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + if (bomb->type == ENTITY_BOMB) + { + static_cast(bomb)->explosionCountdown = 0; + static_cast(bomb)->explosionCountdown2 = 0; + bomb->Update(); + } + } + + npc.i1 = HEAD_OPEN; + npc.state = WORMWOOD_SURFACED; + if (Entity* body = npc.child) + { + Vector away = vector_normalized(vector_sub(body->pos, npc.pos)); + float turn = (Random() % 2 == 0 ? -STUN_ESCAPE_TURN : STUN_ESCAPE_TURN) * DEGREES_TO_RADIANS; + float cosine = std::cos(turn); + float sine = std::sin(turn); + npc.velocity = vector_make((away.x * cosine - away.y * sine) * STUN_ESCAPE_SPEED, + (away.y * cosine + away.x * sine) * STUN_ESCAPE_SPEED); + } + npc.stateFrame = 1; +} + +// The head grows its body and goes under. +static void wormwood_init(Entity_NPC& npc) +{ + if (npc.subtype == 0) + { + Entity_NPC* last = &npc; + for (int i = 1; i <= SEGMENTS; i++) + { + auto* segment = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = i, + .type = npc.type, + .variant = npc.variant, + .seed = Random()})); + segment->parent = last; + last->child = segment; + last = segment; + segment->Update(); + } + npc.stateFrame = SPAWN_SWIM_FRAMES; + } + npc.ClearEntityFlags(FLAG_APPEAR); + npc.v1 = vector_make(0, DEPTH_SUBMERGED); + swim_start(npc); +} + +// While enraged it takes a fifth of its hits. +static void enraged_damage_cut(Entity_NPC& npc) +{ + for (auto* link = &npc; link; link = static_cast(link->child.get())) + { + link->pendingDamage = 0; + for (DamageEvent& event : link->damageEvents) + { + event.damage *= ENRAGED_DAMAGE_TAKEN; + link->pendingDamage += event.damage; + } + } +} + +// Every segment's health falls to the lowest, as harmless hits, and the body dies with the head. +static void health_share(Entity_NPC& npc) +{ + float lowest = HEALTH_SHARE_START; + for (Entity* link = &npc; link; link = link->child) lowest = std::min(lowest, link->health - link->pendingDamage); + + for (Entity* link = &npc; link; link = link->child) + { + float health = link->health - link->pendingDamage; + if (lowest < health) link->TakeDamage(health - lowest, DAMAGE_INVINCIBLE, EntityRef(), HEALTH_SHARE_COUNTDOWN); + } + if (npc.isDead) + for (Entity* link = npc.child; link; link = link->child) link->Kill(EntityRef()); +} + +// 005af800 Wormwood: a worm swimming under the floor that leaps out of pits after the player and rises from them to +// spit or slam new pits into the floor. Enraged, it crosses the room through its walls. +void boss_wormwood_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.subtype != 0) + { + if (!npc.parent) npc.Kill(EntityRef()); + if (npc.state != NPC_STATE_INIT) + { + wormwood_animate(npc); + wormwood_follow(npc); + npc.posOffset.y = npc.v1.y; + return; + } + } + + switch (npc.state) + { + case NPC_STATE_INIT: + wormwood_init(npc); + wormwood_animate(npc); + wormwood_follow(npc); + return; + case WORMWOOD_SWIMMING: + npc.friction *= SWIM_FRICTION; + wormwood_animate(npc); + wormwood_steer(npc); + wormwood_follow(npc); + npc.i1 = HEAD_CLOSED; + if (npc.stateFrame <= 0 || npc.projectileCooldown != 0) break; + npc.stateFrame -= ticks; + if (npc.stateFrame >= 1) break; + if (npc.i2 == TEMPER_ENRAGED) crossing_start(npc); + else pit_pick(npc); + break; + case WORMWOOD_SURFACED: + npc.friction *= SURFACED_FRICTION; + wormwood_animate(npc); + wormwood_follow(npc); + if (npc.stateFrame > 0) + { + npc.stateFrame -= ticks; + if (npc.stateFrame < 1 || npc.i2 == TEMPER_ENRAGED) pit_pick(npc); + } + if (npc.v1.y <= 0 || npc.v1.x < 0) + { + wormwood_steer(npc); + break; + } + npc.projectileDelay = -1; + swim_start(npc); + break; + case WORMWOOD_STUNNED: + stunned_update(npc); + break; + case WORMWOOD_LEAPING: + { + wormwood_animate(npc); + wormwood_follow(npc); + float depth = npc.v1.y; + if (depth > 0 && npc.v1.x > 0) + { + swim_start(npc); + break; + } + if (npc.stateFrame > LEAP_TIRE_FRAMES && npc.i1 == HEAD_CLOSED) npc.i1 = HEAD_OPENING; + npc.stateFrame += ticks; + if (npc.stateFrame > LEAP_FALL_FRAMES && depth <= 0 && depth == DEPTH_LEAP_TOP) + { + npc.stateFrame = LEAP_LAND_FRAMES; + npc.state = WORMWOOD_SURFACED; + } + break; + } + case WORMWOOD_SPITTING: + spit_update(npc); + break; + case WORMWOOD_SLAMMING: + slam_update(npc); + break; + case WORMWOOD_CROSSING: + wormwood_animate(npc); + wormwood_follow(npc); + npc.stateFrame -= ticks; + npc.i1 = HEAD_CLOSED; + if (npc.stateFrame < 1) crossing_burst(npc); + break; + } + + npc.posOffset.y = npc.v1.y; + if (npc.i2 == 0 && npc.health / npc.maxHitPoints < ENRAGE_HEALTH && !is_corpse()) + { + npc.i2 = TEMPER_ENRAGED; + if (npc.state == WORMWOOD_SURFACED) npc.stateFrame = 1; + npc.projectileCooldown = (int)(Random() % 4) + ENRAGED_SLAMS_MIN; + } + if (npc.i2 == TEMPER_ENRAGED) enraged_damage_cut(npc); + health_share(npc); + + if (npc.state != WORMWOOD_SURFACED || npc.stateFrame <= 0 || npc.pendingDamage <= 0) return; + npc.stateFrame = std::max(npc.stateFrame - (int)std::ceil(npc.pendingDamage * HIT_FRAMES), 1); +} diff --git a/src/camera.cpp b/src/camera.cpp index 39ebf88..2165d59 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -68,11 +68,6 @@ constexpr float NET_VIEW_HALF_HEIGHT = 207.6923f; constexpr int ITEM_STATE_LUDOVICO_CHARGE = 49; constexpr int COLLECTIBLE_LUDOVICO_TECHNIQUE = 329; -static float random_unit() -{ - return (float)Random() * 2.3283064e-10f; -} - // 00945130 Adds a vector, dropping the oldest when full. void VectorRing::push(Vector vector) { diff --git a/src/entity.cpp b/src/entity.cpp index fb6504d..e3b9ad6 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -33,7 +33,6 @@ constexpr float ROOM_SCREEN_SCALE = 0.65f; constexpr float ROOM_VIEW_HEIGHT = 182; constexpr float ROOM_VIEW_WIDTH = 338; constexpr float HALF = 0.5f; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; // GetRenderZ's bands: the background layer, the door layer and the normal layer sorted by depth. constexpr int RENDER_INDEX_MASK = 0x3ff; @@ -59,7 +58,6 @@ constexpr float STAGE_HP_CAP = 10; constexpr uint32_t STAGE_HP_REDUCED_FROM = 5; constexpr float STAGE_HP_REDUCED_SCALE = 0.8f; constexpr float STAGE_HP_MIN = 0.001f; -constexpr float PI_FLOAT = 3.1415927f; // The knockback a heavy hit leaves: how it slows, and the speed under which it ends. constexpr float KNOCKBACK_DECAY = 0.95f; @@ -132,16 +130,6 @@ constexpr int GABRIEL_SPAWNED_BIT = 26; KAGE_LogMessage(level, (uint8_t*)message); } -static float vector_length(Vector v) -{ - return std::sqrt(v.x * v.x + v.y * v.y); -} - -static Vector vector_add(Vector a, Vector b) -{ - return vector_make(a.x + b.x, a.y + b.y); -} - // 0067f310 Where a world position draws on screen, optionally snapped to the display's pixels. Vector render_position_get(const Vector& world, RenderSnap snap) { @@ -299,7 +287,7 @@ void Entity::SetSize(float newSize, Vector newSizeMulti, int gridCollisionPoints { for (int i = first; i < gridCollisionPoints; i += 2) { - double angle = (((float)i + (float)i) * PI_FLOAT) / (float)gridCollisionPoints; + double angle = (((float)i + (float)i) * PI_F) / (float)gridCollisionPoints; collisionPoints.push_back(vector_make((float)std::cos(angle) * size * sizeMulti.x, (float)std::sin(angle) * size * sizeMulti.y)); } diff --git a/src/entity.h b/src/entity.h index 9522063..e9b6d71 100644 --- a/src/entity.h +++ b/src/entity.h @@ -221,9 +221,11 @@ enum EntityType : int ENTITY_GYRO = 824, ENTITY_FIRE_WORM = 825, ENTITY_HARDY = 826, + ENTITY_FACELESS = 827, ENTITY_MOLE = 829, ENTITY_BIG_BONY = 830, ENTITY_GUTTED_FATTY = 831, + ENTITY_EXORCIST = 832, ENTITY_PEEPER_FATTY = 835, ENTITY_PON = 840, ENTITY_SMALL_MAGGOT = 853, @@ -244,6 +246,7 @@ enum EntityType : int ENTITY_BALL_AND_CHAIN = 893, ENTITY_REAP_CREEP = 900, ENTITY_VISAGE = 903, + ENTITY_SIREN = 904, ENTITY_HERETIC = 905, ENTITY_HORNFEL = 906, ENTITY_GIDEON = 907, @@ -285,6 +288,13 @@ enum PitfallState : int PITFALL_GONE }; +// A color offset step: one 255th. +constexpr float COLOR_OFFSET_UNIT = 0.003921569f; + +// Gigante Bean's push of every enemy a doubled fart hits, away from the fart. +constexpr float GIGANTE_KNOCKBACK_SPEED = 8; +constexpr int GIGANTE_KNOCKBACK_FRAMES = 18; + // Lua's EntityFlag: the state and status effects an entity carries. enum EntityFlag : uint64_t { @@ -797,6 +807,7 @@ struct Entity void AddSlowing(const EntityRef& source, int duration, float amount, ColorMod slowColor, bool isIgnoreBossCooldown); void AddCharmed(const EntityRef& source, int duration, bool isIgnoreBossCooldown, bool isAddEnemyKillScore); void AddConfusion(const EntityRef& source, int duration, bool isIgnoreBossCooldown); + void AddKnockback(const EntityRef& source, Vector push, int duration, bool isImpactDamage); void AddMidasFreeze(const EntityRef& source, int duration, bool isIgnoreBossCooldown); void AddFear(const EntityRef& source, int duration, bool isIgnoreBossCooldown); void AddBurn(const EntityRef& source, int duration, float damage, bool isIgnoreBossCooldown); diff --git a/src/entity_bomb.h b/src/entity_bomb.h index e69946a..29bee18 100644 --- a/src/entity_bomb.h +++ b/src/entity_bomb.h @@ -109,6 +109,7 @@ private: }; void explosion_damage(Explosion explosion); +void shovel_quest_dig(); bool explosion_line_clear(const Vector& start, const Vector& end, bool isIgnoreWalls); void explosion_effects(const Explosion& explosion); void explosion_tear_flag_effects(const Explosion& explosion); diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 4491352..795742e 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -56,7 +56,6 @@ constexpr float BOUNCE_VOLUME_BASE = 0.2f; constexpr float BOUNCE_VOLUME_MAX = 1.2f; constexpr float BOUNCE_PITCH_BASE = 0.9f; constexpr float BOUNCE_PITCH_SPREAD = 0.2f; -constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; // Samson's Chains' ball breaks rocks it hits faster than this. constexpr int FAMILIAR_SAMSONS_CHAINS = 75; @@ -92,19 +91,6 @@ struct EntityPush float share = 0; }; -static float vector_length(Vector v) -{ - return std::sqrt(v.x * v.x + v.y * v.y); -} - -// A vector scaled to length one, or as it is with no length (Vector::Normalized). -static Vector vector_normalized(Vector v) -{ - float length = vector_length(v); - if (length > 0) return vector_make(v.x * (1 / length), v.y * (1 / length)); - return v; -} - static bool is_unit_size(const Entity& entity) { return entity.sizeMulti.x == 1 && entity.sizeMulti.y == 1; diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index dba77d5..d48c0d6 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -143,6 +143,8 @@ constexpr float THROWN_DAMAGE_SCALE = 3; constexpr float THROWN_DAMAGE_BONUS = 5; constexpr float SLOW_ON_CONTACT = 0.5f; constexpr float ICE_KNOCKBACK_SPEED_SQUARED = 0.001f; +constexpr float ICE_SHOVE_SPEED = 18; +constexpr int ICE_SHOVE_FRAMES = 200; // Entity::BloodExplode and gibs_spawn: the bursts' gibs and blood drops. constexpr int EXTRA_BLOOD_GIBS = 8; @@ -1084,15 +1086,20 @@ static float player_contact_damage(Entity_Player& player, Entity& collider, bool return damage; } -// Part of 0078e1f0: the player's ways of touching, Tainted Magdalene's hug, and those not written yet: shoving an iced -// enemy, Mega Mush's stomp, Tainted Soul grabbing her body and the suplex grab. +// Part of 0078e1f0: the player's ways of touching: shoving an iced enemy, Tainted Magdalene's hug, and those not +// written yet: Mega Mush's stomp, Tainted Soul grabbing her body and the suplex grab. static void player_contact_missing_check(Entity_Player& player, Entity& collider) { bool isEnemyLike = Entity::is_enemy_type(collider.type) || (g_game->deathmatchManager.is_active() && collider.type == ENTITY_PLAYER); bool isShoved = isEnemyLike && collider.HasEntityFlags(FLAG_ICE_FROZEN) && !collider.HasEntityFlags(FLAG_KNOCKED_BACK) && vector_length_squared(player.velocity) > ICE_KNOCKBACK_SPEED_SQUARED; - if (isShoved) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: shoving an iced enemy (AddKnockback)"); + if (isShoved) + { + Vector toward = vector_normalized(vector_sub(collider.pos, player.pos)); + Vector push = vector_normalized(vector_add(vector_normalized(player.velocity), toward)); + collider.AddKnockback(EntityRef(&player), vector_scale(push, ICE_SHOVE_SPEED), ICE_SHOVE_FRAMES, true); + } tainted_magdalene_hug(player, collider); if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Mega Mush's stomp"); diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index a181159..07fd0f9 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -32,14 +32,12 @@ constexpr int FAMILIAR_CREEP_WAVE = 125; constexpr int EFFECT_BLACK_POWDER = 92; constexpr int EFFECT_TIMER = 119; -constexpr int EFFECT_ENEMY_SOUL = 179; // The Hourglass slows Hush's lasers from full speed to half as its effect's cooldown runs from 0 to 30. constexpr float HOURGLASS_COOLDOWN_SPAN = 30; constexpr float HOURGLASS_SLOWEST = 0.5f; constexpr float PAUSE_VELOCITY_DECAY = 0.6f; -constexpr int SOUND_PORTAL_ENTITY_LOOP = 846; constexpr int SOUND_CHAIN_LOOP = 503; // The variants the behaviour tables can index, up to the last vanilla one. @@ -94,12 +92,13 @@ static const EffectBehaviour* behaviour_find(int variant) { static const std::array TABLE = [] { std::array table{}; - for (auto group : {item_effect_behaviours(), ambient_effect_behaviours(), hazard_effect_behaviours(), - floor_effect_behaviours(), beam_effect_behaviours(), player_effect_behaviours(), - mines_effect_behaviours(), - trail_effect_behaviours(), spike_effect_behaviours(), boss_effect_behaviours(), - weapon_effect_behaviours(), passive_effect_behaviours(), alt_effect_behaviours(), - std::span(TIMER_BEHAVIOURS)}) + for (auto group : + {item_effect_behaviours(), portal_effect_behaviours(), blast_effect_behaviours(), soul_effect_behaviours(), + mother_effect_behaviours(), shot_effect_behaviours(), ambient_effect_behaviours(), + hazard_effect_behaviours(), floor_effect_behaviours(), beam_effect_behaviours(), + player_effect_behaviours(), mines_effect_behaviours(), trail_effect_behaviours(), + spike_effect_behaviours(), boss_effect_behaviours(), weapon_effect_behaviours(), + passive_effect_behaviours(), alt_effect_behaviours(), std::span(TIMER_BEHAVIOURS)}) for (const EffectBehaviour& behaviour : group) table[behaviour.variant] = behaviour; return table; }(); @@ -117,7 +116,7 @@ EffectUpdateEnd effect_poof_update(Entity_Effect& effect) } // An angle in degrees wrapped into -180 to 180, as approach_angle wraps it. -static float angle_wrapped(float angle) +float angle_wrapped(float angle) { if (std::fabs(angle) > DEGREES_PER_TURN) angle = std::fmod(angle, DEGREES_PER_TURN); if (angle > DEGREES_PER_TURN / 2) return angle - DEGREES_PER_TURN; @@ -140,21 +139,46 @@ float angle_approach(float current, float target, float maxStep) return angle_wrapped(delta > 0 ? current + maxStep : current - maxStep); } -// 00a15640 (assert_lerp_range, always clamped here) A value's place between two inputs, carried onto two outputs. -float lerp_clamped(float value, float inFirst, float inLast, float outFirst, float outLast) +// Plays a sound through the seeds' fart override. +void effect_sound_play(int sound, SoundPlay play) { - float t = (value - inFirst) / (inLast - inFirst); - if (t <= 0) t = 0; - if (t >= 1) t = 1; - return (outLast - outFirst) * t + outFirst; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, play); +} + +// FUN_007ab0e0 A player is free unless an extra or item animation plays, carrying their twin aside. +bool is_player_free(Entity_Player& player) +{ + bool isAnimating = player.isPlayingExtraAnimation || player.isPlayingItemAnimation; + return !isAnimating || (player.heldEntity && player.heldEntity == player.twinPlayer.get()); +} + +// The tear flags an effect carries in its variant data (a holy water trail's, a brimstone swirl's). +TearFlags effect_tear_flags(const Entity_Effect& effect) +{ + TearFlags flags; + for (size_t bit = 0; bit < flags.size(); bit++) flags[bit] = (effect.varData[bit / 32] >> (bit % 32)) & 1; + return flags; +} + +// BlendMode::SetMode on a layer. +static void layer_blend_set(LayerState& layer, KAGE::Graphics::BlendType type) +{ + KAGE::Graphics::BlendMode mode; + mode.SetMode(type); + layer.blendMode = {mode.equation, mode.rgbSource, mode.rgbDest, mode.alphaSource, mode.alphaDest}; } // BlendMode::SetMode 2 on a layer. void layer_additive_set(LayerState& layer) { - KAGE::Graphics::BlendMode mode; - mode.SetMode(KAGE::Graphics::BLEND_ADDITIVE); - layer.blendMode = {mode.equation, mode.rgbSource, mode.rgbDest, mode.alphaSource, mode.alphaDest}; + layer_blend_set(layer, KAGE::Graphics::BLEND_ADDITIVE); +} + +// BlendMode::SetMode 1 on a layer. +void layer_normal_set(LayerState& layer) +{ + layer_blend_set(layer, KAGE::Graphics::BLEND_NORMAL); } // 0060c400 Only a boss spawn pentagram holds the doors shut. @@ -252,7 +276,8 @@ void Entity_Effect::Update() { TemporaryEffect* hourglass = g_game->room->temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOURGLASS); if (hourglass) - speedMultiplier *= lerp_clamped((float)hourglass->cooldown, 0, HOURGLASS_COOLDOWN_SPAN, 1, HOURGLASS_SLOWEST); + speedMultiplier *= + lerp_range((float)hourglass->cooldown, {0, HOURGLASS_COOLDOWN_SPAN, 1, HOURGLASS_SLOWEST}); } if (variant == EFFECT_BLACK_POWDER) pauseTimer = 0; if (pauseTimer != 0) @@ -349,7 +374,7 @@ void Entity_Effect::TriggerGlowingHourglass() state = 0; if (sprite.animState.animData && sprite.GetAnimation() == "Idle") return; - if (!sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME)) return; + if (!sprite.SetAnimation("Idle", SWITCH_RESET)) return; sprite.animState.Rewind(); sprite.animState.isPlaying = true; } @@ -359,7 +384,7 @@ void Entity_Effect::TriggerGlowingHourglass() void Entity_Effect::ClearReferences() { if (variant == EFFECT_ENEMY_SOUL && target && target->type == ENTITY_PLAYER) - reconstruction_missing("Entity_Effect::ClearReferences 0060abb0: the Urn of Souls' soul"); + static_cast(target.get())->AddUrnSouls(1); if (variant == EFFECT_ANIMA_CHAIN && subtype == 0 && !isVisible) g_manager->sfxManager.Stop(SOUND_CHAIN_LOOP); Entity::ClearReferences(); extraData.reset(); @@ -409,12 +434,6 @@ Entity_Effect* Entity_Effect::CreateTimer(void* fn, uint32_t delay, uint32_t tim return timer; } -// 0060b0d0 -void Entity_Effect::update_variant178_shooter(bool) -{ - reconstruction_missing("Entity_Effect::update_variant178_shooter 0060b0d0"); -} - // 0060b7a0 Entity_Effect* Entity_Effect::CreateLootPreview(void*, const Vector&, Entity*, Entity_Effect*) { diff --git a/src/entity_effect.h b/src/entity_effect.h index fb3a2ab..ce3d8c4 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -1,6 +1,7 @@ #pragma once #include "entity.h" +#include "sfx_manager.h" #include #include #include @@ -36,6 +37,14 @@ template EffectUpdateEnd effect_finishing(Entit return EFFECT_UPDATE_FINISH; } +// Redemption's states: waiting while its player holds an item up, succeeded, failed. +enum RedemptionState +{ + REDEMPTION_WAITING = 1, + REDEMPTION_SUCCESS, + REDEMPTION_FAIL +}; + // The pulling effect's subtypes: the purple, the grey pulsing and the red pulsing champion's. constexpr int PULLING_PURPLE = 0; constexpr int PULLING_GREY = 1; @@ -118,6 +127,7 @@ enum EffectVariant : int EFFECT_SHOCKWAVE_RANDOM = 73, EFFECT_ISAACS_CARPET = 74, EFFECT_DICE_FLOOR = 76, + EFFECT_LARGE_BLOOD_EXPLOSION = 77, EFFECT_PLAYER_CREEP_LEMON_PARTY = 78, EFFECT_TEAR_POOF_SMALL = 79, EFFECT_TEAR_POOF_VERYSMALL = 80, @@ -226,6 +236,7 @@ enum EffectVariant : int EFFECT_DOGMA_ORB = 172, EFFECT_CRACKED_ORB_POOF = 173, EFFECT_SHOP_SPIKES = 174, + EFFECT_ENEMY_SOUL = 179, EFFECT_LAVA_SPAWNER = 181, EFFECT_BIG_KNIFE = 182, EFFECT_MOTHER_SHOCKWAVE = 183, @@ -248,7 +259,8 @@ enum EffectVariant : int // An effect (Lua's EntityEffect): a visual or a hazard such as creep, a poof or a light beam, with its timeout, its // fall, the per-variant data it keeps and the extra data some variants share. // Init, Update and Render run the shared parts here and hand each variant to its group's behaviour table (the ambient, -// hazard, floor and beam files) or to entity_effect_combat.h (blood, gibs, poofs, explosions). Any other variant stops. +// hazard, floor, beam, item, portal, blast, soul, Mother and shot files, and a few the player's and weapons' files +// hold) or to entity_effect_combat.h (blood, gibs, poofs, explosions). Any other variant stops. struct Entity_Effect : Entity { @@ -302,6 +314,17 @@ struct Entity_Effect : Entity void setup_loot_preview(void* lootQueue); }; +// The most pickups a pickup ghost shows. +constexpr int PICKUP_GHOST_SLOTS = 4; + +// Construction and destruction (005d2300, 005d23a0) are the defaults. +// The pickups a pickup ghost (Guppy's Eye's look into a chest) shows, which setup_loot_preview fills. +struct PickupGhostData : Entity_Effect::ExtraData +{ + std::array sprites; + int count = 0; +}; + // The groups of variants Entity_Effect hands out by table (entity_effect_.cpp). std::span ambient_effect_behaviours(); std::span hazard_effect_behaviours(); @@ -311,20 +334,40 @@ std::span spike_effect_behaviours(); std::span boss_effect_behaviours(); std::span alt_effect_behaviours(); std::span item_effect_behaviours(); +std::span portal_effect_behaviours(); +std::span blast_effect_behaviours(); +std::span soul_effect_behaviours(); +std::span mother_effect_behaviours(); +std::span shot_effect_behaviours(); // The frame the plain poofs share: the sprite turned by the effect's rotation (mirrored unless flipped), the effect // gone once its animation ends. EffectUpdateEnd effect_poof_update(Entity_Effect& effect); -// Sets a layer to draw additively (BlendMode::SetMode 2). +// Plays a sound through the seeds' fart override (SoundEffects::PlayWithFartOverride). +void effect_sound_play(int sound, SoundPlay play = {}); + +// FUN_007ab0e0: whether a player is free to step into a light or a portal: no extra or item animation playing, unless +// carrying their twin. +bool is_player_free(Entity_Player& player); + +// The tear flags an effect carries in its variant data. +TearFlags effect_tear_flags(const Entity_Effect& effect); + +// FUN_0060dae0: whether the Siren may charm a familiar. +struct Entity_Familiar; +bool is_familiar_charmable(Entity_Familiar& familiar); + +// Sets a layer to draw additively (BlendMode::SetMode 2), or normally (1). void layer_additive_set(LayerState& layer); +void layer_normal_set(LayerState& layer); // The degrees of a full turn. constexpr float DEGREES_PER_TURN = 360; +float angle_wrapped(float angle); float angle_approach(float current, float target, float maxStep); void vector_lerp(Vector& v, Vector target, float t); -float lerp_clamped(float value, float inFirst, float inLast, float outFirst, float outLast); // A color tinted, with no colorize or offset (Color::Reset and SetTint). constexpr ColorMod tint_color_make(float red, float green, float blue, float alpha) diff --git a/src/entity_effect_alt.cpp b/src/entity_effect_alt.cpp index 4298c56..8eb2979 100644 --- a/src/entity_effect_alt.cpp +++ b/src/entity_effect_alt.cpp @@ -231,7 +231,7 @@ static EffectUpdateEnd attract_update(Entity_Effect& ring) return EFFECT_UPDATE_FINISH; } - float progress = lerp_clamped(ring.updateTime, 0, (float)ring.lifespan, SHOCKWAVE_START, 1); + float progress = lerp_range(ring.updateTime, {0, (float)ring.lifespan, SHOCKWAVE_START, 1}); ring.scale = 1 - (progress - 1) * (progress - 1); if (progress >= 1) { diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp index 4899504..60a681b 100644 --- a/src/entity_effect_ambient.cpp +++ b/src/entity_effect_ambient.cpp @@ -1,3 +1,4 @@ +#include "boss_ai.h" #include "entity_effect.h" #include "data.h" #include "deathmatch_manager.h" @@ -11,6 +12,7 @@ #include "kage_graphics.h" #include "npc_ai.h" #include "room.h" +#include "room_grid.h" #include "room_config.h" #include "room_descriptor.h" #include @@ -170,22 +172,6 @@ static float distance_squared(Vector a, Vector b) return vector_length_squared(vector_sub(a, b)); } -// Game::GetNearestPlayer 00703950: the player nearest a position, the first one on a tie. -static Entity_Player* nearest_player_get(Vector position) -{ - Entity_Player* nearest = nullptr; - float nearestDistance = 0; - - for (Entity_Player* player : g_game->playerManager.playerList) - { - float distance = distance_squared(position, player->pos); - if (nearest && distance >= nearestDistance) continue; - nearest = player; - nearestDistance = distance; - } - return nearest; -} - // Room::GetGridCollisionAtPos 007f0780 and Room::GetGridEntityFromPos 00456620. static int grid_collision_at(Vector position) { @@ -199,41 +185,6 @@ static GridEntity* grid_entity_at(Vector position) return room.GetGridEntity((uint32_t)room.GetGridIndex(position)); } -// What EntityList::QueryRadius 0041a790 looks through: Lua's EntityPartition bits. -enum QueryMask : uint32_t -{ - QUERY_FAMILIARS = 1 << 0, - QUERY_PROJECTILES = 1 << 1, - QUERY_TEARS = 1 << 2, - QUERY_ENEMIES = 1 << 3, - QUERY_PICKUPS = 1 << 4, - QUERY_PLAYERS = 1 << 5 -}; - -// The entities of the masked partitions (and the players) touching a position within a radius, in the original's -// partition order, those in their interpolation update left out. -static EntityList_EL entities_near(Vector position, float radius, uint32_t mask) -{ - constexpr std::array, 5> PARTITIONS = {{{QUERY_FAMILIARS, PARTITION_FAMILIARS}, - {QUERY_TEARS, PARTITION_SHOTS}, - {QUERY_ENEMIES, PARTITION_ENEMIES}, - {QUERY_PROJECTILES, PARTITION_PROJECTILES}, - {QUERY_PICKUPS, PARTITION_PICKUPS}}}; - EntityList& entities = g_game->room->entityList; - EntityList_EL found; - - for (auto [bit, partition] : PARTITIONS) - if (mask & bit) entities.partitions[partition].query_box(found, position, vector_make(radius, radius)); - if (mask & QUERY_PLAYERS) - for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player); - std::erase_if(found, [&](Entity* entity) { - float reach = radius + entity->size; - return entity->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || - distance_squared(entity->pos, position) >= reach * reach; - }); - return found; -} - // Spawns a blood splat of a bug's blood color where it died, at a scale, onto the floor or the wall. static void bug_splat(Entity_Effect& bug, uint64_t addedFlags) { @@ -320,7 +271,7 @@ static void tiny_bug_update(Entity_Effect& bug) bug.state--; } - Entity_Player* player = nearest_player_get(bug.pos); + Entity_Player* player = game_nearest_player(bug.pos); float playerDistance = distance_squared(bug.pos, player->pos); if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && random_below(BUG_FLEE_ODDS) == 0) { @@ -347,7 +298,7 @@ static void tiny_bug_update(Entity_Effect& bug) if (bug.isDead) bug_splat(bug, 0); if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying()) bug.isDead = true; - for (Entity* tear : entities_near(bug.pos, 1, QUERY_TEARS)) + for (Entity* tear : entity_query_radius(bug.pos, 1, QUERY_TEARS)) if (tear->type == ENTITY_TEAR && tear->isDead && distance_squared(tear->pos, bug.pos) < BUG_SPLASH_RANGE_SQUARED) bug.isDead = true; } @@ -438,7 +389,7 @@ static void wall_bug_update(Entity_Effect& bug) if (grid_collision_at(bug.pos) == COLLISION_WALL_EXCEPT_PLAYER) bug.targetPosition.y += WALL_BUG_DOOR_STEP; if (bug.isDead) bug_splat(bug, FLAG_RENDER_WALL); - for (Entity* tear : entities_near(bug.pos, 1, QUERY_TEARS)) + for (Entity* tear : entity_query_radius(bug.pos, 1, QUERY_TEARS)) { if (tear->type != ENTITY_TEAR || !tear->isDead) continue; bug.isDead = true; @@ -469,7 +420,7 @@ static bool is_within_reach(Entity& entity, Vector position, float reach) // and stays in the room. static void tiny_fly_update(Entity_Effect& fly) { - Entity_Player* player = nearest_player_get(fly.pos); + Entity_Player* player = game_nearest_player(fly.pos); Vector toPlayer = vector_sub(player->pos, fly.pos); float distance = vector_length(toPlayer); Vector direction = vector_scale(toPlayer, 1 / (distance == 0 ? MIN_DISTANCE : distance)); @@ -592,7 +543,7 @@ static void wisp_update(Entity_Effect& wisp) Vector drift = random_direction(); vector_lerp(wisp.velocity, vector_scale(drift, random_unit() * WISP_DRIFT_SPEED), driftRate); - Entity_Player* player = nearest_player_get(wisp.pos); + Entity_Player* player = game_nearest_player(wisp.pos); float playerDistance = distance_squared(player->pos, wisp.pos); if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && vector_length_squared(player->velocity) > 1) { @@ -926,28 +877,10 @@ static EffectUpdateEnd backdrop_decoration_update(Entity_Effect& decoration) return backdrop_detail_cleared(decoration) ? EFFECT_UPDATE_RETURN : EFFECT_UPDATE_FINISH; } -// Game::GetNearestPlayerEx 00703ab0 for the main players: the nearest one that is no coop ghost, hologram or held -// body and still collides. -static Entity_Player* nearest_main_player_get(Vector position) -{ - Entity_Player* nearest = nullptr; - float nearestDistance = 1e10f; - - for (Entity_Player* player : g_game->playerManager.playerList) - { - float distance = distance_squared(position, player->pos); - if (distance >= nearestDistance || player->variant != 0 || player->isCoopGhost || player->parent) continue; - if (player->IsHologram() || player->entityCollisionClass == ENTCOLL_NONE) continue; - nearest = player; - nearestDistance = distance; - } - return nearest; -} - // A ladder's frame: it counts the frames no player stands close, and a player climbing it once it is ready leaves. static void tall_ladder_update(Entity_Effect& ladder) { - Entity_Player* player = nearest_main_player_get(ladder.pos); + Entity_Player* player = main_player_nearest(ladder.pos); float distance = player ? vector_length(vector_sub(ladder.pos, player->pos)) : 1e9f; ladder.state = distance < LADDER_NEAR && ladder.state <= LADDER_ARM_FRAMES ? 0 : ladder.state + 1; @@ -1245,14 +1178,6 @@ static void creep_acid_burn(Entity_Effect& creep, Entity& enemy) } } -// The tear flags a holy water trail carries in its extra data. -static TearFlags creep_tear_flags(const Entity_Effect& creep) -{ - TearFlags flags; - for (size_t bit = 0; bit < flags.size(); bit++) flags[bit] = (creep.varData[bit / 32] >> (bit % 32)) & 1; - return flags; -} - // A homing holy water trail picks the nearest enemy on the ground ahead of it (with some chance, and ones it hit // last), and drifts toward its target. static void holy_water_trail_home(Entity_Effect& trail) @@ -1262,7 +1187,7 @@ static void holy_water_trail_home(Entity_Effect& trail) Entity* best = nullptr; float bestScore = HOMING_NONE; Vector ahead = vector_add(trail.pos, vector_scale(trail.velocity, HOMING_LOOKAHEAD)); - for (Entity* enemy : entities_near(ahead, HOMING_RANGE, QUERY_ENEMIES)) + for (Entity* enemy : entity_query_radius(ahead, HOMING_RANGE, QUERY_ENEMIES)) { if (!enemy->IsVulnerableEnemy(nullptr)) continue; if (trail.spawnerEntity && trail.spawnerEntity->IsDescendantOf(enemy)) continue; @@ -1290,8 +1215,8 @@ static void creep_enemies_burn(Entity_Effect& creep) float radius = creep.size * creep.sprite.scale.x; bool isTrail = creep.variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL; - TearFlags flags = creep_tear_flags(creep); - for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + TearFlags flags = effect_tear_flags(creep); + for (Entity* enemy : entity_query_radius(creep.pos, radius, QUERY_ENEMIES)) { if (EntityList::HitListContains(creep.hitList, *enemy) || !is_creep_victim(creep, *enemy, radius)) continue; creep_acid_burn(creep, *enemy); @@ -1331,7 +1256,7 @@ static void creep_update(Entity_Effect& creep) else if (variant == EFFECT_PLAYER_CREEP_WHITE || variant == EFFECT_PLAYER_CREEP_BLACK) { float radius = creep.size * creep.sprite.scale.x; - for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + for (Entity* enemy : entity_query_radius(creep.pos, radius, QUERY_ENEMIES)) if (is_creep_victim(creep, *enemy, radius)) enemy->AddSlowing(EntityRef(&creep), ENEMY_SLOW_FRAMES, PLAYER_CREEP_SLOW, CREEP_SLOW_COLOR, false); } @@ -1341,7 +1266,7 @@ static void creep_update(Entity_Effect& creep) else if (variant == EFFECT_PLAYER_CREEP_GREEN) { float radius = creep.size * creep.sprite.scale.x; - for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + for (Entity* enemy : entity_query_radius(creep.pos, radius, QUERY_ENEMIES)) if (is_creep_victim(creep, *enemy, radius)) enemy->TakeDamage(creep.collisionDamage, 0, EntityRef(&creep), CREEP_DAMAGE_COUNTDOWN); } @@ -1378,7 +1303,7 @@ static void lasting_creep_update(Entity_Effect& creep) { float radius = creep.size * growth * creep.scale; int freezePeriod = g_game->deathmatchManager.is_active() ? HOLY_WATER_VERSUS_FREEZE_PERIOD : HOLY_WATER_FREEZE_PERIOD; - for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES)) + for (Entity* enemy : entity_query_radius(creep.pos, radius, QUERY_ENEMIES)) { if (!is_creep_victim(creep, *enemy, radius)) continue; enemy->TakeDamage(creep.collisionDamage, DAMAGE_COUNTDOWN, EntityRef(&creep), PLAYER_CREEP_COUNTDOWN); @@ -1405,7 +1330,7 @@ static void pentagram_update(Entity_Effect& pentagram) if (!pentagram.isDead) { float damage = g_game->deathmatchManager.is_active() ? PENTAGRAM_VERSUS_DAMAGE : PENTAGRAM_DAMAGE; - for (Entity* enemy : entities_near(pentagram.pos, pentagram.size, QUERY_ENEMIES)) + for (Entity* enemy : entity_query_radius(pentagram.pos, pentagram.size, QUERY_ENEMIES)) { if (!enemy->IsVulnerableEnemy(nullptr) || pentagram.IsDescendantOf(enemy)) continue; float reach = enemy->size + pentagram.size; @@ -1525,7 +1450,7 @@ static void tadpole_update(Entity_Effect& tadpole) if (!isKick) isKick = !vector_is_zero(current) && random_below(TADPOLE_CURRENT_KICK_ODDS) == 0; if (isKick) tadpole_kick(tadpole, current); - Entity_Player* player = nearest_player_get(tadpole.pos); + Entity_Player* player = game_nearest_player(tadpole.pos); float playerDistance = distance_squared(tadpole.pos, player->pos); if (tadpole.minRadius <= TADPOLE_SLOW && playerDistance < TADPOLE_FLEE_RANGE_SQUARED && random_below(TADPOLE_FLEE_ODDS) == 0) @@ -1546,7 +1471,7 @@ static void tadpole_update(Entity_Effect& tadpole) if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying()) tadpole.isDead = true; - for (Entity* tear : entities_near(tadpole.pos, TADPOLE_SPLASH_RANGE, QUERY_TEARS)) + for (Entity* tear : entity_query_radius(tadpole.pos, TADPOLE_SPLASH_RANGE, QUERY_TEARS)) { if (tear->type != ENTITY_TEAR || !tear->isDead) continue; tadpole.isDead = true; @@ -1582,7 +1507,8 @@ static void lil_ghost_spot_find(Entity_Effect& ghost) for (int i = 0; i < tries; i++) { Vector spot = room.GetRandomPosition(GHOST_ROOM_MARGIN); - if (grid_collision_at(spot) != COLLISION_NONE || !entities_near(spot, GHOST_SPOT_CLEARANCE, GHOST_SHY_OF).empty()) + if (grid_collision_at(spot) != COLLISION_NONE || + !entity_query_radius(spot, GHOST_SPOT_CLEARANCE, GHOST_SHY_OF).empty()) continue; ghost.targetPosition = spot; ghost.pos = spot; @@ -1621,18 +1547,11 @@ static void lil_ghost_update(Entity_Effect& ghost) Vector home = vector_scale(vector_sub(ghost.targetPosition, ghost.pos), GHOST_DRIFT); ghost.velocity = vector_add(ghost.velocity, vector_add(wander, home)); ghost.rotation += GHOST_TURN - random_unit() * GHOST_TURN * 2; - if (ghost.sprite.animState.IsLoopingAnimation() && !entities_near(ghost.pos, GHOST_SHY_RANGE, GHOST_SHY_OF).empty()) + if (ghost.sprite.animState.IsLoopingAnimation() && + !entity_query_radius(ghost.pos, GHOST_SHY_RANGE, GHOST_SHY_OF).empty()) ghost.isDead = true; } -// FUN_007ab0e0: whether a player is free to step into a light: no extra or item animation playing, unless carrying -// their twin. -static bool is_player_free(Entity_Player& player) -{ - bool isAnimating = player.isPlayingExtraAnimation || player.isPlayingItemAnimation; - return !isAnimating || (player.heldEntity && player.heldEntity == player.twinPlayer.get()); -} - // The heaven door keeps through overwrites. Luna's moonlight glows additively with its ground layer hidden, and // spawns a copy of itself on the floor that shows that ground layer under everything. static void heaven_door_init(Entity_Effect& door) @@ -1861,7 +1780,7 @@ static void beetle_crawl(Entity_Effect& beetle) } beetle.friction *= BUG_FRICTION; - Entity_Player* player = nearest_player_get(beetle.pos); + Entity_Player* player = game_nearest_player(beetle.pos); float playerDistance = distance_squared(beetle.pos, player->pos); if (playerDistance < BEETLE_TAKEOFF_RANGE_SQUARED && random_below(BEETLE_TAKEOFF_ODDS) == 0) { @@ -1901,7 +1820,7 @@ static void beetle_crawl(Entity_Effect& beetle) if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying()) beetle.isDead = true; - for (Entity* tear : entities_near(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS)) + for (Entity* tear : entity_query_radius(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS)) { if (tear->type != ENTITY_TEAR || !tear->isDead) continue; beetle.isDead = true; @@ -1929,7 +1848,7 @@ static void beetle_fly(Entity_Effect& beetle) Vector heading = vector_from_angle(beetle.rotation); beetle.AddVelocity_divided(vector_scale(heading, random_unit() * BEETLE_FLIGHT_SPEED + BEETLE_FLIGHT_SPEED), false); - Entity_Player* player = nearest_player_get(beetle.pos); + Entity_Player* player = game_nearest_player(beetle.pos); float playerDistance = distance_squared(beetle.pos, player->pos); if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && random_below(BEETLE_FLEE_ODDS) == 0) { @@ -1940,7 +1859,7 @@ static void beetle_fly(Entity_Effect& beetle) else if (random_below(BEETLE_LAND_ODDS) == 0 && grid_collision_at(beetle.pos) == COLLISION_NONE) beetle.subtype = 0; beetle.sprite.Play("FlyHori"); - EntityList_EL tears = entities_near(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS); + EntityList_EL tears = entity_query_radius(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS); bool isHit = std::any_of(tears.begin(), tears.end(), [](Entity* tear) { return tear->type == ENTITY_TEAR; }); for (Entity* entity : g_game->room->entityList.updateEL) { @@ -1981,6 +1900,195 @@ static void beetle_update(Entity_Effect& beetle) } // The ambient variants by their Init, Update and Render. +// The butterflies flutter at a random height toward a spot of the room, wandering to new spots at random (and, near +// another, toward its spot), fleeing a moving player within 100 to come back later. They land for a while at random +// (state 50 to 199), taking off again when disturbed, and die in a small burst of their colour on a tear or a fire. +constexpr float BUTTERFLY_FLIGHT_LOW = -5; +constexpr float BUTTERFLY_FLIGHT_SPAN = -30; +constexpr float BUTTERFLY_SCARE_RANGE_SQUARED = 100 * 100; +constexpr float BUTTERFLY_SCARE_SPEED_SQUARED = 1; +constexpr float BUTTERFLY_SEEK_MIN = 0.05f; +constexpr float BUTTERFLY_SEEK_SPAN = 0.2f; +constexpr float BUTTERFLY_FLEE_MIN = 0.08f; +constexpr float BUTTERFLY_FLEE_SPAN = 0.4f; +constexpr float BUTTERFLY_RETURN_MIN = 0.1f; +constexpr float BUTTERFLY_RETURN_SPAN = 0.3f; +constexpr int BUTTERFLY_FOLLOW_ODDS = 30; +constexpr float BUTTERFLY_FOLLOW_SCATTER = 50; +constexpr float BUTTERFLY_FOLLOW_PULL = 0.05f; +constexpr int BUTTERFLY_WANDER_ODDS = 50; +constexpr int BUTTERFLY_LAND_ODDS = 40; +constexpr int BUTTERFLY_LAND_MIN = 50; +constexpr int BUTTERFLY_LAND_SPAN = 150; +constexpr int BUTTERFLY_FORGET_ODDS = 30; +constexpr float BUTTERFLY_ARRIVED_SQUARED = 20 * 20; +constexpr int BUTTERFLY_HEIGHT_ODDS = 20; +constexpr float BUTTERFLY_HEIGHT_MIN = -1; +constexpr float BUTTERFLY_HEIGHT_SPAN = -30; +constexpr float BUTTERFLY_RISE_MIN = 0.01f; +constexpr float BUTTERFLY_RISE_SPAN = 0.07f; +constexpr float BUTTERFLY_SHADOW = 0.03f; +constexpr float BUTTERFLY_TURN = 0.1f; +constexpr float BUTTERFLY_TILT = 90; +constexpr float BUTTERFLY_TEAR_RANGE = 3; +constexpr float BUTTERFLY_FIRE_REACH = 2; +constexpr float BUTTERFLY_BURST_SCALE = 0.4f; +constexpr float BUTTERFLY_LANDED_FRICTION = 0.1f; +constexpr int BUTTERFLY_FLAP_ODDS = 10; +constexpr float BUTTERFLY_FALL = 1; +constexpr float BUTTERFLY_FRICTION = 0.95f; + +// Part of 005cdb20 (Init's case 69) A butterfly flutters on a random frame at a random turn and height. +static void butterfly_init(Entity_Effect& butterfly) +{ + butterfly.sprite.Play("Idle"); + butterfly.sprite.SetFrame((float)random_below(butterfly.sprite.animState.GetAnimationLength())); + butterfly.rotation = normalize_angle_degrees(random_unit() * FULL_TURN); + butterfly.sprite.rotation = butterfly.rotation; + float height = random_unit() * BUTTERFLY_FLIGHT_SPAN + BUTTERFLY_FLIGHT_LOW; + butterfly.posOffset.y = height; + butterfly.height = height; + butterfly.targetPosition = {}; + butterfly.isUnknown176 = true; +} + +// The butterfly dies in a small burst of its colour. +static void butterfly_burst(Entity_Effect& butterfly) +{ + butterfly.Remove(); + uint32_t seed = Random(); + Vector spot = vector_add(butterfly.pos, vector_make(0, butterfly.height)); + Entity* burst = + g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); + burst->SetColor(butterfly.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + burst->sprite.scale = vector_make(BUTTERFLY_BURST_SCALE, BUTTERFLY_BURST_SCALE); + burst->Update(); + butterfly.sprite.Stop(); +} + +// A flying butterfly's course: toward its spot (fleeing a moving player instead, back toward its spot when it hits the +// room's edge), drawn toward a near butterfly's spot now and then. Without a spot it picks one at random, or lands. +static void butterfly_steer(Entity_Effect& butterfly, Entity_Player* player, bool isFleeing) +{ + Room& room = *g_game->room; + if (vector_is_zero(butterfly.targetPosition)) + { + if (random_below(BUTTERFLY_WANDER_ODDS) == 0 || butterfly.state == 1) + { + float y = lerp_range(random_unit(), {0, 1, room.topLeftPos.y, room.bottomRightPos.y}); + float x = lerp_range(random_unit(), {0, 1, room.topLeftPos.x, room.bottomRightPos.x}); + butterfly.targetPosition = vector_make(x, y); + butterfly.state = 0; + } + else if (random_below(BUTTERFLY_LAND_ODDS) == 0) + butterfly.state = random_below(BUTTERFLY_LAND_SPAN) + BUTTERFLY_LAND_MIN; + return; + } + + if (!isFleeing) + { + Vector toward = vector_sub(butterfly.targetPosition, butterfly.pos); + butterfly.AddVelocity_divided(vector_resized(toward, random_unit() * BUTTERFLY_SEEK_SPAN + BUTTERFLY_SEEK_MIN), + false); + } + else + { + Vector away = vector_sub(butterfly.pos, player->pos); + butterfly.AddVelocity_divided(vector_resized(away, random_unit() * BUTTERFLY_FLEE_SPAN + BUTTERFLY_FLEE_MIN), + false); + Vector clamped = room.GetClampedPosition(butterfly.pos, 0); + if (clamped.x != butterfly.pos.x || clamped.y != butterfly.pos.y) + { + Vector toward = vector_sub(butterfly.targetPosition, butterfly.pos); + butterfly.AddVelocity_divided( + vector_resized(toward, random_unit() * BUTTERFLY_RETURN_SPAN + BUTTERFLY_RETURN_MIN), false); + } + } + for (Entity* other : entity_query(ENTITY_EFFECT, EFFECT_BUTTERFLY)) + { + float distance = vector_length_squared(vector_sub(other->pos, butterfly.pos)); + if (distance >= BUTTERFLY_SCARE_RANGE_SQUARED || random_below(BUTTERFLY_FOLLOW_ODDS) != 0) continue; + if (vector_is_zero(other->targetPosition)) continue; + Vector scatter = random_direction(); + scatter = vector_scale(scatter, random_unit() * BUTTERFLY_FOLLOW_SCATTER); + float pull = (1 - distance / BUTTERFLY_SCARE_RANGE_SQUARED) * BUTTERFLY_FOLLOW_PULL; + vector_lerp(butterfly.targetPosition, room.GetClampedPosition(vector_add(other->targetPosition, scatter), 0), + pull); + break; + } +} + +// A flying butterfly forgets its spot now and then once there (or past it), bobs to a new height, turns along its +// flight and dies on a tear or a lit fire. +static void butterfly_fly(Entity_Effect& butterfly) +{ + if (random_below(BUTTERFLY_FORGET_ODDS) == 0) + { + Vector toward = vector_sub(butterfly.targetPosition, butterfly.pos); + if (vector_length_squared(toward) < BUTTERFLY_ARRIVED_SQUARED || vector_dot(butterfly.velocity, toward) < 0) + butterfly.targetPosition = {}; + } + if (random_below(BUTTERFLY_HEIGHT_ODDS) == 0) + butterfly.height = random_unit() * BUTTERFLY_HEIGHT_SPAN + BUTTERFLY_HEIGHT_MIN; + float rise = random_unit() * BUTTERFLY_RISE_SPAN + BUTTERFLY_RISE_MIN; + butterfly.posOffset.y = (butterfly.height - butterfly.posOffset.y) * rise + butterfly.posOffset.y; + butterfly.shadowSize = BUTTERFLY_SHADOW; + if (!vector_is_zero(butterfly.targetPosition)) + butterfly.sprite.rotation = + angle_lerp(butterfly.sprite.rotation, vector_angle(butterfly.velocity) + BUTTERFLY_TILT, BUTTERFLY_TURN); + + bool isShot = false; + for (Entity* tear : entity_query_radius(butterfly.pos, BUTTERFLY_TEAR_RANGE, QUERY_TEARS)) + if (tear->type == ENTITY_TEAR) isShot = true; + if (isShot) butterfly_burst(butterfly); + for (Entity* fire : entity_query(ENTITY_FIREPLACE, -1)) + { + float reach = fire->size + BUTTERFLY_FIRE_REACH; + if (vector_length_squared(vector_sub(fire->pos, butterfly.pos)) >= reach * reach) continue; + butterfly_burst(butterfly); + break; + } +} + +// A landed butterfly rests until its time is up, settling to the ground and flapping now and then. Something solid +// under it ends its rest. +static void butterfly_rest(Entity_Effect& butterfly) +{ + if (room_grid_collision_at(butterfly.pos) != COLLISION_NONE) butterfly.state = 2; + if (butterfly.posOffset.y >= 0) + { + butterfly.friction *= BUTTERFLY_LANDED_FRICTION; + butterfly.sprite.Stop(); + if (random_below(BUTTERFLY_FLAP_ODDS) == 0) + butterfly.sprite.SetFrame((float)random_below(butterfly.sprite.animState.GetAnimationLength())); + } + else butterfly.posOffset.y = std::min(butterfly.posOffset.y + BUTTERFLY_FALL, 0.0f); + butterfly.state--; +} + +// 005f8a76 (Update's case 69) A butterfly flies (state below 2) or rests, kept inside the room. +static void butterfly_update(Entity_Effect& butterfly) +{ + Entity_Player* player = game_nearest_player(butterfly.pos); + bool isFleeing = false; + if (player && vector_length_squared(vector_sub(player->pos, butterfly.pos)) < BUTTERFLY_SCARE_RANGE_SQUARED && + vector_length_squared(player->velocity) > BUTTERFLY_SCARE_SPEED_SQUARED) + { + isFleeing = true; + butterfly.state = 1; + } + + if (butterfly.state < 2) + { + butterfly.sprite.Play("Idle"); + butterfly_steer(butterfly, player, isFleeing); + butterfly_fly(butterfly); + } + else butterfly_rest(butterfly); + butterfly.pos = g_game->room->GetClampedPosition(butterfly.pos, 0); + butterfly.friction *= BUTTERFLY_FRICTION; +} + constexpr auto AMBIENT_BEHAVIOURS = std::to_array({ {EFFECT_TINY_BUG, tiny_bug_init, effect_finishing, nullptr}, {EFFECT_TINY_FLY, tiny_fly_init, effect_finishing, nullptr}, @@ -2026,6 +2134,7 @@ constexpr auto AMBIENT_BEHAVIOURS = std::to_array({ {EFFECT_PLAYER_CREEP_PUDDLE_MILK, creep_init, effect_finishing, nullptr}, {EFFECT_PENTAGRAM_BLACKPOWDER, creep_init, effect_finishing, nullptr}, {EFFECT_CREEP_SLIPPERY_BROWN_GROWING, growing_creep_init, effect_finishing, nullptr}, + {EFFECT_BUTTERFLY, butterfly_init, effect_finishing, nullptr}, }); std::span ambient_effect_behaviours() diff --git a/src/entity_effect_blast.cpp b/src/entity_effect_blast.cpp new file mode 100644 index 0000000..5c0b321 --- /dev/null +++ b/src/entity_effect_blast.cpp @@ -0,0 +1,732 @@ +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_list.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "weapon_rockets.h" +#include "backdrop.h" +#include "game.h" +#include "loot_list.h" +#include "room_grid.h" +#include "grid_entity_trap_door.h" +#include "npc_ai.h" +#include "room.h" +#include +#include +#include + +// The blasts that sweep a room: Mama Mega's (red) and Mega Bean's (green, freezing and poisoning). The room-wide ones +// (subtypes 0 and 2) grow from the target's distance to the room to 200 past its farthest corner, the small one +// (subtype 1) from its minimum radius to its maximum, in rings of fire. + +// The room-wide blast shakes the screen for 50 frames, blooms for 6 and ripples the floor. +constexpr int MEGA_BLAST_SHAKE = 50; +constexpr int MEGA_BLAST_BLOOM = 6; +constexpr float MEGA_BLAST_RIPPLE_AMPLITUDE = 0.5f; +constexpr float MEGA_BLAST_RIPPLE_SPEED = 0.07f; +constexpr int MEGA_BLAST_RIPPLE_DURATION = 20; +constexpr float MEGA_BLAST_REACH_PAST = 200; +constexpr int MEGA_BLAST_SOUND_DELAY = 15; +constexpr float MEGA_BLAST_RUMBLE_VOLUME = 1.1f; + +// The small blast's ripple and rings scale with its reach from 60 to 600. +constexpr float SMALL_BLAST_REACH_LOW = 60; +constexpr float SMALL_BLAST_REACH_HIGH = 600; +constexpr float SMALL_BLAST_AMPLITUDE_LOW = 0.01f; +constexpr float SMALL_BLAST_AMPLITUDE_HIGH = 0.08f; +constexpr float SMALL_BLAST_SPEED_LOW = 0.01f; +constexpr float SMALL_BLAST_SPEED_HIGH = 0.07f; +constexpr float SMALL_BLAST_DURATION_LOW = 8; +constexpr float SMALL_BLAST_DURATION_HIGH = 20; + +// Its rings of fire (the big attract effect's subtypes 10 and 11): a full ring and three arcs a third of a turn apart, +// each swung up to 30 either way, 14 up. +constexpr int BLAST_RING_FULL = 10; +constexpr int BLAST_RING_ARC = 11; +constexpr int BLAST_RING_ARCS = 3; +constexpr float BLAST_RING_ARC_SPAN = 120; +constexpr float BLAST_RING_ARC_SWING = 60; +constexpr float BLAST_RING_INNER = 10; +constexpr float BLAST_RING_REACH = 0.3f; +constexpr float BLAST_ARC_REACH_MIN = 0.15f; +constexpr float BLAST_ARC_REACH_SPAN = 0.15f; +constexpr float BLAST_ARC_HEIGHT_MIN = 0.6f; +constexpr float BLAST_ARC_HEIGHT_SPAN = 0.4f; +constexpr float BLAST_RING_HEIGHT = -14; + +// The blast's front moves a third of its reach every other frame (30 to 100), pushing what it reaches by 3. It hurts +// each enemy once for its damage, then a fiftieth (an eighth for the small blast) each tick, 1 at least. +constexpr int BLAST_TICK_FRAMES = 2; +constexpr float BLAST_STEP_SHARE = 3; +constexpr float BLAST_STEP_MIN = 30; +constexpr float BLAST_STEP_MAX = 100; +constexpr float BLAST_PUSH = 3; +constexpr float BLAST_TICK_SHARE = 50; +constexpr float SMALL_BLAST_TICK_SHARE = 8; +constexpr uint64_t BLAST_DAMAGE_FLAGS = DAMAGE_EXPLOSION | DAMAGE_CRUSH; +constexpr int BLAST_HIT_COUNTDOWN = 30; +constexpr int BEAN_FREEZE = -50; +constexpr int BEAN_POISON = 90; +constexpr float BEAN_POISON_DAMAGE = 5; + +// The small effects the front clears away: tiny bugs and flies, worms, beetles and lil ghosts. +constexpr std::array BLAST_SWEPT_EFFECTS = {EFFECT_TINY_BUG, EFFECT_TINY_FLY, EFFECT_WORM, EFFECT_BEETLE, + EFFECT_LIL_GHOST}; + +// Behind the front, half the cells inside the room (80 in) more than 50 back throw up dust (blood for the small +// blast) up to 50 off the cell, and the room-wide blast breaks every grid entity it passes (the small one a quarter). +constexpr float DEBRIS_MARGIN = -80; +constexpr float DEBRIS_TRAIL = 50; +constexpr float DEBRIS_SCATTER = 50; +constexpr float DEBRIS_SPEED_MIN = 4; +constexpr float DEBRIS_SPEED_SPAN = 4; +constexpr float BLAST_DUST_SPIN_MIN = 2; +constexpr float BLAST_DUST_SPIN_SPAN = 10; +constexpr int BLAST_DUST_LIFE_MIN = 10; +constexpr int BLAST_DUST_LIFE_SPAN = 10; +constexpr float BLAST_DUST_ALPHA_MIN = 0.2f; +constexpr float BLAST_DUST_ALPHA_SPAN = 0.5f; +constexpr float BLAST_DUST_SCALE_MIN = 1.2f; +constexpr float BLAST_DUST_SCALE_SPAN = 3; +constexpr float BLOOD_SCALE_MIN = 0.8f; +constexpr float BLOOD_SCALE_SPAN = 0.4f; +constexpr float BLOOD_SPLAT_SCALE = 3; +constexpr float BLOOD_LARGE_REACH = 300; +constexpr float BLOOD_MEDIUM_REACH = 150; +constexpr float BLAST_DOORS_REACH = 300; + +// The blasts' colours: Mama Mega's red and Mega Bean's green, and the dust of the glowing blast (subtype 2). +constexpr ColorMod MAMA_MEGA_COLOR = {{1, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod MEGA_BEAN_COLOR = {{0.2f, 1, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod MAMA_MEGA_GLOW = {{5, 0.5f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod MEGA_BEAN_GLOW = {{0.2f, 0.5f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BEAN_DUST_TINT = 0.7f; + +// The blast's states: about to start, sweeping, and past the doors it may open. +enum BlastState +{ + MEGA_BLAST_STARTING, + MEGA_BLAST_SWEEPING, + MEGA_BLAST_DOORS_DONE +}; + +// Whether the blast sweeps the whole room (or is the small one). +static bool is_room_blast(Entity_Effect& blast) +{ + return blast.subtype == 0 || blast.subtype == 2; +} + +// Part of 005cdb20 (Init's case 127 and 202) The blast is unseen and never overwritten. Mega Bean's blares at once. +static void mega_blast_init(Entity_Effect& blast) +{ + blast.isVisible = false; + blast.AddEntityFlags(FLAG_DONT_OVERWRITE); + if (blast.variant == EFFECT_MEGA_BEAN_EXPLOSION) effect_sound_play(SOUND_MEGABEAN_BLAST); +} + +// A ring of fire of the small blast at its target, in its colour, out to a share of its reach. +static Entity_Effect* blast_ring_spawn(Entity_Effect& blast, int subtype, const ColorMod& color, int timeout, + float reach) +{ + auto* ring = static_cast(g_game->Spawn({.position = blast.targetPosition, + .spawner = &blast, + .subType = subtype, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = Random()})); + ring->posOffset = vector_make(0, BLAST_RING_HEIGHT); + ring->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + ring->SetTimeout(timeout); + ring->SetRadii(BLAST_RING_INNER, reach); + return ring; +} + +// The small blast's ripple and rings last 8 to 20 frames with its reach. +static int small_blast_duration(Entity_Effect& blast) +{ + float frames = lerp_range(blast.maxRadius, {SMALL_BLAST_REACH_LOW, SMALL_BLAST_REACH_HIGH, SMALL_BLAST_DURATION_LOW, + SMALL_BLAST_DURATION_HIGH}); + return (int)std::ceil(frames); +} + +// The blast's first frame. The room-wide one reaches from the target's distance to the room to 200 past its farthest +// corner, shaking, blooming and rippling the room (and may dig up Mom's Shovel). The small one ripples and rings. +static void mega_blast_start(Entity_Effect& blast, const ColorMod& color) +{ + if (!is_room_blast(blast)) + { + blast.scale = blast.minRadius; + blast.state = MEGA_BLAST_SWEEPING; + float amplitude = lerp_range(blast.maxRadius, {SMALL_BLAST_REACH_LOW, SMALL_BLAST_REACH_HIGH, + SMALL_BLAST_AMPLITUDE_LOW, SMALL_BLAST_AMPLITUDE_HIGH}); + float speed = lerp_range(blast.maxRadius, {SMALL_BLAST_REACH_LOW, SMALL_BLAST_REACH_HIGH, SMALL_BLAST_SPEED_LOW, + SMALL_BLAST_SPEED_HIGH}); + int duration = small_blast_duration(blast); + shockwave_make(blast.targetPosition, amplitude, speed, duration); + blast_ring_spawn(blast, BLAST_RING_FULL, color, duration * 2, blast.maxRadius * BLAST_RING_REACH)->Update(); + return; + } + + Room& room = *g_game->room; + Vector centre = vector_scale(vector_add(room.topLeftPos, room.bottomRightPos), 0.5f); + Vector half = vector_scale(vector_sub(room.bottomRightPos, room.topLeftPos), 0.5f); + Vector offset = vector_sub(blast.targetPosition, centre); + Vector nearest = + vector_make(std::max(std::fabs(offset.x) - half.x, 0.0f), std::max(std::fabs(offset.y) - half.y, 0.0f)); + Vector farthest = vector_make(std::max(std::fabs(offset.x + half.x), std::fabs(offset.x - half.x)), + std::max(std::fabs(offset.y + half.y), std::fabs(offset.y - half.y))); + blast.minRadius = vector_length(nearest); + blast.maxRadius = vector_length(farthest) + MEGA_BLAST_REACH_PAST; + blast.scale = blast.minRadius; + blast.state = MEGA_BLAST_SWEEPING; + + Game& game = *g_game; + game_shake_screen(MEGA_BLAST_SHAKE); + game.bloomDuration = MEGA_BLAST_BLOOM; + game.bloomTimer = MEGA_BLAST_BLOOM; + game.bloomStrength = 1; + shockwave_make(blast.targetPosition, MEGA_BLAST_RIPPLE_AMPLITUDE, MEGA_BLAST_RIPPLE_SPEED, + MEGA_BLAST_RIPPLE_DURATION); + if (blast.variant == EFFECT_MAMA_MEGA_EXPLOSION) + effect_sound_play(SOUND_EXPLOSION_STRONG, {.frameDelay = MEGA_BLAST_SOUND_DELAY}); + shovel_quest_dig(); +} + +// The small blast's rings each tick: a full ring and three arcs at random turns, of random reach and height. +static void small_blast_rings(Entity_Effect& blast, const ColorMod& color) +{ + int duration = small_blast_duration(blast); + blast_ring_spawn(blast, BLAST_RING_FULL, color, duration * 2, blast.maxRadius * BLAST_RING_REACH)->Update(); + float turn = random_unit() * DEGREES_PER_TURN; + for (int i = 0; i < BLAST_RING_ARCS; i++) + { + uint32_t seed = Random(); + auto* arc = static_cast(g_game->Spawn({.position = blast.targetPosition, + .spawner = &blast, + .subType = BLAST_RING_ARC, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = seed})); + float swing = random_unit() * BLAST_RING_ARC_SWING - BLAST_RING_ARC_SWING / 2; + arc->sprite.rotation = (float)i * BLAST_RING_ARC_SPAN + turn + swing; + arc->posOffset = vector_make(0, BLAST_RING_HEIGHT); + arc->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + arc->SetTimeout(duration); + arc->SetRadii(BLAST_RING_INNER, (random_unit() * BLAST_ARC_REACH_SPAN + BLAST_ARC_REACH_MIN) * blast.maxRadius); + arc->sprite.GetLayer(0)->size.y = random_unit() * BLAST_ARC_HEIGHT_SPAN + BLAST_ARC_HEIGHT_MIN; + arc->Update(); + } +} + +// The blast's push away from its target. +static Vector blast_push(Entity_Effect& blast, Entity& entity) +{ + return vector_scale(vector_normalized(vector_sub(entity.pos, blast.targetPosition)), BLAST_PUSH); +} + +// Hurts an entity the front reaches the first time, true then. +static bool blast_first_hit(Entity_Effect& blast, Entity& entity, float damage) +{ + if (EntityList::HitListContains(blast.hitList, entity)) return false; + hit_list_insert(blast.hitList, entity); + entity.TakeDamage(damage, BLAST_DAMAGE_FLAGS, EntityRef(blast.spawnerEntity.get()), BLAST_HIT_COUNTDOWN); + return true; +} + +// The front reaches an entity: enemies are pushed and hurt (Mega Bean's freezes and poisons them once, Mama Mega's +// keeps hurting them a little), enemy shots vanish, machines and pickups are pushed and hurt, small critters die. +static void blast_entity_hit(Entity_Effect& blast, Entity& entity, float tickDamage) +{ + float damage = blast.collisionDamage; + EntityRef source(blast.spawnerEntity.get()); + if (entity.IsEnemy() && !entity.HasEntityFlags(FLAG_FRIENDLY) && !entity.isDead) + { + entity.AddVelocity(blast_push(blast, entity), false); + if (blast_first_hit(blast, entity, damage)) + { + if (blast.variant != EFFECT_MEGA_BEAN_EXPLOSION) return; + entity.AddFreeze(source, BEAN_FREEZE, false); + entity.AddPoison(source, BEAN_POISON, BEAN_POISON_DAMAGE, false); + } + else if (blast.variant != EFFECT_MEGA_BEAN_EXPLOSION) + entity.TakeDamage(tickDamage, BLAST_DAMAGE_FLAGS, source, BLAST_HIT_COUNTDOWN); + return; + } + + if (entity.IsProjectile()) + { + auto& shot = static_cast(entity); + if (shot.projectileFlags & PROJECTILE_CANT_HIT_PLAYER) return; + shot.projectileFlags = 0; + shot.isDead = true; + } + else if (entity.is_slot()) + { + entity.AddVelocity(blast_push(blast, entity), false); + if (!entity.isDead) entity.TakeDamage(damage, BLAST_DAMAGE_FLAGS, source, BLAST_HIT_COUNTDOWN); + } + else if (entity.is_pickup()) + { + entity.AddVelocity(blast_push(blast, entity), false); + blast_first_hit(blast, entity, damage); + } + else if (entity.type == ENTITY_EFFECT && std::find(BLAST_SWEPT_EFFECTS.begin(), BLAST_SWEPT_EFFECTS.end(), + entity.variant) != BLAST_SWEPT_EFFECTS.end()) + entity.isDead = true; +} + +// A cloud of dust thrown up behind the room-wide front, spinning away from the cell, glowing for subtype 2, else in +// the blast's faint colour. +// The original aims it at the cell plus the target (not away from the target), kept here. +static void blast_dust_throw(Entity_Effect& blast, Vector cell, Vector spot, Vector direction) +{ + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_unit() * DEBRIS_SPEED_SPAN + DEBRIS_SPEED_MIN); + auto* dust = static_cast(g_game->Spawn( + {.position = spot, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + float side = vector_dot(vector_sub(dust->pos, cell), vector_make(direction.y, -direction.x)) < 0 ? -1.0f : 1.0f; + dust->rotation = (random_unit() * BLAST_DUST_SPIN_SPAN + BLAST_DUST_SPIN_MIN) * side; + dust->SetTimeout(random_below(BLAST_DUST_LIFE_SPAN) + BLAST_DUST_LIFE_MIN); + if (blast.subtype == 2) + { + LayerState& layer = *dust->sprite.GetLayer(0); + layer_additive_set(layer); + layer.color = blast.variant == EFFECT_MAMA_MEGA_EXPLOSION ? MAMA_MEGA_GLOW : MEGA_BEAN_GLOW; + } + else + { + float tint = blast.variant == EFFECT_MAMA_MEGA_EXPLOSION ? 1 : BEAN_DUST_TINT; + ColorMod color = tint_color_make(tint, 1, tint, random_unit() * BLAST_DUST_ALPHA_SPAN + BLAST_DUST_ALPHA_MIN); + dust->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + float size = random_unit() * BLAST_DUST_SCALE_SPAN + BLAST_DUST_SCALE_MIN; + dust->sprite.scale = vector_make(size, size); + dust->Update(); +} + +// A burst of blood behind the small front, larger for a longer reach, with a big splat under it. +static void blast_blood_throw(Entity_Effect& blast, Vector spot, Vector direction) +{ + int size = blast.maxRadius > BLOOD_LARGE_REACH ? 4 : blast.maxRadius > BLOOD_MEDIUM_REACH ? 3 : 2; + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_unit() * DEBRIS_SPEED_SPAN + DEBRIS_SPEED_MIN); + auto* blood = static_cast(g_game->Spawn({.position = spot, + .velocity = velocity, + .subType = size, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = seed})); + blood->rotation = random_unit() * DEGREES_PER_TURN; + float scale = random_unit() * BLOOD_SCALE_SPAN + BLOOD_SCALE_MIN; + blood->sprite.scale = vector_make(scale, scale); + blood->Update(); + + Entity* splat = + g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->sprite.scale = vector_make(BLOOD_SPLAT_SCALE, BLOOD_SPLAT_SCALE); + splat->Update(); +} + +// The cells inside the front: the room-wide blast breaks their grid entities (the small one a quarter of them), and +// half the cells well behind the front throw up dust or blood. +static void blast_cells_hit(Entity_Effect& blast, float reachSquared) +{ + Room& room = *g_game->room; + for (int column = 0; column < room.gridWidth; column++) + { + for (int row = 0; row < room.gridHeight; row++) + { + int index = room.GetGridIndexByTile(column, row); + Vector cell = room.GetGridPosition(index); + float distance = vector_length_squared(vector_sub(cell, blast.targetPosition)); + if (distance > reachSquared) continue; + + if (is_room_blast(blast) || random_below(4) == 0) + { + if (GridEntity* grid = room.GetGridEntity((uint32_t)index)) grid->Destroy(false, EntityRef(&blast)); + } + if (random_below(2) != 0 || !room.IsPositionInRoom(cell, DEBRIS_MARGIN)) continue; + float trail = blast.scale - DEBRIS_TRAIL; + if (trail * trail >= distance) continue; + + Vector scatter = random_direction(); + Vector spot = vector_add(cell, vector_scale(scatter, random_unit() * DEBRIS_SCATTER)); + Vector direction = vector_normalized(vector_add(spot, blast.targetPosition)); + if (is_room_blast(blast)) blast_dust_throw(blast, cell, spot, direction); + else blast_blood_throw(blast, spot, direction); + } + } +} + +// 005fa30d (Update's case 127 and 202) The blast starts on its first frame, then every other frame its front moves +// out, hurting and pushing what it reaches and breaking the room behind it, until it passes its reach. The room-wide +// one may open the Boss Rush and Blue Womb doors once 300 out (or once dead), and rumbles on. +static void mega_blast_update(Entity_Effect& blast) +{ + const ColorMod& color = blast.variant == EFFECT_MAMA_MEGA_EXPLOSION ? MAMA_MEGA_COLOR : MEGA_BEAN_COLOR; + if (blast.state == MEGA_BLAST_STARTING) return mega_blast_start(blast, color); + if (blast.GetIntervalTicks(BLAST_TICK_FRAMES, 0) == 0) return; + + if (!is_room_blast(blast)) small_blast_rings(blast, color); + float step = std::clamp(blast.maxRadius / BLAST_STEP_SHARE, BLAST_STEP_MIN, BLAST_STEP_MAX); + blast.scale = std::min(blast.scale + step, blast.maxRadius); + float share = blast.subtype == 0 ? BLAST_TICK_SHARE : SMALL_BLAST_TICK_SHARE; + float tickDamage = std::max(blast.collisionDamage / share, 1.0f); + float reachSquared = blast.scale * blast.scale; + + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity == blast.spawnerEntity.get()) continue; + if (vector_length_squared(vector_sub(entity->pos, blast.targetPosition)) <= reachSquared) + blast_entity_hit(blast, *entity, tickDamage); + } + blast_cells_hit(blast, reachSquared); + if (blast.maxRadius <= blast.scale) blast.Remove(); + + bool isDoorsTime = blast.isDead || blast.scale > BLAST_DOORS_REACH; + if (blast.state == MEGA_BLAST_SWEEPING && is_room_blast(blast) && isDoorsTime) + { + blast.state = MEGA_BLAST_DOORS_DONE; + Difficulty difficulty = g_game->difficulty; + if (difficulty == DIFFICULTY_NORMAL || difficulty == DIFFICULTY_HARD) + { + g_game->room->TrySpawnBossRushDoor(true, false); + g_game->room->TrySpawnBlueWombDoor(true, true, false); + } + } + if (blast.subtype == 0) + effect_sound_play(SOUND_EXPLOSION_DEBRIS, + {.volume = MEGA_BLAST_RUMBLE_VOLUME, .frameDelay = MEGA_BLAST_SOUND_DELAY}); +} + +// A small rocket (Epic Fetus' smaller ones) flies up from 5 at 30 a frame (10 more for each state past the first), +// falling back at 6 a frame squared, faster the further its target (80 to 800 out, up to three times), and lands +// on it with its player's rocket blast, ten times their damage plus 30 but at most twenty times. +constexpr float SMALL_ROCKET_START_HEIGHT = -5; +constexpr float SMALL_ROCKET_LIFT = -30; +constexpr float SMALL_ROCKET_LIFT_STEP = -10; +constexpr float SMALL_ROCKET_GRAVITY = 6; +constexpr float SMALL_ROCKET_NEAR = 80; +constexpr float SMALL_ROCKET_FAR = 800; +constexpr float SMALL_ROCKET_FAR_LIFT = 3; +constexpr float SMALL_ROCKET_TILT = 90; +constexpr float SMALL_ROCKET_DAMAGE_SCALE = 10; +constexpr float SMALL_ROCKET_DAMAGE_BASE = 30; +constexpr float SMALL_ROCKET_DAMAGE_CAP = 20; + +// The small rocket's launch: up at its state's speed, aimed to come down on its target. +static void small_rocket_launch(Entity_Effect& rocket) +{ + rocket.sprite.Play("Flying"); + rocket.height = SMALL_ROCKET_START_HEIGHT; + rocket.fallingSpeed = SMALL_ROCKET_LIFT + (float)(rocket.state - 1) * SMALL_ROCKET_LIFT_STEP; + rocket.fallingAcceleration = SMALL_ROCKET_GRAVITY; + if (vector_is_zero(rocket.targetPosition)) return; + + float distance = vector_length(vector_sub(rocket.targetPosition, rocket.pos)); + rocket.fallingSpeed *= lerp_range(distance, {SMALL_ROCKET_NEAR, SMALL_ROCKET_FAR, 1, SMALL_ROCKET_FAR_LIFT}); + float root = std::sqrt(rocket.fallingSpeed * rocket.fallingSpeed - rocket.fallingAcceleration * 4 * rocket.height); + float pace = rocket.fallingAcceleration / (root - rocket.fallingSpeed); + rocket.velocity = vector_scale(vector_sub(rocket.targetPosition, rocket.pos), pace); +} + +// 00605172 (Update's case 118) A launched small rocket (state 1 and up) arcs up and down, pointing along its flight, +// and blows up with its player's tear effects once it lands. +static void small_rocket_update(Entity_Effect& rocket) +{ + if (rocket.state < 1) return; + if (!rocket.sprite.animState.IsLoopingAnimation()) small_rocket_launch(rocket); + + rocket.height += rocket.fallingSpeed; + rocket.fallingSpeed += rocket.fallingAcceleration; + rocket.posOffset.y = rocket.height; + rocket.sprite.rotation = + vector_angle(vector_add(rocket.velocity, vector_make(0, rocket.fallingSpeed))) + SMALL_ROCKET_TILT; + if (rocket.height < 0) return; + + Entity_Player* player = g_game->GetPlayer(0); + if (rocket.parent && rocket.parent->is_player()) player = static_cast(rocket.parent.get()); + TearParams params = player->GetTearHitParams(WEAPON_ROCKETS, 1, random_below(2) * 2 - 1, nullptr); + if (is_rocket_burst(*player)) params.tearFlags.set(TEAR_SAD_BOMB); + float damage = std::min(params.tearDamage * SMALL_ROCKET_DAMAGE_SCALE + SMALL_ROCKET_DAMAGE_BASE, + params.tearDamage * SMALL_ROCKET_DAMAGE_CAP); + explosion_effects({.tearFlags = params.tearFlags, + .color = params.tearColor, + .position = rocket.pos, + .source = &rocket, + .damage = damage}); + rocket.Remove(); +} + +// The reverse explosion (Reverse Tower) shows once its time is up: a blast, or (subtype 1) rubble in the room's rock +// sheet that settles into a rock (80 in 100), a tinted rock (3) or an alternate rock (17) where one may stand. +constexpr uint32_t RUBBLE_RNG_SHIFT = 3; +constexpr uint32_t RUBBLE_ROCK_RNG_SHIFT = 35; +constexpr int RUBBLE_ROCK_WEIGHT = 80; +constexpr int RUBBLE_TINTED_WEIGHT = 3; +constexpr int RUBBLE_ALT_WEIGHT = 17; + +// Part of 005cdb20 (Init's case 177) The reverse explosion waits unseen. +static void reverse_explosion_init(Entity_Effect& explosion) +{ + explosion.isVisible = false; +} + +// The rubble shows in the room's rock sheet, flipped and one of two kinds at random. +static void rubble_show(Entity_Effect& rubble) +{ + RNG rng = rng_make(rubble.initSeed, RUBBLE_RNG_SHIFT); + rubble.isVisible = true; + Backdrop& backdrop = g_game->room->backdrop; + const std::string& rocks = backdrop.configs[backdrop.backdropId].rocks; + for (int i = 0; i < (int)rubble.sprite.layerStates.size(); i++) rubble.sprite.ReplaceSpritesheet(i, rocks); + rubble.sprite.LoadGraphics(); + rubble.sprite.isFlipX = rng.RandomInt(2) == 0; + rubble.sprite.Play(rng.RandomInt(2) == 0 ? "Rubble02" : "Rubble01", PLAY_FORCED); +} + +// The rubble settles into a rock of a random kind, if one may stand there. +static void rubble_settle(Entity_Effect& rubble) +{ + if (!room_can_spawn_obstacle_at(rubble.pos, false)) return; + + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(GRID_ROCK, RUBBLE_ROCK_WEIGHT); + picker.AddOutcomeWeight(GRID_ROCKT, RUBBLE_TINTED_WEIGHT); + picker.AddOutcomeWeight(GRID_ROCK_ALT, RUBBLE_ALT_WEIGHT); + int type = picker.PickOutcome(rng_make(rubble.dropRNG.Next(), RUBBLE_ROCK_RNG_SHIFT)); + uint32_t seed = rubble.dropRNG.Next(); + Room& room = *g_game->room; + room.SpawnGridEntity(room.GetGridIndex(rubble.pos), (GridEntityType)type, 0, seed, 0); +} + +// 005df989 (Update's case 177) The reverse explosion shows once its time is up (the blast with its sound), then goes +// once its animation ends, rubble settling into a rock. +static void reverse_explosion_update(Entity_Effect& explosion) +{ + if (explosion.timeout < 1 && !explosion.isVisible) + { + if (explosion.subtype == 1) rubble_show(explosion); + else + { + explosion.isVisible = true; + explosion.sprite.Play("Explosion", PLAY_FORCED); + effect_sound_play(SOUND_REVERSE_EXPLOSION); + } + } + if (!explosion.isVisible || !explosion.sprite.IsFinished()) return; + + explosion.Remove(); + if (explosion.subtype == 1) rubble_settle(explosion); +} + +// The fireworks: a launcher (subtype 0) sends a rocket (1) up every 30 frames at 1 to 3 a frame. A rocket climbs +// against a growing fall, sparkling one frame in eight, and dies into a burst (2) and a ring of 5 to 7 stars (3) at +// 10 to 11 a frame, in its colour or (one time in four) each a random one. Stars sparkle (4) every other frame, +// wobbling, and sparks shrink. All glow. +constexpr int FIREWORK_LAUNCHER = 0; +constexpr int FIREWORK_ROCKET = 1; +constexpr int FIREWORK_BURST = 2; +constexpr int FIREWORK_STAR = 3; +constexpr int FIREWORK_SPARK = 4; +constexpr int FIREWORK_LAUNCH_FRAMES = 30; +constexpr float FIREWORK_LAUNCH_SPEED_MIN = 1; +constexpr float FIREWORK_LAUNCH_SPEED_SPAN = 2; +constexpr int FIREWORK_ROCKET_LIFE_MIN = 10; +constexpr int FIREWORK_ROCKET_LIFE_SPAN = 10; +constexpr float FIREWORK_LIFT_MIN = 12; +constexpr float FIREWORK_LIFT_SPAN = 4; +constexpr float FIREWORK_GRAVITY = 0.4f; +constexpr float FIREWORK_ROCKET_FRICTION = 0.98f; +constexpr float FIREWORK_TILT = 90; +constexpr int FIREWORK_STARS_MIN = 5; +constexpr int FIREWORK_STARS_SPAN = 3; +constexpr float FIREWORK_STAR_SPEED = 10; +constexpr float FIREWORK_STAR_SPREAD_MIN = 0.75f; +constexpr float FIREWORK_STAR_SPREAD_SPAN = 0.5f; +constexpr int FIREWORK_STAR_LIFE_MIN = 30; +constexpr int FIREWORK_STAR_LIFE_SPAN = 5; +constexpr int FIREWORK_RAINBOW_ODDS = 4; +constexpr float FIREWORK_BOOM_VOLUME = 0.5f; +constexpr float FIREWORK_BOOM_PITCH = 1.2f; +constexpr int FIREWORK_SPARKLE_ODDS = 8; +constexpr float FIREWORK_SPARK_CARRY = 0.1f; +constexpr float FIREWORK_SPARK_JITTER = 0.5f; +constexpr float FIREWORK_SPARK_SCALE_MIN = 0.5f; +constexpr float FIREWORK_ROCKET_SPARK_SCALE_SPAN = 0.2f; +constexpr float FIREWORK_STAR_SPARK_SCALE_SPAN = 0.5f; +constexpr int FIREWORK_SPARK_LIFE = 20; +constexpr int FIREWORK_STAR_SPARK_FRAMES = 2; +constexpr float FIREWORK_STAR_WOBBLE = 0.4f; +constexpr float FIREWORK_STAR_WOBBLE_RATE = 0.5f; +constexpr int FIREWORK_STAR_WOBBLE_PHASE = 15; +constexpr float FIREWORK_STAR_FRICTION = 0.9f; +constexpr float FIREWORK_SPARK_FRICTION = 0.99f; +constexpr float FIREWORK_SPARK_SHRINK = 0.97f; +constexpr float FIREWORK_STAR_COLORIZE = 0.5f; +constexpr std::array FIREWORK_PARTICLES = {"Particle1", "Particle2", "Particle3", "Particle4"}; + +// A random bright tint, its three parts summing to one. +static ColorMod firework_rainbow() +{ + float red = random_unit(); + float green = random_unit(); + float blue = random_unit(); + float share = 1 / (red + green + blue); + return tint_color_make(red * share, green * share, blue * share, 1); +} + +// Part of 005cdb20 (Init's case 104) A launcher is unseen. A rocket flies up in a random bright colour. A burst +// explodes, a star or spark is one of four particles. All but rockets take a random turn, and all glow. +static void firework_init(Entity_Effect& firework) +{ + if (firework.subtype == FIREWORK_LAUNCHER) firework.isVisible = false; + else if (firework.subtype == FIREWORK_ROCKET) + { + firework.sprite.Play("Projectile"); + firework.height = -(random_unit() * FIREWORK_LIFT_SPAN + FIREWORK_LIFT_MIN); + firework.SetColor(firework_rainbow(), -1, COLOR_PRIORITY_DEFAULT, false, true); + } + else if (firework.subtype == FIREWORK_BURST) firework.sprite.Play("Explode"); + else firework.sprite.Play(FIREWORK_PARTICLES[random_below((int)FIREWORK_PARTICLES.size())]); + if (firework.subtype != FIREWORK_ROCKET) + firework.sprite.rotation = random_unit() * DEGREES_PER_TURN - DEGREES_PER_TURN / 2; + layer_additive_set(*firework.sprite.GetLayer(0)); +} + +// A firework part of the given subtype from this one, at its height. +static Entity_Effect* firework_spawn(Entity_Effect& from, int subtype, Vector velocity, uint32_t seed) +{ + auto* part = static_cast(g_game->Spawn({.position = from.pos, + .velocity = velocity, + .spawner = &from, + .subType = subtype, + .type = ENTITY_EFFECT, + .variant = EFFECT_FIREWORKS, + .seed = seed})); + part->posOffset = from.posOffset; + return part; +} + +// A spark trailing a rocket or star: carried along, jittered, of a random size, lasting longer the faster it went. +static Entity_Effect* firework_spark(Entity_Effect& from, float scaleSpan) +{ + uint32_t seed = Random(); + Vector carry = vector_scale(from.velocity, FIREWORK_SPARK_CARRY); + Vector jitter = random_direction(); + jitter = vector_scale(jitter, random_unit() * FIREWORK_SPARK_JITTER); + Entity_Effect* spark = firework_spawn(from, FIREWORK_SPARK, vector_add(carry, jitter), seed); + float scale = random_unit() * scaleSpan + FIREWORK_SPARK_SCALE_MIN; + spark->sprite.scale = vector_make(scale, scale); + spark->SetTimeout((int)vector_length(from.velocity) + FIREWORK_SPARK_LIFE + random_below(FIREWORK_SPARK_LIFE)); + return spark; +} + +// A rocket's end: a burst in its colour and a ring of stars, all its colour or each a random one, with a boom. +static void firework_explode(Entity_Effect& rocket) +{ + Entity_Effect* burst = firework_spawn(rocket, FIREWORK_BURST, {}, Random()); + burst->SetColor(rocket.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + burst->Update(); + int stars = random_below(FIREWORK_STARS_SPAN) + FIREWORK_STARS_MIN; + float spread = random_unit() * FIREWORK_STAR_SPREAD_SPAN + FIREWORK_STAR_SPREAD_MIN; + bool isRainbow = random_below(FIREWORK_RAINBOW_ODDS) == 0; + for (int i = 0; i < stars; i++) + { + uint32_t seed = Random(); + Vector way = vector_from_angle((float)i / (float)stars * DEGREES_PER_TURN); + Vector velocity = vector_scale(way, (random_unit() + FIREWORK_STAR_SPEED) * spread); + Entity_Effect* star = firework_spawn(rocket, FIREWORK_STAR, velocity, seed); + star->SetTimeout(random_below(FIREWORK_STAR_LIFE_SPAN) + FIREWORK_STAR_LIFE_MIN); + star->SetColor(isRainbow ? firework_rainbow() : rocket.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + star->Update(); + } + rocket.Remove(); + effect_sound_play(SOUND_BOSS_EXPLOSION, {.volume = FIREWORK_BOOM_VOLUME, .pitch = FIREWORK_BOOM_PITCH}); +} + +// A rocket climbing: its fall grows, it bursts once dead, points along its flight and sometimes sparkles. +static void firework_rocket_update(Entity_Effect& rocket) +{ + rocket.posOffset.y += rocket.height; + rocket.height += FIREWORK_GRAVITY; + rocket.friction *= FIREWORK_ROCKET_FRICTION; + if (rocket.isDead) firework_explode(rocket); + Vector flight = vector_make(rocket.velocity.x, rocket.height + rocket.velocity.y); + rocket.sprite.rotation = vector_angle(flight) + FIREWORK_TILT; + if (random_below(FIREWORK_SPARKLE_ODDS) != 0) return; + + Entity_Effect* spark = firework_spark(rocket, FIREWORK_ROCKET_SPARK_SCALE_SPAN); + spark->SetColor(rocket.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + spark->Update(); +} + +// A star: every other frame a spark in its colour colorized at random, and it wobbles as it slows. +static void firework_star_update(Entity_Effect& star) +{ + if (star.IsFrame(FIREWORK_STAR_SPARK_FRAMES, 0)) + { + Entity_Effect* spark = firework_spark(star, FIREWORK_STAR_SPARK_SCALE_SPAN); + float red = random_unit(); + float green = random_unit(); + float blue = random_unit(); + float share = 1 / (red + green + blue); + ColorMod color = star.color; + color._colorize[0] = red * share; + color._colorize[1] = green * share; + color._colorize[2] = blue * share; + color._colorize[3] = FIREWORK_STAR_COLORIZE; + spark->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + spark->Update(); + } + float jitter = random_unit() - 0.5f; + float phase = (float)(g_game->frameCount + star.index * FIREWORK_STAR_WOBBLE_PHASE); + float wobble = std::sin(phase * FIREWORK_STAR_WOBBLE_RATE) * vector_length(star.velocity) * FIREWORK_STAR_WOBBLE; + star.velocity = tear_vector_rotate(star.velocity, jitter + wobble); + star.friction *= FIREWORK_STAR_FRICTION; +} + +// 0060002b (Update's case 104) Each firework part plays its part: the launcher launches, the rocket climbs and bursts, +// the burst goes once shown, stars sparkle and sparks shrink. Any part goes once dead. +static void firework_update(Entity_Effect& firework) +{ + if (firework.subtype == FIREWORK_LAUNCHER) + { + if (firework.IsFrame(FIREWORK_LAUNCH_FRAMES, 0)) + { + uint32_t seed = Random(); + Vector way = random_direction(); + Vector velocity = vector_scale(way, random_unit() * FIREWORK_LAUNCH_SPEED_SPAN + FIREWORK_LAUNCH_SPEED_MIN); + Entity_Effect* rocket = firework_spawn(firework, FIREWORK_ROCKET, velocity, seed); + rocket->SetTimeout(random_below(FIREWORK_ROCKET_LIFE_SPAN) + FIREWORK_ROCKET_LIFE_MIN); + rocket->Update(); + } + } + else if (firework.subtype == FIREWORK_ROCKET) firework_rocket_update(firework); + else if (firework.subtype == FIREWORK_BURST) + { + if (firework.sprite.IsFinished()) firework.Remove(); + } + else if (firework.subtype == FIREWORK_STAR) firework_star_update(firework); + else if (firework.subtype == FIREWORK_SPARK) + { + firework.friction *= FIREWORK_SPARK_FRICTION; + firework.sprite.scale = vector_scale(firework.sprite.scale, FIREWORK_SPARK_SHRINK); + } + if (firework.isDead) firework.Remove(); + firework.state++; +} + +constexpr auto BLAST_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_MAMA_MEGA_EXPLOSION, mega_blast_init, effect_finishing, nullptr}, + {EFFECT_MEGA_BEAN_EXPLOSION, mega_blast_init, effect_finishing, nullptr}, + {EFFECT_SMALL_ROCKET, nullptr, effect_finishing, nullptr}, + {EFFECT_REVERSE_EXPLOSION, reverse_explosion_init, effect_finishing, nullptr}, + {EFFECT_FIREWORKS, firework_init, effect_finishing, nullptr}, +}); + +std::span blast_effect_behaviours() +{ + return BLAST_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_effect_boss.cpp b/src/entity_effect_boss.cpp index 7275568..c77cb63 100644 --- a/src/entity_effect_boss.cpp +++ b/src/entity_effect_boss.cpp @@ -1,10 +1,13 @@ #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_player.h" #include "game.h" #include "npc_caves.h" #include "room.h" #include "room_grid.h" #include "sfx_manager.h" +#include +#include // A beam of light from above (Crack the Sky, Isaac's and the Holy Eye's beams): a spotlight that strikes on its Hit // event, then hurts what stands in it every third frame its beam shows. Subtype 1 is the player's, which takes subtype @@ -190,7 +193,7 @@ static void hush_laser_update(Entity_Effect& laser) laser.velocity = vector_add(laser.velocity, vector_scale(pull, player.speedMultiplier)); } - laser.velocity = vector_scale(laser.velocity, npc_friction_scaled(HUSH_LASER_FRICTION, laser.speedMultiplier)); + laser.velocity = vector_scale(laser.velocity, timescale_factor(HUSH_LASER_FRICTION, laser.speedMultiplier)); if (laser.IsFrame(HUSH_LASER_HIT_SPACING, (int)laser.index)) hush_laser_hit(laser); if (!laser.IsFrame(HUSH_LASER_TRAIL_SPACING, (int)laser.index)) return; @@ -212,12 +215,93 @@ static void hush_beam_update(Entity_Effect& beam) hush_laser_cycle(beam); } +// The Siren's charm on a familiar fades in over its last 15 frames and out over its first 15 from 75, follows the +// familiar, and on frame 20 (subtype 0) steals it for the Siren from its player. It fades early once its familiar or +// the Siren is gone. +constexpr int CHARM_FADE_FRAMES = 15; +constexpr int CHARM_FULL_FRAMES = 61; +constexpr float CHARM_FADE_IN_START = 75; +constexpr float CHARM_FADE_IN_END = 60; +constexpr int CHARM_STEAL_FRAME = 20; +constexpr float CHARM_DEPTH = 4; + +// The familiars the Siren never charms (by variant), and those charmed only with subtype 0. Others past 900 always are. +constexpr std::array SIREN_IMMUNE_FAMILIARS = {12, 20, 21, 22, 23, 24, 26, 27, 28, 43, 57, 62, + 64, 67, 68, 73, 109, 120, 128, 201, 202, 203, 206, 211, + 213, 214, 215, 228, 236, 237, 238, 240, 243, 900}; +constexpr std::array SIREN_SUBTYPE_ZERO_FAMILIARS = {25, 58, 59, 106}; +constexpr int SIREN_INCUBUS = 80; +constexpr int SIREN_STATE_BUSY = 200; +constexpr int SIREN_STATE_IDLE = 216; +constexpr int FAMILIAR_VARIANT_LAST_PLAIN = 900; + +// FUN_0060dae0 Whether the Siren may charm a familiar: not the ones that never follow her, the subtype 0 ones only +// as such, Incubus only away from Lilith, and two only in some states. +bool is_familiar_charmable(Entity_Familiar& familiar) +{ + int variant = familiar.variant; + if (variant > FAMILIAR_VARIANT_LAST_PLAIN) return true; + if (std::find(SIREN_IMMUNE_FAMILIARS.begin(), SIREN_IMMUNE_FAMILIARS.end(), variant) != + SIREN_IMMUNE_FAMILIARS.end()) + return false; + if (std::find(SIREN_SUBTYPE_ZERO_FAMILIARS.begin(), SIREN_SUBTYPE_ZERO_FAMILIARS.end(), variant) != + SIREN_SUBTYPE_ZERO_FAMILIARS.end()) + return familiar.subtype == 0; + if (variant == SIREN_INCUBUS) return !familiar.player || familiar.player->playerType != PLAYER_LILITH; + if (variant == SIREN_STATE_BUSY) return familiar.state != 0; + if (variant == SIREN_STATE_IDLE) return familiar.state < 1; + return true; +} + +// Part of 005cdb20 (Init's case 165) The charm glows, on the floor for subtype 1, else just in front. +static void siren_charm_init(Entity_Effect& charm) +{ + layer_additive_set(*charm.sprite.GetLayer(0)); + if (charm.subtype == 1) charm.sortingLayer = SORTING_BACKGROUND; + else charm.renderDepthOffset = CHARM_DEPTH; +} + +// 005e0f32 (Update's case 165) The charm fades with its time, goes (without Update's shared end) from anything but a +// charmable familiar, follows it, and on its frame hands the familiar to the Siren. +static EffectUpdateEnd siren_charm_update(Entity_Effect& charm) +{ + float alpha = 1; + if (charm.timeout < CHARM_FADE_FRAMES) alpha = lerp_range((float)charm.timeout, {0, CHARM_FADE_FRAMES, 0, 1}); + else if (charm.timeout >= CHARM_FULL_FRAMES) + alpha = lerp_range((float)charm.timeout, {CHARM_FADE_IN_START, CHARM_FADE_IN_END, 0, 1}); + charm.sprite.color._tint[3] = alpha; + + Entity* target = charm.target; + if (target) + { + if (!target->IsFamiliar() || !is_familiar_charmable(static_cast(*target))) + { + charm.Remove(); + return EFFECT_UPDATE_RETURN; + } + charm.pos = target->pos; + charm.velocity = target->velocity; + } + if ((!target || !charm.parent || charm.parent->isDead) && charm.timeout > CHARM_FADE_FRAMES) + charm.timeout = CHARM_FADE_FRAMES; + if (charm.subtype != 0 || charm.timeout != CHARM_STEAL_FRAME || !target || !charm.parent) + return EFFECT_UPDATE_FINISH; + + Entity* siren = charm.parent->to_npc_or_coop_player(); + auto* familiar = static_cast(target); + Entity_Player* player = charm.child ? charm.child->ToPlayer() : nullptr; + if (siren && siren->IsType(ENTITY_SIREN, 0, -1) && !familiar->HasEntityFlags(FLAG_CHARM) && player) + familiar->siren_charm(siren, player); + return EFFECT_UPDATE_FINISH; +} + // Hush's lasers and the poof of his shots have no Init case of their own. constexpr auto BOSS_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_CRACK_THE_SKY, crack_init, effect_finishing, nullptr}, {EFFECT_HUSH_LASER, nullptr, effect_finishing, nullptr}, {EFFECT_HUSH_LASER_UP, nullptr, effect_finishing, nullptr}, {EFFECT_BULLET_POOF_HUSH, nullptr, effect_poof_update, nullptr}, + {EFFECT_CHARM_EFFECT, siren_charm_init, siren_charm_update, nullptr}, }); std::span boss_effect_behaviours() diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index 919702e..bcacb26 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -314,18 +314,6 @@ constexpr float HALF_TURN = 180; constexpr float FULL_TURN = 360; constexpr float SPRITE_UP = 90; -// The sounds the explosions play (Lua's SoundEffect). -enum CombatSound : int -{ - SOUND_BOSS_EXPLOSION = 182, - SOUND_EXPLOSION_WEAK = 183, - SOUND_EXPLOSION_STRONG = 184, - SOUND_ROCKET_EXPLOSION = 587, - SOUND_GFUEL_EXPLOSION = 822, - SOUND_GFUEL_EXPLOSION_BIG = 823, - SOUND_GLITTER_BOMB = 866 -}; - static CombatEffect variant_get(const Entity_Effect& effect) { return static_cast(effect.variant); @@ -351,12 +339,6 @@ static float angle_wrap(float angle) return angle; } -// Math::timescale_factor 00684cb0: a per-frame factor stretched to the time scale. -static float timescale_factor(float factor, float timeScale) -{ - return timeScale == 1 ? factor : factor / (factor + timeScale - factor * timeScale); -} - // Plays a sound through the fart seeds. static void sound_play(int sound, float volume, float pitch) { diff --git a/src/entity_effect_floor.cpp b/src/entity_effect_floor.cpp index a7b9f99..1773474 100644 --- a/src/entity_effect_floor.cpp +++ b/src/entity_effect_floor.cpp @@ -2,6 +2,7 @@ #include "capsule.h" #include "entity_effect.h" #include "fx_layers.h" +#include "entity_player.h" #include "game.h" #include "npc_ai.h" #include "npc_basement.h" @@ -10,6 +11,7 @@ #include "sfx_manager.h" #include #include +#include // The floor effects: splashes and ripples on the room's water, the tar's bubbles, the dirt piles and patches // shovels and diggers leave, and the haemolacria trail's drops. @@ -541,6 +543,84 @@ static void hole_helper_render(Entity_Effect& helper, const Vector& offset) hole->isVisible = false; } +// The Colostomia's puddle of poop: its bubbles rise within its BubbleGuide null (one frame in three while the null +// shows), and while it does it burns the grounded players standing on its drawn poop (Callus and Socks spare them) for +// 1, leaving them slippery with brown footprints. It ripples in time with the game and fades once its parent is gone. +constexpr float PUDDLE_GUIDE_ALPHA = 0.5f; +constexpr int PUDDLE_BUBBLE_ODDS = 3; +constexpr float PUDDLE_BUBBLE_SPREAD = 4; +constexpr float PUDDLE_SCREEN_SCALE = 0.65f; +constexpr float PUDDLE_TEXEL_ALPHA = 0.5f; +constexpr float PUDDLE_DAMAGE = 1; +constexpr int PUDDLE_HIT_COUNTDOWN = 30; +constexpr int PUDDLE_FADE_FRAMES = 15; +constexpr int PUDDLE_SORTING_Z = 2000; +constexpr std::string_view POOP_BUBBLE_SHEET = "gfx/effects/poop_bubble.png"; + +// Part of 005cdb20 (Init's case 168) The puddle lies on the floor over the creep and appears. +static void colostomia_puddle_init(Entity_Effect& puddle) +{ + puddle.sortingLayer = SORTING_BACKGROUND; + puddle.renderZOffset = PUDDLE_SORTING_Z; + puddle.sprite.Play("Appear"); +} + +// A bubble of poop rising somewhere inside the puddle's guide. +static void colostomia_bubble(Entity_Effect& puddle, const NullFrame& guide) +{ + Vector direction = random_direction(); + Vector spot = vector_scale(direction, std::sqrt(random_unit())); + spot = vector_make(spot.x * guide.scale.x * PUDDLE_BUBBLE_SPREAD / PUDDLE_SCREEN_SCALE, + spot.y * guide.scale.y * PUDDLE_BUBBLE_SPREAD / PUDDLE_SCREEN_SCALE); + Entity* bubble = g_game->Spawn({.position = vector_add(puddle.pos, spot), + .type = ENTITY_EFFECT, + .variant = EFFECT_TAR_BUBBLE, + .seed = Random()}); + bubble->parent = &puddle; + bubble->sprite.ReplaceSpritesheet(0, POOP_BUBBLE_SHEET); + bubble->sprite.LoadGraphics(); + bubble->Update(); +} + +// Burns a grounded player standing on the puddle's drawn poop. +static void colostomia_player_burn(Entity_Effect& puddle, Entity_Player& player) +{ + bool isGrounded = !player.isDead && player.entityCollisionClass != ENTCOLL_NONE && + player.entityGridCollisionClass == GRIDCOLL_GROUND; + if (!isGrounded || player.HasTrinket(TRINKET_CALLUS) || player.HasCollectible(COLLECTIBLE_SOCKS)) return; + float distance = vector_length(vector_sub(player.pos, puddle.pos)); + if (distance >= puddle.size * puddle.sprite.scale.x + player.size) return; + + KColor texel = puddle.sprite.GetTexel({.renderPos = vector_scale(puddle.pos, PUDDLE_SCREEN_SCALE), + .sample = vector_scale(player.pos, PUDDLE_SCREEN_SCALE), + .alphaThreshold = PUDDLE_TEXEL_ALPHA, + .layerId = 0}); + if (texel._alpha <= PUDDLE_TEXEL_ALPHA) return; + player.TakeDamage(PUDDLE_DAMAGE, DAMAGE_ACID, EntityRef(&puddle), PUDDLE_HIT_COUNTDOWN); + player.AddEntityFlags(FLAG_SLIPPERY_PHYSICS); + player.SetFootprintColor(texel, false); +} + +// 005dc0ef (Update's case 168) The puddle idles once it has appeared, rippling with the game's frames, bubbles and +// burns while its guide shows, fades once its parent is gone, and disappears once dead. +static void colostomia_puddle_update(Entity_Effect& puddle) +{ + const NullFrame* guide = puddle.sprite.GetNullFrame("BubbleGuide"); + if (puddle.sprite.GetAnimation().starts_with("A") && puddle.sprite.IsFinished()) puddle.sprite.Play("Idle"); + AnimationState& anim = puddle.sprite.animState; + if (anim.IsLoopingAnimation()) puddle.sprite.SetFrame((float)((int)g_game->frameCount % anim.GetAnimationLength())); + if (puddle.timeout < 0 && (!puddle.parent || puddle.parent->isDead)) puddle.timeout = PUDDLE_FADE_FRAMES; + + if (guide && guide->color._tint[3] > PUDDLE_GUIDE_ALPHA) + { + if (random_below(PUDDLE_BUBBLE_ODDS) == 0) colostomia_bubble(puddle, *guide); + for (Entity_Player* player : g_game->playerManager.playerList) colostomia_player_burn(puddle, *player); + } + if (!puddle.isDead) return; + puddle.sprite.Play("Disappear"); + if (puddle.sprite.IsFinished()) puddle.Remove(); +} + constexpr auto FLOOR_BEHAVIOURS = std::to_array({ {EFFECT_WATER_SPLASH, water_splash_init, effect_finishing, nullptr}, {EFFECT_HAEMO_TRAIL, haemo_trail_init, effect_finishing, nullptr}, @@ -552,6 +632,7 @@ constexpr auto FLOOR_BEHAVIOURS = std::to_array({ {EFFECT_DIRT_PILE, dirt_pile_init, effect_finishing, nullptr}, {EFFECT_BIG_HORN_HOLE_HELPER, nullptr, effect_finishing, hole_helper_render}, {EFFECT_BIG_HORN_HAND, big_horn_hand_init, big_horn_hand_update, nullptr}, + {EFFECT_COLOSTOMIA_PUDDLE, colostomia_puddle_init, effect_finishing, nullptr}, }); std::span floor_effect_behaviours() diff --git a/src/entity_effect_hazard.cpp b/src/entity_effect_hazard.cpp index 0bda7a3..6c5345b 100644 --- a/src/entity_effect_hazard.cpp +++ b/src/entity_effect_hazard.cpp @@ -182,9 +182,9 @@ static void shockwave_update(Entity_Effect& wave) { if (wave.state < wave.timeout) wave.state = wave.timeout; float timeout = (float)wave.timeout; - float radius = lerp_clamped(timeout, (float)wave.state, 0, wave.minRadius, wave.maxRadius); - float arc = lerp_clamped(timeout * timeout, (float)(wave.state * wave.state), 0, SHOCKWAVE_ARC_WIDEST, - SHOCKWAVE_ARC_NARROWEST); + float radius = lerp_range(timeout, {(float)wave.state, 0, wave.minRadius, wave.maxRadius}); + float arc = lerp_range(timeout * timeout, + {(float)(wave.state * wave.state), 0, SHOCKWAVE_ARC_WIDEST, SHOCKWAVE_ARC_NARROWEST}); if (wave.timeout % SHOCKWAVE_PERIOD == 0) { @@ -250,8 +250,8 @@ static float crackwave_wobble(Entity_Effect& wave, int frame) { Vector cell = g_game->room->GetGridPosition(wave.state); distance = vector_length(vector_sub(cell, wave.targetPosition)); - float turn = lerp_clamped(distance, CRACKWAVE_HOMING_NEAR, CRACKWAVE_HOMING_FAR, - CRACKWAVE_HOMING_TURN_NEAR, CRACKWAVE_HOMING_TURN_FAR); + float turn = lerp_range(distance, {CRACKWAVE_HOMING_NEAR, CRACKWAVE_HOMING_FAR, + CRACKWAVE_HOMING_TURN_NEAR, CRACKWAVE_HOMING_TURN_FAR}); wave.rotation = angle_approach(wave.rotation, vector_angle(vector_sub(cell, wave.targetPosition)), turn); if (room_grid_collision_at(cell) == 0 || wave.FrameCount() > CRACKWAVE_HOMING_FRAMES) @@ -259,7 +259,7 @@ static float crackwave_wobble(Entity_Effect& wave, int frame) } if (wave.FrameCount() <= CRACKWAVE_START_FRAMES) return 0; float wobble = random_unit() - 0.5f; - return lerp_clamped(distance, CRACKWAVE_HOMING_NEAR, CRACKWAVE_HOMING_FAR, 0, 1) * CRACKWAVE_WOBBLE_SPAN * + return lerp_range(distance, {CRACKWAVE_HOMING_NEAR, CRACKWAVE_HOMING_FAR, 0, 1}) * CRACKWAVE_WOBBLE_SPAN * wobble; } default: return 0; @@ -423,6 +423,73 @@ static void statue_update(Entity_Effect& statue) npc_sound_play(SOUND_ISAACDIES, 1, 2, player ? player->get_voice_pitch() : 1); } +// The fissure spawner (Ashpit) ripples the floor every 10 ticks and, every 150 frames over one more than its subtype's +// third nibble, sends a fissure out at its first nibble's sixteenth of a turn, its second nibble's tenth plus one +// tenth of 3 a frame. It goes once the room is clear (and its pressure plates done, or not about to). +constexpr int FISSURE_RIPPLE_TICKS = 10; +constexpr int FISSURE_PERIOD = 150; +constexpr float FISSURE_TURNS = 16; +constexpr float FISSURE_SPEED_STEP = 0.1f; +constexpr float FISSURE_SPEED = 3; +constexpr int FISSURE_PLATES_DELAY = 9; +constexpr int NIBBLE_BITS = 4; +constexpr uint32_t NIBBLE_MASK = 0xf; + +// Part of 005cdb20 (Init's case 192) The fissure spawner is unseen. +static void fissure_spawner_init(Entity_Effect& spawner) +{ + spawner.isVisible = false; +} + +// Whether the fissure spawner's room is done: no enemies alive after its first frame and no pressure plates still +// due to trigger. +static bool is_fissure_room_done() +{ + Room& room = *g_game->room; + if (room.GetFrameCount() <= 1 || room.GetAliveEnemiesCount() > 0) return false; + return !room.isTriggerPressurePlates || room.roomClearDelay < FISSURE_PLATES_DELAY; +} + +// A fissure from the spawner, on its way out at its aim (kept as its target position). +static void fissure_send(Entity_Effect& spawner, Vector aim) +{ + uint32_t seed = Random(); + Entity* fissure = g_game->Spawn( + {.position = spawner.pos, .velocity = vector_scale(aim, FISSURE_SPEED), .type = ENTITY_FISSURE, .seed = seed}); + fissure->AddEntityFlags(FLAG_NO_REWARD); + fissure->ClearEntityFlags(FLAG_APPEAR); + fissure->targetPosition = aim; + fissure->Update(); +} + +// 005e5ace (Update's case 192) The fissure spawner ripples the floor and sends fissures out on its beat, and goes +// (without Update's shared end) once its room is done. +static EffectUpdateEnd fissure_spawner_update(Entity_Effect& spawner) +{ + uint32_t subtype = (uint32_t)spawner.subtype; + int period = FISSURE_PERIOD / (int)(((subtype >> (NIBBLE_BITS * 2)) & NIBBLE_MASK) + 1); + if (spawner.GetIntervalTicks(FISSURE_RIPPLE_TICKS, 0) != 0) + g_game + ->Spawn({.position = spawner.pos, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_RIPPLE, .seed = Random()}) + ->Update(); + if (is_fissure_room_done()) + { + spawner.Remove(); + return EFFECT_UPDATE_RETURN; + } + + int ticks = spawner.update_ticks_get(); + for (int i = 0; i < ticks; i++) + { + if (++spawner.state < period) continue; + spawner.state = 0; + float angle = (float)(subtype & NIBBLE_MASK) * DEGREES_PER_TURN / FISSURE_TURNS; + float speed = (float)((subtype >> NIBBLE_BITS) & NIBBLE_MASK) * FISSURE_SPEED_STEP + FISSURE_SPEED_STEP; + fissure_send(spawner, vector_scale(vector_from_angle(angle), speed)); + } + return EFFECT_UPDATE_FINISH; +} + constexpr auto HAZARD_BEHAVIOURS = std::to_array({ {EFFECT_DEVIL, nullptr, effect_finishing, nullptr}, {EFFECT_ANGEL, nullptr, effect_finishing, nullptr}, @@ -432,6 +499,7 @@ constexpr auto HAZARD_BEHAVIOURS = std::to_array({ {EFFECT_CRACKWAVE, crackwave_init, effect_finishing, nullptr}, {EFFECT_SHOCKWAVE_RANDOM, shockwave_random_init, effect_finishing, nullptr}, {EFFECT_HALLOWED_GROUND, hallowed_ground_init, hallowed_ground_update, nullptr}, + {EFFECT_FISSURE_SPAWNER, fissure_spawner_init, fissure_spawner_update, nullptr}, }); std::span hazard_effect_behaviours() diff --git a/src/entity_effect_items.cpp b/src/entity_effect_items.cpp index d95b662..283edd0 100644 --- a/src/entity_effect_items.cpp +++ b/src/entity_effect_items.cpp @@ -12,6 +12,7 @@ #include "entity_projectile.h" #include "game.h" #include "grid_entity_door.h" +#include "kage_graphics.h" #include "level.h" #include "manager.h" #include "npc_ai.h" @@ -205,13 +206,6 @@ constexpr float BOOMERANG_FRICTION = 0.95f; constexpr float BOOMERANG_RETURN_SPEED = 15; constexpr int STICKY_NICKEL_COOLDOWN = 10; -// Plays a sound through the seeds' fart override. -static void overridden_sound_play(int sound, SoundPlay play = {}) -{ - seed_fart_sound_override(&sound); - g_manager->sfxManager.Play(sound, play); -} - // Redemption's sign over its player: a damage up and a soul heart's worth (two halves) with a white flash on success, // a thumbs down and a poof 20 up on failure. constexpr float REDEMPTION_DEPTH = -10; @@ -220,13 +214,6 @@ constexpr int REDEMPTION_FLASH_FRAMES = 6; constexpr float REDEMPTION_POOF_HEIGHT = -20; constexpr ColorMod REDEMPTION_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 1, 1}}; -// Redemption's states: waiting while its player holds an item up, succeeded, failed. -enum RedemptionState -{ - REDEMPTION_WAITING = 1, - REDEMPTION_SUCCESS, - REDEMPTION_FAIL -}; // Part of 005cdb20 (Init's fire case) A fire keeps off pits, owned by whoever fired the tear or bomb that set it. The // item fires burn for 300 frames at full size. @@ -297,7 +284,7 @@ static void blue_flame_update(Entity_Effect& flame) if (!fire_hit(flame, *entity, flame.collisionDamage * damageScale, 0)) continue; float volume = std::min(entity->health * FLAME_HISS_PER_HEALTH + FLAME_HISS_VOLUME, 1.0f); - overridden_sound_play(SOUND_FIREDEATH_HISS, {.volume = volume, .frameDelay = FLAME_HISS_DELAY}); + effect_sound_play(SOUND_FIREDEATH_HISS, {.volume = volume, .frameDelay = FLAME_HISS_DELAY}); } else if (is_shot_put_out(flame, *entity)) entity->Remove(); } @@ -319,7 +306,7 @@ static void item_fire_update(Entity_Effect& fire) if (fire.parent && fire.parent->IsEnemy()) { radius = fire.parent->size + FIRE_ENEMY_REACH; - fire.scale = lerp_clamped(fire.parent->health, FIRE_ENEMY_HEALTH_LOW, FIRE_ENEMY_HEALTH_HIGH, 0, 1); + fire.scale = lerp_range(fire.parent->health, {FIRE_ENEMY_HEALTH_LOW, FIRE_ENEMY_HEALTH_HIGH, 0, 1}); } if (fire.IsFrame(FIRE_HIT_RESET_FRAMES, (int)fire.index)) fire.hitList.clear(); layer_additive_set(*fire.sprite.GetLayer(0)); @@ -344,7 +331,7 @@ static void item_fire_update(Entity_Effect& fire) { fire.isDead = true; if (fire.parent && fire.parent->IsEnemy()) - overridden_sound_play(SOUND_STEAM_HALFSEC, {.volume = FIRE_STEAM_VOLUME}); + effect_sound_play(SOUND_STEAM_HALFSEC, {.volume = FIRE_STEAM_VOLUME}); } if (!fire.isDead) return; @@ -382,7 +369,7 @@ static void foot_update(Entity_Effect& foot) } else if (frame == FOOT_STOMP_FRAME) { - overridden_sound_play(SOUND_HELLBOSS_GROUNDPOUND); + effect_sound_play(SOUND_HELLBOSS_GROUNDPOUND); float damage = g_game->deathmatchManager.is_active() ? FOOT_VERSUS_DAMAGE : foot.collisionDamage; explosion_damage({.position = foot.pos, .source = &foot, .damageFlags = DAMAGE_CRUSH, .damage = damage, @@ -607,7 +594,7 @@ static void fire_jet_update(Entity_Effect& jet) int frame = jet.FrameCount(); if (frame == 1 && jet.subtype == 0) { - overridden_sound_play(SOUND_CANDLE_LIGHT); + effect_sound_play(SOUND_CANDLE_LIGHT); } if ((frame == 2 || frame == 4) && jet.collisionDamage > 0) { @@ -649,7 +636,7 @@ static void xray_wall_update(Entity_Effect& hole) static void moms_hand_init(Entity_Effect& hand) { hand.sprite.Play("JumpDown"); - overridden_sound_play(SOUND_BIRD_FLAP); + effect_sound_play(SOUND_BIRD_FLAP); } // 005ffc5d (Update's case 91) Mom's hand lands on its target for its damage with a stomp, grabs it, and dies (going @@ -659,7 +646,7 @@ static void moms_hand_update(Entity_Effect& hand) if (hand.sprite.IsEventTriggered("Land") && hand.target && hand.target->isExists) { hand.target->TakeDamage(hand.collisionDamage, 0, EntityRef(&hand), MOMS_HAND_HIT_COUNTDOWN); - overridden_sound_play(SOUND_FORESTBOSS_STOMPS); + effect_sound_play(SOUND_FORESTBOSS_STOMPS); } if (hand.sprite.IsFinished("JumpDown")) hand.sprite.Play("Grab"); if (!hand.target || !hand.target->isExists) hand.isDead = true; @@ -775,7 +762,7 @@ static void tooth_update(Entity_Effect& tooth) else if (tooth.sprite.IsFinished("JumpUp")) tooth.Remove(); if (tooth.state == MONSTRO_TOOTH_LAND_FRAME) { - overridden_sound_play(SOUND_FORESTBOSS_STOMPS, {.volume = MONSTRO_TOOTH_VOLUME}); + effect_sound_play(SOUND_FORESTBOSS_STOMPS, {.volume = MONSTRO_TOOTH_VOLUME}); explosion_damage({.position = tooth.pos, .source = &tooth, .damageFlags = DAMAGE_CRUSH, .damage = MONSTRO_TOOTH_DAMAGE, .radius = MONSTRO_TOOTH_RADIUS, .isLineCheck = false}); } @@ -916,7 +903,7 @@ static void ground_glow_update(Entity_Effect& glow) if (glow.parent->type == ENTITY_PROJECTILE) { float height = static_cast(*glow.parent).height; - alpha = lerp_clamped(height, GLOW_HEIGHT_HIGH, GLOW_HEIGHT_LOW, GLOW_DIMMEST, 1); + alpha = lerp_range(height, {GLOW_HEIGHT_HIGH, GLOW_HEIGHT_LOW, GLOW_DIMMEST, 1}); } return; } @@ -1158,7 +1145,7 @@ static void boomerang_init(Entity_Effect& boomerang) boomerang.entityGridCollisionClass = GRIDCOLL_WALLS; boomerang.sprite.Play("Rotate"); boomerang.posOffset = vector_make(0, BOOMERANG_HEIGHT); - overridden_sound_play(SOUND_BOOMERANG_LOOP, {.loop = SOUND_LOOP}); + effect_sound_play(SOUND_BOOMERANG_LOOP, {.loop = SOUND_LOOP}); } // The first pickup the boomerang touches that can be taken becomes its catch. A sticky nickel only rattles. @@ -1176,7 +1163,7 @@ static void boomerang_grab(Entity_Effect& boomerang) continue; } boomerang.child = pickup; - overridden_sound_play(SOUND_BOOMERANG_HIT); + effect_sound_play(SOUND_BOOMERANG_HIT); } } @@ -1203,13 +1190,13 @@ static void boomerang_update(Entity_Effect& boomerang) entity->AddFreeze(EntityRef(&boomerang), BOOMERANG_FREEZE, false); entity->AddVelocity(boomerang.velocity, false); hit_list_insert(boomerang.hitList, *entity); - overridden_sound_play(SOUND_BOOMERANG_HIT); + effect_sound_play(SOUND_BOOMERANG_HIT); } if (boomerang.isCollidesWithGrid) { boomerang.timeout = 1; - overridden_sound_play(SOUND_BOOMERANG_HIT); + effect_sound_play(SOUND_BOOMERANG_HIT); } if (boomerang.timeout < BOOMERANG_SLOWING_FRAMES) boomerang.friction *= BOOMERANG_FRICTION; if (boomerang.timeout < 2) @@ -1224,7 +1211,7 @@ static void boomerang_update(Entity_Effect& boomerang) if (distance <= thrower->size + boomerang.size) { boomerang.isDead = true; - overridden_sound_play(SOUND_BOOMERANG_CATCH); + effect_sound_play(SOUND_BOOMERANG_CATCH); if (boomerang.child) boomerang.child->entityGridCollisionClass = GRIDCOLL_WALLS; } } @@ -1232,7 +1219,7 @@ static void boomerang_update(Entity_Effect& boomerang) if (boomerang.isDead) boomerang.Remove(); else if (!g_manager->sfxManager.IsPlaying(SOUND_BOOMERANG_LOOP)) - overridden_sound_play(SOUND_BOOMERANG_LOOP, {.loop = SOUND_LOOP}); + effect_sound_play(SOUND_BOOMERANG_LOOP, {.loop = SOUND_LOOP}); } // Part of 005cdb20 (Init's case 185) Redemption's sign hangs behind its player, its glow additive. @@ -1261,7 +1248,7 @@ static void redemption_update(Entity_Effect& sign) { if (!player || player->IsHoldingItem()) return; sign.state = REDEMPTION_FAIL; - overridden_sound_play(SOUND_THUMBS_DOWN); + effect_sound_play(SOUND_THUMBS_DOWN); } else if (sign.state == REDEMPTION_SUCCESS) { @@ -1275,7 +1262,7 @@ static void redemption_update(Entity_Effect& sign) player->AddSoulHearts(REDEMPTION_SOUL_HEARTS, false); player->AnimateHappy(); player->SetColor(REDEMPTION_FLASH, REDEMPTION_FLASH_FRAMES, 1, true, true); - overridden_sound_play(SOUND_POWERUP_SPEWER); + effect_sound_play(SOUND_POWERUP_SPEWER); } sign.Remove(); } @@ -1297,6 +1284,150 @@ static void redemption_update(Entity_Effect& sign) // The variants of this group by their Init, Update and Render. Those that only play their animation share Update's // poof case. The empty ones have no Init or Update case in the original. +// The halos (subtypes: 0 halo, 1 Telekinesis, 2 Monstrance, 3 curse, 4 static, 5 Saturnus, 6 Salvation, 7 static +// prerendered, 8 Dark Arts, 9 Breath of Life) follow what they belong to, under it. The static ones touch what is near +// for nothing every frame, Telekinesis' pushes enemies within 80 away on its Push event, Salvation's grows with its +// scale. +enum HaloSubtype +{ + HALO_CURSE = 3, + HALO_STATIC = 4, + HALO_TELEKINESIS = 1, + HALO_SALVATION = 6, + HALO_STATIC_PRERENDERED = 7, + HALO_DARK_ARTS = 8, + HALO_BREATH_OF_LIFE = 9 +}; +constexpr int HALO_RENDER_Z = -1000; +constexpr unsigned int HALO_PRERENDERED_FLAG = 1u << 8; +constexpr float HALO_PUSH_RANGE = 80; +constexpr float HALO_PUSH_MAX = 7; +constexpr float HALO_PUSH_SCALE = 2; +constexpr float HALO_HEAVY_MASS = 20; +constexpr float HALO_HEAVIER_MASS = 30; +constexpr float HALO_HEAVIEST_MASS = 50; +constexpr float HALO_HEAVY_SHARE = 0.5f; +constexpr float HALO_HEAVIER_SHARE = 0.2f; +constexpr float HALO_HEAVIEST_SHARE = 0.015f; +constexpr float HALO_PUSH_CARRY = 0.5f; +constexpr float HALO_STATIC_REACH = 40; +constexpr uint64_t HALO_STATIC_DAMAGE_FLAGS = DAMAGE_POISON_BURN; +constexpr int HALO_STATIC_COUNTDOWN = 30; +constexpr float HALO_SALVATION_BIG = 1.5f; + +// Part of 005cdb20 (Init's case 123) A halo draws under what it follows: the curse one multiplying the floor, the +// static and Breath of Life ones glowing. +static void halo_init(Entity_Effect& halo) +{ + LayerState& layer = *halo.sprite.GetLayer(halo.subtype == HALO_BREATH_OF_LIFE ? 1 : 0); + if (halo.subtype == HALO_CURSE) + layer.blendMode = {KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ZERO, KAGE::Graphics::FACTOR_SRC_COLOR, + KAGE::Graphics::FACTOR_ZERO, KAGE::Graphics::FACTOR_SRC_COLOR}; + else if (halo.subtype == HALO_STATIC || halo.subtype == HALO_STATIC_PRERENDERED || + halo.subtype == HALO_BREATH_OF_LIFE) + { + if (halo.subtype == HALO_STATIC) halo.sprite.bitflags |= ANIM_RENDER_STATIC; + if (halo.subtype == HALO_STATIC_PRERENDERED) halo.sprite.bitflags |= HALO_PRERENDERED_FLAG; + layer_additive_set(layer); + } + halo.renderZOffset = HALO_RENDER_Z; +} + +// Telekinesis' push on an enemy within reach: up to 7 (twice that) by how close, halved for one heavier than 20. +static void halo_push(Entity_Effect& halo, Entity& enemy) +{ + if (enemy.mass == 0 || enemy.HasEntityFlags(FLAG_NO_KNOCKBACK)) return; + if (halo.spawnerEntity && halo.spawnerEntity->IsDescendantOf(&enemy)) return; + + Vector away = vector_sub(enemy.pos, halo.pos); + float distance = vector_length(away); + if (distance <= 0) return; + float push = std::min(HALO_PUSH_MAX, enemy.size + HALO_PUSH_RANGE - distance) * HALO_PUSH_SCALE; + if (enemy.mass > HALO_HEAVY_MASS) push *= HALO_HEAVY_SHARE; + else if (enemy.mass > HALO_HEAVIER_MASS) push *= HALO_HEAVIER_SHARE; + else if (enemy.mass > HALO_HEAVIEST_MASS) push *= HALO_HEAVIEST_SHARE; + enemy.velocity = vector_add(vector_scale(enemy.velocity, HALO_PUSH_CARRY), vector_scale(away, push / distance)); +} + +// Telekinesis' halo blinks while it holds (its state), and pushes enemies away on its Push event. +static void telekinesis_halo_update(Entity_Effect& halo) +{ + std::string_view animation = halo.sprite.GetAnimation(); + if (halo.state >= 1 && animation != "Blink") halo.sprite.SetAnimation("Blink", SWITCH_KEEP_FRAME); + else if (halo.state == 0 && halo.sprite.IsPlaying("Idle")) halo.sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME); + if (!halo.sprite.IsEventTriggered("Push")) return; + + for (Entity* enemy : entity_query_radius(halo.pos, HALO_PUSH_RANGE, QUERY_ENEMIES)) + if (enemy->IsEnemy()) halo_push(halo, *enemy); +} + +// A static halo touches everything near it for nothing, unless friendly. +static void static_halo_touch(Entity_Effect& halo) +{ + if (halo.HasEntityFlags(FLAG_FRIENDLY)) return; + float reach = halo.sprite.scale.x * HALO_STATIC_REACH; + for (Entity* entity : entity_query_radius(halo.pos, reach, QUERY_FAMILIARS | QUERY_PLAYERS)) + if (entity->entityCollisionClass != ENTCOLL_NONE) + entity->TakeDamage(0, HALO_STATIC_DAMAGE_FLAGS, EntityRef(&halo), HALO_STATIC_COUNTDOWN); +} + +// 006064cc (Update's case 123) A halo without its holder goes (the lasting ones disappear first), and goes (without +// Update's shared end) with a dying enemy. Otherwise it shows while its holder lives, the static ones riding it, and +// Telekinesis', Breath of Life's and Salvation's play their parts. +static EffectUpdateEnd halo_update(Entity_Effect& halo) +{ + bool isLasting = halo.subtype == HALO_STATIC || halo.subtype == HALO_STATIC_PRERENDERED || + halo.subtype == HALO_DARK_ARTS || halo.subtype == HALO_BREATH_OF_LIFE; + Entity* holder = halo.parent; + if (!holder) + { + if (!isLasting) halo.Remove(); + else + { + halo.velocity = {}; + halo.sprite.Play("Disappear"); + if (halo.sprite.IsFinished()) halo.Remove(); + } + return EFFECT_UPDATE_RETURN; + } + + if (halo.subtype == HALO_TELEKINESIS) telekinesis_halo_update(halo); + if (halo.subtype == HALO_BREATH_OF_LIFE && !halo.sprite.animState.IsLoopingAnimation() && halo.sprite.IsFinished()) + halo.sprite.Play("Idle"); + bool isStatic = halo.subtype == HALO_STATIC || halo.subtype == HALO_STATIC_PRERENDERED; + if (!holder->IsEnemy()) + { + if (!isStatic) halo.isVisible = !holder->isDead; + } + else + { + if (static_cast(holder)->state == NPC_STATE_DEATH) + { + if (halo.sprite.GetAnimationData("Disappear")) halo.sprite.Play("Disappear"); + else halo.isVisible = false; + } + if (halo.sprite.IsFinished()) + { + halo.Remove(); + return EFFECT_UPDATE_RETURN; + } + } + + if (isStatic) + { + halo.pos = holder->pos; + halo.velocity = holder->velocity; + halo.posOffset = holder->posOffset; + static_halo_touch(halo); + } + if (halo.subtype != HALO_SALVATION) return EFFECT_UPDATE_FINISH; + bool isBig = halo.scale > HALO_SALVATION_BIG; + halo.sprite.Play(isBig ? "Idle2" : "Idle1"); + float size = isBig ? halo.scale / 2 : halo.scale; + halo.sprite.scale = vector_make(size, size); + return EFFECT_UPDATE_FINISH; +} + constexpr auto ITEM_EFFECT_BEHAVIOURS = std::to_array({ {0, nullptr, nullptr, nullptr}, {EFFECT_LADDER, ladder_init, nullptr, nullptr}, @@ -1345,6 +1476,7 @@ constexpr auto ITEM_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_ULTRA_DEATH_SCYTHE, scythe_init, effect_finishing, nullptr}, {EFFECT_BULLET_POOF_STATIC, static_poof_init, effect_poof_update, nullptr}, {EFFECT_GUN, nullptr, nullptr, nullptr}, + {EFFECT_HALO, halo_init, halo_update, nullptr}, }); std::span item_effect_behaviours() diff --git a/src/entity_effect_mother.cpp b/src/entity_effect_mother.cpp new file mode 100644 index 0000000..54a1a8c --- /dev/null +++ b/src/entity_effect_mother.cpp @@ -0,0 +1,300 @@ +#include "beam_renderer.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "game.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include +#include + +// The final chapters' effects: the tracers that warn of a coming attack (Mother's and the generic one), and the +// Beast's lava. + +// A tracer is a beam of light from its position along its aim, 0.8 of the room's span that way, drawn from its second +// layer. Both its layers blend additively and only the beam shows, 20 up. +constexpr int TRACER_BEAM_LAYER = 1; +constexpr float TRACER_HEIGHT = -20; +constexpr float TRACER_REACH = 0.8f; +constexpr float TRACER_MID_MAX = 60; + +// Mother's tracer fades in over 30 frames, then pulses, then (state 3) rushes along its aim at 60 a frame shedding +// fiery shots up to a tenth as fast, until it leaves the room. +constexpr float MOTHER_TRACER_FADE = 30; +constexpr float MOTHER_TRACER_PULSE_SPEED = 2; +constexpr float MOTHER_TRACER_PULSE_DEPTH = 0.3f; +constexpr float MOTHER_TRACER_PULSE_BASE = 0.5f; +constexpr float MOTHER_TRACER_RUSH = 60; +constexpr float MOTHER_TRACER_SHOT_SPEED = 0.1f; +constexpr float MOTHER_TRACER_SHOT_SCALE_MIN = 0.4f; +constexpr float MOTHER_TRACER_SHOT_SCALE_SPAN = 0.7f; +constexpr float MOTHER_TRACER_SHOT_ACCEL = -0.007f; +constexpr float MOTHER_TRACER_ROOM_MARGIN = -80; +constexpr ColorMod FIERY_SHOT_COLOR = {{1, 1, 1, 1}, {3.5f, 2.5f, 1, 1}, {0, 0, 0}}; +constexpr std::array MOTHER_TRACER_MOVES = {"MoveLeft", "MoveUp", "MoveRight", "MoveDown"}; + +// Mother's tracer's states: just spawned, fading in, pulsing, rushing. +enum MotherTracerState +{ + MOTHER_TRACER_START, + MOTHER_TRACER_FADING, + MOTHER_TRACER_PULSING, + MOTHER_TRACER_RUSHING +}; + +// The generic tracer fades out (a fifth per frame at full time scale) once dead. +constexpr float TRACER_FADE = 0.2f; + +// The room's span along a tracer's aim: its height when the aim is mostly vertical, else its width. +static float tracer_span(Vector aim) +{ + Room& room = *g_game->room; + if (std::fabs(aim.x) <= std::fabs(aim.y)) return room.bottomRightPos.y - room.topLeftPos.y; + return room.bottomRightPos.x - room.topLeftPos.x; +} + +// A point of a tracer's beam on screen, some way along its aim. +static BeamPoint tracer_point(Entity_Effect& tracer, Vector along, const Vector& offset) +{ + Vector world = vector_add(vector_add(tracer.pos, tracer.posOffset), along); + return BeamPoint{.pos = vector_add(render_position_get(world, RENDER_SNAPPED), offset)}; +} + +// Part of 005cdb20 (Init's case 190 and 198) A tracer's layers blend additively, hidden, its beam drawn 20 up and +// smoothly filtered. +static void tracer_init(Entity_Effect& tracer) +{ + for (int layerId : {0, TRACER_BEAM_LAYER}) + { + LayerState& layer = *tracer.sprite.GetLayer(layerId); + layer_additive_set(layer); + layer.isVisible = false; + } + tracer.posOffset = vector_make(0, TRACER_HEIGHT); + LayerState& beam = *tracer.sprite.GetLayer(TRACER_BEAM_LAYER); + beam.minFilterMode = 1; + beam.magFilterMode = 1; +} + +// A fiery shot Mother's rushing tracer sheds behind it. +static void mother_tracer_shot(Entity_Effect& tracer) +{ + uint32_t seed = Random(); + Vector velocity = vector_scale(tracer.velocity, random_unit() * MOTHER_TRACER_SHOT_SPEED); + auto* shot = static_cast(g_game->Spawn({.position = tracer.pos, + .velocity = velocity, + .spawner = tracer.parent, + .type = ENTITY_PROJECTILE, + .seed = seed})); + shot->parent = tracer.parent; + shot->SetColor(FIERY_SHOT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->scale = random_unit() * MOTHER_TRACER_SHOT_SCALE_SPAN + MOTHER_TRACER_SHOT_SCALE_MIN; + shot->fallingAccel = MOTHER_TRACER_SHOT_ACCEL; + shot->fallingSpeed = random_unit() * -1; +} + +// 005e56eb (Update's case 190) Mother's tracer turns to its aim on its first frame (on the floor when aimed up). It +// goes with Mother. Otherwise it fades in, pulses, or rushes along shedding fiery shots until it leaves the room. +static EffectUpdateEnd mother_tracer_update(Entity_Effect& tracer) +{ + if (tracer.state == MOTHER_TRACER_START) + { + tracer.state++; + if (vector_to_direction(tracer.targetPosition) == DIRECTION_UP) tracer.posOffset.y = 0; + tracer.sprite.rotation = vector_angle(tracer.targetPosition); + } + if (!tracer.parent || tracer.parent->isDead) + { + tracer.Remove(); + return EFFECT_UPDATE_RETURN; + } + + float& alpha = tracer.sprite.color._tint[3]; + if (tracer.state == MOTHER_TRACER_FADING) alpha = std::min(tracer.updateTime / MOTHER_TRACER_FADE, 1.0f); + else if (tracer.state == MOTHER_TRACER_PULSING) + alpha = std::sin(tracer.updateTime * MOTHER_TRACER_PULSE_SPEED) * MOTHER_TRACER_PULSE_DEPTH + + MOTHER_TRACER_PULSE_BASE; + else + { + tracer.sprite.Play(MOTHER_TRACER_MOVES[vector_to_direction(tracer.targetPosition)]); + tracer.velocity = vector_scale(tracer.targetPosition, MOTHER_TRACER_RUSH); + mother_tracer_shot(tracer); + if (!g_game->room->IsPositionInRoom(tracer.pos, MOTHER_TRACER_ROOM_MARGIN)) + { + tracer.Remove(); + return EFFECT_UPDATE_RETURN; + } + } + return EFFECT_UPDATE_FINISH; +} + +// Part of 00607620 (Render's case 190) Mother's tracer over its sprite, until it rushes: a beam widening from its aim's +// tip to 0.8 of the room, fading out along it. +static void mother_tracer_render(Entity_Effect& tracer, const Vector& offset) +{ + tracer.sprite.Render(SpriteDraw{tracer.renderPosition, {}, {}}); + if (tracer.state == MOTHER_TRACER_RUSHING) return; + + Vector aim = tracer.targetPosition; + g_beamRenderer.Begin(tracer.sprite, TRACER_BEAM_LAYER, BEAM_FRAME_MAIN, BEAM_COORDINATE_HEIGHTS); + BeamPoint tip = tracer_point(tracer, aim, offset); + tip.color = tint_color_make(1, 1, 1, tracer.sprite.color._tint[3]); + tip.coordinate = 1; + g_beamRenderer.Add(tip); + BeamPoint end = tracer_point(tracer, vector_resized(aim, tracer_span(aim) * TRACER_REACH), offset); + end.color = tint_color_make(1, 1, 1, 0); + end.coordinate = 1; + end.width = 1; + g_beamRenderer.Add(end); + g_beamRenderer.End(); +} + +// 005e5550 (Update's case 198) A generic tracer faces its aim and grows in as its time runs out, then fades away once +// dead. +static void generic_tracer_update(Entity_Effect& tracer) +{ + float& alpha = tracer.sprite.GetLayer(TRACER_BEAM_LAYER)->color._tint[3]; + if (!tracer.isDead) + { + alpha = 1 - (float)tracer.timeout / (float)tracer.lifespan; + tracer.sprite.rotation = vector_angle(tracer.targetPosition); + return; + } + alpha -= tracer.speedMultiplier * TRACER_FADE; + if (alpha <= 0) tracer.Remove(); +} + +// Part of 00607620 (Render's case 198) A generic tracer over its sprite: a beam along its aim to 0.8 of the room, +// strongest at 60 out (or halfway), as wide as its sprite, in its beam layer's colour over the sprite's. +static void generic_tracer_render(Entity_Effect& tracer, const Vector& offset) +{ + tracer.sprite.Render(SpriteDraw{tracer.renderPosition, {}, {}}); + Vector aim = tracer.targetPosition; + float length = tracer_span(aim) * TRACER_REACH; + ColorMod strong = tracer.sprite.color; + color_multiply(strong, tracer.sprite.GetLayer(TRACER_BEAM_LAYER)->color); + ColorMod faint = strong; + faint._tint[3] = 0; + + g_beamRenderer.Begin(tracer.sprite, TRACER_BEAM_LAYER, BEAM_FRAME_MAIN, BEAM_COORDINATE_HEIGHTS); + for (auto [reach, color, width] : + {std::tuple{0.0f, faint, 1.0f}, std::tuple{std::min(length * 0.5f, TRACER_MID_MAX), strong, 0.0f}, + std::tuple{length, faint, 1.0f}}) + { + BeamPoint point = tracer_point(tracer, reach > 0 ? vector_resized(aim, reach) : Vector{}, offset); + point.color = color; + point.coordinate = tracer.sprite.scale.x; + point.width = width; + g_beamRenderer.Add(point); + } + g_beamRenderer.End(); +} + +// The Beast's lava spawner: subtype 2 glows in over its time, keeping walkers off its cell, and erupts once dead; +// subtype 1 glows in as the arena scrolls it to its target and erupts once past; subtype 0 is a glow following its +// spawner's colour at its share, which lingers its state's frames after it. An eruption throws up a lava ball from +// the lava's line at 20 a frame, with a blast and a shake. +constexpr int LAVA_PATH_LEVEL = 900; +constexpr float LAVA_LINE_ABOVE = 30; +constexpr float LAVA_BALL_SPEED = -20; +constexpr float LAVA_BALL_ACCEL = 0.5f; +constexpr int LAVA_SHAKE = 6; +constexpr float LAVA_GLOW_RANGE = 200; +constexpr int LAVA_SORTING_Z = 1000; + +// The lava spawner's states: glowing, and erupted. +enum LavaState +{ + LAVA_GLOWING, + LAVA_ERUPTED +}; + +// Part of 005cdb20 (Init's case 181) The lava glows over everything. +static void lava_spawner_init(Entity_Effect& lava) +{ + lava.renderZOffset = LAVA_SORTING_Z; + layer_additive_set(*lava.sprite.GetLayer(0)); +} + +// An eruption at the spawner's column: a lava ball thrown up from the lava's line, a blast and a shake. +static void lava_erupt(Entity_Effect& lava) +{ + Vector line = vector_make(lava.pos.x, g_game->room->bottomRightPos.y - LAVA_LINE_ABOVE); + effect_sound_play(SOUND_BEAST_LAVABALL_RISE); + uint32_t seed = Random(); + auto* ball = static_cast(g_game->Spawn({.position = line, + .velocity = vector_make(0, LAVA_BALL_SPEED), + .spawner = lava.spawnerEntity.get(), + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_LAVA, + .seed = seed})); + ball->projectileFlags = PROJECTILE_NO_WALL_COLLIDE; + ball->fallingAccel = LAVA_BALL_ACCEL; + ball->Update(); + auto* blast = static_cast( + g_game->Spawn({.position = line, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()})); + blast->state = 1; + blast->Update(); + game_shake_screen(LAVA_SHAKE); + lava.sprite.Play("Disappear"); + lava.state = LAVA_ERUPTED; +} + +// Whether the arena has scrolled a subtype 1 spawner past its target. +static bool is_lava_past_target(Entity_Effect& lava) +{ + float speed = g_game->room->beastArena.scrollSpeed; + float target = lava.targetPosition.x; + return (speed > 0 && lava.pos.x > target) || (speed < 0 && lava.pos.x < target); +} + +// 005e1f3a (Update's case 181) A lava spawner glows toward its eruption and erupts, then goes once its animation ends. +// A glow follows its spawner's colour and goes once dead. +static void lava_spawner_update(Entity_Effect& lava) +{ + if (lava.subtype == 0) + { + Entity* source = lava.parent; + if (!source && !lava.isDead) lava.isDead = true; + if (source && source->IsType(ENTITY_EFFECT, EFFECT_LAVA_SPAWNER, -1)) + { + if (source->isDead && lava.lifespan < 1 && lava.state > 0) lava.SetTimeout(lava.state); + lava.sprite.color = source->sprite.color; + lava.sprite.color._tint[3] *= lava.minRadius; + } + if (!lava.isDead) return; + lava.sprite.Play("Disappear"); + if (lava.sprite.IsFinished()) lava.Remove(); + return; + } + + if (lava.state != LAVA_GLOWING) + { + if (lava.sprite.IsFinished()) lava.Remove(); + return; + } + float& alpha = lava.sprite.color._tint[3]; + if (lava.subtype == 2) + { + alpha = 1 - std::clamp((float)lava.timeout / (float)lava.lifespan, 0.0f, 1.0f); + room_path_raise_at(lava.pos, LAVA_PATH_LEVEL); + if (lava.isDead) lava_erupt(lava); + return; + } + alpha = 1 - std::clamp(std::fabs(lava.pos.x - lava.targetPosition.x) / LAVA_GLOW_RANGE, 0.0f, 1.0f); + if (is_lava_past_target(lava)) lava_erupt(lava); +} + +constexpr auto MOTHER_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_MOTHER_TRACER, tracer_init, mother_tracer_update, mother_tracer_render}, + {EFFECT_GENERIC_TRACER, tracer_init, effect_finishing, generic_tracer_render}, + {EFFECT_LAVA_SPAWNER, lava_spawner_init, effect_finishing, nullptr}, +}); + +std::span mother_effect_behaviours() +{ + return MOTHER_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_effect_portal.cpp b/src/entity_effect_portal.cpp new file mode 100644 index 0000000..7f088f9 --- /dev/null +++ b/src/entity_effect_portal.cpp @@ -0,0 +1,279 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_list.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_trap_door.h" +#include "level.h" +#include "manager.h" +#include "room.h" +#include "sfx_manager.h" +#include + +// The portals: Ventricle Razor's pair of womb holes, each leading to the other, and the portals a room or Card +// Reading opens to a room of a kind (a room index past 1000 for one given room). + +// A portal opens once no player is within 40 (nor the Forgotten's body within 20) and takes a free player within 20 +// after the room's first 10 frames. A player stepping out is hurt by nothing for 35 frames. +constexpr float PORTAL_CLEAR_RANGE_SQUARED = 40 * 40; +constexpr float PORTAL_ENTER_RANGE_SQUARED = 20 * 20; +constexpr int PORTAL_FIRST_FRAMES = 2; +constexpr int PORTAL_READY_FRAMES = 10; +constexpr int PORTAL_LANDING_COOLDOWN = 35; +constexpr int PORTAL_LANDING_FRAME = 2; + +// The portal's swirl layers drift toward the screen's centre, each deeper layer further, by a thirtieth of the way +// up to 1.5. +constexpr int PORTAL_SWIRL_FIRST_LAYER = 2; +constexpr int PORTAL_SWIRL_LAYERS = 3; +constexpr float PORTAL_SWIRL_SPAN = 30; +constexpr float PORTAL_SWIRL_MAX = 1.5f; + +// A portal's room: its kind by subtype (treasure, boss, secret, shop, else a normal room), or one room past 1000. +constexpr std::array PORTAL_ROOM_TYPES = {ROOM_TREASURE, ROOM_BOSS, ROOM_SECRET, ROOM_SHOP}; +constexpr int PORTAL_ROOM_INDEX_BASE = 1000; +constexpr int PORTAL_GIVEN_ROOM = 900; + +// The colours of the portals to a room of a kind, and of the orange womb hole and its wisp. +constexpr std::array PORTAL_COLORS = {{ + {{1, 1, 1, 1}, {2.3f, 1.8f, 0.5f, 1}, {0, 0, 0}}, + {{1, 1, 1, 1}, {2, 0.4f, 0.4f, 1}, {0, 0, 0}}, + {{1, 1, 1, 1}, {1, 1.2f, 2, 1}, {0, 0, 0}}, + {{0.6f, 1, 0.6f, 1}, {0, 1.8f, 0, 1}, {0, 0, 0}}, +}}; +constexpr std::string_view WOMB_HOLE_ORANGE_SHEET = "gfx/Effects/wombhole_orange.png"; +constexpr float BYTE_SCALE = 1.0f / 255; +constexpr ColorMod ORANGE_WISP_BODY = { + {400 * BYTE_SCALE, 250 * BYTE_SCALE, 60 * BYTE_SCALE, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod ORANGE_WISP_FLAME = { + {300 * BYTE_SCALE, 200 * BYTE_SCALE, 10 * BYTE_SCALE, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int WISP_ORBIT_LAYER = 9; + +// The portal states: closed, opening, open, taking a player in, and letting one out. +enum PortalState +{ + PORTAL_CLOSED, + PORTAL_OPENING, + PORTAL_OPEN, + PORTAL_TAKING, + PORTAL_LANDING +}; + +// The other womb hole of a Ventricle Razor pair, and whether it stands in this room. +static VentricleRazorPortal& womb_hole_link(Entity_Effect& hole) +{ + return g_game->ventricleRazorPortals[(hole.subtype + 1) % VENTRICLE_RAZOR_PORTAL_COUNT]; +} + +// Whether a womb hole's other end is placed: on a floor room, or here. +static bool is_womb_hole_linked(Entity_Effect& hole, bool& isHere) +{ + VentricleRazorPortal& link = womb_hole_link(hole); + isHere = g_game->GetRoomByIdx(link.roomIndex) == g_game->GetCurrentRoomDesc(); + return link.roomIndex >= 0 || isHere; +} + +// Whether a player (within 40) or the Forgotten's body (within 20) stands by the portal. +static bool is_portal_occupied(Entity_Effect& portal) +{ + Entity_Player* player = main_player_nearest(portal.pos); + if (player && vector_length_squared(vector_sub(player->pos, portal.pos)) <= PORTAL_CLEAR_RANGE_SQUARED) return true; + return is_forgotten_body_on(portal.pos); +} + +// Part of 005cdb20 (Init's case 82) A womb hole lies on the floor, orange for the second of the pair, open once its +// other end is placed. One placed by a wisp's use brings Ventricle Razor's wisp along, orange for the second. +static void womb_hole_init(Entity_Effect& hole) +{ + if (hole.subtype == 1) hole.sprite.ReplaceSpritesheet(0, WOMB_HOLE_ORANGE_SHEET); + hole.sortingLayer = SORTING_BACKGROUND; + hole.state = PORTAL_CLOSED; + hole.sprite.Play("Closed"); + bool isHere = false; + hole.sprite.Play(is_womb_hole_linked(hole, isHere) ? "Opened" : "Closed"); + if (!g_game->ventricleRazorPortals[hole.subtype].isMarked) return; + + Entity_Familiar* wisp = g_game->GetPlayer(0)->AddWisp(COLLECTIBLE_VENTRICLE_RAZOR, hole.pos, false, true); + if (!wisp) return; + wisp->parent = &hole; + if (hole.subtype != 0) + { + wisp->sprite.GetLayer(0)->color = ORANGE_WISP_BODY; + wisp->sprite.GetLayer(1)->color = ORANGE_WISP_FLAME; + } + wisp->AddToOrbit(WISP_ORBIT_LAYER); + if (g_game->room->GetFrameCount() < PORTAL_FIRST_FRAMES) wisp->ClearEntityFlags(FLAG_APPEAR); + wisp->Update(); +} + +// Part of 005cdb20 (Init's case 161) A portal takes its room kind's colour and lies open on the floor, its swirl on +// a random frame. +static void portal_init(Entity_Effect& portal) +{ + if ((uint32_t)portal.subtype < PORTAL_COLORS.size()) portal.sprite.color = PORTAL_COLORS[portal.subtype]; + portal.sortingLayer = SORTING_BACKGROUND; + portal.state = PORTAL_CLOSED; + portal.sprite.Play("Opened"); + int length = portal.sprite.animState.GetAnimationLength(); + portal.sprite.SetFrame((float)portal.dropRNG.RandomInt((uint32_t)length)); +} + +// The portal's swirl layers lean toward the screen's centre, and its hum plays. +static void portal_swirl_update(Entity_Effect& portal) +{ + Room& room = *g_game->room; + Vector screen = render_position_get(portal.pos, RENDER_SNAPPED); + screen = vector_add(screen, vector_add(room.renderScrollOffset, g_game->screenShakeOffset)); + Vector centre = vector_make(g_screenWidth * 0.5f, g_screenHeight * 0.5f); + Vector lean = vector_scale(vector_sub(centre, screen), 1 / (g_screenPointScale * PORTAL_SWIRL_SPAN)); + if (vector_length(lean) > PORTAL_SWIRL_MAX) lean = vector_resized(lean, PORTAL_SWIRL_MAX); + for (int i = 0; i < PORTAL_SWIRL_LAYERS; i++) + portal.sprite.GetLayer(PORTAL_SWIRL_FIRST_LAYER + i)->pos = vector_scale(lean, (float)(i + 1)); + if (!g_manager->sfxManager.IsPlaying(SOUND_PORTAL_ENTITY_LOOP)) + effect_sound_play(SOUND_PORTAL_ENTITY_LOOP, {.loop = SOUND_LOOP}); +} + +// A closed portal waits out the room's first frames, then opens once nobody stands by it (a womb hole only once +// linked). Otherwise it stays shut. +static void portal_closed_update(Entity_Effect& portal, bool isLinked) +{ + if (g_game->room->GetFrameCount() < PORTAL_FIRST_FRAMES) return; + bool isOccupied = isLinked && is_portal_occupied(portal); + if (!isLinked || isOccupied) + { + if (portal.spawnerType != 0 || isLinked) + portal.sprite.Play(portal.spawnerType == 0 ? "Close Animation" : "Appear"); + return; + } + + portal.state = PORTAL_OPENING; + if (portal.spawnerType == 0 && portal.sprite.IsPlaying("Opened")) + { + portal.state = PORTAL_OPEN; + return; + } + portal.sprite.Play("Open Animation"); +} + +// The room a portal to a room of a kind leads to, drawn from the floor's rooms, or its given room. +static int portal_room_find(Entity_Effect& portal) +{ + if ((uint32_t)portal.subtype >= PORTAL_GIVEN_ROOM) return portal.subtype - PORTAL_ROOM_INDEX_BASE; + int type = (uint32_t)portal.subtype < PORTAL_ROOM_TYPES.size() ? PORTAL_ROOM_TYPES[portal.subtype] : ROOM_DEFAULT; + return g_game->QueryRoomTypeIndex(type, false, portal.dropRNG, false); +} + +// An open portal takes in a free player standing in it: to its room (a womb hole to its other end's room), or, with +// nowhere to go or its other end here, down out of the way to come up again. +static void portal_enter(Entity_Effect& portal, Entity_Player& player, bool isLinkedHere) +{ + Game& game = *g_game; + game.leaveDoor = -1; + if (portal.variant == EFFECT_PORTAL_TELEPORT) + { + int roomIndex = portal_room_find(portal); + if (roomIndex < 0 && roomIndex != ROOM_LIL_PORTAL_IDX) player.entityCollisionClass = ENTCOLL_NONE; + else + { + game.StartRoomTransition( + {.player = &player, .animation = TRANSITION_PORTAL_TELEPORT, .roomIndex = roomIndex}); + effect_sound_play(SOUND_PORTAL_ENTITY_ENTER); + } + } + else if (!isLinkedHere) + game.StartRoomTransition( + {.player = &player, .animation = TRANSITION_WOMB_TELEPORT, .roomIndex = womb_hole_link(portal).roomIndex}); + else player.entityCollisionClass = ENTCOLL_NONE; + + player.AnimateTrapdoor(); + player.moveToTarget = portal.pos; + player.isControlsEnabled = false; + portal.target = &player; + portal.state = PORTAL_TAKING; +} + +// A player taken in comes out once free again, at the womb hole's other end in this room if there is one, jumping +// up with a moment of safety. The portal that let them out stays shut while they stand by it. +static void portal_exit(Entity_Effect& portal) +{ + Entity_Player* player = portal.target ? portal.target->ToPlayer() : nullptr; + if (!player) + { + if (portal.state == PORTAL_TAKING) portal.state = PORTAL_OPEN; + portal.target = nullptr; + return; + } + if (!is_player_free(*player)) return; + + int otherHole = (portal.subtype + 1) % VENTRICLE_RAZOR_PORTAL_COUNT; + for (Entity* other : entity_query(ENTITY_EFFECT, EFFECT_WOMB_TELEPORT)) + { + if (other->subtype != otherHole) continue; + player->pos = other->pos; + static_cast(other)->state = PORTAL_LANDING; + other->sprite.Play("Close Animation"); + break; + } + if (portal.state == PORTAL_TAKING) portal.state = PORTAL_OPEN; + player->isVisible = true; + player->entityCollisionClass = ENTCOLL_ALL; + player->isControlsEnabled = true; + player->PlayExtraAnimation("Jump"); + player->sprite.SetFrame((float)PORTAL_LANDING_FRAME); + player->SetMinDamageCooldown(PORTAL_LANDING_COOLDOWN); + player->moveToTarget = {}; + portal.target = nullptr; +} + +// 005fdcb2 (Update's case 82 and 161) A portal shuts and goes once dead. Otherwise it opens once its way is clear, +// takes in a player stepping into it once open and lets them out again, staying shut while someone stands by the end +// they came out of. +static void portal_update(Entity_Effect& portal) +{ + if (portal.isDead) + { + portal.sprite.Play("Disappear"); + if (portal.sprite.IsFinished()) portal.Remove(); + return; + } + + bool isLinked = true; + bool isLinkedHere = false; + if (portal.variant == EFFECT_WOMB_TELEPORT) isLinked = is_womb_hole_linked(portal, isLinkedHere); + else portal_swirl_update(portal); + if (portal.state == PORTAL_CLOSED) return portal_closed_update(portal, isLinked); + + if (portal.sprite.IsFinished("Open Animation")) + { + portal.sprite.Play("Opened"); + portal.state = PORTAL_OPEN; + } + if (portal.state == PORTAL_OPEN) + { + if (g_game->room->GetFrameCount() <= PORTAL_READY_FRAMES || !isLinked) return; + Entity_Player* player = main_player_nearest(portal.pos); + if (player && vector_length_squared(vector_sub(player->pos, portal.pos)) < PORTAL_ENTER_RANGE_SQUARED && + is_player_free(*player)) + portal_enter(portal, *player, isLinkedHere); + return; + } + if (portal.state != PORTAL_TAKING && portal.state != PORTAL_LANDING) return; + + portal_exit(portal); + if (portal.state != PORTAL_LANDING || is_portal_occupied(portal)) return; + portal.state = PORTAL_OPEN; + if (portal.sprite.IsPlaying("Opened")) return; + portal.sprite.Play("Open Animation"); + portal.state = PORTAL_OPENING; +} + +constexpr auto PORTAL_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_WOMB_TELEPORT, womb_hole_init, effect_finishing, nullptr}, + {EFFECT_PORTAL_TELEPORT, portal_init, effect_finishing, nullptr}, +}); + +std::span portal_effect_behaviours() +{ + return PORTAL_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_effect_shots.cpp b/src/entity_effect_shots.cpp new file mode 100644 index 0000000..a72e2f2 --- /dev/null +++ b/src/entity_effect_shots.cpp @@ -0,0 +1,535 @@ +#include "capsule.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "beam_renderer.h" +#include "entity_combat.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_list.h" +#include "entity_tear.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "deathmatch_manager.h" +#include "game.h" +#include "item_config.h" +#include "manager.h" +#include "temporary_effects.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_grid.h" +#include "weapon.h" +#include +#include +#include + +// The effects that shoot or strike for their player: Evil Eye's floating eye, the brimstone swirls and Technology +// dots charged shots leave, Dark Arts' snares and Divine Intervention's shield. + +// The Evil Eye fires its player's tears (or, subtype 10, bone clubs reaching with their tear height) the way its +// player fires, at most four a frame, on its player's fire delay counted in 256ths. It bursts on a wall or a pit, off +// the room, or (after its first 10 frames) on an enemy. +constexpr int EVIL_EYE_KNIFE = 10; +constexpr int EVIL_EYE_SHOTS = 4; +constexpr int EVIL_EYE_DELAY_UNITS = 256; +constexpr int EVIL_EYE_SAFE_FRAMES = 10; +constexpr float EVIL_EYE_SHOT_SPEED = 10; +constexpr uint32_t EVIL_EYE_FIRE_FLAGS = 7; +constexpr float EVIL_EYE_KNIFE_HEIGHT = -23.75f; +constexpr float EVIL_EYE_KNIFE_REACH = 4; +constexpr int EVIL_EYE_KNIFE_VARIANT = 1; +constexpr int EVIL_EYE_KNIFE_SUBTYPE = 4; +constexpr float EVIL_EYE_KNIFE_HEIGHT_OFFSET = -14; +constexpr float SHOT_POOF_TURN = 90; +constexpr int SHOT_POOF_TURNS = 4; + +// The eye's animations by the side it looks to (left, up, right, down). +constexpr std::array EVIL_EYE_SHOOTS = {"ShootSide", "ShootUp", "ShootSide", "ShootDown"}; +constexpr std::array EVIL_EYE_IDLES = {"IdleSide", "IdleUp", "IdleSide", "IdleDown"}; + +// Whether the eye bursts: off the room, over a wall or pit, or (after its first frames) on an enemy. +static bool is_evil_eye_bursting(Entity_Effect& eye) +{ + uint32_t collision = room_grid_collision_at(eye.pos); + Vector clamped = g_game->room->GetClampedPosition(eye.pos, eye.size); + if (clamped.x != eye.pos.x || clamped.y != eye.pos.y || collision > GRIDCOLL_WALLS_X) return true; + return eye.FrameCount() > EVIL_EYE_SAFE_FRAMES && !entity_query_radius(eye.pos, eye.size, QUERY_ENEMIES).empty(); +} + +// A bone club the knife eye swings toward where its player fires, reaching with the player's tear height. +static void evil_eye_club(Entity_Effect& eye, Entity_Player& player, int direction) +{ + float reach = std::max((EVIL_EYE_KNIFE_HEIGHT - player.tearHeight) * 0.5f, 0.0f) + EVIL_EYE_KNIFE_REACH; + TearParams params = player.GetTearHitParams(WEAPON_BONE, 1, 1, nullptr); + uint32_t seed = Random(); + auto* club = static_cast(g_game->Spawn({.position = eye.pos, + .spawner = &eye, + .subType = EVIL_EYE_KNIFE_SUBTYPE, + .type = ENTITY_KNIFE, + .variant = EVIL_EYE_KNIFE_VARIANT, + .seed = seed})); + club->parent = &eye; + club->targetPosition = vector_make(reach, 0); + club->rotation = vector_angle(vector_from_direction(direction)); + club->posOffset = vector_make(0, EVIL_EYE_KNIFE_HEIGHT_OFFSET); + club->SetColor(params.tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + club->sprite.scale = eye.sprite.scale; + club->tearFlags = params.tearFlags; + club->SetCollisionDamage(params.tearDamage); + club->SetAttackAnimation(); + club->Update(); +} + +// 005fee6f (Update's case 84) The Evil Eye bursts into a poof where it may not float. It looks and fires where its +// player fires, as fast as they do, and idles toward where they last moved once its shot ends. +static void evil_eye_update(Entity_Effect& eye) +{ + if (is_evil_eye_bursting(eye)) + { + eye.Remove(); + Entity* poof = g_game->Spawn( + {.position = eye.pos, .type = ENTITY_EFFECT, .variant = EFFECT_TEAR_POOF_A, .seed = Random()}); + poof->sprite.rotation = (float)random_below(SHOT_POOF_TURNS) * SHOT_POOF_TURN; + } + if (!eye.parent || eye.parent->type != ENTITY_PLAYER) return; + + auto& player = static_cast(*eye.parent); + int direction = player.fireDirection; + if (eye.state > 0) eye.state -= EVIL_EYE_DELAY_UNITS; + if (direction != DIRECTION_NONE) + { + eye.sprite.isFlipX = direction == DIRECTION_LEFT; + for (int i = 0; i < EVIL_EYE_SHOTS && eye.state < 1; i++) + { + if (eye.subtype == EVIL_EYE_KNIFE) evil_eye_club(eye, player, direction); + else + { + Vector velocity = + vector_scale(vector_from_direction(direction), player.shotSpeed * EVIL_EYE_SHOT_SPEED); + player.FireTear({eye.pos, velocity}, EVIL_EYE_FIRE_FLAGS, nullptr, 1); + } + eye.state += (int)((player.maxFireDelay + 1) * EVIL_EYE_DELAY_UNITS); + eye.sprite.Play(EVIL_EYE_SHOOTS[direction], PLAY_FORCED); + } + } + if (!eye.sprite.IsFinished()) return; + if (direction == DIRECTION_NONE) direction = vector_to_direction(player.lastDirection); + eye.sprite.Play(EVIL_EYE_IDLES[direction], PLAY_FORCED); +} + +// A brimstone swirl (or a tech dot, smaller) hurts the vulnerable enemies within 30 (10) of its size every third +// frame with its player's laser effects, a tech dot each enemy once. With Strange Attractor's flag it pulls within +// 250. A tech dot fades in 90 frames (60 for Dogma's Jacob's ladder dot, subtype 1, which fires a thin laser along +// its aim when it pops). Both go once their animation ends, unless they hold a child. +constexpr float SWIRL_REACH = 30; +constexpr float TECH_DOT_REACH = 10; +constexpr float SWIRL_PULL = 14; +constexpr float TECH_DOT_PULL = 8; +constexpr float SWIRL_PULL_RANGE = 250; +constexpr int SWIRL_HIT_FRAMES = 3; +constexpr int SWIRL_HIT_COUNTDOWN = 30; +constexpr int TECH_DOT_LASER_TIMEOUT = 10; +constexpr int TECH_DOT_LIFE = 90; +constexpr int DOGMA_DOT_LIFE = 60; +constexpr float DOGMA_DOT_PITCH_MIN = 0.9f; +constexpr float DOGMA_DOT_PITCH_SPAN = 0.2f; +constexpr float TECH_DOT_PITCH_MIN = 2.7f; +constexpr float TECH_DOT_PITCH_SPAN = 0.3f; +constexpr float TECH_DOT_VOLUME = 0.6f; +constexpr int DOGMA_DOT = 1; + +// Part of 005cdb20 (Init's case 71) A brimstone swirl's second layer is smoothly filtered. +static void swirl_init(Entity_Effect& swirl) +{ + LayerState& layer = *swirl.sprite.GetLayer(1); + layer.minFilterMode = 1; + layer.magFilterMode = 1; +} + +// Part of 005cdb20 (Init's case 126) A tech dot lies at a random quarter turn, maybe flipped, its second layer hidden, +// and buzzes for its life (Dogma's dot a zap). +static void tech_dot_init(Entity_Effect& dot) +{ + dot.sprite.rotation = (float)random_below(SHOT_POOF_TURNS) * SHOT_POOF_TURN; + dot.sprite.isFlipX = random_below(2) == 0; + dot.sprite.GetLayer(1)->isVisible = false; + if (dot.subtype == DOGMA_DOT) + { + dot.SetTimeout(DOGMA_DOT_LIFE); + effect_sound_play(SOUND_DOGMA_JACOBS_DOT, + {.pitch = random_unit() * DOGMA_DOT_PITCH_SPAN + DOGMA_DOT_PITCH_MIN}); + return; + } + dot.SetTimeout(TECH_DOT_LIFE); + effect_sound_play(SOUND_LASERRING_WEAK, + {.volume = TECH_DOT_VOLUME, .pitch = random_unit() * TECH_DOT_PITCH_SPAN + TECH_DOT_PITCH_MIN}); +} + +// Dogma's dot's laser along its aim as it pops, owned like the dot, in its colour (zapping for Dogma's own). +static void dogma_dot_fire(Entity_Effect& dot) +{ + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = dot.pos, + .posOffset = dot.posOffset, + .source = dot.spawnerEntity.get(), + .angleDegrees = vector_angle(dot.targetPosition), + .timeout = TECH_DOT_LASER_TIMEOUT, + .variant = LASER_THIN_RED}); + laser->spawnerType = dot.spawnerType; + laser->spawnerVariant = dot.spawnerVariant; + laser->isDisableFollowParent = true; + laser->sprite.color = dot.sprite.color; + if (dot.spawnerType == ENTITY_DOGMA) + { + laser->isDisableInitSound = true; + effect_sound_play(SOUND_DOGMA_JACOBS_ZAP, + {.pitch = random_unit() * DOGMA_DOT_PITCH_SPAN + DOGMA_DOT_PITCH_MIN}); + } + laser->Update(); +} + +// Hurts a vulnerable enemy the swirl touches with its player's laser effects (a tech dot once per enemy). +static void swirl_enemy_hurt(Entity_Effect& swirl, Entity& enemy, Entity_Player* player) +{ + bool isDot = swirl.variant == EFFECT_TECH_DOT; + if (isDot && EntityList::HitListContains(swirl.hitList, enemy)) return; + + TearParams params{}; + uint64_t damageFlags = 0; + if (player) + { + params = player->GetTearHitParams(WEAPON_LASER, 1, 0, swirl.spawnerEntity.get()); + damageFlags = tear_damage_flags_get(params.tearFlags, &swirl); + } + enemy.TakeDamage(swirl.collisionDamage, damageFlags, EntityRef(&swirl), SWIRL_HIT_COUNTDOWN); + if (isDot) hit_list_insert(swirl.hitList, enemy); + if (player) Entity_Tear::ApplyTearFlagEffects(&enemy, swirl.pos, params.tearFlags, &swirl, swirl.collisionDamage); +} + +// Every third frame the swirl hurts the vulnerable enemies within its reach, scaled by its sprite and frame. +static void swirl_hurt(Entity_Effect& swirl, Entity_Player* player) +{ + float reach = (swirl.variant == EFFECT_BRIMSTONE_SWIRL ? SWIRL_REACH : TECH_DOT_REACH) * swirl.sprite.scale.x; + if (const AnimationFrame* frame = swirl.sprite.animState.GetLayerFrame(0)) reach *= frame->scale.x; + for (Entity* enemy : entity_query_radius(swirl.pos, reach, QUERY_ENEMIES)) + if (enemy->IsVulnerableEnemy(nullptr)) swirl_enemy_hurt(swirl, *enemy, player); +} + +// Part of 00607620 (Render's case 126) A Dogma dot aiming draws, over its sprite, a fading guide 700 along its aim: +// shrinking in over its last 5 frames, fading as its time runs out before. +static void tech_dot_render(Entity_Effect& dot, const Vector& offset) +{ + constexpr int DOT_GUIDE_FRAMES = 5; + constexpr float DOT_GUIDE_REACH = 700; + constexpr float DOT_GUIDE_ALPHA = 0.5f; + + dot.sprite.Render(SpriteDraw{dot.renderPosition, {}, {}}); + if (dot.subtype != DOGMA_DOT || vector_is_zero(dot.targetPosition)) return; + + float fade = 0; + float coordinate = 1; + if (dot.timeout <= DOT_GUIDE_FRAMES) + { + fade = std::clamp((float)dot.timeout / DOT_GUIDE_FRAMES, 0.0f, 1.0f) * 0.8f + 0.2f; + coordinate = 2 - fade; + } + else + { + float spent = ((float)dot.timeout - DOT_GUIDE_FRAMES) / ((float)dot.lifespan - DOT_GUIDE_FRAMES); + fade = std::sqrt(1 - std::clamp(spent, 0.0f, 1.0f)); + } + + Vector start = vector_add(dot.pos, dot.posOffset); + g_beamRenderer.Begin(dot.sprite, 1, BEAM_FRAME_MAIN, BEAM_COORDINATE_HEIGHTS); + g_beamRenderer.Add({.color = tint_color_make(1, 1, 1, fade * DOT_GUIDE_ALPHA), + .pos = vector_add(render_position_get(start, RENDER_SNAPPED), offset), + .coordinate = coordinate}); + Vector end = vector_add(start, vector_scale(dot.targetPosition, DOT_GUIDE_REACH)); + g_beamRenderer.Add({.color = tint_color_make(1, 1, 1, 0), + .pos = vector_add(render_position_get(end, RENDER_SNAPPED), offset), + .coordinate = coordinate}); + g_beamRenderer.End(); +} + +// 005f9b88 (Update's case 71 and 126) The swirl keeps its shadow under it. A tech dot pops when it shoots or dies (a +// Dogma dot firing its laser once). Live, it pulls with Strange Attractor and hurts what it touches every third +// frame, then goes once its animation ends with no child. +static void swirl_update(Entity_Effect& swirl) +{ + Entity* spawner = swirl.spawnerEntity; + Entity_Player* player = spawner ? spawner->ToPlayer() : nullptr; + if (!player && spawner) player = spawner->GetLastSpawner()->ToPlayer(); + swirl.shadowOffset.x = swirl.posOffset.x; + + if (swirl.sprite.IsEventTriggered("Shoot") || swirl.isDead) + { + if (swirl.variant == EFFECT_TECH_DOT) + { + swirl.sprite.Play("Disappear"); + if (swirl.state == 0 && swirl.subtype == DOGMA_DOT && !vector_is_zero(swirl.targetPosition)) + dogma_dot_fire(swirl); + } + swirl.state = 1; + } + if (!swirl.isDead && swirl.subtype != DOGMA_DOT) + { + if (effect_tear_flags(swirl)[TEAR_ATTRACTOR]) + { + float pull = (swirl.variant == EFFECT_BRIMSTONE_SWIRL ? SWIRL_PULL : TECH_DOT_PULL) * swirl.sprite.scale.x; + entities_attract({.position = swirl.pos, .radius = SWIRL_PULL_RANGE, .strength = pull}); + } + if (swirl.IsFrame(SWIRL_HIT_FRAMES, 0)) swirl_hurt(swirl, player); + } + if (swirl.sprite.IsFinished() && !swirl.child) swirl.Remove(); +} + +// Dark Arts' snare holds and darkens its target while it lasts. Once dead it strikes: an enemy shot vanishes, an +// enemy takes its damage and its tear effects (a killed one gives Book of Virtues a Dark Arts wisp). A black trail +// then runs from it to its child (or its player), and a strike lengthens Judas' Dark Arts effect. +constexpr int SNARE_HOLD_FRAMES = 4; +constexpr int SNARE_TINT_PRIORITY = 1; +constexpr int SNARE_HIT_COUNTDOWN = 30; +constexpr int SNARE_SOUND_DELAY = 1; +constexpr float SNARE_PITCH_MIN = 1.5f; +constexpr float SNARE_PITCH_SPAN = 0.2f; +constexpr float SNARE_LINK_VOLUME = 1.2f; +constexpr float SNARE_LINK_PITCH = 2; +constexpr int SNARE_CHILD_TIMEOUT = 3; +constexpr float SNARE_TRAIL_RADIUS = 0.08f; +constexpr float SNARE_TRAIL_END_RADIUS = 0.04f; +constexpr float SNARE_TRAIL_END_SCALE = 2; +constexpr int SNARE_JUDAS_FRAMES = 4; +constexpr int SNARE_FRAMES_PER_COUNT = 30; +constexpr ColorMod SNARE_HOLD_TINT = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SNARE_POOF_TINT = {{0.2f, 0.2f, 0.2f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SNARE_TRAIL_TINT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Part of 005cdb20 (Init's case 194) The snare lies on the floor, its shadow showing. +static void dark_snare_init(Entity_Effect& snare) +{ + snare.state = 0; + snare.sprite.Play("Shadow"); + snare.sortingLayer = SORTING_BACKGROUND; +} + +// The snare's strike on its target, true when it struck. +static bool dark_snare_strike(Entity_Effect& snare) +{ + Entity* target = snare.target; + if (target->IsProjectile() && !target->isDead) + { + target->isDead = true; + return true; + } + if (!target->IsEnemy() || target->isDead) return false; + + target->TakeDamage(snare.collisionDamage, 0, EntityRef(&snare), SNARE_HIT_COUNTDOWN); + Entity_Tear::ApplyTearFlagEffects(target, snare.pos, effect_tear_flags(snare), &snare, snare.collisionDamage); + Entity* spawner = snare.spawnerEntity; + if (!target->HasMortalDamage() || !spawner || !spawner->is_player()) return true; + Entity_Player& player = *spawner->ToPlayer(); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) + player.AddWisp(COLLECTIBLE_DARK_ARTS, player.pos, false, false); + return true; +} + +// A black trail from the snare drawn to where its end stands. +static void dark_snare_trail(Entity_Effect& snare, Vector end) +{ + auto* trail = static_cast(g_game->Spawn({.position = snare.pos, + .spawner = &snare, + .type = ENTITY_EFFECT, + .variant = EFFECT_SPRITE_TRAIL, + .seed = Random()})); + trail->parent = &snare; + trail->sprite.color = SNARE_TRAIL_TINT; + layer_normal_set(*trail->sprite.GetLayer(0)); + trail->sprite.scale = vector_make(1, 1); + trail->SetRadii(SNARE_TRAIL_RADIUS, SNARE_TRAIL_RADIUS); + trail->Update(); + trail->pos = end; + trail->sprite.scale = vector_make(SNARE_TRAIL_END_SCALE, SNARE_TRAIL_END_SCALE); + trail->SetRadii(SNARE_TRAIL_END_RADIUS, SNARE_TRAIL_END_RADIUS); + trail->Update(); +} + +// A strike lengthens Dark Arts for Judas' dark and tainted forms (and Judas' soul), and with Belial's book and Dark +// Arts (or the Void holding it) at hand. +static void dark_snare_judas_bonus(Entity_Player& player) +{ + int active = player.GetActiveItem(0); + bool isBelial = player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && + (active == COLLECTIBLE_DARK_ARTS || + (player.VoidHasCollectible(COLLECTIBLE_DARK_ARTS) && active == COLLECTIBLE_VOID)); + int count = 0; + if (player.playerType == PLAYER_BLACKJUDAS || player.playerType == PLAYER_JUDAS_B || + player.temporaryEffects.HasNullEffect(NULLITEM_SOUL_JUDAS)) + count += SNARE_JUDAS_FRAMES; + if (isBelial) count += SNARE_JUDAS_FRAMES; + if (count <= 0) return; + + TemporaryEffect effect(g_manager->itemConfig.GetNullItem(NULLITEM_DARK_ARTS)); + effect.cooldown = count * SNARE_FRAMES_PER_COUNT; + player.temporaryEffects.AddEffect(effect, true, count); +} + +// 005e6831 (Update's case 194) The snare holds and darkens its target. Dead, it strikes, leaves a dark poof and a +// trail to its child (or its player) and goes. +static void dark_snare_update(Entity_Effect& snare) +{ + Entity* target = snare.target; + if (target && !target->isDead) + { + static_cast(target)->hold_set(SNARE_HOLD_FRAMES, {}); + target->SetColor(SNARE_HOLD_TINT, SNARE_HOLD_FRAMES, SNARE_TINT_PRIORITY, true, true); + } + if (!snare.isDead) return; + + bool isHit = target && dark_snare_strike(snare); + if (isHit) + effect_sound_play(SOUND_TOOTH_AND_NAIL, {.frameDelay = SNARE_SOUND_DELAY, + .pitch = random_unit() * SNARE_PITCH_SPAN + SNARE_PITCH_MIN}); + Entity* poof = + g_game->Spawn({.position = snare.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->SetColor(SNARE_POOF_TINT, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + + Entity* child = snare.child; + if (child && child->type == ENTITY_EFFECT) + { + static_cast(child)->SetTimeout(SNARE_CHILD_TIMEOUT); + dark_snare_trail(snare, child->pos); + effect_sound_play(SOUND_PORTAL_SPAWN, + {.volume = SNARE_LINK_VOLUME, .frameDelay = SNARE_SOUND_DELAY, .pitch = SNARE_LINK_PITCH}); + } + else if (snare.spawnerEntity) + { + dark_snare_trail(snare, snare.spawnerEntity->pos); + effect_sound_play(SOUND_TOOTH_AND_NAIL, {.frameDelay = SNARE_SOUND_DELAY, + .pitch = random_unit() * SNARE_PITCH_SPAN + SNARE_PITCH_MIN}); + } + Entity* spawner = snare.spawnerEntity; + Entity_Player* player = spawner ? spawner->ToPlayer() : nullptr; + if (isHit && player) dark_snare_judas_bonus(*player); + snare.Remove(); +} + +// Divine Intervention's shield appears facing its angle, idles, and goes once it has disappeared. Up, it drifts at +// least 1 a frame (friction 0.86) and turns back the enemy shots (and tears in versus mode) that come at its face +// within its 0.4 by 1 capsule, knocking enemies back at 16 for 18 frames. Dead, it flies off at up to 10. +constexpr float SHIELD_DEPTH = 5; +constexpr float SHIELD_FRICTION = 0.86f; +constexpr float SHIELD_DRIFT_MIN = 1; +constexpr float SHIELD_WIDTH = 0.4f; +constexpr float SHIELD_PUSH = 16; +constexpr int SHIELD_PUSH_FRAMES = 18; +constexpr float SHIELD_LEAVE_PULL = 0.1f; +constexpr float SHIELD_LEAVE_SPEED = 10; + +// The shield's states: about to appear, appearing, up. +enum ShieldState +{ + SHIELD_START, + SHIELD_APPEARING, + SHIELD_UP +}; + +// Part of 005cdb20 (Init's case 188) The shield waits unseen. +static void shield_init(Entity_Effect& shield) +{ + shield.isVisible = false; + shield.state = SHIELD_START; +} + +// Plays one of the shield's animations for the side it faces (the left one mirrored for the right). +static void shield_animate(Entity_Effect& shield, std::string_view name, int direction) +{ + if (direction == DIRECTION_UP) return shield.sprite.Play(std::string(name) + "Up"); + if (direction == DIRECTION_DOWN) return shield.sprite.Play(std::string(name) + "Down"); + shield.sprite.Play(std::string(name) + "Left"); + shield.sprite.isFlipX = direction == DIRECTION_RIGHT; +} + +// A shot the shield turns back: mirrored off its face if it comes at it. +static Vector shield_mirror(Vector velocity, Vector face) +{ + return vector_sub(velocity, vector_scale(face, 2 * vector_dot(face, velocity))); +} + +// The shots and enemies the shield's capsule touches: enemy shots and tears coming at its face turn back, enemies are +// knocked back unless already. +static void shield_block(Entity_Effect& shield) +{ + uint32_t partitions = QUERY_PROJECTILES | QUERY_ENEMIES; + if (g_game->deathmatchManager.is_active()) partitions |= QUERY_TEARS; + Capsule capsule(shield.pos, vector_make(SHIELD_WIDTH, 1), shield.rotation, shield.size); + Vector face = vector_from_angle(shield.rotation); + + for (Entity* entity : entity_query_radius(shield.pos, shield.size, partitions)) + { + if (!Capsule::Collide(capsule, entity->GetCollisionCapsule({}))) continue; + bool isComing = vector_dot(entity->velocity, face) < 0; + if (entity->type == ENTITY_PROJECTILE) + { + if (isComing) static_cast(entity)->Reflect(shield_mirror(entity->velocity, face)); + } + else if (entity->IsTear()) + { + if (isComing) static_cast(entity)->Deflect(&shield, shield_mirror(entity->velocity, face)); + } + else if (entity->IsEnemy() && !shield.IsDescendantOf(entity) && !entity->HasEntityFlags(FLAG_KNOCKED_BACK)) + entity->AddKnockback(EntityRef(shield.spawnerEntity.get()), vector_scale(face, SHIELD_PUSH), + SHIELD_PUSH_FRAMES, true); + } +} + +// 005e3dd8 (Update's case 188) The shield appears facing its angle, idles once it has, disappears once dead and goes +// after. Up, it drifts and blocks. Dead, it flies off. +static void shield_update(Entity_Effect& shield) +{ + int direction = vector_to_direction(vector_from_angle(shield.rotation)); + if (shield.state == SHIELD_START) + { + shield.state = SHIELD_APPEARING; + shield.isVisible = true; + shield_animate(shield, "Appear", direction); + if (direction != DIRECTION_UP) shield.renderDepthOffset = SHIELD_DEPTH; + } + else + { + if (shield.isDead) shield_animate(shield, "Disappear", direction); + if (shield.sprite.IsFinished()) + { + if (shield.state != SHIELD_APPEARING) shield.Remove(); + else + { + shield_animate(shield, "Idle", direction); + shield.state = SHIELD_UP; + } + } + } + + if (shield.isDead) + { + shield.AddVelocity(vector_scale(vector_from_angle(shield.rotation), SHIELD_LEAVE_PULL), false); + if (vector_length(shield.velocity) > SHIELD_LEAVE_SPEED) + shield.velocity = vector_resized(shield.velocity, SHIELD_LEAVE_SPEED); + return; + } + shield.friction *= SHIELD_FRICTION; + if (vector_length(shield.velocity) < SHIELD_DRIFT_MIN) + shield.velocity = vector_resized(shield.velocity, SHIELD_DRIFT_MIN); + shield_block(shield); +} + +constexpr auto SHOT_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_EVIL_EYE, nullptr, effect_finishing, nullptr}, + {EFFECT_BRIMSTONE_SWIRL, swirl_init, effect_finishing, nullptr}, + {EFFECT_TECH_DOT, tech_dot_init, effect_finishing, tech_dot_render}, + {EFFECT_DARK_SNARE, dark_snare_init, effect_finishing, nullptr}, + {EFFECT_DIVINE_INTERVENTION, shield_init, effect_finishing, nullptr}, +}); + +std::span shot_effect_behaviours() +{ + return SHOT_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_effect_souls.cpp b/src/entity_effect_souls.cpp new file mode 100644 index 0000000..6542382 --- /dev/null +++ b/src/entity_effect_souls.cpp @@ -0,0 +1,945 @@ +#include "capsule.h" +#include "entity_effect.h" +#include "entity_list.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "npc_basement.h" +#include "entity_slot.h" +#include "kage_graphics.h" +#include "deathmatch_manager.h" +#include "game.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include +#include + +// The souls and spirits items send out: the Urn of Souls' flame thrower and the enemy souls it gathers, Vade Retro's +// hungry souls, Soul of Eve's birds, Purgatory's rifts and ghosts, and the ghosts of the pickups a chest holds (Guppy's +// Eye). + +// The Urn of Souls' thrower turns toward its aim four tenths of the way each frame (slower at a lower time scale) and +// stands 18 out from its player. Its animation names its state and the side it faces, 20 degrees off the axes. +constexpr float SHOOTER_TURN = 0.4f; +constexpr float SHOOTER_REACH = 18; +constexpr float SHOOTER_SIDE_SPAN = 20; +constexpr float SHOOTER_SIDE_FAR = 160; + +// The thrower's states: idle (counting up to 0 from below), starting, starting past its shot, firing and stopping. +enum ShooterState +{ + SHOOTER_IDLE, + SHOOTER_BEGIN, + SHOOTER_BEGUN, + SHOOTER_LOOP, + SHOOTER_END +}; + +// An enemy soul grows faster as it flies (its scale per frame squared, up to 20) and is gathered within 10 (or its +// speed plus 2) of its player, its trail twice the size in red (subtype 1) or blue, faint unless its null shows. +constexpr float SOUL_SCALE_MIN = 0.9f; +constexpr float SOUL_SCALE_SPAN = 0.3f; +constexpr float SOUL_PULL_MIN = 0.06f; +constexpr float SOUL_PULL_SPAN = 0.08f; +constexpr float SOUL_SPEED_MAX = 20; +constexpr float SOUL_GATHER_MARGIN = 2; +constexpr float SOUL_GATHER_RANGE = 10; +constexpr float SOUL_TRAIL_SCALE = 2; +constexpr float SOUL_TRAIL_RADIUS = 0.15f; +constexpr float SOUL_TRAIL_ALPHA = 0.5f; +constexpr float SOUL_NULL_SCALE = 0.65f; +constexpr ColorMod SOUL_RED_TRAIL = {{1, 0.2f, 0.2f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SOUL_BLUE_TRAIL = {{0.3f, 0.6f, 1, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// A hungry soul hunts the nearest enemy within 300 (else its player) at 0.8 per frame up to 10, biting each enemy it +// touches every 8 frames for half its player's poison damage. Gone, it bursts into an enemy ghost of twice its damage. +constexpr float HUNGRY_SOUL_RANGE = 300; +constexpr float HUNGRY_SOUL_PULL = 0.8f; +constexpr float HUNGRY_SOUL_SPEED_MAX = 10; +constexpr float HUNGRY_SOUL_FRICTION = 0.95f; +constexpr float HUNGRY_SOUL_STOP_FRICTION = 0.8f; +constexpr int HUNGRY_SOUL_HIT_RESET_FRAMES = 8; +constexpr float HUNGRY_SOUL_BITE_SHARE = 0.5f; +constexpr int SOUL_HIT_COUNTDOWN = 30; +constexpr float HUNGRY_SOUL_PITCH_MIN = 0.9f; +constexpr float HUNGRY_SOUL_PITCH_SPAN = 0.2f; +constexpr int HUNGRY_SOUL_SHAKE = 6; +constexpr float HUNGRY_SOUL_GHOST_DAMAGE = 2; +constexpr std::string_view HUNGRY_SOUL_WHITE_SHEET = "gfx/Effects/spookier_ghost_white.png"; + +// A bird fades in over its state's frames, flies at 1.6 to 2.4 a frame (its friction 0.9 to 0.93), keeps a target +// (dropped one time in a hundred, picked each fourth frame after the first eight, the nearest give or take 1000), and +// pecks what it touches every 8 frames. With nothing to chase it follows its player beyond 80, or leaves the room. +constexpr int BIRD_FADE_FRAMES = 30; +constexpr uint32_t BIRD_RNG_SHIFT = 13; +constexpr float BIRD_SPEED_MIN = 0.8f; +constexpr float BIRD_SPEED_SPAN = 0.4f; +constexpr float BIRD_SPEED_SCALE = 2; +constexpr float BIRD_FRICTION_MIN = 0.9f; +constexpr float BIRD_FRICTION_SPAN = 0.03f; +constexpr int BIRD_RETARGET_ODDS = 100; +constexpr int BIRD_FIRST_FRAMES = 7; +constexpr int BIRD_SEARCH_FRAMES = 4; +constexpr float BIRD_SEARCH_JITTER = 1000; +constexpr float BIRD_SEARCH_FAR = 1e9f; +constexpr int BIRD_PECK_FRAMES = 8; +constexpr float BIRD_FOLLOW_RANGE_SQUARED = 80 * 80; +constexpr float BIRD_LEAVE_DISTANCE = 2000; +constexpr float BIRD_LEAVE_MARGIN = -200; + +// The turn the thrower lerps by at the room's time scale. +static float shooter_turn_share(Entity_Effect& shooter) +{ + float speed = shooter.speedMultiplier; + if (speed == 1) return SHOOTER_TURN; + return SHOOTER_TURN / ((speed + SHOOTER_TURN) - speed * SHOOTER_TURN); +} + +// The side the thrower faces at an angle: down or up within 20 of the vertical, else left or right. +static std::string_view shooter_side(float angle) +{ + angle = angle_wrapped(angle); + if (angle >= SHOOTER_SIDE_SPAN && angle <= SHOOTER_SIDE_FAR) return "Down"; + if (angle >= -SHOOTER_SIDE_FAR && angle <= -SHOOTER_SIDE_SPAN) return "Up"; + if (angle > SHOOTER_SIDE_FAR || angle < -SHOOTER_SIDE_FAR) return "Left"; + return "Right"; +} + +// Plays the thrower's state facing its side, keeping the frame when only the side changes. +static void shooter_animate(Entity_Effect& shooter, std::string_view state) +{ + std::string name = std::string(state) + std::string(shooter_side(shooter.sprite.rotation)); + std::string_view current = shooter.sprite.animState.animData ? shooter.sprite.GetAnimation() : std::string_view{}; + if (current.starts_with(state)) + { + if (current != name) shooter.sprite.SetAnimation(name, SWITCH_KEEP_FRAME); + return; + } + shooter.sprite.Play(name); +} + +// 0060b0d0 The Urn of Souls' thrower stands by its player at its turned angle (half a turn's lead ahead when only +// placed). Updated, it turns toward its aim and plays its state, moving on once it shoots or its animation ends. It +// goes with its player. +void Entity_Effect::update_variant178_shooter(bool isPositionOnly) +{ + if (!parent) + { + if (!isPositionOnly) Remove(); + return; + } + + if (!isPositionOnly) + { + float delta = angle_wrapped(rotation - sprite.rotation); + sprite.rotation = angle_approach(sprite.rotation, rotation, std::fabs(delta * shooter_turn_share(*this))); + } + float angle = sprite.rotation; + if (isPositionOnly) + angle = angle_approach(angle, rotation, + std::fabs(angle_wrapped(rotation - angle) * shooter_turn_share(*this)) * 0.5f); + pos = vector_add(parent->pos, vector_scale(vector_from_angle(angle), SHOOTER_REACH)); + velocity = {}; + if (isPositionOnly) return; + + if (state < 0) state++; + if (state <= SHOOTER_IDLE) shooter_animate(*this, "Idle"); + else if (state <= SHOOTER_BEGUN) shooter_animate(*this, "ShootBegin"); + else if (state == SHOOTER_LOOP) shooter_animate(*this, "ShootLoop"); + else if (state == SHOOTER_END) shooter_animate(*this, "ShootEnd"); + + bool isStopped = !sprite.animState.animData || !sprite.animState.isPlaying; + if (state == SHOOTER_BEGIN && sprite.animState.animData && sprite.animState.IsEventTriggered("Shoot")) + state = SHOOTER_BEGUN; + else if (state == SHOOTER_BEGUN && isStopped) state = SHOOTER_LOOP; + else if (state == SHOOTER_END && isStopped) state = SHOOTER_IDLE; +} + +// Part of 005cdb20 (Init's case 178) The thrower lasts, unscaled, through rooms and overwrites. +static void urn_shooter_init(Entity_Effect& shooter) +{ + shooter.timeout = -1; + shooter.scale = 0; + shooter.AddEntityFlags(FLAG_PERSISTENT | FLAG_DONT_OVERWRITE); +} + +// 005dfd48 (Update's case 178) The thrower's frame. +static void urn_shooter_update(Entity_Effect& shooter) +{ + shooter.update_variant178_shooter(false); +} + +// Part of 005cdb20 (Init's case 179) An enemy soul glows, of a random size and pull. +static void enemy_soul_init(Entity_Effect& soul) +{ + layer_additive_set(*soul.sprite.GetLayer(0)); + float size = soul.dropRNG.RandomFloat() * SOUL_SCALE_SPAN + SOUL_SCALE_MIN; + soul.sprite.scale = vector_make(size, size); + soul.scale = soul.dropRNG.RandomFloat() * SOUL_PULL_SPAN + SOUL_PULL_MIN; +} + +// An enemy soul's trail: twice its size in its colour, drawn after it. +static void enemy_soul_trail_make(Entity_Effect& soul) +{ + auto* trail = static_cast(g_game->Spawn({.position = soul.pos, + .spawner = &soul, + .type = ENTITY_EFFECT, + .variant = EFFECT_SPRITE_TRAIL, + .seed = Random()})); + trail->sprite.color = soul.subtype == 1 ? SOUL_RED_TRAIL : SOUL_BLUE_TRAIL; + trail->sprite.scale = vector_make(SOUL_TRAIL_SCALE, SOUL_TRAIL_SCALE); + trail->SetRadii(SOUL_TRAIL_RADIUS, SOUL_TRAIL_RADIUS); + trail->parent = &soul; + trail->Update(); + soul.child = trail; +} + +// 005dfd5a (Update's case 179) An enemy soul with nowhere to go stops and goes when its animation ends. Otherwise it +// speeds toward its player and is gathered into the urn once there, its trail following its null. +static void enemy_soul_update(Entity_Effect& soul) +{ + if (!soul.target) + { + soul.velocity = {}; + if (soul.sprite.IsFinished()) soul.Remove(); + return; + } + + soul.sprite.Play("Move"); + Vector goal = soul.target->pos; + float pull = soul.scale * soul.updateTime; + soul.AddVelocity(vector_scale(vector_normalized(vector_sub(goal, soul.pos)), pull * pull), false); + if (vector_length(soul.velocity) > SOUL_SPEED_MAX) soul.velocity = vector_resized(soul.velocity, SOUL_SPEED_MAX); + float reach = std::max(vector_length(soul.velocity) + SOUL_GATHER_MARGIN, SOUL_GATHER_RANGE); + if (vector_length(vector_sub(goal, soul.pos)) <= reach) + { + soul.sprite.Play("Collect"); + vector_lerp(soul.pos, goal, 0.5f); + soul.velocity = {}; + if (soul.target && soul.target->is_player()) + { + static_cast(soul.target.get())->AddUrnSouls(1); + effect_sound_play(SOUND_SOUL_PICKUP); + } + soul.target = nullptr; + } + + const NullFrame* null = soul.sprite.animState.GetNullFrameById(0); + if (!soul.child) enemy_soul_trail_make(soul); + if (!null || !null->isVisible) + { + soul.child->sprite.color._tint[3] = 0; + return; + } + soul.child->sprite.color._tint[3] = SOUL_TRAIL_ALPHA; + Vector nullOffset = vector_scale(null->pos, 1 / SOUL_NULL_SCALE); + soul.child->pos = vector_add(vector_add(soul.pos, soul.posOffset), nullOffset); +} + +// Part of 005cdb20 (Init's case 186) A hungry soul appears, white for subtype 1. +static void hungry_soul_init(Entity_Effect& soul) +{ + if (soul.subtype == 1) soul.sprite.ReplaceSpritesheet(0, HUNGRY_SOUL_WHITE_SHEET); + soul.sprite.Play("Appear"); +} + +// A hungry soul bites the vulnerable enemies it touches, each once per hit list reset. +static void hungry_soul_bite(Entity_Effect& soul, Entity_Player& player) +{ + for (Entity* enemy : entity_query_radius(soul.pos, soul.size, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(&player) || EntityList::HitListContains(soul.hitList, *enemy)) continue; + enemy->TakeDamage(player.meleeDamage * HUNGRY_SOUL_BITE_SHARE, 0, EntityRef(&soul), SOUL_HIT_COUNTDOWN); + hit_list_insert(soul.hitList, *enemy); + } +} + +// The hungry soul gone: it dies out and bursts into an enemy ghost (a white one for subtype 1) of twice its damage. +static void hungry_soul_burst(Entity_Effect& soul) +{ + soul.friction *= HUNGRY_SOUL_STOP_FRICTION; + soul.sprite.Play("Die"); + if (!soul.sprite.IsFinished()) return; + + soul.Remove(); + effect_sound_play(SOUND_DEMON_HIT, {.pitch = random_unit() * HUNGRY_SOUL_PITCH_SPAN + HUNGRY_SOUL_PITCH_MIN}); + game_shake_screen(HUNGRY_SOUL_SHAKE); + uint32_t seed = Random(); + Entity* ghost = g_game->Spawn({.position = soul.pos, + .spawner = soul.spawnerEntity.get(), + .subType = soul.subtype == 1 ? 2 : 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, + .seed = seed}); + ghost->sprite.rotation = random_unit() * DEGREES_PER_TURN; + ghost->sprite.scale = soul.sprite.scale; + ghost->SetCollisionDamage(soul.collisionDamage * HUNGRY_SOUL_GHOST_DAMAGE); + ghost->Update(); +} + +// 00605b8e (Update's case 186) A hungry soul idles once it has appeared, slowing until it does. Idling, it hunts the +// nearest enemy (or follows its player) and bites what it touches. +static void hungry_soul_update(Entity_Effect& soul) +{ + if (soul.isDead) return hungry_soul_burst(soul); + + if (soul.sprite.IsFinished()) soul.sprite.Play("Idle"); + if (!soul.sprite.animState.IsLoopingAnimation()) + { + soul.friction *= HUNGRY_SOUL_STOP_FRICTION; + return; + } + + soul.friction *= HUNGRY_SOUL_FRICTION; + if (!soul.target) soul.target = game_nearest_enemy(soul.pos, soul.spawnerEntity.get(), HUNGRY_SOUL_RANGE); + Entity* goal = soul.target ? soul.target.get() : soul.spawnerEntity.get(); + if (goal) + { + soul.AddVelocity(vector_resized(vector_sub(goal->pos, soul.pos), HUNGRY_SOUL_PULL), false); + if (vector_length_squared(soul.velocity) > HUNGRY_SOUL_SPEED_MAX * HUNGRY_SOUL_SPEED_MAX) + soul.velocity = vector_resized(soul.velocity, HUNGRY_SOUL_SPEED_MAX); + } + if (soul.IsFrame(HUNGRY_SOUL_HIT_RESET_FRAMES, (int)soul.index)) soul.hitList.clear(); + Entity* spawner = soul.spawnerEntity.get(); + Entity_Player* player = spawner ? spawner->ToPlayer() : nullptr; + if (player && player->is_player()) hungry_soul_bite(soul, *player); +} + +// Part of 005cdb20 (Init's case 197) A bird takes wing. +static void dead_bird_init(Entity_Effect& bird) +{ + bird.sprite.Play("Flying"); +} + +// A bird's new target: a vulnerable enemy, the nearest give or take a random 1000 (squared), or none. +static Entity* dead_bird_target_find(Entity_Effect& bird) +{ + Entity* best = nullptr; + float bestScore = BIRD_SEARCH_FAR; + + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!entity->IsVulnerableEnemy(&bird)) continue; + float score = vector_length_squared(vector_sub(entity->pos, bird.pos)) + random_unit() * BIRD_SEARCH_JITTER; + if (score >= bestScore) continue; + best = entity; + bestScore = score; + } + return best; +} + +// The way a bird flies with no target: after its player while it lives and is far, else off out of the room. +static void dead_bird_wander(Entity_Effect& bird, float speed) +{ + Entity* spawner = bird.spawnerEntity.get(); + if (spawner && !bird.isDead) + { + Vector toward = vector_sub(spawner->pos, bird.pos); + if (vector_length_squared(toward) > BIRD_FOLLOW_RANGE_SQUARED) + bird.velocity = vector_add(bird.velocity, vector_scale(vector_normalized(toward), speed)); + return; + } + + Vector centre = Room::GetCenterPos(); + if (vector_is_zero(bird.targetPosition)) + bird.targetPosition = vector_add(centre, vector_resized(vector_sub(bird.pos, centre), BIRD_LEAVE_DISTANCE)); + Vector away = vector_normalized(vector_sub(bird.targetPosition, bird.pos)); + bird.velocity = vector_add(bird.velocity, vector_scale(away, speed)); + if (!g_game->room->IsPositionInRoom(bird.pos, BIRD_LEAVE_MARGIN)) bird.Remove(); +} + +// 005e74b3 (Update's case 197) A bird fades in, then hunts a vulnerable enemy, pecking those it touches, its speed +// eased toward its new one and its sprite facing its way. +static void dead_bird_update(Entity_Effect& bird) +{ + if (bird.state > 0) + { + bird.state--; + bird.sprite.color._tint[3] = std::max(1 - (float)bird.state / BIRD_FADE_FRAMES, 0.0f); + return; + } + + RNG rng = rng_make(bird.initSeed, BIRD_RNG_SHIFT); + float speed = (rng.RandomFloat() * BIRD_SPEED_SPAN + BIRD_SPEED_MIN) * BIRD_SPEED_SCALE; + float friction = rng.RandomFloat() * BIRD_FRICTION_SPAN + BIRD_FRICTION_MIN; + bool isRetarget = !bird.target || !bird.target->IsVulnerableEnemy(nullptr) || random_below(BIRD_RETARGET_ODDS) == 0; + if (isRetarget && (bird.FrameCount() <= BIRD_FIRST_FRAMES || bird.IsFrame(BIRD_SEARCH_FRAMES, 0))) + bird.target = dead_bird_target_find(bird); + + if (bird.IsFrame(BIRD_PECK_FRAMES, 0)) + { + for (Entity* entity : entity_query_capsule(bird.GetCollisionCapsule({}), QUERY_ENEMIES)) + if (entity->IsVulnerableEnemy(&bird)) + entity->TakeDamage(bird.collisionDamage, 0, EntityRef(nullptr), SOUL_HIT_COUNTDOWN); + } + + float lastSpeed = vector_length(bird.velocity); + if (bird.target) + { + Vector toward = vector_normalized(vector_sub(bird.target->pos, bird.pos)); + bird.velocity = vector_add(bird.velocity, vector_scale(toward, speed)); + } + else dead_bird_wander(bird, speed); + float newSpeed = vector_length(bird.velocity); + bird.velocity = vector_resized(bird.velocity, (newSpeed - lastSpeed) * 0.5f + lastSpeed); + bird.sprite.isFlipX = bird.velocity.x > 0; + bird.friction = friction; +} + +// The pickup ghosts show up to four pickups at half size around their chest, laid out by count, drawn over all in a +// crawlspace and just in front elsewhere. +constexpr float PICKUP_GHOST_DEPTH = 10; +constexpr int PICKUP_GHOST_CRAWLSPACE_Z = 10000; +constexpr float PICKUP_GHOST_SCALE = 0.5f; +constexpr float PICKUP_GHOST_SPREAD = 0.65f; +constexpr int PICKUP_GHOST_HOLDER_VARIANT = 69; +constexpr float PICKUP_GHOST_LAYOUTS[PICKUP_GHOST_SLOTS][PICKUP_GHOST_SLOTS][2] = { + {{0, 0}}, + {{-8, 0}, {8, 0}}, + {{0, -4}, {12, 4}, {-12, 4}}, + {{0, -4}, {-14, 0}, {14, 0}, {0, 4}}, +}; + +// Part of 005cdb20 (Init's case 191) A pickup ghost keeps the pickups it shows, in front of its holder. +static void pickup_ghost_init(Entity_Effect& ghost) +{ + ghost.extraData = std::make_shared(); + if (g_game->room->roomType == ROOM_DUNGEON) ghost.renderZOffset = PICKUP_GHOST_CRAWLSPACE_Z; + else ghost.renderDepthOffset = PICKUP_GHOST_DEPTH; +} + +// Part of 00607620 (Render's case 191) The pickups around their holder, following its sprite's size (and a pedestal's +// bob), shown only while the holder's own sprite shows. +static void pickup_ghost_render(Entity_Effect& ghost, const Vector& offset) +{ + auto* data = dynamic_cast(ghost.extraData.get()); + if (!data || data->count < 1) return; + + Vector scale = vector_make(1, 1); + Vector shift{}; + Entity* holder = ghost.parent; + if (holder && holder->sprite.isLoaded && holder->sprite.animState.animData) + { + const AnimationFrame* frame = holder->sprite.animState.GetLayerFrame(0); + scale = holder->sprite.scale; + if (frame) + { + LayerState& layer = *holder->sprite.GetLayer(0); + if (holder->type == ENTITY_PICKUP && holder->variant == PICKUP_GHOST_HOLDER_VARIANT) + shift = vector_add(layer.pos, frame->pos); + scale = vector_make(scale.x * layer.size.x * frame->scale.x, scale.y * layer.size.y * frame->scale.y); + } + Vector screen = render_position_get(vector_add(holder->pos, holder->posOffset), RENDER_SNAPPED); + ghost.renderPosition = vector_add(screen, offset); + if (!frame || !frame->isVisible) return; + } + + int count = std::min(data->count, PICKUP_GHOST_SLOTS); + for (int i = 0; i < count; i++) + { + ANM2& sprite = data->sprites[i]; + const float* place = PICKUP_GHOST_LAYOUTS[count - 1][i]; + sprite.offset = shift; + sprite.scale = vector_scale(scale, PICKUP_GHOST_SCALE); + Vector at = vector_make(scale.x * place[0] * PICKUP_GHOST_SPREAD + ghost.renderPosition.x, + scale.y * place[1] * PICKUP_GHOST_SPREAD + ghost.renderPosition.y); + sprite.Render(SpriteDraw{at, {}, {}}); + } +} + +// Purgatory: a rift (subtype 0) idles until the room is clear or a player steps in, then sends out a ghost (1) on its +// Shoot event and moves to a far spot of the room (one of twenty tries more than 80 out, a quarter of them settling) +// while it is not clear. A ghost charges at the nearest enemy (or a random spot), gaining speed (up to 10, 20 at +// most) until it reaches it within 30 or for 60 frames, then bursts into an enemy ghost of twice its player's poison +// damage (7 without one). +constexpr uint32_t PURGATORY_RNG_SHIFT = 8; +constexpr int PURGATORY_ROWS = 4; +constexpr float PURGATORY_ROW_HEIGHT = 64; +constexpr int PURGATORY_CLEAR_FRAME = 30; +constexpr int PURGATORY_RIFT = 0; +constexpr int PURGATORY_GHOST = 1; +constexpr int PURGATORY_SPOT_TRIES = 20; +constexpr float PURGATORY_SPOT_MARGIN = 20; +constexpr int PURGATORY_SPOT_PATH = 901; +constexpr float PURGATORY_SPOT_FAR = 80; +constexpr int PURGATORY_SPOT_SETTLE_ODDS = 4; +constexpr float PURGATORY_GHOST_RANGE = 5000; +constexpr float PURGATORY_LAUNCH_MIN = 4; +constexpr float PURGATORY_LAUNCH_SPAN = 6; +constexpr float PURGATORY_PULL_PER_FRAME = 0.3f; +constexpr float PURGATORY_PULL_MAX = 10; +constexpr float PURGATORY_SPEED_MAX = 20; +constexpr float PURGATORY_REACH_SQUARED = 30 * 30; +constexpr int PURGATORY_CHARGE_FRAMES = 59; +constexpr float PURGATORY_DAMAGE = 7; +constexpr float PURGATORY_PLAYER_DAMAGE = 2; +constexpr float PURGATORY_TRAIL_ALPHA = 0.5f; +constexpr ColorMod PURGATORY_TRAIL_COLOR = {{1, 0.8f, 0.8f, 0.3f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The ghost's tail: five copies of its frames trailing behind its flight (its speed up to 7), waving with time. +constexpr int PURGATORY_TAIL = 5; +constexpr float PURGATORY_TAIL_SPEED = 7; +constexpr float PURGATORY_TAIL_SPACING = 1.5f; +constexpr float PURGATORY_TAIL_WAVE_RATE = 0.6f; +constexpr float PURGATORY_TAIL_WAVE = 2; +constexpr float PURGATORY_TAIL_SCALE = 0.65f; + +// Part of 005cdb20 (Init's case 189) A rift lies on the floor in one of four looks, maybe mirrored, its darkness +// multiplying the floor. Both appear. +static void purgatory_init(Entity_Effect& purgatory) +{ + if (purgatory.subtype == PURGATORY_RIFT) + { + RNG rng = rng_make(purgatory.initSeed, PURGATORY_RNG_SHIFT); + float row = (float)rng.RandomInt(PURGATORY_ROWS) * PURGATORY_ROW_HEIGHT; + purgatory.sprite.isFlipX = rng.RandomInt(2) != 0; + purgatory.sprite.GetLayer(0)->cropOffset.y = row; + purgatory.sprite.GetLayer(1)->cropOffset.y = row; + purgatory.sprite.GetLayer(1)->blendMode = {KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ZERO, + KAGE::Graphics::FACTOR_SRC_COLOR, KAGE::Graphics::FACTOR_ZERO, + KAGE::Graphics::FACTOR_SRC_COLOR}; + } + purgatory.sprite.Play("Appear"); + if (purgatory.subtype == PURGATORY_RIFT) purgatory.sortingLayer = SORTING_BACKGROUND; +} + +// A far spot of the room the rift moves to: of twenty free spots open enough to walk, the farthest so far, settling +// one time in four once more than 80 out, or a random free spot. +static Vector purgatory_spot_find(Entity_Effect& rift) +{ + Room& room = *g_game->room; + Vector best{}; + float bestDistance = 0; + for (int i = 0; i < PURGATORY_SPOT_TRIES; i++) + { + Vector spot = room_free_pickup_position_find( + {.position = room.GetRandomPosition(PURGATORY_SPOT_MARGIN), .isAvoidActiveEntities = true}); + int index = room.GetGridIndex(spot); + if ((index < 0 ? 0 : room.GetGridPath(index)) >= PURGATORY_SPOT_PATH) continue; + float distance = vector_length_squared(vector_sub(spot, rift.pos)); + if (distance <= bestDistance) continue; + bestDistance = distance; + best = spot; + if (distance > PURGATORY_SPOT_FAR && random_below(PURGATORY_SPOT_SETTLE_ODDS) == 0) break; + } + return vector_is_zero(best) ? room_pickup_position_random(true, false) : best; +} + +// The rift's frame: it opens for a player stepping in (or closes with the room clear), then sends its ghost out and +// moves on. +static void purgatory_rift_update(Entity_Effect& rift) +{ + if (rift.state == 0) + { + if (rift.sprite.IsFinished()) rift.sprite.Play("Idle"); + if (g_game->room->IsClear() && !g_game->ambush.isActive) + { + rift.state++; + rift.sprite.Play("Disappear"); + rift.sprite.SetFrame((float)PURGATORY_CLEAR_FRAME); + return; + } + for (Entity_Player* player : g_game->playerManager.playerList) + { + float reach = player->size + rift.size; + if (vector_length_squared(vector_sub(player->pos, rift.pos)) >= reach * reach) continue; + if (player->isDead || player->entityCollisionClass == ENTCOLL_NONE) continue; + if (g_game->deathmatchManager.is_active()) rift.damageSource = (int)player->index; + rift.state++; + rift.sprite.Play("Disappear"); + break; + } + return; + } + + if (rift.sprite.IsEventTriggered("Shoot")) + { + Entity* owner = rift.spawnerEntity; + if (g_game->deathmatchManager.is_active()) + for (Entity_Player* player : g_game->playerManager.playerList) + if ((int)player->index == rift.damageSource) + { + owner = player; + break; + } + g_game + ->Spawn({.position = rift.pos, + .spawner = owner, + .subType = PURGATORY_GHOST, + .type = ENTITY_EFFECT, + .variant = EFFECT_PURGATORY, + .seed = rift.dropRNG.Next()}) + ->Update(); + effect_sound_play(SOUND_PORTAL_SPAWN); + } + if (!rift.sprite.IsFinished()) return; + rift.Remove(); + if (g_game->room->IsClear()) return; + Vector spot = purgatory_spot_find(rift); + uint32_t seed = rift.dropRNG.Next(); + g_game + ->Spawn({.position = spot, + .spawner = rift.spawnerEntity.get(), + .type = ENTITY_EFFECT, + .variant = EFFECT_PURGATORY, + .seed = seed}) + ->Update(); +} + +// The ghost bursts into an enemy ghost of its player's poison damage, twice. +static void purgatory_ghost_burst(Entity_Effect& ghost) +{ + ghost.Remove(); + effect_sound_play(SOUND_DEMON_HIT, {.pitch = random_unit() * HUNGRY_SOUL_PITCH_SPAN + HUNGRY_SOUL_PITCH_MIN}); + game_shake_screen(HUNGRY_SOUL_SHAKE); + Entity* spawner = ghost.spawnerEntity; + float damage = PURGATORY_DAMAGE; + if (spawner && spawner->is_player()) + damage = static_cast(spawner)->meleeDamage * PURGATORY_PLAYER_DAMAGE; + Entity* burst = g_game->Spawn({.position = ghost.pos, + .spawner = spawner, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, + .seed = Random()}); + burst->sprite.rotation = random_unit() * DEGREES_PER_TURN; + burst->sprite.scale = ghost.sprite.scale; + burst->SetCollisionDamage(damage); + burst->Update(); +} + +// The ghost's frame: it charges once it has appeared, then flies at its target faster and faster, its trail on its +// null, and bursts on reaching it. +static void purgatory_ghost_update(Entity_Effect& ghost) +{ + if (ghost.state == 0) + { + if (!ghost.sprite.IsFinished()) return; + ghost.state++; + ghost.sprite.SetFrame("Charge", 0); + ghost.target = game_nearest_enemy(ghost.pos, &ghost, PURGATORY_GHOST_RANGE); + ghost.targetPosition = + ghost.target ? ghost.target->pos : g_game->room->GetRandomPosition(PURGATORY_SPOT_MARGIN); + Vector way = random_direction(); + ghost.velocity = vector_scale(way, random_unit() * PURGATORY_LAUNCH_SPAN + PURGATORY_LAUNCH_MIN); + return; + } + + ghost.state += ghost.update_ticks_get(); + if (ghost.target) ghost.targetPosition = ghost.target->pos; + const NullFrame* null = ghost.sprite.animState.GetNullFrameById(0); + if (!ghost.child) + { + auto* trail = static_cast(g_game->Spawn({.position = ghost.pos, + .spawner = &ghost, + .type = ENTITY_EFFECT, + .variant = EFFECT_SPRITE_TRAIL, + .seed = Random()})); + trail->sprite.color = PURGATORY_TRAIL_COLOR; + float size = ghost.sprite.scale.x * SOUL_TRAIL_SCALE; + trail->sprite.scale = vector_make(size, size); + trail->SetRadii(SOUL_TRAIL_RADIUS, SOUL_TRAIL_RADIUS); + trail->parent = &ghost; + trail->Update(); + ghost.child = trail; + } + ghost.child->sprite.color._tint[3] = PURGATORY_TRAIL_ALPHA; + Vector nullOffset = null ? vector_scale(null->pos, 1 / SOUL_NULL_SCALE) : Vector{}; + ghost.child->pos = vector_add(vector_add(ghost.pos, ghost.posOffset), nullOffset); + + float pull = std::min((float)ghost.state * PURGATORY_PULL_PER_FRAME, PURGATORY_PULL_MAX); + ghost.AddVelocity(vector_scale(vector_normalized(vector_sub(ghost.targetPosition, ghost.pos)), pull), false); + if (vector_length(ghost.velocity) > PURGATORY_SPEED_MAX) + ghost.velocity = vector_resized(ghost.velocity, PURGATORY_SPEED_MAX); + float distance = vector_length_squared(vector_sub(ghost.pos, ghost.targetPosition)); + if (distance <= PURGATORY_REACH_SQUARED || ghost.state > PURGATORY_CHARGE_FRAMES) purgatory_ghost_burst(ghost); +} + +// 005e472c (Update's case 189) Purgatory's rift or ghost. +static void purgatory_update(Entity_Effect& purgatory) +{ + if (purgatory.subtype == PURGATORY_RIFT) purgatory_rift_update(purgatory); + else purgatory_ghost_update(purgatory); +} + +// Draws the layer of the ghost at frames along its tail. +static void purgatory_tail_layer(Entity_Effect& ghost, int layerId, const std::array& offsets, + const std::array& frames) +{ + ANM2& sprite = ghost.sprite; + for (int i = 0; i < PURGATORY_TAIL; i++) + { + if (!sprite.animState.animData) continue; + sprite.animState.SetFrameFloat((float)frames[i]); + if ((int)sprite.layerStates.size() <= layerId || sprite.animState.animData->layerMap[layerId] < 0) continue; + sprite.RenderLayer(layerId, SpriteDraw{vector_add(ghost.renderPosition, offsets[i]), {}, {}}); + } +} + +// Part of 00607620 (Render's case 189) A charging ghost draws a waving tail of five of its frames behind its flight +// (from its front down when it flies down, from its back up otherwise), its second layer before its first. +static void purgatory_render(Entity_Effect& ghost, const Vector&) +{ + if (ghost.subtype != PURGATORY_GHOST || ghost.state <= 0) + return ghost.sprite.Render(SpriteDraw{ghost.renderPosition, {}, {}}); + + Vector flight = vector_length(ghost.velocity) > PURGATORY_TAIL_SPEED + ? vector_resized(ghost.velocity, PURGATORY_TAIL_SPEED) + : ghost.velocity; + bool isFalling = flight.y >= 0; + float wave = ghost.updateTime * PURGATORY_TAIL_WAVE_RATE; + std::array offsets{}; + std::array frames{}; + for (int i = 0; i < PURGATORY_TAIL; i++) + { + float spacing = std::sqrt((float)(isFalling ? PURGATORY_TAIL - 1 - i : i)) * PURGATORY_TAIL_SPACING; + float sway = std::sin(spacing + wave) * PURGATORY_TAIL_WAVE; + offsets[i] = + vector_make(-flight.x * spacing * PURGATORY_TAIL_SCALE, (sway - flight.y * spacing) * PURGATORY_TAIL_SCALE); + frames[i] = isFalling ? i : (i == 0 ? PURGATORY_TAIL : PURGATORY_TAIL - 1 - i); + } + purgatory_tail_layer(ghost, 1, offsets, frames); + purgatory_tail_layer(ghost, 0, offsets, frames); +} + +// The enemy ghosts: a lingering one (subtype 0, Vade Retro's) drifts with the tears that pass it and shoots Book of +// Virtues' purple tears where its player fires every 30 frames, and leaves in a red poof once the room is clear (no +// Exorcist about); its state 1 makes it burst into one or three ghost explosions. An explosion (1 Vade Retro's, 2 +// white, 3 golden) farts on its fourth frame and every 5 frames blasts 80 times its size: enemy shots vanish, +// vulnerable enemies (and fires, TNT and poops) take its damage and are pushed 4, and walls within 2 cells take +// a hit. +constexpr float GHOST_CLEAR_POOF_HEIGHT = 4; +constexpr int GHOST_TEAR_FRAMES = 30; +constexpr float GHOST_TEAR_SPEED = 10; +constexpr float GHOST_TEAR_FALL = 0.2f; +constexpr float GHOST_TEAR_DAMAGE = 3.5f; +constexpr float GHOST_TEAR_SCALE = 0.5f; +constexpr float GHOST_BIG_SCALE = 1.15f; +constexpr float GHOST_SPREAD = 40; +constexpr float GHOST_BURST_HEIGHT = -13; +constexpr float GHOST_ALPHA = 0.8f; +constexpr float GHOST_FRICTION = 0.9f; +constexpr int GHOST_FACE_FRAMES = 10; +constexpr int GHOST_DRIFT_FRAMES = 3; +constexpr float GHOST_DRIFT_RANGE = 80; +constexpr float GHOST_DRIFT_REACH = 10; +constexpr float GHOST_DRIFT_SHARE = 0.1f; +constexpr int GHOST_FART_FRAME = 4; +constexpr int GHOST_BLAST_FRAMES = 5; +constexpr float GHOST_BLAST_REACH = 80; +constexpr float GHOST_BLAST_PUSH = 4; +constexpr int GHOST_BLAST_COUNTDOWN = 30; +constexpr int GHOST_GRID_CELLS = 2; +constexpr float GHOST_GRID_REACH = 15; +constexpr float GHOST_DEPTH = 100; +constexpr std::string_view FART_ANM2 = "resources/gfx/1000.034_Fart.anm2"; +constexpr std::array GHOST_IDLES = {"Idle1", "Idle2", "Idle3", "Idle4"}; +constexpr std::array GHOST_BLASTED_TYPES = {ENTITY_FIREPLACE, ENTITY_MOVABLE_TNT, ENTITY_POOP}; +constexpr ColorMod GHOST_RED = {{1, 1, 1, 1}, {1, 0, 0, 1}, {0, 0, 0}}; +constexpr ColorMod GHOST_WHITE = {{1.5f, 1.5f, 1.5f, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr ColorMod GHOST_GOLDEN = {{1, 1, 1, 1}, {0.75f, 0.6f, 1, 1}, {0, 0, 0}}; +constexpr ColorMod GHOST_GOLDEN_FART = {{1.5f, 1.5f, 1.5f, 1}, {0.75f, 0.6f, 1, 1}, {0, 0, 0}}; +constexpr ColorMod GHOST_WHITE_POOF = {{1.5f, 1.5f, 1.5f, 0.7f}, {1, 1, 1, 1}, {0.7f, 0.7f, 0.7f}}; +constexpr ColorMod GHOST_TEAR = {{1, 0.5f, 0.2f, 0.5f}, {0, 0, 0, 0}, {50 / 255.0f, 0, 0}}; + +// Part of 005cdb20 (Init's case 144) A lingering ghost idles one of four ways, over the walls, facing the nearest +// player. An explosion explodes in front, white or golden by its subtype. +static void enemy_ghost_init(Entity_Effect& ghost) +{ + if (ghost.subtype == 0) + { + ghost.sprite.Play(GHOST_IDLES[ghost.dropRNG.RandomInt((uint32_t)GHOST_IDLES.size())]); + ghost.entityGridCollisionClass = GRIDCOLL_WALLS; + if (Entity_Player* player = game_nearest_player(ghost.pos)) ghost.sprite.isFlipX = ghost.pos.x < player->pos.x; + return; + } + ghost.sprite.Play("Explosion"); + ghost.renderDepthOffset = GHOST_DEPTH; + if (ghost.subtype == 2) ghost.sprite.color = GHOST_WHITE; + else if (ghost.subtype == 3) ghost.sprite.color = GHOST_GOLDEN; +} + +// Book of Virtues' purple tear from a lingering ghost where its player fires. +static void enemy_ghost_shoot(Entity_Effect& ghost, Entity_Player& player, int direction) +{ + Vector velocity = vector_scale(vector_from_direction(direction), GHOST_TEAR_SPEED); + uint32_t seed = Random(); + auto* tear = static_cast(g_game->Spawn( + {.position = ghost.pos, .velocity = velocity, .spawner = &player, .type = ENTITY_TEAR, .seed = seed})); + tear->fallingSpeed = random_unit() * GHOST_TEAR_FALL; + tear->fallingAccel = 0; + tear->SetCollisionDamage(GHOST_TEAR_DAMAGE); + tear->SetScale(GHOST_TEAR_SCALE); + tear->parent = &player; + tear->SetColor(GHOST_TEAR, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->tearIdx = random_below(2); +} + +// A lingering ghost bursts into one ghost explosion of its damage, or three around it for a big one. +static void enemy_ghost_burst(Entity_Effect& ghost) +{ + int count = ghost.sprite.scale.x > GHOST_BIG_SCALE ? 3 : 1; + float turn = random_unit() * DEGREES_PER_TURN; + float spread = count == 1 ? 0 : GHOST_SPREAD; + for (int i = 0; i < count; i++) + { + float angle = (float)i * DEGREES_PER_TURN / (float)count + turn; + Vector spot = vector_add(ghost.pos, vector_scale(vector_from_angle(angle), spread)); + Entity* burst = g_game->Spawn( + {.position = spot, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_ENEMY_GHOST, .seed = Random()}); + burst->sprite.rotation = random_unit() * DEGREES_PER_TURN; + burst->SetCollisionDamage(ghost.collisionDamage); + burst->Update(); + burst->posOffset = vector_make(0, GHOST_BURST_HEIGHT); + } + ghost.Remove(); +} + +// A lingering ghost: gone in a red poof once the room is clear, else it shoots, faces its nearest player and drifts +// along with the tears that pass near. +static EffectUpdateEnd enemy_ghost_linger(Entity_Effect& ghost) +{ + Room& room = *g_game->room; + if (room.IsClear() && !room.isExorcistActive) + { + Entity* poof = g_game->Spawn( + {.position = ghost.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->posOffset = vector_add(ghost.posOffset, vector_make(0, GHOST_CLEAR_POOF_HEIGHT)); + poof->SetColor(GHOST_RED, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + ghost.Remove(); + return EFFECT_UPDATE_RETURN; + } + if (ghost.state == 1) + { + enemy_ghost_burst(ghost); + return EFFECT_UPDATE_RETURN; + } + + Entity* spawner = ghost.spawnerEntity; + Entity_Player* player = spawner && spawner->type == ENTITY_PLAYER ? spawner->ToPlayer() : nullptr; + if (ghost.state == 0 && player && player->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && + player->fireDirection != DIRECTION_NONE && ghost.IsFrame(GHOST_TEAR_FRAMES, (int)ghost.index)) + enemy_ghost_shoot(ghost, *player, player->fireDirection); + ghost.sprite.color._tint[3] = GHOST_ALPHA; + ghost.friction = GHOST_FRICTION; + if (ghost.IsFrame(GHOST_FACE_FRAMES, (int)ghost.initSeed)) + if (Entity_Player* nearest = game_nearest_player(ghost.pos)) + ghost.sprite.isFlipX = ghost.pos.x < nearest->pos.x; + if (!ghost.IsFrame(GHOST_DRIFT_FRAMES, (int)ghost.initSeed)) return EFFECT_UPDATE_FINISH; + for (Entity* tear : entity_query_radius(ghost.pos, GHOST_DRIFT_RANGE, QUERY_TEARS)) + { + if (!tear->IsTear()) continue; + if (vector_length(vector_sub(tear->pos, ghost.pos)) < tear->size + GHOST_DRIFT_REACH) + ghost.velocity = vector_add(ghost.velocity, vector_scale(tear->velocity, GHOST_DRIFT_SHARE)); + } + return EFFECT_UPDATE_FINISH; +} + +// The explosion's fart on its fourth frame, coloured by its kind, with a large poof (and a blood splat for Vade +// Retro's). +static void enemy_ghost_fart(Entity_Effect& ghost) +{ + auto* fart = static_cast( + g_game->Spawn({.position = ghost.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()})); + fart->sprite.Load(FART_ANM2, GRAPHICS_LOAD); + fart->sprite.Play("Explode"); + fart->sprite.scale = ghost.sprite.scale; + fart->posOffset = vector_add(ghost.posOffset, vector_make(0, GHOST_CLEAR_POOF_HEIGHT)); + const ColorMod& color = ghost.subtype == 2 ? GHOST_WHITE : ghost.subtype == 3 ? GHOST_GOLDEN_FART : GHOST_RED; + fart->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + fart->Update(); + if (ghost.subtype == 3) return; + + int size = ghost.subtype == 2 ? 3 : 0; + Entity* poof = g_game->Spawn({.position = ghost.pos, + .subType = size, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + if (ghost.subtype == 2) poof->SetColor(GHOST_WHITE_POOF, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->sprite.Play(ghost.subtype == 2 ? "Poof_Large2" : "Poof_Large1"); + poof->sprite.rotation = random_unit() * DEGREES_PER_TURN; + poof->sprite.scale = ghost.sprite.scale; + poof->posOffset = ghost.posOffset; + poof->Update(); + if (ghost.subtype == 2) return; + g_game->Spawn({.position = ghost.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}) + ->Update(); +} + +// The explosion's blast: enemy shots vanish, enemies (with fires, TNT and poops) take its damage and are +// pushed out, and the room's walls nearby take a hit. +static void enemy_ghost_blast(Entity_Effect& ghost) +{ + float reach = ghost.sprite.scale.x * GHOST_BLAST_REACH; + Room& room = *g_game->room; + bool isEnemyHurting = ghost.spawnerType < ENTITY_FIRST_ENEMY || ghost.spawnerType >= ENTITY_EFFECT || + ghost.HasEntityFlags(FLAG_FRIENDLY); + if (isEnemyHurting) + for (Entity* entity : entity_query_radius(ghost.pos, reach, QUERY_PROJECTILES | QUERY_ENEMIES)) + { + if (entity->IsProjectile()) + { + static_cast(entity)->projectileFlags = 0; + entity->isDead = true; + continue; + } + bool isBlasted = entity->IsVulnerableEnemy(nullptr) || + std::find(GHOST_BLASTED_TYPES.begin(), GHOST_BLASTED_TYPES.end(), entity->type) != + GHOST_BLASTED_TYPES.end(); + if (!isBlasted) continue; + entity->TakeDamage(ghost.collisionDamage, 0, EntityRef(nullptr), GHOST_BLAST_COUNTDOWN); + Vector away = vector_normalized(vector_sub(entity->pos, ghost.pos)); + entity->velocity = vector_add(entity->velocity, vector_scale(away, GHOST_BLAST_PUSH)); + } + + int index = room.GetGridIndex(ghost.pos); + if (index < 0) return; + int column = index % room.gridWidth; + int row = index / room.gridWidth; + for (int x = column - GHOST_GRID_CELLS; x <= column + GHOST_GRID_CELLS; x++) + for (int y = row - GHOST_GRID_CELLS; y <= row + GHOST_GRID_CELLS; y++) + { + int cell = room.GetGridIndexByTile(x, y); + GridEntity* grid = cell < 0 ? nullptr : room.GetGridEntity((uint32_t)cell); + if (!grid || grid->collisionClass <= COLLISION_PIT) continue; + if (vector_length(vector_sub(room.GetGridPosition(cell), ghost.pos)) < reach + GHOST_GRID_REACH) + grid->Hurt(1, EntityRef(&ghost)); + } +} + +// 005d78ee (Update's case 144) A lingering ghost lingers. An explosion farts on its fourth frame, blasts every fifth +// and goes once shown. +static EffectUpdateEnd enemy_ghost_update(Entity_Effect& ghost) +{ + if (ghost.subtype == 0) return enemy_ghost_linger(ghost); + + if (ghost.FrameCount() == GHOST_FART_FRAME) enemy_ghost_fart(ghost); + if (ghost.IsFrame(GHOST_BLAST_FRAMES, 0) || ghost.state == 0) + { + ghost.state = 1; + enemy_ghost_blast(ghost); + } + if (ghost.sprite.IsFinished()) ghost.Remove(); + return EFFECT_UPDATE_FINISH; +} + +constexpr auto SOUL_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_URN_OF_SOULS, urn_shooter_init, effect_finishing, nullptr}, + {EFFECT_ENEMY_SOUL, enemy_soul_init, effect_finishing, nullptr}, + {EFFECT_HUNGRY_SOUL, hungry_soul_init, effect_finishing, nullptr}, + {EFFECT_DEAD_BIRD, dead_bird_init, effect_finishing, nullptr}, + {EFFECT_PICKUP_GHOST, pickup_ghost_init, nullptr, pickup_ghost_render}, + {EFFECT_PURGATORY, purgatory_init, effect_finishing, purgatory_render}, + {EFFECT_ENEMY_GHOST, enemy_ghost_init, enemy_ghost_update, nullptr}, +}); + +std::span soul_effect_behaviours() +{ + return SOUL_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index 8dd53ab..b761bf6 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -157,7 +157,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 float DEGREES_TO_RADIANS = 0.017453292f; constexpr float FULL_TURN = 360; // The odds layouts roll with (one in n). diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index 548d57b..fecc55b 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -6,6 +6,7 @@ #include "entity_player.h" #include "entity_player_forgotten.h" #include "familiar_gello.h" +#include "familiar_variants.h" #include "game_state_player.h" #include "log.h" #include "lua_engine.h" @@ -36,8 +37,8 @@ constexpr std::pair ORBIT_LAYERS[] = { {121, 5}, {128, 5}, {84, 4}, {123, 4}, {204, 6}, {216, 6}, {217, 6}, {229, 10}, {237, 8}}; // The familiars whose setup, drawing and links wait for their takeovers. -constexpr int UNWRITTEN_INIT_VARIANTS[] = {48, 62, 122, 131, 228, 231, 233, 234, 236, 238, 239}; -constexpr int UNWRITTEN_RENDER_VARIANTS[] = {48, 68, 75, 78, 79, 231, 243}; +constexpr int UNWRITTEN_INIT_VARIANTS[] = {62, 122, 228, 231, 233, 236, 238}; +constexpr int UNWRITTEN_RENDER_VARIANTS[] = {231}; // The familiars that walk, Init's grid collision for them, and the ones whose hit list survives the reset. constexpr int GROUND_VARIANTS[] = {46, 47, 71, 72, 48, 56, 73}; @@ -155,6 +156,7 @@ constexpr int VERSUS_GIVE_UP_FRAMES = -900; constexpr int HEADLESS_SPLAT_INTERVAL = 3; constexpr int HEADLESS_CREEP_INTERVAL = 2; constexpr int HEADLESS_CREEP_ODDS = 5; +constexpr int DEPRESSION_TRAIL_ODDS = 5; constexpr int JUICY_SACK_CREEP_INTERVAL = 4; constexpr float TRAIL_SCALE_RANGE = 0.5f; constexpr float TRAIL_SCALE_MIN = 0.2f; @@ -443,6 +445,9 @@ void Entity_Familiar::variant_init(int initSubtype) switch (variant) { case FORGOTTEN_BODY: forgotten_body_init(*this); break; + case ISAACS_BODY: + if (player) isaacs_body_init(*this); + break; case WISP: case ITEM_WISP: WispInit(); break; case BLUE_FLY: @@ -492,6 +497,15 @@ void Entity_Familiar::variant_init(int initSubtype) sprite.Play(LEPROSY_ANIMS[subtype]); break; case BONE_ORBITAL: bone_orbital_init(*this); break; + case MY_SHADOW: + my_shadow_init(*this); + break; + case BONE_SPUR: + bone_spur_init(*this); + break; + case CUBE_BABY: + cube_baby_init(*this); + break; } } @@ -735,6 +749,7 @@ void Entity_Familiar::variant_update() return; } if (familiar_listed(FOLLOW_ONLY_VARIANTS, variant)) return FollowParent(); + if (familiar_listed(IDLE_VARIANTS, variant)) return; switch (variant) { @@ -786,8 +801,70 @@ void Entity_Familiar::variant_update() if (IsFrame(JUICY_SACK_CREEP_INTERVAL, 0)) creep_drop(*this, EFFECT_PLAYER_CREEP_WHITE); return; case BBF: return bbf_update(*this); + case ISAACS_BODY: + return isaacs_body_update(*this); + case BROWN_NUGGET_POOTER: + return brown_nugget_update(*this); + case CHARGED_BABY: + return charged_baby_update(*this); + case LOST_FLY: + return lost_fly_update(*this); + case CENSER: + return censer_update(*this); + case OBSESSED_FAN: + return MoveDelayed(DELAYED_FOLLOW_FRAMES); + case PAPA_FLY: + ai_lil_monstro(); + return MoveDelayed(DELAYED_FOLLOW_FRAMES); + case MILK: + return milk_update(*this); + case DEPRESSION: + FollowParent(); + if (IsFrame(HEADLESS_SPLAT_INTERVAL, 0) && random_below(DEPRESSION_TRAIL_ODDS) != 0) + creep_drop(*this, EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL); + return; + case SHADE: + return shade_update(*this); + case HUSHY: + return hushy_update(*this); + case KING_BABY: + return king_baby_update(*this); + case FINGER: + return finger_update(*this); + case FARTING_BABY: + return farting_baby_update(*this); + case SUCCUBUS: + return succubus_update(*this); + case BLOODSHOT_EYE: + return bloodshot_eye_update(*this); + case SMART_FLY: + return ai_orbital_variant_50(); + case SAMSONS_CHAINS: + return ai_samsons_chains(); + case GEMINI: + return gemini_update(*this); + case SISSY_LONGLEGS: + return sissy_longlegs_update(*this); + case PUNCHING_BAG: + return punching_bag_update(*this); + case ANGRY_FLY: + return update_angry_fly(); + case SPIDER_MOD: + case SPIDER_BABY: + return spider_update(*this); + case BLUE_BABYS_ONLY_FRIEND: + return ai_blue_babys_only_friend(); + case GUILLOTINE: + case SCISSORS: + return detached_head_update(*this); case LITTLE_CHUBBY: - case BOBS_BRAIN: return ai_charger(); + case BOBS_BRAIN: + case JAW_BONE: + case KNIFE_PIECE_1: + case KNIFE_PIECE_2: + case KNIFE_FULL: + case LIL_PORTAL: + return ai_charger(); case DEAD_BIRD: case EVES_BIRD_FOOT: case LIL_HAUNT: return ai_flying_bird(); @@ -819,6 +896,40 @@ void Entity_Familiar::variant_update() case UMBILICAL_BABY: return ai_umbilical_baby(false); case BONE_ORBITAL: return bone_orbital_update(*this); case SWARM_FLY_ORBITAL: return orbit_chase(*this); + case POINTY_RIB: + return pointy_rib_update(*this); + case HALLOWED_GROUND: + return hallowed_ground_update(*this); + case MY_SHADOW: + return my_shadow_update(*this); + case BLOOD_OATH: + return ai_blood_oath(); + case LOST_SOUL: + return lost_soul_update(*this); + case PASCHAL_CANDLE: + return paschal_candle_update(*this); + case SPIN_TO_WIN: + return spin_to_win_update(*this); + case BONE_SPUR: + return bone_spur_update(*this); + case TWISTED_BABY: + return twisted_baby_update(*this); + case STITCHES: + return ai_stitches(); + case MYSTERY_EGG: + return mystery_egg_update(*this); + case ESAU_JR: + return esau_jr_update(*this); + case SPRINKLER: + return sprinkler_update(*this); + case DIP: + return zhl_misfit_006414c0(); + case CUBE_BABY: + return cube_baby_update(*this); + case BLOOD_PUPPY: + return blood_puppy_update(*this); + case FRUITY_PLUM: + return fruity_plum_update(*this); default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); } } @@ -907,9 +1018,9 @@ void Entity_Familiar::Interpolate() orbitAngleOffset = savedAngle; } -// 00624e10 Draws a familiar with its charge bar. The familiars drawn their own way (Isaac's body, Samson's chains, the -// locusts, the co-op babies) and Tainted Lazarus's hologram stop the game. Gello draws its cord first, and an item wisp -// shows its item's icon. +// 00624e10 Draws a familiar with its charge bar. Isaac's body draws its parts, a detached head its player's head, Gello +// its cord first, Samson's Chains and Gemini hang their links, and an item wisp shows its item's icon. The familiars +// drawn their own way (the locusts, the co-op babies) and Tainted Lazarus's hologram stop the game. void Entity_Familiar::Render(const Vector& offset) { if (IsLilithBirthrightIncubus()) @@ -922,9 +1033,13 @@ void Entity_Familiar::Render(const Vector& offset) if (familiar_listed(UNWRITTEN_RENDER_VARIANTS, variant)) return reconstruction_missing("Entity_Familiar::Render 00624e10 (this familiar's drawing)"); + if (variant == SAMSONS_CHAINS) samsons_chains_links_place(*this); + else if (variant == GEMINI) gemini_cord_place(*this); ColorMod saved = sprite.color; if (variant == UMBILICAL_BABY) umbilical_baby_render(*this, offset); - else Entity::Render(offset); + else if (variant == GUILLOTINE || variant == SCISSORS || variant == DECAP_ATTACK) + detached_head_render(*this, offset); + else if (variant != ISAACS_BODY || !isaacs_body_render(*this, offset)) Entity::Render(offset); if (variant == ITEM_WISP) item_wisp_icon_render(*this); lua_engine_get().PostFamiliarRender(this, offset); render_charge_indicator(renderPosition); @@ -1003,7 +1118,8 @@ void Entity_Familiar::render_charge_indicator(const Vector& renderPos) bar.Render({.position = vector_add(renderPos, vector_make(CHARGE_BAR_OFFSET_X, CHARGE_BAR_OFFSET_Y))}); } -// 00610470 Removes it, leaving its orbit and lines, and its player's counts of blue flies and spiders. +// 00610470 Removes it, leaving its orbit and lines, and its player's counts of blue flies and spiders. A detached head +// sends its player's tears from the player again. void Entity_Familiar::Remove() { Entity::Remove(); @@ -1012,8 +1128,7 @@ void Entity_Familiar::Remove() RemoveFromDelayed(); if (variant == BLUE_FLY && subtype == 0) player->numBlueFlies--; else if (variant == BLUE_SPIDER) player->numBlueSpiders--; - if (variant == GUILLOTINE || variant == SCISSORS || variant == DECAP_ATTACK) - reconstruction_missing("Entity_Familiar::Remove 00610470 (the player's detached head)"); + if (variant == GUILLOTINE || variant == SCISSORS || variant == DECAP_ATTACK) player->tearsOffset = {}; ResolveOrbitConflict(); } @@ -1072,15 +1187,14 @@ int Entity_Familiar::overwrite_limit() } } -// 0060d6a0 How often its hit list resets, letting it hit an enemy again: its config's interval, eight frames while -// spinning, two for the Lemegeton wisp that never blocks, never for Gello, and longer ones in a versus match. Locusts, -// Blood Babies and Decap Attack's head stop the game. +// 0060d6a0 How often its hit list resets, letting it hit an enemy again: its config's interval (a locust's own +// config's), eight frames while spinning, two for the Lemegeton wisp that never blocks, and longer ones in a versus +// match. Gello, a bursting Blood Baby and Decap Attack's head while thrown or held never reset it. int Entity_Familiar::hit_list_interval() { - if (variant == ABYSS_LOCUST || variant == BLOOD_BABY || variant == DECAP_ATTACK) - reconstruction_missing("Entity_Familiar::hit_list_interval 0060d6a0 (this " - "familiar's interval)"); - if (variant == UMBILICAL_BABY) return 0; + if (variant == ABYSS_LOCUST) return ItemConfig::locust_config_get(subtype, coins)->collisionInterval; + if (variant == UMBILICAL_BABY || (variant == BLOOD_BABY && state >= 2)) return 0; + if (variant == DECAP_ATTACK && (state > 0 || HasEntityFlags(FLAG_THROWN))) return 0; int interval = (int)config->collisionInterval; if (orbitLayer >= 0 && HasEntityFlags(FLAG_SPIN)) interval = SPIN_HIT_INTERVAL; diff --git a/src/entity_familiar.h b/src/entity_familiar.h index b40979b..237be46 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -61,6 +61,10 @@ constexpr int WISP_PRIORITY_NONE = 9999; // The formation slot of a familiar outside any. constexpr uint8_t FORMATION_NONE = 0xff; +// How many of its leader's past positions a delayed familiar keeps, and how far behind most trail. +constexpr size_t MOVE_HISTORY_SIZE = 60; +constexpr int DELAYED_FOLLOW_FRAMES = 20; + // A target search (PickEnemyTarget's arguments): how far, how often, how it ranks the enemies, and an optional cone. struct TargetSearch { @@ -105,6 +109,7 @@ struct Entity_Familiar : Entity KEY_PIECE_1 = 26, KEY_PIECE_2 = 27, KEY_FULL = 28, + GUARDIAN_ANGEL = 32, FLY_ORBITAL = 33, SACRIFICIAL_DAGGER = 35, DEAD_CAT = 40, @@ -141,7 +146,9 @@ struct Entity_Familiar : Entity MONGO_BABY = 74, SAMSONS_CHAINS = 75, CAINS_OTHER_EYE = 76, + BLUE_BABYS_ONLY_FRIEND = 77, SCISSORS = 78, + GEMINI = 79, INCUBUS = 80, FATES_REWARD = 81, LIL_CHEST = 82, @@ -171,6 +178,7 @@ struct Entity_Familiar : Entity HUSHY = 107, LIL_MONSTRO = 108, KING_BABY = 109, + FINGER = 110, YO_LISTEN = 111, ACID_BABY = 112, SPIDER_BABY = 113, @@ -189,12 +197,14 @@ struct Entity_Familiar : Entity BONE_ORBITAL = 128, HALLOWED_GROUND = 129, JAW_BONE = 130, + ANGELIC_PRISM = 123, MY_SHADOW = 131, INTRUDER = 200, DIP = 201, DAMOCLES = 202, BLOOD_OATH = 203, PSY_FLY = 204, + MENORAH = 205, WISP = 206, PEEPER_2 = 207, BOILED_BABY = 208, @@ -204,18 +214,24 @@ struct Entity_Familiar : Entity LIL_DUMPY = 212, KNIFE_PIECE_1 = 213, KNIFE_PIECE_2 = 214, + KNIFE_PIECE_3 = 215, TINYTOMA = 216, + TINYTOMA_2 = 217, BOT_FLY = 218, + SIREN_MINION = 220, PASCHAL_CANDLE = 221, STITCHES = 222, KNIFE_FULL = 223, BABY_PLUM = 224, FRUITY_PLUM = 225, + SPIN_TO_WIN = 226, + BETHS_HEART = 227, MINISAAC = 228, SWARM_FLY_ORBITAL = 229, LIL_ABADDON = 230, ABYSS_LOCUST = 231, LIL_PORTAL = 232, + WORM_FRIEND = 233, BONE_SPUR = 234, TWISTED_BABY = 235, STAR_OF_BETHLEHEM = 236, @@ -226,6 +242,7 @@ struct Entity_Familiar : Entity BLOOD_PUPPY = 241, VANISHING_TWIN = 242, DECAP_ATTACK = 243, + ESAU_JR = 244, FORGOTTEN_BODY = 900 }; @@ -240,6 +257,7 @@ struct Entity_Familiar : Entity std::map targetFrames; std::unique_ptr extraData; std::vector hitList; + std::array moveHistory{}; ColorMod dirtColor = COLOR_DEFAULT; EntityPtr linkedEntity; EntityPtr sirenHelper; @@ -314,7 +332,6 @@ struct Entity_Familiar : Entity void ai_mr_me_wisp(); void ai_mega_blast_wisp(); static int GetRandomWisp(RNG* rng); - void ai_buddy_inbox(); KColor* GetPlayerSlot(KColor* outColor, Entity_Player* player); bool CanBeDamagedByEnemy(); bool CanBlockProjectiles(); @@ -438,6 +455,19 @@ private: bool solid_check(Entity& collider, bool isIgnored); }; +// The body parts Isaac's body (Pinking Shears) draws: the player's body, its two body layers and the top layer. +constexpr int BODY_PART_COUNT = 4; + +// Destruction (0060d530) is the default. +// Isaac's body's extra data: the blood gush on its neck, and a copy of the sprite drawing each body part (the player's +// own or the costume covering it) with the layer it draws, -1 for none. +struct IsaacsBodyData : Entity_Familiar::ExtraData +{ + ANM2 bloodGush; + std::array parts; + std::array partLayers{-1, -1, -1, -1}; +}; + // How many of a familiar a player should have (Entity_Player::CheckFamiliar's arguments): the item behind them and the // generator their spawns draw from, a subtype of -1 counting every subtype. struct FamiliarCount @@ -464,6 +494,33 @@ Entity* spawn_dip_at(int subType, const Vector* position, Entity* spawner, const float angle_wrap(float angle); Vector direction_unit(int direction); +// Isaac's body and the player's detached head (Guillotine, Scissors, Decap Attack) (familiar_body.cpp). +void isaacs_body_init(Entity_Familiar& body); +void isaacs_body_update(Entity_Familiar& body); +bool isaacs_body_render(Entity_Familiar& body, const Vector& offset); +void detached_head_update(Entity_Familiar& head); +void detached_head_render(Entity_Familiar& head, const Vector& offset); + +// The variant behaviours of Update written as their own functions (familiar_update.cpp). +void brown_nugget_update(Entity_Familiar& fly); +void charged_baby_update(Entity_Familiar& baby); +void lost_fly_update(Entity_Familiar& fly); +void milk_update(Entity_Familiar& milk); +void shade_update(Entity_Familiar& shade); +void hushy_update(Entity_Familiar& hushy); +void king_baby_update(Entity_Familiar& king); +void finger_update(Entity_Familiar& finger); +void farting_baby_update(Entity_Familiar& baby); +void succubus_update(Entity_Familiar& succubus); +void bloodshot_eye_update(Entity_Familiar& eye); +void spider_update(Entity_Familiar& spider); +void samsons_chains_links_place(Entity_Familiar& ball); +void gemini_update(Entity_Familiar& gemini); +void gemini_cord_place(Entity_Familiar& gemini); +void sissy_longlegs_update(Entity_Familiar& sissy); +void punching_bag_update(Entity_Familiar& bag); +void censer_update(Entity_Familiar& censer); + // The wisps' shared parts of the familiar's animations, hits, touches and death (familiar_wisp.cpp). void wisp_anim_play(Entity_Familiar& wisp, std::string_view name); int wisp_hit_countdown(int damageCountdown); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 480d9fb..ab06fb2 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -242,14 +242,6 @@ static Vector knife_path_point(const BezierPoint& start, const BezierPoint& end, b0 * start.point.y + b1 * start.handleOut.y + b2 * end.handleIn.y + b3 * end.point.y); } -// Turns a vector by an angle in degrees. -static Vector vector_rotated(Vector v, float degrees) -{ - float c = std::cos(degrees * DEGREES_TO_RADIANS); - float s = std::sin(degrees * DEGREES_TO_RADIANS); - return vector_make(v.x * c - v.y * s, v.x * s + v.y * c); -} - // Whether the knife's holder still has the weapon the knife belongs to. Abyss's knife locust is not reconstructed yet. static bool is_owner_armed(Entity* owner, WeaponType weaponType) { diff --git a/src/entity_knife_hits.cpp b/src/entity_knife_hits.cpp index 56bae35..7c44d5f 100644 --- a/src/entity_knife_hits.cpp +++ b/src/entity_knife_hits.cpp @@ -34,6 +34,11 @@ constexpr float BAG_KNOCKBACK = 36; constexpr float KNOCKBACK_SHARE = 3; constexpr float RECOIL = 4; constexpr float SWING_KNOCKBACK_MASS = 50; +constexpr float AXE_KNOCKBACK_LIGHT_MASS = 10; +constexpr float AXE_KNOCKBACK_MASS_RANGE = 70; +constexpr float AXE_KNOCKBACK_MOST_FRAMES = 20; +constexpr float AXE_KNOCKBACK_FRAME_SPAN = 19; +constexpr float AXE_KNOCKBACK_SPEED = 16; // A swing's damage by weapon, and the sword's own (a spin's, and the touch of an idle sword's wider hit box). constexpr float CLUB_DAMAGE = 3; @@ -504,7 +509,13 @@ static bool swing_enemy_hit(Entity_Knife& knife, Entity& enemy, SwingHit& hit) float strength = hit.knockback * SWING_KNOCKBACK_MASS / (enemy.mass + SWING_KNOCKBACK_MASS); if (enemy.friction != 0) enemy.velocity = vector_add(enemy.velocity, vector_scale(away, enemy.speedMultiplier * strength / enemy.friction)); - if (isEmpowered) reconstruction_missing("Entity_Knife::UpdateSwingHits 009688d0 (Entity::AddKnockback)"); + if (isEmpowered) + { + float heaviness = + std::clamp((enemy.mass - AXE_KNOCKBACK_LIGHT_MASS) / AXE_KNOCKBACK_MASS_RANGE, 0.0f, 1.0f); + int frames = (int)std::floor(AXE_KNOCKBACK_MOST_FRAMES - heaviness * AXE_KNOCKBACK_FRAME_SPAN); + enemy.AddKnockback(EntityRef(hit.player), vector_scale(away, AXE_KNOCKBACK_SPEED), frames, true); + } } uint64_t damageFlags = swing_damage_flags(knife, enemy, hit.player); diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index c0b1762..1e538b1 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -1,9 +1,11 @@ #include "entity_npc.h" +#include "active_items.h" #include "boss_ai.h" #include "boss_death.h" #include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" +#include "entity_factory.h" #include "entity_familiar.h" #include "entity_laser.h" #include "entity_pickup.h" @@ -13,6 +15,7 @@ #include "game.h" #include "grid_entity.h" #include "log.h" +#include "lua_engine.h" #include "manager.h" #include "npc_ai.h" #include "npc_basement.h" @@ -23,6 +26,7 @@ #include "room_descriptor.h" #include "room_grid.h" #include "sfx_manager.h" +#include "menu_manager.h" #include "mines.h" #include "npc_alt.h" #include @@ -40,7 +44,6 @@ constexpr uint32_t DOPLE_PICK_SHIFT = 11; constexpr int ENTITY_UNREACHABLE_EXEMPT = 886; constexpr int ENTITY_DEATH_SPARK_TYPE = 882; constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964; -constexpr int ENTITY_ERASE_EXEMPT = 950; constexpr int APPEAR_OVERLAY_KEPT_TYPE = 266; constexpr float BIG_HORN_APPEAR_VOLUME = 2; constexpr std::array APPEAR_EVENT_TYPES = {404, 912, 913, 917}; @@ -92,6 +95,12 @@ constexpr float MIDAS_COIN_SPEED = 3; constexpr float TOXIC_CREEP_SCALE = 0.05f; constexpr int TOXIC_SHOCK_POISON = -40; constexpr int MODEM_FRAMES = 50; +constexpr int MODEM_ODDS = 55; +constexpr int MODEM_MIN_ODDS = 38; +constexpr int SLOWED_TIME_COLOR_PRIORITY = 250; +constexpr ColorMod GAME_KID_COLOR = {{0.3f, 0.5f, 1.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SLOWED_TIME_COLOR = { + {1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 * COLOR_OFFSET_UNIT, 40 * COLOR_OFFSET_UNIT, 40 * COLOR_OFFSET_UNIT}}; constexpr int PUPPY_HIT_FRAMES = 3; constexpr int FORCED_TARGET_BOSS_COOLDOWN = 150; constexpr int CONFUSION_RETARGET_FRAMES = 15; @@ -154,7 +163,6 @@ enum DeathBurst : int }; constexpr int ENTITY_SIREN_HELPER = 966; -constexpr int ENTITY_EXORCIST = 832; constexpr int ENTITY_SHADOW_CHARGER = 23; constexpr int ENTITY_ULTRA_GREED_DOOR = 889; constexpr int SUCKER_VARIANT_BULB = 5; @@ -208,14 +216,9 @@ constexpr float CHAMPION_CHANCE_LATE_SPAWN = 0.2f; constexpr float CHAMPION_CHANCE_VICTORY_LAP = 0.25f; constexpr float CHAMPION_CHANCE_PURPLE_HEART = 3; -// What a layer's bitflags say about it: drawn in the floor's dirt color, and wearing its champion sheet. -constexpr unsigned int LAYER_DIRT_COLORED = 1 << 0; -constexpr unsigned int LAYER_CHAMPION_SHEET = 1 << 4; -constexpr unsigned int SPRITE_UNKNOWN_FLAG_20 = 1 << 5; constexpr unsigned int STATUS_SHARED = 1u << 31; -constexpr int TYPE_SPRITE_FLAG_A = 950; -constexpr int TYPE_SPRITE_FLAG_B = 960; -constexpr int VARIANT_SPRITE_FLAG_B = 4; +// Dogma and the generic prop's TV (960.4) draw with the static shader. +constexpr int GENERIC_PROP_TV = 4; constexpr std::string_view STATUS_EFFECTS_ANM2 = "gfx/StatusEffects.anm2"; // The target search: how far enemies look for players, and what pushes a player back or pulls a twin forward. @@ -353,6 +356,26 @@ Entity_Player* game_nearest_player(const Vector& position) return nearest; } +// (00703ab0) Game::GetNearestPlayerEx for the main players only: the nearest player itself (not a co-op ghost, baby, +// twin's hold or hologram) that collides with entities. +Entity_Player* main_player_nearest(const Vector& position) +{ + Entity_Player* nearest = nullptr; + float best = 1e10f; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = vector_length_squared(vector_sub(position, player->pos)); + if (distance >= best) continue; + if (player->variant != 0 || player->isCoopGhost || player->parent || player->IsHologram()) continue; + if (player->entityCollisionClass == ENTCOLL_NONE) continue; + + nearest = player; + best = distance; + } + return nearest; +} + // The charge Bulb drains a player for: one per full active, else its charges. static int active_charges_get(Entity_Player& player) { @@ -612,7 +635,7 @@ void Entity_NPC::Init(int entityType, int entityVariant, int entitySubType, uint isDeathSoundAlt = false; aiCallFlags = 0; controllerID = -1; - unknownF2c = 0; + isControlSwapped = false; controllerMovement = {}; aimTargetEffect = nullptr; forwardVector = {}; @@ -829,23 +852,24 @@ void Entity_NPC::load_graphics(bool isReloadAnm2) std::string name = layer.layerData ? layer.layerData->name : ""; if (name == DIRT_LAYER || name == HOLE_LAYER) { - layer.bitflags |= LAYER_DIRT_COLORED; + layer.bitflags |= ANIM_RENDER_UNTINTED; isDirtUsed = true; } - if (name == HOLE2_LAYER) layer.bitflags |= LAYER_DIRT_COLORED; + if (name == HOLE2_LAYER) layer.bitflags |= ANIM_RENDER_UNTINTED; bool isChampionSheet = false; std::string sheet = layer.layerData ? layer.layerData->spriteSheetPath : ""; sprite.ReplaceSpritesheet(i, sheet_path_resolve(sheet, floorSuffix, championSuffix, isChampionSheet)); LayerState& replaced = sprite.layerStates[i]; - replaced.bitflags = - isChampionSheet ? replaced.bitflags | LAYER_CHAMPION_SHEET : replaced.bitflags & ~LAYER_CHAMPION_SHEET; + replaced.bitflags &= ~ANIM_RENDER_COLOROFFSET_CHAMPION; + if (isChampionSheet) replaced.bitflags |= ANIM_RENDER_COLOROFFSET_CHAMPION; isChampionSheetUsed = isChampionSheetUsed || isChampionSheet; } sprite.championColor = isChampionSheetUsed && championLook ? *championLook : ColorMod{}; - bool isFlagged = type == TYPE_SPRITE_FLAG_A || (type == TYPE_SPRITE_FLAG_B && variant == VARIANT_SPRITE_FLAG_B); - sprite.bitflags = isFlagged ? sprite.bitflags | SPRITE_UNKNOWN_FLAG_20 : sprite.bitflags & ~SPRITE_UNKNOWN_FLAG_20; + bool isStatic = type == ENTITY_DOGMA || (type == ENTITY_GENERIC_PROP && variant == GENERIC_PROP_TV); + sprite.bitflags &= ~ANIM_RENDER_STATIC; + if (isStatic) sprite.bitflags |= ANIM_RENDER_STATIC; sprite.LoadGraphics(); if (isDirtUsed) UpdateDirtColor(true); } @@ -1059,15 +1083,7 @@ void Entity_NPC::Morph(int entityType, int entityVariant, int entitySubType, int pathfinder.Reset(); g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant); isBestiaryEncountered = true; - if (game_is_enemy_erased(*this)) Entity::RemoveWithPoof(this); -} - -// 007078f0 Whether the run erased this kind of enemy (Eraser). A friendly enemy is never erased. -bool game_is_enemy_erased(Entity& entity) -{ - if (entity.type == ENTITY_ERASE_EXEMPT || (Entity::is_enemy_type(entity.type) && entity.IsFriendly())) return false; - if (g_game->erasedEntities.empty()) return false; - reconstruction_missing("Game::ShouldEraseEnemy 007078f0: FixErasedEnemyID"); + if (entity_is_erased(*this)) Entity::RemoveWithPoof(this); } // 006c4ac0 Remembers where it was, and keeps the Exorcist's room in its state while it lives. @@ -1605,27 +1621,53 @@ void Entity_NPC::item_effects_update() Entity_Player* targetPlayer = GetPlayerTarget()->ToPlayer(); if (targetPlayer && targetPlayer->IsInvisible()) AddConfusion(EntityRef(this), STATUS_REFRESH, false); if (players.FirstCollectibleOwner(COLLECTIBLE_BROKEN_MODEM_ID, LAZARUS_SHARE_IGNORE)) - reconstruction_missing("Entity_NPC::Update 006c4b30: Broken Modem's stalls"); + { + int odds = std::max(MODEM_MIN_ODDS, MODEM_ODDS - (int)players.get_total_luck()); + odds *= IsBoss() ? 3 : 2; + if (IsVulnerableEnemy(nullptr) && random_below(odds) == 0 && !isDead) + { + Entity& head = *GetStatusEffectTarget(); + head.AddEntityFlags(FLAG_FREEZE); + head.CopyStatusEffects(); + } + } if (IsActiveEnemy(DEAD_EXCLUDED) && HasEntityFlags(FLAG_FREEZE) && freezeCountdown < 1 && IsFrame(MODEM_FRAMES, 0)) - reconstruction_missing("Entity_NPC::Update 006c4b30: Broken Modem's release"); + modem_release(); - if (!HasEntityFlags(FLAG_NO_TARGET)) - for (Entity_Player* player : players.playerList) - if (player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_GAMEKID_ID)) - reconstruction_missing("Entity_NPC::Update 006c4b30: Game Kid's fear"); + if (!HasEntityFlags(FLAG_NO_TARGET) && std::ranges::any_of(players.playerList, [](Entity_Player* player) { + return player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_GAMEKID_ID); + })) + { + SetColor(GAME_KID_COLOR, 2, 0, false, true); + AddFear(EntityRef(this), STATUS_REFRESH, false); + } TemporaryEffects& roomEffects = g_game->room->temporaryEffects; bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) || roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) || g_game->room->GetBrokenWatchState() == BROKEN_WATCH_SLOW; - bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD; - if (isTimeSlowed && !isTimeImmune) reconstruction_missing("Entity_NPC::Update 006c4b30: the slowed time tint"); + bool isTimeImmune = HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS) && type != ENTITY_DEATHS_HEAD; + if (isTimeSlowed && !isTimeImmune) SetColor(SLOWED_TIME_COLOR, 2, SLOWED_TIME_COLOR_PRIORITY, false, true); } -// How much of a per-tick factor is left over a step of timeScale ticks (Math::timescale_factor). -static float timescale_factor(float factor, float timeScale) +// Part of 006c4b30: Broken Modem lets a stalled enemy go, and a moving one skips seven units each way at random, kept +// in the room when it was in it. +void Entity_NPC::modem_release() { - return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale); + constexpr float MODEM_SKIP_STEP = 14; + constexpr float MODEM_SKIP_OFFSET = 21; + Entity& head = *GetStatusEffectTarget(); + head.ClearEntityFlags(FLAG_FREEZE); + head.CopyStatusEffects(); + if (vector_is_zero(velocity)) return; + + float skipX = (float)(Random() % 2 + 1) * MODEM_SKIP_STEP - MODEM_SKIP_OFFSET; + float skipY = (float)(Random() % 2 + 1) * MODEM_SKIP_STEP - MODEM_SKIP_OFFSET; + Room& room = *g_game->room; + Vector clamped = room.GetClampedPosition(pos, 0); + bool isInRoom = clamped.x == pos.x && clamped.y == pos.y; + pos = vector_add(pos, vector_make(skipX, skipY)); + if (isInRoom) pos = room.GetClampedPosition(pos, 0); } // Part of 006c4b30: a poof02 event puffs half-faded smoke at the NPC, placed and sized (a third) by the null of that @@ -1929,8 +1971,9 @@ void Entity_NPC::ResetColor() { if (isChampion) { - bool isChampionSheet = std::ranges::any_of(sprite.layerStates, [](const LayerState& layer) - { return layer.bitflags & LAYER_CHAMPION_SHEET; }); + bool isChampionSheet = std::ranges::any_of(sprite.layerStates, [](const LayerState& layer) { + return layer.bitflags & ANIM_RENDER_COLOROFFSET_CHAMPION; + }); if (championColorIdx >= 0 && championColorIdx < CHAMPION_COUNT) sprite.color = isChampionSheet ? champion_look_get(championColorIdx).spriteColor : champion_sprite_color_get(championColorIdx); @@ -2196,9 +2239,9 @@ static void fan_velocities_add(std::vector& shots, Vector velocity, floa } // 006cb2e0 Shoots projectiles of params' variant from a position in a mode's spread, then applies params to each: -// the fans also fall at once and take on part of its motion unless params keeps their fall. -void Entity_NPC::FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, - const ProjectileParams& params) +// the fans also fall at once and take on part of its motion unless params keeps their fall. The first shot, if any. +Entity_Projectile* Entity_NPC::fire_projectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, + const ProjectileParams& params) { std::vector shots; float speed = velocity.x; @@ -2287,6 +2330,14 @@ void Entity_NPC::FireProjectiles(const Vector& position, const Vector& velocity, } for (Entity_Projectile* projectile : projectiles) projectile_params_apply(*projectile, params); for (Entity_Projectile* projectile : projectiles) fire_projectile_from_params(projectile); + return projectiles.empty() ? nullptr : projectiles.front(); +} + +// FireProjectiles as the AIs call it, the shot left unused. +void Entity_NPC::FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, + const ProjectileParams& params) +{ + fire_projectiles(position, velocity, mode, params); } // Part of 006cb2e0: what params set on a shot fired. @@ -2600,33 +2651,96 @@ void Entity_NPC::hold_set(int countdown, const Vector& position) holdPosition = position; } -// 006d8260 Whether the controlling player holds an action, never without one. -bool Entity_NPC::IsControllerActionPressed(int) +// 009562d0 How far an action is pushed on a controller, or on the first device pushing it for -1, through the key +// configs. In a run a mod may answer first through MC_INPUT_ACTION. Netplay's remote devices are offline. +float input_action_value_get(ButtonAction action, int controllerIndex, Entity* entity) { - if (controllerID == -1) return false; - reconstruction_missing("Entity_NPC::IsControllerActionPressed 006d8260"); + if (g_manager->state == MANAGER_STATE_GAME && g_luaEngine) + if (std::optional modValue = lua_engine_get().InputActionValue(entity, action)) return *modValue; + + KAGE::Input::Manager& input = KAGE::Input::manager; + for (int i = 0; i < input.get_device_count(); i++) + { + std::shared_ptr device = input.get_device(i); + if (!device || !device->isConnected || (controllerIndex != -1 && device->id != controllerIndex)) continue; + + float value = 0; + for (int button : g_manager->keyConfigs.binding_get(*device, action)) + if (button != KAGE::Input::BUTTON_NONE) value = std::max(value, device->button_value(button)); + if (value != 0) return value; + } + return 0; +} + +// The controlling player's movement actions (or its shooting ones) as a vector, read left, right, up, then down. +static Vector controller_axes_get(Entity_NPC& npc, ButtonAction leftAction) +{ + float left = input_action_value_get(leftAction, npc.controllerID, &npc); + float right = input_action_value_get((ButtonAction)(leftAction + 1), npc.controllerID, &npc); + float up = input_action_value_get((ButtonAction)(leftAction + 2), npc.controllerID, &npc); + float down = input_action_value_get((ButtonAction)(leftAction + 3), npc.controllerID, &npc); + return vector_make(right - left, down - up); +} + +// Finishes a controlling player's input: snapped to its main axis under the axis aligned seed, none below the +// deadzone, at most 1 long, and mirrored in the mirror world. +static Vector controller_input_finish(Vector input, float deadzone) +{ + Game& game = *g_game; + if (game.seedEffects.HasSeedEffect(SEED_AXIS_ALIGNED_CONTROLS)) + input = vector_scale(vector_cardinal(input), vector_length(input)); + + float length = vector_length(input); + if (deadzone > 0 && length < deadzone) return {}; + if (length > 1) input = vector_make(input.x / length, input.y / length); + + bool isAltStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + bool isMirrored = game.stage == 2 || (game.stage == 1 && (game.GetCurses() & CURSE_OF_LABYRINTH)); + if (game.currentDimensionIdx == 1 && isAltStage && isMirrored) input.x = -input.x; + return input; +} + +// 006d8260 Whether the controlling player holds an action, never without one. +bool Entity_NPC::IsControllerActionPressed(int action) +{ + return controllerID != -1 && input_is_action_pressed((ButtonAction)action, controllerID, this); } // 006d8290 Whether the controlling player pressed an action this frame, never without one. bool Entity_NPC::IsControllerActionTriggered(int buttonAction) { - if (controllerID == -1) return false; - (void)buttonAction; - reconstruction_missing("Entity_NPC::IsControllerActionTriggered 006d8290"); + return controllerID != -1 && input_is_action_triggered((ButtonAction)buttonAction, controllerID, this); } -// 006d82d0 The controlling player's shooting input, none without one. -Vector Entity_NPC::GetControllerInput(float) +// 006d82d0 The controlling player's walking input (its shooting one when the controls are swapped), reversed by the +// reversed controls seed. None without a player or below the deadzone. +Vector Entity_NPC::GetControllerInput(float deadzone) { if (controllerID == -1) return {}; - reconstruction_missing("Entity_NPC::GetControllerInput 006d82d0"); + + Vector input = controller_axes_get(*this, isControlSwapped ? ACTION_SHOOT_LEFT : ACTION_LEFT); + if (g_game->seedEffects.HasSeedEffect(SEED_CONTROLS_REVERSED)) input = vector_make(-input.x, -input.y); + return controller_input_finish(input, deadzone); } -// 006d85a0 The controlling player's movement input, none without one. -Vector Entity_NPC::GetControllerMovementInput(float) +// 006d85a0 The controlling player's shooting input (its walking one when the controls are swapped), or its walking +// input under the seeds that shoot with movement, reversed by the reversed controls seed. None without a player or +// below the deadzone. +Vector Entity_NPC::GetControllerMovementInput(float deadzone) { if (controllerID == -1) return {}; - reconstruction_missing("Entity_NPC::GetControllerMovementInput 006d85a0"); + + Seeds& seeds = g_game->seedEffects; + Vector input{}; + if (seeds.HasSeedEffect(SEED_SHOOT_IN_MOVEMENT_DIRECTION)) input = GetControllerInput(0); + else if (seeds.HasSeedEffect(SEED_SHOOT_OPPOSITE_MOVEMENT_DIRECTION)) + input = vector_scale(GetControllerInput(0), -1); + else + { + input = controller_axes_get(*this, isControlSwapped ? ACTION_LEFT : ACTION_SHOOT_LEFT); + if (seeds.HasSeedEffect(SEED_CONTROLS_REVERSED)) input = vector_make(-input.x, -input.y); + } + return controller_input_finish(input, deadzone); } // 006d9050 Keeps the controlling player's last movement, or none without one. @@ -2826,9 +2940,3 @@ void Entity_NPC::UpdatePickupGhosts() if (pickupGhostsEntity) pickupGhostsEntity->Remove(); } - -// 009a8b90 -void Entity_NPC::render_debug(float*, int) -{ - reconstruction_missing("Entity_NPC::render_debug 009a8b90"); -} diff --git a/src/entity_npc.h b/src/entity_npc.h index 36f7434..0b07654 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -212,7 +212,6 @@ struct Entity_NPC : Entity int shieldFrames = 0; int state = NPC_STATE_INIT; int stateFrame = 0; - int unknownF2c = 0; uint32_t aiCallFlags = 0; uint32_t deliriumBossType = 0; uint32_t deliriumBossVariant = 0; @@ -239,6 +238,7 @@ struct Entity_NPC : Entity bool isCanShutDoors = false; bool isChampion = false; bool isCollisionIsLow = false; + bool isControlSwapped = false; bool isDeathSoundAlt = false; bool isUnknownC61 = false; bool isUnknownC62 = false; @@ -295,6 +295,7 @@ struct Entity_NPC : Entity void toxic_shock_creep_spawn(); void player_aura_update(); void item_effects_update(); + void modem_release(); void poof02_spawn(); void ripple_spawn(); void seed_effects_update(); @@ -321,6 +322,8 @@ 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); + Entity_Projectile* fire_projectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, + 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); @@ -378,7 +381,6 @@ struct Entity_NPC : Entity static Entity_NPC* ThrowStrider(const Vector& pos, Entity* spawner, const Vector& targetPos); static void* QueryNPCsType(void* outList, int type, int variant); static std::vector QueryNPCsGroup(int groupIdx); - static void render_debug(float* position, int unused); }; extern bool g_isChampionRollSkipped; @@ -397,8 +399,8 @@ constexpr int LINE_CHECK_THRESHOLD = 999; // Game's, Room's and PlayerManager's queries the enemies need, until those classes carry them. Entity_Player* game_nearest_player(const Vector& position); +Entity_Player* main_player_nearest(const Vector& position); Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius); -bool game_is_enemy_erased(Entity& entity); bool any_player_flying(); Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys, float maxDistance); diff --git a/src/entity_npc_boss.cpp b/src/entity_npc_boss.cpp index f1af897..89704e1 100644 --- a/src/entity_npc_boss.cpp +++ b/src/entity_npc_boss.cpp @@ -248,7 +248,11 @@ void game_fart(const Fart& fart) 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 > 1) + entity->AddKnockback( + EntityRef(fart.source), + vector_scale(vector_normalized(vector_sub(entity->pos, fart.position)), GIGANTE_KNOCKBACK_SPEED), + GIGANTE_KNOCKBACK_FRAMES, false); if (multiplier > 2) entity->AddConfusion(EntityRef(fart.source), FART_CONFUSION_FRAMES, false); } diff --git a/src/entity_npc_champion.cpp b/src/entity_npc_champion.cpp index fa6e740..c219c98 100644 --- a/src/entity_npc_champion.cpp +++ b/src/entity_npc_champion.cpp @@ -606,7 +606,7 @@ static void pulse_champion_update(Entity_NPC& npc) npc.sprite.championColor = tint_color_make(sheet[0], sheet[1], sheet[2], 1 - slowPulse); if (npc.championColorIdx == CHAMPION_PULSE_GREY && slowPulse < PULSE_PUSH_END) - pulse_tears_push(npc, lerp_clamped(slowPulse, PULSE_PUSH_START, PULSE_PUSH_END, 1, 0)); + pulse_tears_push(npc, lerp_range(slowPulse, {PULSE_PUSH_START, PULSE_PUSH_END, 1, 0})); else if (npc.championColorIdx == CHAMPION_PULSE_RED && npc.IsFrame(PULSE_HEAL_FRAMES, (int)npc.index)) pulse_enemies_heal(npc); } diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp index 6171663..4620e7c 100644 --- a/src/entity_npc_render.cpp +++ b/src/entity_npc_render.cpp @@ -19,6 +19,24 @@ constexpr int NPC_DEBUG_HEALTH_FLAG = 1 << 6; constexpr int SPAWN_BAR_DELAY = 2; constexpr float HEALTH_BAR_DROP = 10; +// The health bar's sheet: left cap, stretched middle and right cap 8 high in the top row, the fill below the middle. +// Its width grows with the log of the NPC's toughness, from 8 to 48. The fill's hue runs from red (none left) to green, +// blue for the toughest, and greys a little away from green. +constexpr float HEALTH_BAR_CAP = 4; +constexpr float HEALTH_BAR_HEIGHT = 8; +constexpr float HEALTH_BAR_MIDDLE = 24; +constexpr float HEALTH_BAR_WIDTH_MIN = 8; +constexpr float HEALTH_BAR_WIDTH_MAX = 48; +constexpr float HEALTH_BAR_WIDTH_PER_DECADE = 24; +constexpr float HEALTH_BAR_STAGE_BASE = 6; +constexpr float HEALTH_BAR_TOUGH_STEPS = 5; +constexpr float HEALTH_BAR_HUE_GREEN = 120; +constexpr float HEALTH_BAR_HUE_TOUGH = 80; +constexpr float HEALTH_BAR_LOW = 0.2f; +constexpr float HEALTH_BAR_SPAN = 0.8f; +constexpr float HEALTH_BAR_SATURATION = 0.9f; +constexpr float HEALTH_BAR_SATURATION_GREY = 0.8f; + // The variants with their own height or drawing: Wormwood, Big Bony's bone, Singe's ball, the Ultra Greed coin // pile's statue, the Shell and Dogma's body. constexpr int WORMWOOD = 3; @@ -302,6 +320,45 @@ static bool npc_is_locally_controlled(Entity_NPC& npc) return npc.controllerID != -1 && (!netplay.is_online() || netplay.IsIdxLocalPlayer(npc.controllerID)); } +// 009a8b90 Draws the health bar over an NPC with the HUD's sheet, its toughness its max health against the stage's +// (twice the stage plus 6, an alternate floor counting one deeper). Like the original it leaves normal blending set. +static void health_bar_render(Entity_NPC& npc, const Vector& position) +{ + Game& game = *g_game; + KAGE::Graphics::ImageBase& image = *game.hud.spiderModHealthBarImage; + KColor white = kcolor_rgba(1, 1, 1, 1); + KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); + + bool isAltStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + float stage = (float)(game.stage + (isAltStage ? 1 : 0)); + float toughness = npc.maxHitPoints / (stage + stage + HEALTH_BAR_STAGE_BASE); + float width = std::floor((std::log10(toughness) + 1) * HEALTH_BAR_WIDTH_PER_DECADE + 0.5f); + width = std::clamp(width, HEALTH_BAR_WIDTH_MIN, HEALTH_BAR_WIDTH_MAX); + float left = position.x - width * 0.5f; + float top = position.y - HEALTH_BAR_CAP; + + auto piece = [&](Vector from, Vector size, Vector at, Vector drawn, const KColor& color) { + SourceQuad source = KAGE::Graphics::source_quad_rect(from, size); + image.Render(source, KAGE::Graphics::color_quad_rect(at, drawn, white), color); + }; + Vector capSize = vector_make(HEALTH_BAR_CAP, HEALTH_BAR_HEIGHT); + piece(vector_make(0, 0), capSize, vector_make(left - HEALTH_BAR_CAP, top), capSize, white); + Vector rightCap = vector_make(HEALTH_BAR_CAP + HEALTH_BAR_MIDDLE, 0); + piece(rightCap, capSize, vector_make(position.x + width * 0.5f, top), capSize, white); + piece(vector_make(HEALTH_BAR_CAP, 0), vector_make(HEALTH_BAR_MIDDLE, HEALTH_BAR_HEIGHT), vector_make(left, top), + vector_make(width, HEALTH_BAR_HEIGHT), white); + + float healthShare = npc.health / npc.maxHitPoints; + float hueTop = std::clamp((toughness - 1) / HEALTH_BAR_TOUGH_STEPS, 0.0f, 1.0f) * HEALTH_BAR_HUE_TOUGH; + float hueShare = std::clamp((healthShare - HEALTH_BAR_LOW) / HEALTH_BAR_SPAN, 0.0f, 1.0f); + float hue = (hueTop + HEALTH_BAR_HUE_GREEN) * hueShare; + float grey = std::clamp(std::abs(hue - HEALTH_BAR_HUE_GREEN) / HEALTH_BAR_HUE_GREEN, 0.0f, 1.0f); + float saturation = HEALTH_BAR_SATURATION - grey * (HEALTH_BAR_SATURATION - HEALTH_BAR_SATURATION_GREY); + piece(vector_make(HEALTH_BAR_CAP, HEALTH_BAR_HEIGHT), + vector_make(healthShare * HEALTH_BAR_MIDDLE, HEALTH_BAR_HEIGHT), vector_make(left, top), + vector_make(std::ceil(healthShare * width), HEALTH_BAR_HEIGHT), hsv_to_rgb(hue, saturation, 1, 1)); +} + // Whether a health bar shows over it: Spider Mod's over a hurtable enemy with its OverlayEffect null shown, or the bar // of a local player's controlled enemy. static bool npc_is_health_bar_shown(Entity_NPC& npc) @@ -389,10 +446,7 @@ void Entity_NPC::Render(const Vector& offset) if (type == ENTITY_DUMMY) reconstruction_missing("Entity_NPC::Render 006d2e50: the dummy's damage text"); status_overlay_render(base); if (npc_is_health_bar_shown(*this)) - { - float barPosition[2] = {renderPosition.x, renderPosition.y + HEALTH_BAR_DROP}; - render_debug(barPosition, 0); - } + health_bar_render(*this, vector_make(renderPosition.x, renderPosition.y + HEALTH_BAR_DROP)); } if (cart && isVisible) diff --git a/src/entity_npc_rewards.cpp b/src/entity_npc_rewards.cpp index f5e887b..7056a89 100644 --- a/src/entity_npc_rewards.cpp +++ b/src/entity_npc_rewards.cpp @@ -3,6 +3,7 @@ #include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_pickup.h" +#include "entity_tear.h" #include "entity_player.h" #include "item_config.h" #include "item_pool.h" @@ -48,6 +49,37 @@ constexpr float BONE_PARTICLE_SPEED_RANGE = 3; constexpr float BONE_BREAK_VOLUME = 0.7f; constexpr float BONE_BREAK_PITCH_RANGE = 0.2f; +// Hungry Soul's soul (one kill in three), Cricket's Leg's locusts (one kill in six per multiplier), Vasculitis's +// tears, Vade Retro's ghost, Quints' familiar and the Urn of Souls' souls. +constexpr std::array HUNGRY_SOUL_SHIFTS = {2, 7, 9}; +constexpr uint32_t HUNGRY_SOUL_SEED_SHIFT = 25; +constexpr uint32_t HUNGRY_SOUL_ODDS = 3; +constexpr float HUNGRY_SOUL_VOLUME = 0.7f; +constexpr float HUNGRY_SOUL_PITCH_RANGE = 0.4f; +constexpr uint32_t CRICKETS_LEG_ODDS = 6; +constexpr std::array VASCULITIS_SHIFTS = {2, 21, 9}; +constexpr float VASCULITIS_RANDOM_UNIT = 2.3283062e-10f; +constexpr float VASCULITIS_DAMAGE_STEP = 0.3f; +constexpr float VASCULITIS_DAMAGE_BASE = 3.2f; +constexpr int VASCULITIS_MAX_TEARS = 16; +constexpr float VASCULITIS_SPEED_MIN = 8; +constexpr float VASCULITIS_SPEED_RANGE = 4; +constexpr ColorMod VASCULITIS_TEAR_COLOR = {{2, 0, 0, 1}, {0, 0, 0, 0}, {0.2f, 0, 0}}; +constexpr float VADE_RETRO_SCALE_MIN = 0.9f; +constexpr float VADE_RETRO_SCALE_RANGE = 0.2f; +constexpr float VADE_RETRO_DAMAGE_BASE = 2.5f; +constexpr float VADE_RETRO_DAMAGE_STEP = 0.5f; +constexpr float VADE_RETRO_HEALTH_SHARE = 0.04f; +constexpr float VADE_RETRO_BOSS_SCALE = 1.5f; +constexpr float VADE_RETRO_CHAMPION_SCALE = 1.2f; +constexpr float VADE_RETRO_SPEED_SCALE = 20; +constexpr float VADE_RETRO_MAX_SPEED = 8; +constexpr std::array QUINTS_SHIFTS = {6, 3, 17}; +constexpr int QUINTS_SUBTYPE = 55555; +constexpr ColorMod QUINTS_POOF_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; +constexpr int URN_BOSS_SOULS = 8; +constexpr float URN_SOUL_SPREAD = 10; + // Cantripped: one kill in five drops a card. constexpr uint32_t CANTRIPPED_ODDS = 5; constexpr float CANTRIPPED_CARD_SPEED = 3; @@ -117,6 +149,223 @@ static void kill_flag_drops(Entity_NPC& npc) drop(PICKUP_TAROTCARD, ItemPool::GetCardEx((int)npc.dropRNG.Next(), 0, -1, 0, false)); } +// 007dc2d0 Cricket's Leg: a random locust thrown out of the player (a Conquest one comes as one to four), each running +// for six to ten frames. +void Entity_Player::SpawnTrinketRandomPickup() +{ + constexpr std::array LOCUSTS = {3, 2, 1, 4, 5}; + constexpr int LOCUST_CONQUEST = 5; + constexpr float LOCUST_SPREAD = 48; + constexpr float CRICKET_LOCUST_SPEED_MIN = 10; + constexpr float CRICKET_LOCUST_SPEED_RANGE = 4; + constexpr int LOCUST_STATE_MIN = 6; + constexpr uint32_t LOCUST_STATE_RANGE = 5; + RNG& rng = GetTrinketRNG(TRINKET_CRICKET_LEG); + int locust = LOCUSTS[rng.Next() % LOCUSTS.size()]; + int count = locust == LOCUST_CONQUEST ? (int)(rng.Next() & 3) + 1 : 1; + + for (int i = 0; i < count; i++) + { + auto* fly = static_cast(g_game->Spawn({.position = pos, + .spawner = this, + .subType = locust, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::BLUE_FLY, + .seed = Random()})); + fly->ClearEntityFlags(FLAG_APPEAR); + Vector away = vector_normalized(vector_sub(pos, fly->pos)); + float turn = (random_unit() * LOCUST_SPREAD - LOCUST_SPREAD / 2) * DEGREES_TO_RADIANS; + float cosine = std::cos(turn); + float sine = std::sin(turn); + float speed = random_unit() * CRICKET_LOCUST_SPEED_RANGE + CRICKET_LOCUST_SPEED_MIN; + fly->velocity = + vector_make((away.x * cosine - away.y * sine) * speed, (away.x * sine + away.y * cosine) * speed); + fly->state = (int)(Random() % LOCUST_STATE_RANGE) + LOCUST_STATE_MIN; + } +} + +// A Blood Puppy that killed an enemy eats it: healed by its health, chewing when biting, and the familiar it grew +// from gets coins (four for a boss). +static void blood_puppy_feed(Entity_NPC& npc, Entity* puppy) +{ + bool isVersusPlayer = g_game->deathmatchManager.is_active() && puppy && puppy->type == ENTITY_PLAYER; + if (!puppy || (!isVersusPlayer && !Entity::is_enemy_type(puppy->type))) return; + puppy->health = std::min(npc.maxHitPoints + puppy->health, puppy->maxHitPoints); + const AnimationData* animation = puppy->sprite.animState.animData; + if (static_cast(puppy)->state == NPC_STATE_ATTACK && animation && animation->isLooping) + npc_sound_play(SOUND_SMB_LARGE_CHEWS_4, 1, 2, 1); + Entity* parent = puppy->parent; + if (parent && parent->type == ENTITY_FAMILIAR) + static_cast(parent)->AddCoins(npc.IsBoss() ? BLOOD_PUPPY_BOSS_COINS : 1); +} + +// Hungry Soul's soul: one kill in three lets out a soul that bites for three seconds, with a cry. +static void hungry_soul_spawn(Entity_NPC& npc) +{ + constexpr int HUNGRY_SOUL_FRAMES = 180; + Entity_Player* owner = g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_HUNGRY_SOUL, npc.initSeed, nullptr); + RNG rng = {npc.initSeed, HUNGRY_SOUL_SHIFTS[0], HUNGRY_SOUL_SHIFTS[1], HUNGRY_SOUL_SHIFTS[2]}; + if (rng.Next() % HUNGRY_SOUL_ODDS != 0) return; + + npc_sound_play(SOUND_FLOATY_BABY_ROAR, HUNGRY_SOUL_VOLUME, 2, random_unit() * HUNGRY_SOUL_PITCH_RANGE + 2); + RNG seedRng = {npc.initSeed, HUNGRY_SOUL_SHIFTS[0], HUNGRY_SOUL_SHIFTS[1], HUNGRY_SOUL_SEED_SHIFT}; + auto* soul = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = owner, + .type = ENTITY_EFFECT, + .variant = EFFECT_HUNGRY_SOUL, + .seed = seedRng.Next()})); + soul->timeout = HUNGRY_SOUL_FRAMES; + soul->lifespan = HUNGRY_SOUL_FRAMES; + soul->Update(); +} + +// Vasculitis: the enemy bursts into one tear per few points of its health (up to sixteen), spread around it, carrying +// its status effects and red tinted. +static void vasculitis_tears_fire(Entity_NPC& npc) +{ + constexpr std::array, 8> STATUS_TEARS = {{{FLAG_SLOW, TEAR_SLOW}, + {FLAG_POISON, TEAR_POISON}, + {FLAG_FREEZE, TEAR_FREEZE}, + {FLAG_CHARM, TEAR_CHARM}, + {FLAG_CONFUSION, TEAR_CONFUSION}, + {FLAG_FEAR, TEAR_FEAR}, + {FLAG_BURN, TEAR_BURN}, + {FLAG_MAGNETIZED, TEAR_MAGNETIZE}}}; + float tearDamage = (float)g_game->stage * VASCULITIS_DAMAGE_STEP + VASCULITIS_DAMAGE_BASE; + int count = std::min((int)std::ceil(npc.maxHitPoints / tearDamage), VASCULITIS_MAX_TEARS); + float damage = std::max(npc.maxHitPoints / (float)count, tearDamage); + + TearFlags tearFlags; + for (auto [flag, tearFlag] : STATUS_TEARS) + if (npc.HasEntityFlags(flag)) tearFlags.set(tearFlag); + int variant = npc.HasEntityFlags(FLAG_BURN) ? TEAR_FIRE_MIND : TEAR_BOOGER; + if (npc.HasEntityFlags(FLAG_ICE)) + { + tearFlags.set(TEAR_ICE_FLAG); + variant = TEAR_ICE; + } + if (npc.HasEntityFlags(FLAG_BAITED)) tearFlags.set(TEAR_BAIT); + + RNG rng = {npc.initSeed, VASCULITIS_SHIFTS[0], VASCULITIS_SHIFTS[1], VASCULITIS_SHIFTS[2]}; + float startAngle = (float)rng.Next() * VASCULITIS_RANDOM_UNIT * FULL_TURN_DEGREES; + float step = FULL_TURN_DEGREES / (float)count; + for (int i = 0; i < count; i++) + { + float jitter = (float)rng.Next() * VASCULITIS_RANDOM_UNIT - 0.5f; + float angle = ((float)i * step + startAngle + jitter * step) * DEGREES_TO_RADIANS; + float speed = (float)rng.Next() * VASCULITIS_RANDOM_UNIT * VASCULITIS_SPEED_RANGE + VASCULITIS_SPEED_MIN; + Vector velocity = vector_make(speed * std::cos(angle), speed * std::sin(angle)); + uint32_t seed = Random(); + float reach = npc.shrinkStatus1 * npc.size + 1; + auto* tear = static_cast( + g_game->Spawn({.position = vector_add(vector_scale(vector_normalized(velocity), reach), npc.pos), + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_TEAR, + .variant = variant, + .seed = seed})); + tear->spawnerType = ENTITY_PLAYER; + tear->SetCollisionDamage(damage); + tear->SetTearFlags(tearFlags); + tear->SetColor(VASCULITIS_TEAR_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->Update(); + } +} + +// Vade Retro's ghost: the dead enemy's ghost flies on its way, hurting by the floor and its health, bigger for a +// boss or a champion. +static void vade_retro_ghost_spawn(Entity_NPC& npc) +{ + float scale = random_unit() * VADE_RETRO_SCALE_RANGE + VADE_RETRO_SCALE_MIN; + float damage = (float)reward_stage_get() * VADE_RETRO_DAMAGE_STEP + VADE_RETRO_DAMAGE_BASE + + npc.maxHitPoints * VADE_RETRO_HEALTH_SHARE; + if (npc.IsBoss()) scale *= VADE_RETRO_BOSS_SCALE; + else if (npc.isChampion) scale *= VADE_RETRO_CHAMPION_SCALE; + Vector velocity = vector_scale(npc.velocity, VADE_RETRO_SPEED_SCALE); + float speed = vector_length(velocity); + if (speed > VADE_RETRO_MAX_SPEED && speed > 0) velocity = vector_scale(velocity, VADE_RETRO_MAX_SPEED / speed); + + Entity_Player* owner = g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_VADE_RETRO, Random(), nullptr); + Entity* ghost = g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .spawner = owner, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, + .seed = npc.dropRNG.Next()}); + ghost->SetCollisionDamage(damage); + ghost->sprite.scale = vector_make(scale, scale); + ghost->Update(); +} + +// Quints: the first player with it whose quints are fewer than five per copy gets a random familiar where the enemy +// died, with a grey poof. +static void quints_familiar_spawn(Entity_NPC& npc) +{ + constexpr std::array QUINTS_FAMILIARS = {1, 7, 6, 5, 32, 2, 9, 10, 11, 8, 13, 54, 61, 92, 101, 208, 209}; + constexpr int QUINTS_PER_COPY = 5; + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER || !player->HasCollectible(COLLECTIBLE_QUINTS)) continue; + int quints = (int)std::ranges::count_if(g_game->room->GetEntities()->updateEL, [&](Entity* entity) { + auto* familiar = static_cast(entity); + return entity->type == ENTITY_FAMILIAR && familiar->isSubtype55555 && familiar->player == player; + }); + if (quints >= std::max(1, player->GetCollectibleNum(COLLECTIBLE_QUINTS)) * QUINTS_PER_COPY) continue; + + RNG rng = {npc.initSeed, QUINTS_SHIFTS[0], QUINTS_SHIFTS[1], QUINTS_SHIFTS[2]}; + int variant = QUINTS_FAMILIARS[rng.Next() % QUINTS_FAMILIARS.size()]; + g_game + ->Spawn({.position = npc.pos, + .spawner = player, + .subType = QUINTS_SUBTYPE, + .type = ENTITY_FAMILIAR, + .variant = variant, + .seed = rng.Next()}) + ->Update(); + Entity* poof = + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->SetColor(QUINTS_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + return; + } +} + +// The Urn of Souls: souls fly from the dead enemy to random urn holders, one (two from a champion, up to eight from a +// boss by its health). Judas' Birthright makes them dark. +static void urn_souls_spawn(Entity_NPC& npc) +{ + std::vector owners; + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && player->HasCollectible(COLLECTIBLE_URN_OF_SOULS)) + owners.push_back(player); + if (owners.empty()) return; + + RNG rng = {npc.initSeed, VASCULITIS_SHIFTS[0], VASCULITIS_SHIFTS[1], VASCULITIS_SHIFTS[2]}; + int count = npc.championColorIdx >= 0 ? 2 : 1; + if (npc.IsBoss()) + { + float health = (float)reward_stage_get() * KEEPER_BOSS_HEALTH_STEP + KEEPER_BOSS_HEALTH_BASE; + count = std::min((int)std::ceil(npc.maxHitPoints / health), URN_BOSS_SOULS); + } + for (int i = 0; i < count; i++) + { + Entity_Player* owner = owners[rng.Next() % owners.size()]; + bool isDark = owner->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE); + Vector direction = random_direction(); + Vector position = vector_add(npc.pos, vector_scale(direction, random_unit() * URN_SOUL_SPREAD)); + Vector velocity = vector_scale(direction, random_unit() * URN_SOUL_SPREAD); + Entity* soul = g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .subType = isDark ? 1 : 0, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_SOUL, + .seed = Random()}); + soul->target = owner; + soul->Update(); + } +} + // What the killing hits' sources do: a Leech heals its player, a Blood Puppy grows, Guppy's Hairball grows, and one // Sharp Key kill in ten opens a chest at once. static void kill_source_rewards(Entity_NPC& npc) @@ -144,7 +393,10 @@ static void kill_source_rewards(Entity_NPC& npc) continue; } if (event.source.type == ENTITY_BLOOD_PUPPY) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: a Blood Puppy's feeding"); + { + blood_puppy_feed(npc, source); + continue; + } bool isSharpKey = event.source.type == ENTITY_TEAR && (event.source.variant == TEAR_SHARP_KEY || event.source.variant == TEAR_SHARP_KEY_SPECTRAL); @@ -228,9 +480,11 @@ static void kill_item_rewards(Entity_NPC& npc) if (spurs && !is_killed_by(npc, ENTITY_FAMILIAR, Entity_Familiar::BONE_SPUR)) bone_spurs_spawn(npc, *spurs); if (players.RandomCollectibleOwner(COLLECTIBLE_HUNGRY_SOUL, npc.initSeed, nullptr) && !is_killed_by(npc, ENTITY_EFFECT, EFFECT_HUNGRY_SOUL)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Hungry Soul's soul"); - if (players.RandomTrinketOwner(TRINKET_CRICKET_LEG, npc.initSeed, nullptr)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Cricket's Leg (SpawnTrinketRandomPickup)"); + hungry_soul_spawn(npc); + if (Entity_Player* cricket = players.RandomTrinketOwner(TRINKET_CRICKET_LEG, npc.initSeed, nullptr)) + if ((int)(cricket->GetTrinketRNG(TRINKET_CRICKET_LEG).Next() % CRICKETS_LEG_ODDS) < + cricket->GetTrinketMultiplier(TRINKET_CRICKET_LEG)) + cricket->SpawnTrinketRandomPickup(); if (g_game->challenge == CHALLENGE_CANTRIPPED && npc.dropRNG.Next() % CANTRIPPED_ODDS == 0) { @@ -325,19 +579,13 @@ void Entity_NPC::trigger_death_rewards() if (!HasEntityFlags(FLAG_NO_REWARD)) kill_item_rewards(*this); if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_VASCULITIS, LAZARUS_SHARE_CHECK)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Vasculitis's tears"); + vasculitis_tears_fire(*this); if (!CanShutDoors()) return; Room& room = *g_game->room; - if (room.isExorcistActive && room.IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Vade Retro's souls"); - if (room.IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) - for (Entity_Player* player : g_game->playerManager.playerList) - if (player->variant == PLAYER_VARIANT_PLAYER && player->HasCollectible(COLLECTIBLE_QUINTS)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Quints' familiars"); + if (room.isExorcistActive && room.IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) vade_retro_ghost_spawn(*this); + if (room.IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) quints_familiar_spawn(*this); magdalene_hearts_drop(*this); keeper_coins_drop(*this); - for (Entity_Player* player : g_game->playerManager.playerList) - if (player->variant == PLAYER_VARIANT_PLAYER && player->HasCollectible(COLLECTIBLE_URN_OF_SOULS)) - reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the Urn of Souls' souls"); + urn_souls_spawn(*this); } diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index faa49b7..23de8d3 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -14,6 +14,7 @@ #include "platform.h" #include "room.h" #include "room_grid.h" +#include "room_render.h" #include #include #include @@ -88,6 +89,10 @@ constexpr int FAMILIAR_SUPER_BUM = 102; constexpr int FIREPLACE_VARIANT_COUNT = 10; constexpr int MINECART_UNSAVED_VARIANT = 10; constexpr int BOMB_THROWABLE = 13; +// A sack's loot flies out at 2 to 5, drawn by this RNG shift. +constexpr int SACK_SHIFT_INDEX = 23; +constexpr float SACK_SPEED_MIN = 2; +constexpr float SACK_SPEED_RANGE = 3; constexpr int BOMB_ROCKET = 19; constexpr int BOMB_ROCKET_GIGA = 20; constexpr uint32_t PORTAL_SAVED_SUBTYPE_MIN = 899; @@ -308,11 +313,6 @@ static bool is_player_near(const Vector& position, float range) return false; } -static Vector vector_sub(Vector a, Vector b) -{ - return vector_make(a.x - b.x, a.y - b.y); -} - static void pickup_sound_play(int sound, SoundPlay play = {}) { grid_sound_play(sound, play); @@ -1375,10 +1375,129 @@ void Entity_Pickup::update_magnet_attraction() reconstruction_missing("Entity_Pickup::update_magnet_attraction 006ed690: the coins pulled to a second player"); } +// Part of 006e8ae0: a devil deal taken (bought, or a spike offer paid for). The run counts it, Azazel unlocking at +// the third, and with a pickup that came from the room's layout too, Redemption waiting on its first sin notes this +// one. +static void devil_deal_count(Entity_Pickup& pickup, Entity_Player& player, int paidPrice) +{ + + Game& game = *g_game; + if (pickup.state == 1 || paidPrice != 0) + { + if (++game.devilRoomDeals >= AZAZEL_DEALS) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_AZAZEL); + g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_DEVIL_DEALS_TAKEN, 1); + } + else if (pickup.spawnGridIndex < 0) return; + + Entity* redemption = player.redemptionEffect; + TemporaryEffects& effects = player.temporaryEffects; + if (!redemption || redemption->type != ENTITY_EFFECT || effects.isDisabled) return; + TemporaryEffect* effect = effects.GetCollectibleEffect(COLLECTIBLE_REDEMPTION); + if (!effect || effect->count != 1) return; + effects.AddCollectibleEffect(COLLECTIBLE_REDEMPTION, true, 1); + static_cast(redemption)->state = REDEMPTION_WAITING; +} + +// The red and soul hearts (soul charge included) a player and its sub player hold. +struct HeartTotals +{ + int red = 0; + int soul = 0; +}; + +// What a player and its sub player hold, for Candy Heart's and Soul Locket's count of hearts gained. +static HeartTotals heart_totals_get(Entity_Player& player) +{ + HeartTotals totals = {player.redHearts, player.soulHearts + player.effectiveSoulCharge}; + if (Entity_Player* sub = player.subPlayer) + { + totals.red += sub->redHearts; + totals.soul += sub->soulHearts + sub->effectiveSoulCharge; + } + return totals; +} + +// Each half heart gained rolls one of the six stats up with the item's RNG, then the stats are evaluated. +static void heart_stat_ups_roll(Entity_Player& player, int item, int gained, + std::array& ups) +{ + constexpr std::array STAT_CACHES = {CACHE_DAMAGE, CACHE_FIREDELAY, CACHE_RANGE, + CACHE_SHOTSPEED, CACHE_SPEED, CACHE_LUCK}; + if (!player.HasCollectible(item) || gained <= 0) return; + + for (int i = 0; i < gained; i++) + { + uint32_t stat = player.collectibleRNGs[item].Next() % HEART_STAT_COUNT; + player.cacheFlags |= STAT_CACHES[stat]; + ups[stat]++; + } + player.EvaluateItems(); +} + +// Candy Heart's ups for the red hearts a pickup gave and Soul Locket's for its soul hearts. A player without health +// counts the soul hearts the pickup offered, which it never holds. +static void heart_stat_ups_apply(Entity_Player& player, HeartTotals before, int heartKind) +{ + HeartTotals after = heart_totals_get(player); + if (player.GetHealthType() == HEALTH_NO_HEALTH) + { + bool isSoulPair = is_listed({HEART_SOUL, HEART_BLACK, HEART_BLENDED}, heartKind); + after.soul = before.soul + (isSoulPair ? 2 : heartKind == HEART_HALF_SOUL); + } + heart_stat_ups_roll(player, COLLECTIBLE_CANDY_HEART, after.red - before.red, player.candyHeartStatUps); + heart_stat_ups_roll(player, COLLECTIBLE_SOUL_LOCKET, after.soul - before.soul, player.soulLocketStatUps); +} + +// Opens a sack: its loot's pickups fly out from a random spot beside it, and its blue flies and spiders go to the +// player. +static void sack_open(Entity_Pickup& sack, Entity_Player& player) +{ + LootList loot = sack.GetChestLoot(POOL_DRAW_TAKE, &player); + RNG rng; + rng.SetSeed(sack.initSeed, SACK_SHIFT_INDEX); + + for (const LootEntry& entry : loot.entries) + { + if (entry.type == ENTITY_FAMILIAR) + { + if (entry.variant == Entity_Familiar::BLUE_FLY) player.AddBlueFlies(1, sack.pos, nullptr); + else if (entry.variant == Entity_Familiar::BLUE_SPIDER) player.ThrowBlueSpider(sack.pos, {}); + continue; + } + Vector direction = RandomVector(rng.Next()); + float speed = rng.RandomFloat() * SACK_SPEED_RANGE + SACK_SPEED_MIN; + Vector offset = RandomVector(rng.Next()); + g_game + ->Spawn({.position = vector_make(sack.pos.x + offset.x, sack.pos.y + offset.y), + .velocity = vector_make(direction.x * speed, direction.y * speed), + .spawner = &sack, + .subType = entry.subType, + .type = entry.type, + .variant = entry.variant, + .seed = entry.seed}) + ->Update(); + } + g_game->room->isPickupVisionInvalid = true; +} + +// Lifts a throwable bomb over the player's head, a live bomb in its place for its parent. Returns whether it was taken. +static bool throwable_bomb_lift(Entity_Pickup& pickup, Entity_Player& player) +{ + if (player.IsHoldingItem() || player.itemHoldCooldown != 0) return false; + + Entity* bomb = g_game->Spawn( + {.position = pickup.pos, .spawner = &player, .type = ENTITY_BOMB, .variant = BOMB_THROWABLE, .seed = Random()}); + player.TryHoldEntity(bomb); + if (pickup.parent && pickup.parent->child.get() == &pickup) pickup.parent->child = bomb; + pickup.Remove(); + return true; +} + // 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, and chests open (entity_pickup_chest.cpp). Sacks, +// A priced pickup is bought with the player's coins or health, and chests open (entity_pickup_chest.cpp). Taking an +// item, opening a chest or a sack starts a challenge room's fight. The bed, // 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) @@ -1473,8 +1592,12 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) switch (variant) { case PICKUP_HEART: + { + HeartTotals before = heart_totals_get(*player); isPickedUp = heart_collect(*player); + if (isPickedUp) heart_stat_ups_apply(*player, before, subtype); break; + } case PICKUP_COIN: coin_collect(*player); isPickedUp = true; @@ -1487,6 +1610,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) break; case PICKUP_COLLECTIBLE: isPickedUp = collectible_collect(*player); + isChestOpened = isPickedUp; break; case PICKUP_LIL_BATTERY: isPickedUp = battery_collect(*this, *player); @@ -1519,8 +1643,20 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_TROPHY: ending_pickup_touch(*this, *player); break; + case PICKUP_GRAB_BAG: + sack_open(*this, *player); + isPickedUp = true; + isChestOpened = true; + break; + case PICKUP_POOP: + player->AddPoopMana(subtype == 1 ? 3 : 1); + isPickedUp = true; + break; + case PICKUP_THROWABLEBOMB: + isPickedUp = throwable_bomb_lift(*this, *player); + break; default: - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: sacks"); + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the bed"); } Room& room = *g_game->room; @@ -1530,13 +1666,12 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) 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 (isDevilDeal) devil_deal_count(*this, *player, paidPrice); + if (isChestOpened && (room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH)) + g_game->ambush.StartChallenge(); } 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); diff --git a/src/entity_pickup_shop.cpp b/src/entity_pickup_shop.cpp index d418280..35ad5ce 100644 --- a/src/entity_pickup_shop.cpp +++ b/src/entity_pickup_shop.cpp @@ -57,24 +57,6 @@ struct HeartCost constexpr std::array HEART_COSTS = { {{}, {1, 0}, {2, 0}, {0, 3}, {1, 2}, {}, {}, {0, 1}, {0, 2}, {1, 1}}}; -// (00703ab0) Game::GetNearestPlayerEx for the main players: the nearest one that is no co-op ghost, baby, held twin -// or hologram and still collides. -Entity_Player* player_nearest_find(const Vector& position) -{ - Entity_Player* nearest = nullptr; - float best = 1e10f; - - for (Entity_Player* player : g_game->playerManager.playerList) - { - float distance = vector_length_squared(vector_sub(position, player->pos)); - if (distance >= best || player->variant != 0 || player->isCoopGhost || player->parent) continue; - if (player->IsHologram() || player->entityCollisionClass == ENTCOLL_NONE) continue; - nearest = player; - best = distance; - } - return nearest; -} - // The ware a shop slot sells, the Init part of 006e02f0: the room rolls the slot's ware and price from the pickup's // seed, the pick's modifiers may change it (pricing it again), and a devil treasure room's crawlspace ware stands // higher. @@ -244,7 +226,7 @@ void Entity_Pickup::update_price_sprite(int newPrice) void Entity_Pickup::price_refresh() { Room& room = *g_game->room; - Entity_Player* player = player_nearest_find(pos); + Entity_Player* player = main_player_nearest(pos); ShopOffer offer = {.shopItemId = shopItemId, .subType = subtype, .variant = variant}; int newPrice = room_shop_discount(room, shopItemId, room_shop_item_price(room, offer, player), player); if (newPrice != price) update_price_sprite(newPrice); diff --git a/src/entity_player.cpp b/src/entity_player.cpp index ca1ffc1..5386918 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -6,6 +6,10 @@ #include "entity_laser.h" #include "entity_npc.h" #include "entity_slot.h" +#include "active_items.h" +#include "hud.h" +#include "pocket_items.h" +#include "sfx_manager.h" #include "game.h" #include "log.h" #include "lua_engine.h" @@ -49,6 +53,10 @@ constexpr uint32_t PRE_LEVEL_RNG_SHIFT = 2; constexpr uint32_t FLOOR_RNG_SHIFT = 12; constexpr uint32_t JACOBS_CURSE_RNG_SHIFT = 66; constexpr int JACOBS_CURSE_STEPS = 20; +constexpr int REDEMPTION_LIGHT_FADE = 2; +constexpr int NECROMANCER_OVERLAY_DELAY = 3; +// The step from a door slot (left, up, right, down) into the room. +constexpr float ASCENT_DOOR_STEPS[][2] = {{40, 0}, {0, 40}, {-40, 0}, {0, -40}}; constexpr int JACOBS_CURSE_STEP_FRAMES = 30; constexpr int JACOBS_CURSE_MIN_FRAMES = 610; @@ -907,6 +915,7 @@ void Entity_Player::level_start(bool isForced) if (!isPostLevelInitFinished) return; spawn_low_health_blood_splat(); + ventricleRazorPortal = 0; if (variant == PLAYER_VARIANT_COOP_BABY) { if (isGlitchBaby) reconstruction_missing("Entity_Player::level_start 007a4ba0 (the glitched co-op baby)"); @@ -936,14 +945,42 @@ void Entity_Player::start_position_set() uint32_t curses = (Seeds::GetForcedCurses() | game.debugCurses | game.curses) & ~Seeds::GetPreventedCurses(); int stage = (int)game.stage + (curses & CURSE_OF_LABYRINTH ? 1 : 0); - if (game.IsAscent() && !(stage == ASCENT_HOME_STAGE && game.IsAltPath())) - reconstruction_missing("Entity_Player::level_start 007a4ba0 (the Ascent's door start)"); + if (game.IsAscent() && !(stage == ASCENT_HOME_STAGE && game.IsAltPath())) ascent_start_set(); return; } } pos = PlayerManager::get_player_start_position(this, vector_make(START_SPOT_X, startY)); } +// The Ascent starts the player a cell inside a door: the room's first, or from a random slot the next one its shape +// allows. A trapdoor reachable from there takes the start instead. +void Entity_Player::ascent_start_set() +{ + Room& room = *g_game->room; + auto door = std::ranges::find_if(room.doors, [](GridEntity_Door* slot) { return slot != nullptr; }); + int slot = (int)(door - room.doors.begin()); + if (door == room.doors.end()) + { + slot = (int)(Random() & (DOOR_SLOT_COUNT - 1)); + uint32_t allowed = room.descriptor->data->doors; + for (int tries = 0; tries < DOOR_SLOT_COUNT && !(allowed & (1u << slot)); tries++) + slot = (slot + 1) % DOOR_SLOT_COUNT; + } + Vector start = room.GetGridPosition(room.doorGridPositions[slot]); + start = vector_make(start.x + ASCENT_DOOR_STEPS[slot % 4][0], start.y + ASCENT_DOOR_STEPS[slot % 4][1]); + pos = start; + + for (int cell = 0; cell < room.gridHeight * room.gridWidth && cell < ROOM_GRID_CELLS; cell++) + { + GridEntity* grid = room.gridEntities[cell]; + if (!grid || grid->type != GRID_TRAPDOOR) continue; + Vector trapdoor = room.GetGridPosition(grid->gridIndex); + if (!pathfinder_can_reach_pos(&trapdoor, &start, &room)) continue; + pos = trapdoor; + return; + } +} + // Ends the floor-long effects and restores what each floor gives back: Holy Mantle from Wooden Cross, the floor's // health, map and compass effects, items that recharge, pickups some trinkets spawn, the Backasswards penalty and the // per-floor generators, then evaluates. A forced start also restarts the player's familiars. @@ -974,9 +1011,14 @@ void Entity_Player::level_items_apply(bool isForced) player->AddMaxHearts(2, false); game.itemOverlay.Show(GIANTBOOK_EMPTY_HEART, 0, nullptr); } - if (TemporaryEffect* redemption = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_REDEMPTION)) - if (redemption->count > 0) - reconstruction_missing("Entity_Player::level_start 007a4ba0 (Redemption's blessing)"); + if (TemporaryEffect* redemption = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_REDEMPTION); + redemption && redemption->count > 0) + { + if (Entity* light = redemptionEffect; light && light->type == ENTITY_EFFECT && redemption->count == 1) + static_cast(light)->state = REDEMPTION_LIGHT_FADE; + if (ItemConfig_Item* item = items.GetCollectible(COLLECTIBLE_REDEMPTION)) + temporaryEffects.RemoveEffect(item, -1); + } forgottenBodyRoomIdx = FORGOTTEN_BODY_ROOM_NONE; for (int i = HasTrinket(TRINKET_LUCKY_SACK) ? GetTrinketMultiplier(TRINKET_LUCKY_SACK) : 0; i > 0; i--) { @@ -1003,8 +1045,7 @@ void Entity_Player::level_items_apply(bool isForced) floor_maps_apply(); floor_items_recharge(); if (HasTrinket(TRINKET_HOLLOW_HEART)) AddBoneHearts(GetTrinketMultiplier(TRINKET_HOLLOW_HEART)); - if (HasCollectible(COLLECTIBLE_MISSING_NO)) - reconstruction_missing("Entity_Player::level_start 007a4ba0 (Missing No.)"); + if (HasCollectible(COLLECTIBLE_MISSING_NO)) missing_no_reroll(); if (HasCollectible(COLLECTIBLE_ZODIAC)) { if (!HasCollectible(COLLECTIBLE_TAURUS) && !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_TAURUS)) @@ -1096,12 +1137,59 @@ void Entity_Player::floor_items_recharge() } else if (active.item == COLLECTIBLE_ERASER) AddActiveCharge(1, slot, false, false, true); } - if (!hasCurseMistEffect && !isCoopGhost && playerForms[PLAYER_FORM_NECROMANCER] > 2) - reconstruction_missing("Entity_Player::level_start 007a4ba0 (the Necronomicon transformation)"); + if (!hasCurseMistEffect && !isCoopGhost && playerForms[PLAYER_FORM_NECROMANCER] > 2) necromancer_recharge(); for (int i = HasTrinket(TRINKET_BETHS_FAITH) ? GetTrinketMultiplier(TRINKET_BETHS_FAITH) * 4 : 0; i > 0; i--) AddWisp(COLLECTIBLE_BOOK_OF_VIRTUES, pos, false, false); } +// Missing No. rerolls the player's items for the new floor with the D4 (no animation, from no slot), and the player +// glitches into it. +void Entity_Player::missing_no_reroll() +{ + UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM, .slot = ACTIVE_SLOT_NONE}); + isPlayingItemAnimation = false; + bodySprite.Reset(); + sprite.playbackSpeed = 1; + sprite.overlayAnimState.SetAnimationData(nullptr); + if (sprite.SetAnimation("Glitch", SWITCH_KEEP_FRAME)) + { + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; + } + isPlayingExtraAnimation = true; + isPlayingItemAnimation = false; +} + +// The Necromancer transformation recharges the first Necronomicon a slot holds with its form's charge (none in the +// pocket's book slot), the others losing theirs, with the giant book and its sound. Without one marked the main active +// becomes the transformation's book, fully charged. +void Entity_Player::necromancer_recharge() +{ + Game& game = *g_game; + bool isRecharged = false; + + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + ActiveItemDesc& active = activeItems[slot]; + if (active.item != COLLECTIBLE_NECRONOMICON) continue; + if (isRecharged) active.varData = 0; + else if (active.varData == 1) + { + int charge = slot == POCKET_ACTIVE_SLOT + 1 ? 0 : GetCollectibleMaxCharge(COLLECTIBLE_NECRONOMICON, 1); + AddActiveCharge(charge, slot, false, false, true); + game.itemOverlay.Show(GIANTBOOK_NECROMANCER, NECROMANCER_OVERLAY_DELAY, nullptr); + sound_fart_play(SOUND_NECROMANCER); + isRecharged = true; + } + game.hud.InvalidateActiveItem(this, slot); + } + if (isRecharged) return; + activeItems[ACTIVE_SLOT_PRIMARY].varData = 1; + AddActiveCharge(GetCollectibleMaxCharge(activeItems[ACTIVE_SLOT_PRIMARY].item, 1), ACTIVE_SLOT_PRIMARY, false, + false, true); + game.itemOverlay.Show(GIANTBOOK_NECROMANCER, NECROMANCER_OVERLAY_DELAY, nullptr); +} + // Stem Cell heals half the missing red hearts, all of them at two, and all of them with two heart drops at three. void Entity_Player::stem_cell_heal() { @@ -1435,6 +1523,8 @@ void Entity_Player::release_weapons_and_effects(bool isRemoveEntities) link_release(azazelsRageLaser, isRemoveEntities); link_release(breathOfLifeEffect, isRemoveEntities); link_release(trinityShield, isRemoveEntities); + link_release(deadToothRing, isRemoveEntities); + link_release(redemptionEffect, isRemoveEntities); link_release(bestFriend, isRemoveEntities); link_release(megaBlastLaser, isRemoveEntities); link_release(markedTarget, isRemoveEntities); diff --git a/src/entity_player.h b/src/entity_player.h index 2b18ee1..e8d9a7f 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -140,6 +140,8 @@ enum HeartKind : int // The weight of a player Gnawed Leaf turned to stone. constexpr float STATUE_MASS = 1000; +// How long a bleeding out player lasts before it loses a red heart. +constexpr int BLEED_OUT_FRAMES = 600; // The flavours the G FUEL! seed's stacks give (get_seeded_variant): none below two stacks, then Soy Milk's, Mutant // Spider's slower and wobbly tears, slow tears, rapid weak tears, and slow far reaching ones. @@ -285,6 +287,7 @@ enum PlayerItemId : int COLLECTIBLE_YUM_HEART = 45, COLLECTIBLE_LUCKY_FOOT = 46, COLLECTIBLE_SHOOP_DA_WHOOP = 49, + COLLECTIBLE_PENTAGRAM = 51, COLLECTIBLE_DR_FETUS = 52, COLLECTIBLE_TREASURE_MAP = 54, COLLECTIBLE_MOMS_EYE = 55, @@ -347,6 +350,7 @@ enum PlayerItemId : int COLLECTIBLE_FANNY_PACK = 204, COLLECTIBLE_SPIDERBABY = 211, COLLECTIBLE_ANEMIC = 214, + COLLECTIBLE_MOMS_WIG = 217, COLLECTIBLE_PLACENTA = 218, COLLECTIBLE_OLD_BANDAGE = 219, COLLECTIBLE_ANTI_GRAVITY = 222, @@ -514,6 +518,7 @@ enum PlayerItemId : int COLLECTIBLE_ETERNAL_D6 = 609, COLLECTIBLE_BIRD_CAGE = 610, COLLECTIBLE_LARYNX = 611, + COLLECTIBLE_LOST_SOUL = 612, COLLECTIBLE_BIRTHRIGHT = 619, COLLECTIBLE_GENESIS = 622, COLLECTIBLE_BOOSTER_PACK = 624, @@ -521,6 +526,10 @@ enum PlayerItemId : int COLLECTIBLE_KNIFE_PIECE_1 = 626, COLLECTIBLE_KNIFE_PIECE_2 = 627, COLLECTIBLE_EVIL_CHARM = 632, + COLLECTIBLE_LADDER = 60, + COLLECTIBLE_MAW_OF_THE_VOID = 399, + COLLECTIBLE_INTRUDER = 575, + COLLECTIBLE_AKELDAMA = 641, COLLECTIBLE_DOGMA = 633, COLLECTIBLE_CANDY_HEART = 671, COLLECTIBLE_FRIEND_BALL = 382, @@ -680,9 +689,11 @@ enum PlayerItemId : int TRINKET_STEM_CELL = 119, TRINKET_WOODEN_CROSS = 121, TRINKET_BUTTER = 122, + TRINKET_DOOR_STOP = 124, TRINKET_BABY_BENDER = 127, TRINKET_GIGANTE_BEAN = 134, TRINKET_BROKEN_PADLOCK = 136, + TRINKET_FORGOTTEN_LULLABY = 141, TRINKET_BETHS_FAITH = 142, TRINKET_PERFECTION = 145, TRINKET_FRIENDSHIP_NECKLACE = 148, @@ -754,6 +765,7 @@ enum PlayerItemId : int NULLITEM_BLANKFACE = 15, NULLITEM_CHRISTMAS = 16, NULLITEM_PURITY_GLOW = 17, + NULLITEM_HEMOPTYSIS = 117, NULLITEM_EMPTY_VESSEL = 18, NULLITEM_HOLY_CARD = 46, NULLITEM_LAZARUS_BOOST = 49, @@ -762,7 +774,11 @@ enum PlayerItemId : int NULLITEM_IT_HURTS = 57, NULLITEM_TOOTH_AND_NAIL_STATUE = 59, NULLITEM_REVERSE_CHARIOT = 63, + NULLITEM_JUPITER_BODY = 75, NULLITEM_JUPITER_BODY_ANGEL = 76, + NULLITEM_JUPITER_BODY_PONY = 77, + NULLITEM_JUPITER_BODY_WHITEPONY = 78, + NULLITEM_BERSERK_SAMSON = 103, NULLITEM_LILITH_B = 90, NULLITEM_REVERSE_HANGED_MAN = 65, NULLITEM_REVERSE_SUN = 66, @@ -801,6 +817,7 @@ enum PlayerItemId : int NULLITEM_HEMOPTYSIS_BOOST = 127, NULLITEM_ERA_WALK = 42, NULLITEM_HUGE_GROWTH = 41, + NULLITEM_SACRIFICIAL_ALTAR = 43, NULLITEM_PUBERTY = 1, NULLITEM_I_FOUND_PILLS = 2, NULLITEM_WIZARD = 6, @@ -915,6 +932,7 @@ enum PlayerAchievement : int ACHIEVEMENT_MAGDALENE = 1, ACHIEVEMENT_CAIN = 2, ACHIEVEMENT_ISAAC_HOLDS_THE_D6 = 29, + ACHIEVEMENT_AZAZEL = 79, ACHIEVEMENT_LAZARUS = 80, ACHIEVEMENT_KEEPER_HOLDS_A_PENNY = 191, ACHIEVEMENT_KEEPER_HOLDS_WOODEN_NICKEL = 236, @@ -979,6 +997,13 @@ struct CostumeWalk bool isMoving = false; }; +// A passive the Void absorbed, with the pool it came from. +struct VoidedPassive +{ + int id = 0; + int value = 0; +}; + // The item a player holds over its head, picked up and not yet added, with the pool it came from (-1 for none). struct QueueItemData { @@ -1015,6 +1040,30 @@ struct CostumeSpriteDesc bool isOverwriteColor = false; }; +// A frame of the player's walk as the Void's hallucination replays it: where it stood and how it moved, and its body +// and head animations (their indices, -1 for none) at their frames. +struct TrailFrame +{ + Vector position{}; + Vector velocity{}; + int animation = -1; + int frame = 0; + int overlayAnimation = -1; + int overlayFrame = 0; +}; + +// The player's walk through a room (HallucinationOverlay): its last 900 frames, the one replayed next, the distance +// walked and the faded copy of the player's sprite that replays it. +struct PlayerTrail +{ + std::deque frames; + ANM2 sprite; + float distance = 0; + size_t current = 0; +}; + +void hallucination_trail_render(Entity_Player& player, Vector offset); + // The skin colors the worn costumes leave the player's head and body. struct SkinColors { @@ -1244,7 +1293,7 @@ public: std::vector levelEffectItems; std::vector pillEffectUses; std::vector voidedCollectibles; - std::vector voidedPassives; + std::vector voidedPassives; std::vector smeltedTrinkets; std::vector cardRNGs; std::vector collectibleRNGs; @@ -1343,12 +1392,16 @@ public: std::vector curseMistFamiliars; std::vector pendingWisps; std::deque echoChamberItems; + PlayerTrail hallucinationTrail; + PlayerTrail roomTrail; EntityDesc friendBallEnemy; EntityPtr astralProjectionBody; EntityPtr babyFamiliar; EntityPtr bestFriend; EntityPtr breathOfLifeEffect; EntityPtr darkEsau; + EntityPtr deadToothRing; + EntityPtr redemptionEffect; EntityPtr salvationEffect; EntityPtr tetheredEffect; EntityPtr tractorBeam; @@ -1530,6 +1583,7 @@ public: bool RenderShadowLayer(const Vector& offset) override; void render_pass(const Vector& offset, RenderPass pass); void RenderGlow(const Vector& position); + void render_back(const Vector& position); void RenderBody(const Vector& position); void RenderHead(const Vector& position); void RenderTop(const Vector& position); @@ -1574,13 +1628,13 @@ public: int tagged_item_count(uint64_t tag); void collectible_unlocks_check(int collectibleId, ItemConfig_Item& item); void collectible_pickups_add(ItemConfig_Item& item); - bool is_character_plain(); - bool is_frame_plain(); + std::string frame_gap(); 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(SkinColors& colors); + void costume_items_dress(); void costume_skin_apply(CostumeSpriteDesc& costume, int skinColor); void skin_recolor(const SkinColors& colors); void eden_hair_apply(ANM2& hair); @@ -1590,6 +1644,7 @@ public: int AddActiveCharge(int charge, int slot, bool isFlashHud, bool isOvercharge, bool isForce); void RemoveCollectible(int type, bool isIgnoreModifiers, int activeSlot, bool isRemoveFromForm); Entity_Familiar* AddWisp(int collectible, Vector position, bool isAdjustOrbitLayer, bool isDontUpdate); + void SpawnTrinketRandomPickup(); void StoreGameState(GameStatePlayer* state, bool isSaveTemporaryFamiliars); void PlayCollectibleAnim(int collectible, bool isCheckBodyLayers, std::string_view animation, int frame); void PlayExtraAnimation(std::string_view animation, bool isUnknown); @@ -1626,10 +1681,13 @@ private: void companions_init(); void jacobs_curse_add(); void start_position_set(); + void ascent_start_set(); void level_items_apply(bool isForced); void floor_maps_apply(); void floor_items_recharge(); void stem_cell_heal(); + void missing_no_reroll(); + void necromancer_recharge(); void backasswards_penalty(); void floor_rngs_reseed(); void wooden_cross_mantles_add(); @@ -1637,17 +1695,16 @@ private: void costume_map_reset(int priority); Vector walk_direction_update(Vector input); void walk_velocity_update(Vector walkInput); - void walk_animation_update(); - void sprite_scale_update(); void shoot_input_read(ShootInput& input); void head_turn(Vector toward); void charge_store_changed(int effectiveCharge, int oldCharge); - void render_back(const Vector& position); ANM2& layer_sprite(int layer); int layer_id(int layer); static bool is_body_layer(int layer); public: + void walk_animation_update(); + void sprite_scale_update(); int GetBatteryCharge(int slot); void SetMinDamageCooldown(int cooldown); int GetActiveItem(int slot); @@ -1934,7 +1991,7 @@ public: void MorphToCoopGhost(); void reset_body_sprite(); static CraftingRecipe CalculateBagOfCraftingOutput(const std::array& bag); - void SpawnClot(Vector pos, bool isUnknown); + void SpawnClot(Vector position, bool isFromItem); bool TryForgottenThrow(Vector dir); void ResetPlayer(); void remove_wooden_cross_mantles(); diff --git a/src/entity_player_actives_afterbirth.cpp b/src/entity_player_actives_afterbirth.cpp new file mode 100644 index 0000000..c5ab98f --- /dev/null +++ b/src/entity_player_actives_afterbirth.cpp @@ -0,0 +1,628 @@ +#include "entity_player.h" +#include "active_items.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_tear.h" +#include "item_pool.h" +#include "room.h" +#include "room_grid.h" +#include "room_state.h" +#include "boss_ai.h" +#include "game.h" +#include "grid_entity_spikes.h" +#include "hud.h" +#include "item_overlay.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include +#include + +// The achievement a character entry carries when nothing unlocks it at all. +constexpr int PLAYER_NEVER_UNLOCKED = -2; +constexpr int CLICKER_RESERVE = 41; + +// The Void: Breath of Life's blink, Apollyon's Birthright throwing a passive back one use in ten, and the stats an +// eaten item rereads. +constexpr int VOID_BLINK_FRAMES = 8; +constexpr int VOID_BLINK_COLOR_FRAMES = 15; +constexpr ColorMod VOID_BLINK_COLOR = { + {1, 1, 1, 1}, {0, 0, 0, 0}, {64 * COLOR_OFFSET_UNIT, 64 * COLOR_OFFSET_UNIT, 128 * COLOR_OFFSET_UNIT}}; +constexpr uint32_t VOID_BIRTHRIGHT_SHIFT_INDEX = 47; +constexpr uint32_t VOID_BIRTHRIGHT_ODDS = 10; +constexpr uint32_t VOID_CACHE_FLAGS = 0x41f; +constexpr float VOID_POOF_DROP = 10; +constexpr uint32_t CROOKED_PENNY_SHIFT_INDEX = 4; + +// Sharp Straw: a tenth of the health, a spray of two or three gore drops and six to fifteen blood drops at most +// thirty units out, and a half heart fifteen uses in a hundred. +constexpr float SHARP_STRAW_SHARE = 0.1f; +constexpr float SHARP_STRAW_MAX_SPRAY = 30; +constexpr float SHARP_STRAW_SPREAD = 10; +constexpr float SHARP_STRAW_GORE_SPEED = 0.2f; +constexpr float SHARP_STRAW_DROP_FALL = -8; +constexpr int SHARP_STRAW_DROPS_MIN = 6; +constexpr int SHARP_STRAW_DROPS_RANGE = 10; +constexpr int SHARP_STRAW_SHAKE = 6; +constexpr uint32_t SHARP_STRAW_HEART_PERCENT = 15; +constexpr int SHARP_STRAW_EXPLOSION = 3; +constexpr int SHARP_STRAW_DROP = 99; + +// The pickups the Moving Box holds. +constexpr size_t MOVING_BOX_CAPACITY = 10; + +// The Sacrificial Altar: two sacrifices, the devil items it draws from (00b62cc0), the darkness and Judas' Birthright's +// longer damage bonus. +constexpr size_t ALTAR_RESERVE = 16; +constexpr size_t ALTAR_SACRIFICES = 2; +constexpr int ALTAR_DARKNESS_FRAMES = 75; +constexpr int ALTAR_BELIAL_FRAMES = 2700; +constexpr std::array ALTAR_ITEMS = {34, 477, 526, 408, 391, 420, 412, 216, 241, 278, 259, 113, 409, 225, + 215, 519, 79, 433, 51, 172, 468, 417, 122, 230, 118, 442, 237, 462, + 360, 311, 82, 399, 114, 80, 159, 565, 679, 572, 702, 684}; + +// 0078fec0 Takes away the collectible a history entry recorded (never a trinket, and only while the player still has +// it), keeping the history locked meanwhile, then drops the entry. Whether it was removed is not read. +void Entity_Player::RemoveCollectibleByHistoryIndex(int index, bool) +{ + std::vector& items = history.historyItems; + if (index < 0 || index >= (int)items.size() || items[index].isTrinket) return; + int id = items[index].id; + bool isOwned = id < 0 ? proceduralItems.contains(id) : collectibleCounts[id] > 0; + if (!isOwned) return; + + bool wasLocked = history.isLocked; + history.isLocked = true; + RemoveCollectible(id, true, ACTIVE_SLOT_PRIMARY, true); + history.isLocked = wasLocked; + history.RemoveHistoryItemByIndex(index); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + +// Clicker: the player becomes another unlocked character of the same kind (normal or tainted), half the time losing +// the last item it can lose first (a smelted trinket, or a rerollable collectible but Clicker and the first active). +// Judas' Birthright adds the Pentagram, a twin raises it too, Book of Virtues adds a random wisp. +static void clicker_use(ItemUse& use) +{ + Entity_Player& player = use.player; + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_CLICKER); + Entity_Player* twin = player.twin_get(); + + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + if (player.isDead || (twin && twin->isDead)) return; + if (player.GetMainTwin() != &player) + { + player.GetMainTwin()->UseActiveItem({.item = use.id, .flags = use.request.flags}); + return; + } + + int current = player.playerType == PLAYER_THESOUL ? PLAYER_THEFORGOTTEN : player.playerType; + bool isTainted = player.playerType >= PLAYER_ISAAC_B && player.playerType <= PLAYER_THESOUL_B; + std::vector candidates; + candidates.reserve(CLICKER_RESERVE); + for (int type = isTainted ? PLAYER_ISAAC_B : PLAYER_ISAAC; type < (isTainted ? PLAYER_THESOUL_B : PLAYER_ESAU); + type++) + { + EntityConfig_Player* config = g_manager->entityConfig.GetPlayer(type); + if (!config || config->achievement == PLAYER_NEVER_UNLOCKED) continue; + if (config->achievement >= 0 && !g_manager->persistentGameData.Unlocked(config->achievement)) continue; + if (type != current) candidates.push_back(type); + } + + bool isBelial = player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE); + if (!candidates.empty()) + { + int next = candidates[rng.RandomInt((uint32_t)candidates.size())]; + std::vector& items = player.history.historyItems; + if (!items.empty() && rng.RandomInt(2) == 0) + for (int i = (int)items.size() - 1; i >= 0; i--) + { + if (items[i].isTrinket) + { + player.TryRemoveSmeltedTrinket((uint32_t)items[i].id); + break; + } + int id = items[i].id; + if (id == COLLECTIBLE_CLICKER || id == player.activeItems[ACTIVE_SLOT_PRIMARY].item) continue; + if (!player.CanRerollCollectible(id, true) || player.collectibleCounts[id] <= 0) continue; + player.RemoveCollectibleByHistoryIndex(i, true); + break; + } + player.ChangePlayerType(next, false); + if (isBelial) player.AddCollectible(COLLECTIBLE_PENTAGRAM, 0, true, ACTIVE_SLOT_PRIMARY, 0); + } + + if (use.isShowAnimation && twin) twin->AnimateCollectible(use.id, "UseItem", "PlayerPickupSparkle"); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) + player.AddWisp(Entity_Familiar::GetRandomWisp(&rng), player.pos, false, false); + g_game->itemOverlay.Show(GIANTBOOK_CLICKER, 0, nullptr); + use_animate(use); +} + +// The Void's stat up, as Black Rune's: two of the six stats, shuffled with the Void's generator, one step up each. +static void void_stats_raise(Entity_Player& player, RNG& rng) +{ + std::array stats = {&player.speedModifier, &player.fireDelayModifier, &player.damageModifier, + &player.tearRangeModifier, &player.shotSpeedModifier, &player.luckModifier}; + for (int i = (int)stats.size() - 1; i > 0; i--) std::swap(stats[i], stats[rng.RandomInt(i + 1)]); + (*stats[0])++; + (*stats[1])++; +} + +// The Void eats an item: an active (but the Moving Box) is kept to fire with every use, anything else is a stat up, +// a passive also remembered with its pool. A poof just under where it was. +static void void_item_absorb(Entity_Player& player, RNG& rng, const VoidedPassive& item, Vector position) +{ + ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(item.id); + if (config->type == ITEM_ACTIVE && item.id != COLLECTIBLE_MOVING_BOX) player.voidedCollectibles.push_back(item.id); + else + { + void_stats_raise(player, rng); + if (config->type != ITEM_ACTIVE) player.voidedPassives.push_back(item); + } + g_game->Spawn({.position = vector_add(position, vector_make(0, VOID_POOF_DROP)), + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = Random()}); +} + +// The Void: every active it ate fires again (Breath of Life as a blink of invincibility), then it eats the item held +// up and every free pedestal item (a co-op choice is put back rolled from the boss pool). Apollyon's Birthright may +// first throw out a passive it ate. Book of Virtues adds a wisp per eaten active, and eating starts a challenge room. +static void void_use(ItemUse& use) +{ + Entity_Player& player = use.player; + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_VOID); + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + + std::vector pedestals; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + { + if (entity->type != ENTITY_PICKUP || entity->isDead) continue; + auto* pickup = static_cast(entity); + if (pickup->CanReroll() && pickup->variant == PICKUP_COLLECTIBLE && !pickup->IsShopItem()) + pedestals.push_back(pickup); + } + QueueItemData queued = player.queuedItem; + bool isQueued = queued.item && queued.item->IsCollectible() && !queued.item->HasTags(TAG_QUEST); + if (isQueued) player.ClearQueueItem(); + + for (size_t i = 0; i < player.voidedCollectibles.size(); i++) + { + int id = player.voidedCollectibles[i]; + if (id == COLLECTIBLE_BREATH_OF_LIFE) + { + if (player.damageCooldown >= VOID_BLINK_FRAMES) continue; + player.SetColor(VOID_BLINK_COLOR, VOID_BLINK_COLOR_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + player.damageCooldown = VOID_BLINK_FRAMES; + player.AddEntityFlags(FLAG_NO_DAMAGE_BLINK); + } + else if (id != COLLECTIBLE_VOID) + { + player.UseActiveItem({.item = id, .flags = USE_NOANIM | USE_NOCOSTUME | USE_VOID}); + player.AddCostume(g_manager->itemConfig.GetCollectible(id), true); + } + } + if (player.itemState != 0) player.DischargeActiveItem(ACTIVE_SLOT_PRIMARY, false); + + if (player.playerType == PLAYER_APOLLYON && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT)) + { + RNG birthright; + birthright.SetSeed(rng._seed, VOID_BIRTHRIGHT_SHIFT_INDEX); + if (birthright.RandomInt(VOID_BIRTHRIGHT_ODDS) == 0 && !player.voidedPassives.empty()) + { + Vector position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + VoidedPassive passive = player.voidedPassives[birthright.RandomInt((uint32_t)player.voidedPassives.size())]; + auto* pickup = static_cast(g_game->Spawn({.position = position, + .spawner = &player, + .subType = passive.id, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = birthright.Next()})); + pickup->itemPoolType = passive.value; + sound_play(SOUND_PORTAL_SPAWN); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + } + } + rng.Next(); + + if (isQueued) void_item_absorb(player, rng, {.id = queued.item->id, .value = queued.itemPoolType}, player.pos); + bool isAbsorbed = false; + for (Entity_Pickup* pickup : pedestals) + { + if (!pickup->isExists || pickup->isDead || pickup->IsShopItem() || pickup->variant != PICKUP_COLLECTIBLE) + continue; + if (pickup->subtype == 0 || pickup->timeout >= 1) continue; + void_item_absorb(player, rng, {.id = pickup->subtype, .value = pickup->itemPoolType}, pickup->pos); + pickup->Remove(); + pickup->RemoveOtherOptions(); + int duplicate = pickup->coopDuplicateIndex; + if (duplicate != -1 && duplicate + 1 < g_game->playerManager.GetNumAlivePlayers()) + { + Vector position = pickup->pos; + pickup->Remove(); + int item = g_game->itemPool.GetCollectible(POOL_BOSS, player.dropRNG.Next(), 0, 0, 0); + auto* choice = static_cast(g_game->Spawn({.position = position, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = player.dropRNG.Next()})); + choice->coopDuplicateIndex = duplicate + 1; + if (choice->coopDuplicateIndex != 0 && choice->coopDuplicateIndex != -1) choice->cycleCollectibleCount = 0; + choice->Update(); + } + isAbsorbed = true; + } + if (isAbsorbed) + { + sound_play(SOUND_VOID_CONSUME); + sound_play(SOUND_VOID_SUCCESS); + } + else sound_play(player.voidedCollectibles.empty() ? SOUND_VOID_FAIL : SOUND_VOID_SUCCESS); + + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) + for (size_t i = 0; i < player.voidedCollectibles.size(); i++) + player.AddWisp(player.voidedCollectibles[i], player.pos, false, false); + player.cacheFlags |= VOID_CACHE_FLAGS; + player.EvaluateItems(); + int roomType = g_game->room->roomType; + if (isAbsorbed && (roomType == ROOM_CHALLENGE || roomType == ROOM_BOSSRUSH)) g_game->ambush.StartChallenge(); + use.isLuaAnimationAllowed = isAbsorbed; + use_animate(use); +} + +// Crooked Penny: a coin flip on the item's generator and the room. Heads doubles every pickup that can be rerolled +// (but empty chests and pedestals), the copy sharing its seed, blindness, pedestal and a new set of options. Tails +// takes them all (lowering shop spikes left under one) and leaves a penny. +static void crooked_penny_use(ItemUse& use) +{ + Entity_Player& player = use.player; + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_CROOKED_PENNY); + Room& room = *g_game->room; + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + + sound_play(SOUND_CROOKED_PENNY); + std::vector pickups = entity_query(ENTITY_PICKUP, -1); + uint32_t seed = rng.Next() ^ room.GetDecorationSeed(); + RNG flip; + flip.SetSeed(seed == 0 ? 1 : seed, CROOKED_PENNY_SHIFT_INDEX); + bool isHeads = flip.RandomInt(2) == 0; + + std::map options; + for (Entity* entity : pickups) + { + auto* pickup = static_cast(entity); + bool isEmpty = pickup->subtype == 0 && + (Entity_Pickup::IsChest(pickup->variant) || (isHeads && pickup->variant == PICKUP_COLLECTIBLE)); + if (!pickup->CanReroll() || isEmpty) continue; + if (!isHeads) + { + int below = room.GetGridIndex(pickup->pos) + room.gridWidth; + GridEntity* spikes = room.GetGridEntity(below); + if (spikes && spikes->type == GRID_SPIKES_ALT && spikes->state == 0) + static_cast(spikes)->unsummon(false); + pickup->Remove(); + continue; + } + + Vector position = room_free_pickup_position_find({.position = pickup->pos, .step = PICKUP_SPOT_STEP}); + auto* copy = static_cast(g_game->Spawn({.position = position, + .spawner = &player, + .subType = pickup->subtype, + .type = ENTITY_PICKUP, + .variant = pickup->variant, + .seed = pickup->initSeed})); + copy->SetForceBlind(pickup->isForceBlind); + copy->SetAlternatePedestal(pickup->GetAlternatePedestal()); + if (pickup->optionsPickupIndex <= 0) continue; + auto option = options.find(pickup->optionsPickupIndex); + if (option != options.end()) copy->optionsPickupIndex = option->second; + else options[pickup->optionsPickupIndex] = copy->AssignOptionsIndex(); + } + if (!isHeads) + g_game->Spawn({.position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}), + .spawner = &player, + .subType = COIN_PENNY, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = rng.Next()}); + use_animate(use); +} + +// Sharp Straw: every vulnerable enemy takes a tenth of its health (a versus player a tenth of its hearts) plus the +// player's damage, and a hurt one bursts blood toward the player (Book of Virtues: a wisp one time in three). Any +// target shakes the screen, and one use in seven leaves a half heart. +static void sharp_straw_use(ItemUse& use) +{ + Entity_Player& player = use.player; + bool isTargetFound = false; + + EntityList_EL& entities = room_entities(); + for (size_t i = 0; i < entities.size(); i++) + { + Entity* target = entities[i]; + if (!target->IsVulnerableEnemy(nullptr) || target == &player || target->HasEntityFlags(FLAG_FRIENDLY)) continue; + float damage = target->maxHitPoints * SHARP_STRAW_SHARE; + if (g_game->deathmatchManager.is_active() && target->is_player()) + { + Entity_Player& rival = *target->ToPlayer(); + int hearts = rival.blackHearts + rival.boneHearts + rival.rottenHearts + rival.goldenHearts + + rival.soulHearts + rival.maxHearts; + damage = (float)hearts * SHARP_STRAW_SHARE; + } + isTargetFound = true; + if (!target->TakeDamage(damage + player.damage, 0, EntityRef(&player), DAMAGE_COUNTDOWN_FRAMES)) continue; + + Vector direction = vector_scale(vector_sub(player.pos, target->pos), SHARP_STRAW_SHARE); + if (vector_length(direction) > SHARP_STRAW_MAX_SPRAY) + direction = vector_resized(direction, SHARP_STRAW_MAX_SPRAY); + uint32_t seed = Random(); + g_game->Spawn({.position = target->pos, + .subType = SHARP_STRAW_EXPLOSION, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = seed}); + int gore = random_below(2) + 2; + int count = gore + random_below(SHARP_STRAW_DROPS_RANGE) + SHARP_STRAW_DROPS_MIN; + for (int i = 0; i < count; i++) + { + Vector turned = tear_vector_rotate(direction, random_unit() * SHARP_STRAW_SPREAD - SHARP_STRAW_SPREAD / 2); + Vector spray = vector_scale(turned, random_unit()); + Vector position = vector_add(target->pos, spray); + uint32_t dropSeed = Random(); + bool isGore = i < gore; + auto* drop = static_cast( + g_game->Spawn({.position = position, + .velocity = isGore ? vector_scale(spray, SHARP_STRAW_GORE_SPEED) : spray, + .subType = isGore ? 0 : SHARP_STRAW_DROP, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = dropSeed})); + drop->Update(); + if (!isGore) drop->fallingSpeed = SHARP_STRAW_DROP_FALL; + } + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed && random_below(3) == 0) + player.AddWisp(COLLECTIBLE_SHARP_STRAW, target->pos, false, false); + } + if (isTargetFound) + { + game_shake_screen(SHARP_STRAW_SHAKE); + sound_play(SOUND_MEAT_JUMPS); + if (player.GetCollectibleRNG(COLLECTIBLE_SHARP_STRAW).RandomInt(100) < SHARP_STRAW_HEART_PERCENT) + { + uint32_t seed = Random(); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + g_game + ->Spawn({.position = position, + .spawner = &player, + .subType = HEART_HALF, + .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, + .seed = seed}) + ->Update(); + } + } + use_animate(use); +} + +// The Moving Box empty packs up to ten free pickups (but empty chests and pedestals) as the room would save them, +// starting a challenge room when a chest or an item goes in. Full, it lets them all out around the player, each set of +// options given a new index. +static void moving_box_use(ItemUse& use) +{ + Entity_Player& player = use.player; + Room& room = *g_game->room; + std::vector& contents = player.movingBoxContents; + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + + if (contents.empty()) + { + sound_play(SOUND_MOVING_BOX_PACK); + std::vector captured; + for (Entity* entity : room_entities()) + { + if (entity->type != ENTITY_PICKUP || entity->isDead) continue; + auto* pickup = static_cast(entity); + bool isEmpty = pickup->subtype == 0 && + (pickup->variant == PICKUP_COLLECTIBLE || Entity_Pickup::IsChest(pickup->variant)); + if (pickup->CanReroll() && !pickup->IsShopItem() && !isEmpty && pickup->timeout < 0) + captured.push_back(pickup); + } + bool isTaken = false; + for (Entity_Pickup* pickup : captured) + { + if (contents.size() >= MOVING_BOX_CAPACITY) break; + if (Entity_Pickup::IsChest(pickup->variant) || pickup->variant == PICKUP_COLLECTIBLE) isTaken = true; + EntitySaveState state; + if (!entity_state_save(room, *pickup, state, MINECART_REFUSED)) continue; + contents.push_back(state); + if (pickup->timeout < 0) + { + uint32_t seed = Random(); + g_game->Spawn({.position = pickup->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + } + pickup->RemoveOtherOptions(); + pickup->Remove(); + } + if (isTaken && (room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH)) + g_game->ambush.StartChallenge(); + use.isLuaAnimationAllowed = isTaken; + return use_animate(use); + } + + sound_play(SOUND_MOVING_BOX_UNPACK); + g_pickupIgnoreModifiers++; + std::map options; + std::vector released; + for (const EntitySaveState& state : contents) + { + Entity* entity = g_game->Spawn({.position = state.targetPosition, + .spawner = &player, + .subType = state.subtype, + .type = state.type, + .variant = state.variant, + .seed = state.initSeed}); + entity_state_restore(room, *entity, state); + released.push_back(entity); + auto* pickup = static_cast(entity); + if (pickup->optionsPickupIndex <= 0) continue; + auto option = options.find(pickup->optionsPickupIndex); + if (option != options.end()) pickup->optionsPickupIndex = option->second; + else + { + int index = pickup->AssignOptionsIndex(); + options[pickup->optionsPickupIndex] = index; + } + } + g_pickupIgnoreModifiers--; + for (Entity* entity : released) + entity->pos = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + contents.clear(); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) + player.AddWisp(COLLECTIBLE_MOVING_BOX, player.pos, false, false); + use_animate(use); +} + +// 0075d800 Puts on the costume of a null item (none for an id out of range). +void Entity_Player::AddNullCostume(int id) +{ + AddCostume(g_manager->itemConfig.GetNullItem(id), false); +} + +// What the Sacrificial Altar gives for a familiar that turns into a pickup instead of being sacrificed: a penny, a half +// heart for a wisp, a half soul heart for an item wisp. None for familiars that are not. +static const EntitySpawn* altar_pickup_get(int variant) +{ + static constexpr EntitySpawn PENNY = {.subType = COIN_PENNY, .type = ENTITY_PICKUP, .variant = PICKUP_COIN}; + static constexpr EntitySpawn HALF_HEART = {.subType = HEART_HALF, .type = ENTITY_PICKUP, .variant = PICKUP_HEART}; + static constexpr EntitySpawn HALF_SOUL = { + .subType = HEART_HALF_SOUL, .type = ENTITY_PICKUP, .variant = PICKUP_HEART}; + switch (variant) + { + case Entity_Familiar::BLUE_FLY: + case Entity_Familiar::BLUE_SPIDER: + case Entity_Familiar::BROWN_NUGGET_POOTER: + case Entity_Familiar::MINISAAC: + case Entity_Familiar::DIP: + case Entity_Familiar::SWARM_FLY_ORBITAL: + case Entity_Familiar::BLOOD_BABY: + return &PENNY; + case Entity_Familiar::WISP: + return &HALF_HEART; + case Entity_Familiar::ITEM_WISP: + return &HALF_SOUL; + default: + return nullptr; + } +} + +// The Sacrificial Altar: the player's spare familiars turn into pennies or hearts, and up to two of its real ones (Lil +// Delirium or any sacrificable one, shuffled) are sacrificed for devil items. An angel among them leaves two black +// hearts, and Judas' Birthright lengthens the damage bonus. A sacrifice darkens the room and gives the altar costume. +static void sacrificial_altar_use(ItemUse& use) +{ + Entity_Player& player = use.player; + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_SACRIFICIAL_ALTAR); + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + + bool isConverted = false; + std::vector candidates; + candidates.reserve(ALTAR_RESERVE); + EntityList_EL& entities = room_entities(); + for (size_t i = 0; i < entities.size(); i++) + { + if (entities[i]->type != ENTITY_FAMILIAR) continue; + auto* familiar = static_cast(entities[i]); + int variant = familiar->variant; + if (familiar->player != &player) continue; + if (player.playerType == PLAYER_LILITH && variant == Entity_Familiar::INCUBUS) continue; + if (g_game->challenge == CHALLENGE_GUARDIAN && variant == Entity_Familiar::PUNCHING_BAG) continue; + + if (const EntitySpawn* drop = altar_pickup_get(variant)) + { + EntitySpawn spawn = *drop; + spawn.position = familiar->pos; + spawn.spawner = familiar; + spawn.seed = familiar->dropRNG._seed; + g_game->Spawn(spawn); + if (drop->variant == PICKUP_COIN) familiar->isDead = true; + else familiar->Kill(EntityRef()); + isConverted = true; + } + else if (familiar->isLilDelirium || (familiar->config->tags & ENTITY_TAG_CANSACRIFICE)) + candidates.push_back(familiar); + } + + for (size_t i = candidates.size(); i-- > 1;) std::swap(candidates[i], candidates[rng.Next() % (uint32_t)(i + 1)]); + size_t sacrifices = std::min(ALTAR_SACRIFICES, candidates.size()); + if (sacrifices == 0 && !isConverted) return use_animate(use); + for (size_t i = 0; i < sacrifices; i++) + { + Entity_Familiar* familiar = candidates[i]; + g_game + ->Spawn( + {.position = familiar->pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}) + ->Update(); + familiar->RemoveFromPlayer(1); + int variant = familiar->variant; + bool isAngel = variant == Entity_Familiar::GUARDIAN_ANGEL || variant == Entity_Familiar::SWORN_PROTECTOR || + variant == Entity_Familiar::SERAPHIM; + for (int heart = 0; isAngel && heart < 2; heart++) + { + uint32_t seed = rng.Next(); + g_game->Spawn({.position = room_free_pickup_position_find({.position = familiar->pos, .step = 1}), + .spawner = familiar, + .subType = HEART_BLACK, + .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, + .seed = seed}); + } + int item = g_game->itemPool.GetCollectibleFromList(ALTAR_ITEMS, rng.Next(), COLLECTIBLE_PENTAGRAM, + LIST_PICK_BLACKLIST); + uint32_t seed = rng.Next(); + auto* pedestal = static_cast( + g_game->Spawn({.position = room_free_pickup_position_find({.position = familiar->pos, .step = 1}), + .spawner = familiar, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed})); + pedestal->itemPoolType = POOL_DEVIL; + g_game->itemPool.AddRoomBlacklist(item); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + player.redStewBonusDuration += ALTAR_BELIAL_FRAMES; + } + + if (use.request.flags & (USE_OWNED | USE_VOID)) use.result.isRemove = true; + g_game->darknessStrength = 1; + g_game->darknessTimeout = ALTAR_DARKNESS_FRAMES; + sound_play(SOUND_SATAN_GROW); + player.AddNullCostume(NULLITEM_SACRIFICIAL_ALTAR); + if (sacrifices > 0 && player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) + player.AddWisp(COLLECTIBLE_SACRIFICIAL_ALTAR, player.pos, false, false); + use_animate(use); +} + +// The Afterbirth and Afterbirth+ actives whose effects are large (477 to 545), else the stop for an uncased active. +void afterbirth_item_effect_run(ItemUse& use) +{ + switch (use.id) + { + case COLLECTIBLE_VOID: + return void_use(use); + case COLLECTIBLE_CLICKER: + return clicker_use(use); + case COLLECTIBLE_CROOKED_PENNY: + return crooked_penny_use(use); + case COLLECTIBLE_SHARP_STRAW: + return sharp_straw_use(use); + case COLLECTIBLE_MOVING_BOX: + return moving_box_use(use); + case COLLECTIBLE_SACRIFICIAL_ALTAR: + return sacrificial_altar_use(use); + default: + return active_missing_report(use); + } +} diff --git a/src/entity_player_actives_grid.cpp b/src/entity_player_actives_grid.cpp new file mode 100644 index 0000000..a123d4f --- /dev/null +++ b/src/entity_player_actives_grid.cpp @@ -0,0 +1,479 @@ +#include "entity_player.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_factory.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "level.h" +#include "npc_basement.h" +#include "room_grid.h" +#include "game.h" +#include "log.h" +#include "loot_list.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "pocket_items.h" +#include "room.h" +#include "room_config.h" +#include "room_descriptor.h" +#include "room_path.h" +#include "grid_entity_door.h" +#include +#include +#include + +// The shifts of the draw among an entity's devolve list, seeded by the room's decoration. +constexpr std::array DEVOLVE_SHIFTS = {4, 3, 27}; +constexpr float DEVOLVE_RANDOM_UNIT = 2.3283062e-10f; +constexpr int GRID_ENTRY_FIRST = 1000; +constexpr int ENTRY_EFFECT_OLD = 999; + +// Whether an entity config walks: a ground grid collision, or none named with collision points. +static bool is_config_walking(const EntityConfig_Entity* config) +{ + if (!config) return true; + std::string_view grid = config->gridCollisionClassString; + return grid == "ground" || (grid.empty() && config->gridCollisionPoints >= 1); +} + +// 00705480 Turns an entity into one of its weaker forms from entities2.xml, drawn by weight on the room's decoration +// seed: an enemy keeps its health share and champion and is counted with the ambush, a flying one turning into a walker +// is moved where the players can reach. A grid form replaces it on its cell with a poof. A friendly entity, one a +// mod keeps or the Delirium cannot change. +bool game_enemy_devolve(Entity& entity, Entity** outEntity) +{ + EntityConfig_Entity* config = entity.config; + if (entity.HasEntityFlags(FLAG_FRIENDLY)) return false; + if (lua_engine_get().PreEntityDevolve(&entity)) return true; + if (!config || config->devolve.empty() || entity.type == ENTITY_DELIRIUM) return false; + + Room& room = *g_game->room; + float healthShare = 1; + int champion = CHAMPION_NONE; + if (entity.IsEnemy()) + { + champion = static_cast(entity).championColorIdx; + if (entity.maxHitPoints > 0) healthShare = std::clamp(entity.health / entity.maxHitPoints, 0.0f, 1.0f); + } + float total = 0; + for (const Devolve& form : config->devolve) total += form.weight; + bool isFlying = !is_config_walking(config); + RNG rng = {room.descriptor ? room.descriptor->decorationSeed : 0, DEVOLVE_SHIFTS[0], DEVOLVE_SHIFTS[1], + DEVOLVE_SHIFTS[2]}; + float roll = (float)rng.Next() * DEVOLVE_RANDOM_UNIT * total; + + for (const Devolve& form : config->devolve) + { + if (roll >= form.weight) + { + roll -= form.weight; + continue; + } + if (form.type >= GRID_ENTRY_FIRST) + { + int gridIndex = room.GetGridIndex(entity.pos); + if (gridIndex != -1) + room_entry_spawn(room, {.type = (uint32_t)form.type, .variant = form.variant}, + {.gridIndex = gridIndex, .seed = Random()}); + if (entity.spawnGridIndex >= 0 && room_entity_is_persistent(entity.type, entity.variant)) + room.descriptor->restrictedGridIndexes.insert(entity.spawnGridIndex); + entity.Remove(); + Entity* poof = g_game->Spawn({.position = room.GetGridPosition(gridIndex), + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = Random()}); + poof->Update(); + if (outEntity) *outEntity = poof; + return true; + } + if (form.type == 0) return false; + + int type = form.type == ENTRY_EFFECT_OLD ? ENTITY_EFFECT : form.type; + int variant = form.variant; + Entity_NPC::Redirect(&type, &variant); + bool isWalking = is_config_walking(g_manager->entityConfig.GetEntity(type, variant, form.subtype)); + if (isFlying && isWalking && !is_reachable_from_player(room, {.position = entity.pos})) + { + reconstruction_missing("Game::DevolveEnemy 00705480: Room::find_reachable_position 00823d10"); + entity.velocity = {}; + } + auto* devolved = static_cast(g_game->Spawn({.position = entity.pos, + .velocity = entity.velocity, + .subType = form.subtype, + .type = type, + .variant = variant, + .seed = Random()})); + if (devolved->IsEnemy()) + { + if (champion >= 0) devolved->Morph(devolved->type, devolved->variant, devolved->subtype, champion); + devolved->AddEntityFlags(FLAG_AMBUSH); + devolved->health = healthShare * devolved->maxHitPoints; + } + devolved->Update(); + devolved->spawnGridIndex = entity.spawnGridIndex; + if (outEntity) *outEntity = devolved; + entity.Remove(); + return true; + } + return false; +} + +// A grid entity or entity the D12 may turn a cell into, with its weight: a negative type is an entity (a fireplace or +// movable TNT) spawned on a decoration. The soft draw holds only the first fifteen rows (00b62d60). +struct D12Outcome +{ + int type = 0; + int variant = 0; + int weight = 0; +}; + +constexpr int D12_SOFT_ROWS = 15; +constexpr uint32_t D12_SHIFT_INDEX = 17; +constexpr uint32_t D12_PICK_SHIFT_INDEX = 35; +constexpr int D12_DECORATION_VARIANT = 1000; +constexpr int D12_ACHIEVEMENT_HOLY_POOP = 398; +constexpr int D12_ACHIEVEMENT_CHARMING_POOP = 605; +constexpr int D12_ACHIEVEMENT_GOLDEN_ROCK = 612; +constexpr int D12_ACHIEVEMENT_SUPERSTITION_ROCK = 323; +constexpr std::array D12_OUTCOMES = { + {{GRID_POOP, 0, 500}, {GRID_POOP, 1, 100}, {GRID_POOP, 2, 100}, + {GRID_POOP, 3, 10}, {GRID_POOP, 4, 10}, {GRID_POOP, 5, 50}, + {GRID_POOP, 6, 10}, {GRID_SPIKES_ONOFF, 0, 100}, {GRID_SPIDERWEB, 0, 150}, + {GRID_TNT, 0, 100}, {-ENTITY_FIREPLACE, 0, 300}, {-ENTITY_FIREPLACE, 1, 150}, + {-ENTITY_MOVABLE_TNT, 0, 50}, {GRID_PRESSURE_PLATE, 1, 10}, {GRID_PRESSURE_PLATE, 9, 1}, + {GRID_ROCK, 0, 500}, {GRID_ROCKB, 0, 250}, {GRID_ROCKT, 0, 25}, + {GRID_ROCK_BOMB, 0, 25}, {GRID_ROCK_ALT, 0, 100}, {GRID_ROCK_SPIKED, 0, 100}, + {GRID_ROCK_GOLD, 0, 25}, {GRID_ROCK_SS, 0, 5}, {GRID_SPIKES, 0, 100}, + {GRID_LOCK, 0, 25}, {GRID_TRAPDOOR, 0, 5}, {GRID_STAIRS, 0, 3}, + {-ENTITY_FIREPLACE, 2, 40}, {-ENTITY_FIREPLACE, 3, 40}}}; + +// An outcome as the run allows it (FUN_005c7bf0): locked poops and rocks fall back to plain ones, and a daily run gets +// a rock for a trapdoor. +static D12Outcome d12_outcome_allowed(D12Outcome outcome) +{ + PersistentGameData& data = g_manager->persistentGameData; + bool isDaily = g_game->dailyChallenge._id != 0; + if (outcome.type == GRID_POOP && outcome.variant == 6 && !data.Unlocked(D12_ACHIEVEMENT_HOLY_POOP)) + return {GRID_POOP, 0}; + if (outcome.type == GRID_POOP && outcome.variant == 11 && !data.Unlocked(D12_ACHIEVEMENT_CHARMING_POOP)) + return {GRID_POOP, 0}; + if (outcome.type == GRID_ROCK_GOLD && !data.Unlocked(D12_ACHIEVEMENT_GOLDEN_ROCK)) return {GRID_ROCK, 0}; + if (outcome.type == GRID_ROCK_SS && !data.Unlocked(D12_ACHIEVEMENT_SUPERSTITION_ROCK)) return {GRID_ROCKT, 0}; + if (outcome.type == GRID_TRAPDOOR && isDaily) return {GRID_ROCK, 0}; + return outcome; +} + +// Which draw a grid entity rerolls with: hard for standing rocks, locks and spikes, soft for webs, on/off spikes and +// standing TNT or poop, none for anything else. +static WeightedOutcomePicker* d12_grid_picker(GridEntity& grid, WeightedOutcomePicker& soft, + WeightedOutcomePicker& hard) +{ + switch (grid.type) + { + case GRID_ROCK: + case GRID_ROCKB: + case GRID_ROCKT: + case GRID_ROCK_ALT: + case GRID_LOCK: + case GRID_ROCK_SS: + case GRID_PILLAR: + case GRID_ROCK_SPIKED: + case GRID_ROCK_GOLD: + return grid.collisionClass != COLLISION_NONE ? &hard : nullptr; + case GRID_SPIKES: + return &hard; + case GRID_SPIKES_ONOFF: + case GRID_SPIDERWEB: + return &soft; + case GRID_TNT: + case GRID_POOP: + return grid.collisionClass != COLLISION_NONE ? &soft : nullptr; + default: + return nullptr; + } +} + +// The D12: every rock, poop, web, TNT, spike and fireplace of the room turns into another at random (rocks and spikes +// from every outcome, the rest from the soft ones), eternal flies without a host leave, and the room's pickups look +// again. +void d12_use(ItemUse& use) +{ + Entity_Player& player = use.player; + Room& room = *g_game->room; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + WeightedOutcomePicker soft; + WeightedOutcomePicker hard; + for (int i = 0; i < (int)D12_OUTCOMES.size(); i++) + { + if (i < D12_SOFT_ROWS) soft.AddOutcomeWeight(i, D12_OUTCOMES[i].weight); + hard.AddOutcomeWeight(i, D12_OUTCOMES[i].weight); + } + std::array rolled; + rolled.fill(-1); + int cells = room.gridWidth * room.gridHeight; + RNG rng; + rng.SetSeed(player.GetCollectibleRNG(COLLECTIBLE_D12).Next(), D12_SHIFT_INDEX); + auto pick = [&](WeightedOutcomePicker& picker) { + RNG pickRng; + pickRng.SetSeed(rng.Next(), D12_PICK_SHIFT_INDEX); + return (int8_t)picker.PickOutcome(pickRng); + }; + + for (int i = 0; i < cells; i++) + { + GridEntity* grid = room.GetGridEntity(i); + WeightedOutcomePicker* picker = grid ? d12_grid_picker(*grid, soft, hard) : nullptr; + if (!picker) continue; + room.RemoveGridEntityImmediate(i, 0, DECORATION_KEPT); + rolled[i] = pick(*picker); + } + + std::vector entities(room_entities().begin(), room_entities().end()); + for (Entity* entity : entities) + { + if (entity->type == ENTITY_ETERNALFLY) + { + if (!entity->parent) entity->Remove(); + continue; + } + bool isFireplace = entity->type == ENTITY_FIREPLACE && entity->entityCollisionClass != ENTCOLL_NONE; + bool isTnt = entity->type == ENTITY_MOVABLE_TNT && entity->entityCollisionClass != ENTCOLL_NONE; + if ((!isFireplace || entity->variant > 3) && !isTnt) continue; + bool isHard = isFireplace && entity->variant >= 2; + + int i = room.GetGridIndex(entity->pos); + if (i < 0 || rolled[i] != -1) continue; + if (GridEntity* grid = room.GetGridEntity(i)) + { + if (is_grid_floor_special(grid->type)) continue; + room.RemoveGridEntityImmediate(i, 0, DECORATION_REMOVED); + } + entity->Remove(); + rolled[i] = pick(isHard ? hard : soft); + } + + for (int i = 0; i < cells; i++) + { + if (rolled[i] == -1) continue; + D12Outcome outcome = d12_outcome_allowed(D12_OUTCOMES[rolled[i]]); + Vector position = room.GetGridPosition(i); + if (outcome.type < 0) + { + room.SpawnGridEntity(i, GRID_DECORATION, D12_DECORATION_VARIANT, rng.Next(), 0); + g_game->Spawn( + {.position = position, .type = -outcome.type, .variant = outcome.variant, .seed = rng.Next()}); + } + else + { + room.SpawnGridEntity(i, (GridEntityType)outcome.type, outcome.variant, rng.Next(), 0); + if (outcome.type == GRID_POOP) continue; + } + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + } + for (int i = 0; i < cells; i++) + if (rolled[i] != -1) + if (GridEntity* grid = room.GetGridEntity(i)) grid->PostInit(); + room.isPickupVisionInvalid = true; + if (use.isShowAnimation) + { + sound_play_local(player, SOUND_D6_ROLL); + player.AnimateCollectible(use.id, "UseItem", "PlayerPickupSparkle"); + } +} + +// 0081fd60 Brings back the enemies of the room's layout (a special miniboss room's override layout), each cell drawn +// again from its spawn seed and never on a restricted cell. Respawned enemies hold the room shut, and whatever still +// stood on their cells goes. With nothing back the room counts as cleared, else its doors close (secret doors keep +// opening as holes). The visit counts again. +void Room::RespawnEnemies() +{ + constexpr std::array RESPAWN_SHIFTS = {2, 7, 7}; + constexpr float RESPAWN_RANDOM_UNIT = 2.3283062e-10f; + RoomDescriptor& room = *descriptor; + RNG rng = {room.spawnSeed, RESPAWN_SHIFTS[0], RESPAWN_SHIFTS[1], RESPAWN_SHIFTS[2]}; + log_printf(LOG_INFO, "SpawnRNG seed: %u\n", room.spawnSeed); + + RoomConfig_Room* layout = room.data; + if (room.overrideData && room.overrideData->stageId == 0 && room.overrideData->type == ROOM_MINIBOSS) + layout = room.overrideData; + room.visitedCount++; + isFirstVisit = false; + + std::set respawnedCells; + std::set respawned; + std::vector spawned; + for (RoomSpawn& spawn : layout->spawns) + { + uint32_t seed = rng.Next(); + int gridIndex = spawn.x + 1 + (spawn.y + 1) * gridWidth; + if (spawn.entries.empty()) continue; + RoomEntry* entry = spawn.PickEntry((float)seed * RESPAWN_RANDOM_UNIT); + if (room.restrictedGridIndexes.contains(gridIndex)) continue; + Entity* entity = nullptr; + if (!room_entry_spawn(*this, *entry, + {.outEntity = &entity, .gridIndex = gridIndex, .seed = seed, .mode = ENTRY_RESPAWN}) || + !entity) + continue; + respawnedCells.insert(gridIndex); + respawned.insert(entity); + spawned.push_back(entity); + } + for (Entity* entity : spawned) + { + entity->Update(); + if (entity->CanShutDoors()) room.flags &= ~(ROOM_DESCRIPTOR_FLAG_CLEAR | ROOM_DESCRIPTOR_FLAG_NO_REWARD); + } + if (respawnedCells.empty()) + { + room.flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; + return; + } + + for (Entity* entity : entityList.updateEL) + if (!respawned.contains(entity) && respawnedCells.contains(entity->spawnGridIndex)) entity->Remove(); + for (GridEntity_Door* door : doors) + { + if (!door || door->state == DOOR_STATE_CLOSED) continue; + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + bool isSecret = std::ranges::any_of(std::array{door->currentRoomType, door->targetRoomType}, [](int type) { + return type == ROOM_SECRET || type == ROOM_SUPERSECRET || type == ROOM_ULTRASECRET; + }); + if (isSecret) door->openAnimation = "Open"; + } +} + +// We Need To Go Deeper and Mom's Shovel: a dirt patch under the player is dug up for a chest (Mom's Shovel only once +// unlocked, else the patch just empties), else the floor is dug where the player stands, kept seventy units off the +// doors: a crawlspace in a decoration the first time a floor allows it, a trapdoor elsewhere (a womb hole bleeds, +// tinted green on the Corpse). Book of Virtues gives Mom's Shovel a broken shovel wisp. +void deeper_use(ItemUse& use) +{ + constexpr int PATCH_UNDUG = 0; + constexpr int PATCH_DUG = 1; + constexpr int PATCH_EMPTIED = 2; + constexpr int ACHIEVEMENT_MOMS_SHOVEL_DIGS = 390; + constexpr std::array DIRT_PATCH_CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_REDCHEST}; + constexpr float DIRT_CHEST_SPEED = 4; + constexpr uint32_t DIRT_PATCH_SHIFT_INDEX = 5; + constexpr float DOOR_CLEARANCE_SQUARED = 4900; + constexpr float DIG_STEP = 20; + constexpr int DIG_TRIES = 20; + constexpr int CRAWLSPACE_DECORATIONS = 31; + constexpr int WOMB_HOLE_PREFIX = 25; + constexpr float WOMB_HOLE_TURN = 90; + constexpr int BLOOD_EXPLOSION_TRAPDOOR = 3; + Entity_Player& player = use.player; + Room& room = *g_game->room; + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_WE_NEED_TO_GO_DEEPER); + bool isDig = true; + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + + int playerCell = room.GetGridIndex(player.pos); + for (Entity* entity : entity_query(ENTITY_EFFECT, EFFECT_DIRT_PATCH)) + { + auto* patch = static_cast(entity); + if (patch->state != PATCH_UNDUG || room.GetGridIndex(patch->pos) != playerCell) continue; + isDig = false; + if (use.id == COLLECTIBLE_MOMS_SHOVEL && !g_manager->persistentGameData.Unlocked(ACHIEVEMENT_MOMS_SHOVEL_DIGS)) + { + patch->state = PATCH_EMPTIED; + continue; + } + patch->state = PATCH_DUG; + RNG chestRng; + chestRng.SetSeed(patch->initSeed, DIRT_PATCH_SHIFT_INDEX); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(patch->pos, &chestRng, 0); + uint32_t seed = chestRng.Next(); + g_game->Spawn({.position = player.pos, + .velocity = vector_scale(velocity, DIRT_CHEST_SPEED), + .type = ENTITY_PICKUP, + .variant = DIRT_PATCH_CHESTS[chestRng.RandomInt(3)], + .seed = seed}); + sound_play(SOUND_SHOVEL_DIG2); + sound_play(SOUND_SHOVEL_HOLE_OPEN); + } + if (use.id == COLLECTIBLE_MOMS_SHOVEL && player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) + player.AddWisp(COLLECTIBLE_BROKEN_SHOVEL_1, player.pos, false, false); + if (!isDig || room.roomType == ROOM_DUNGEON) return use_animate(use); + + Vector digPos = player.pos; + for (GridEntity_Door* door : room.doors) + { + if (!door || vector_length_squared(vector_sub(door->Position(), digPos)) >= DOOR_CLEARANCE_SQUARED) continue; + for (int tries = DIG_TRIES; + tries > 0 && vector_length_squared(vector_sub(door->Position(), digPos)) < DOOR_CLEARANCE_SQUARED; tries--) + digPos = room_free_pickup_position_find({.position = digPos, .step = DIG_STEP}); + break; + } + int cell = room.GetGridIndex(digPos); + GridEntity* grid = room.GetGridEntity(cell); + if (grid && (grid->type == GRID_TRAPDOOR || grid->type == GRID_STAIRS)) return use_animate(use); + + bool isCrawlspace = grid && grid->type == GRID_DECORATION && grid->variant < CRAWLSPACE_DECORATIONS && + !g_game->Level::GetStateFlag(LEVEL_STATE_DUNGEON_ROCK_BROKEN); + room_grid_destroy({.source = EntityRef(&player), .gridIndex = cell}); + if (isCrawlspace) + { + room.SpawnGridEntity(cell, GRID_STAIRS, 0, rng.Next(), 0); + g_game->Level::SetStateFlag(LEVEL_STATE_DUNGEON_ROCK_BROKEN, true); + return use_animate(use); + } + if (!g_game->CanSpawnTrapDoor()) return use_animate(use); + room.SpawnGridEntity(cell, GRID_TRAPDOOR, 0, rng.Next(), 0); + GridEntity* trapdoor = room.GetGridEntity(cell); + if (!trapdoor || trapdoor->type != GRID_TRAPDOOR) return use_animate(use); + + bool isWombHole = + trapdoor->sprite.filename.size() >= WOMB_HOLE_PREFIX && + std::equal(trapdoor->sprite.filename.begin(), trapdoor->sprite.filename.begin() + WOMB_HOLE_PREFIX, + "gfx/grid/door_11_wombhole", [](char a, char b) { return std::tolower(a) == std::tolower(b); }); + if (!isWombHole) + { + sound_play(SOUND_SHOVEL_DIG2); + return use_animate(use); + } + + Entity* blood = g_game->Spawn({.position = trapdoor->Position(), + .subType = BLOOD_EXPLOSION_TRAPDOOR, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->subtype = 0; + blood->sprite.rotation = (float)random_below(4) * WOMB_HOLE_TURN; + if (g_game->IsMausoleumHeartStage() || (g_game->stage == STAGE_WOMB_I && g_game->IsAltPath())) + blood->SetColor(COLOR_GREEN_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->Update(); + sound_play(SOUND_MEAT_JUMPS); + use_animate(use); +} + +// 00820910 Mama Mega's blast in the room, marked as done: at a spot, or (entering a room the blast reaches) two hundred +// units past the first player away from the room's center. +void Room::MamaMegaExplosion(Vector position, Entity_Player* player) +{ + constexpr float MAMA_MEGA_ENTRY_REACH = 200; + descriptor->flags |= ROOM_DESCRIPTOR_FLAG_MAMA_MEGA; + uint32_t seed = Random(); + Entity_Player* first = g_game->playerManager.playerList[0]; + if (!player) player = first; + auto* blast = static_cast(g_game->Spawn({.position = position, + .spawner = player, + .type = ENTITY_EFFECT, + .variant = EFFECT_MAMA_MEGA_EXPLOSION, + .seed = seed})); + if (vector_is_zero(position)) + { + Vector center = vector_add(topLeftPos, vector_scale(vector_sub(bottomRightPos, topLeftPos), 0.5f)); + Vector away = vector_sub(first->pos, center); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, MAMA_MEGA_ENTRY_REACH / distance); + position = vector_add(first->pos, away); + } + blast->targetPosition = position; + blast->Update(); +} diff --git a/src/entity_player_actives_rebirth.cpp b/src/entity_player_actives_rebirth.cpp index 8140ff3..dfd2c04 100644 --- a/src/entity_player_actives_rebirth.cpp +++ b/src/entity_player_actives_rebirth.cpp @@ -18,6 +18,7 @@ #include "manager.h" #include "npc_ai.h" #include "npc_basement.h" +#include "pocket_items.h" #include "room.h" #include "room_grid.h" #include "sfx_manager.h" @@ -407,13 +408,6 @@ static void wisp_reroll(Entity_Familiar& wisp, RNG& rng) wisp.WispInit(); } -// Game::DevolveEnemy, which the D10 calls, is not written yet. -static void game_enemy_devolve(Entity& enemy) -{ - (void)enemy; - reconstruction_missing("Game::DevolveEnemy 00705480"); -} - // The items held up until thrown or let go (Glass Cannon, Friend Ball): the item lifted, its sound played. static void lift_sound_use(ItemUse& use, int sound) { @@ -792,7 +786,7 @@ static void d10_use(ItemUse& use) for (Entity* entity : room_entities()) if (!entity->HasMortalDamage() && !entity->isDead && entity->CanDevolve()) enemies.emplace_back() = entity; for (EntityPtr& enemy : enemies) - if (enemy) game_enemy_devolve(*enemy.get()); + if (enemy) game_enemy_devolve(*enemy.get(), nullptr); } dice_end(use); } @@ -968,7 +962,7 @@ static void flush_npc(ItemUse& use, Entity_NPC& npc) { npc.KillUnique(); if (!npc.IsBoss()) return; - int dips = (int)lerp_clamped(npc.health, 0, npc.maxHitPoints, 0, FLUSH_DIPS_MAX); + int dips = (int)lerp_range(npc.health, {0, npc.maxHitPoints, 0, FLUSH_DIPS_MAX}); bool isCorny = (npc.type == ENTITY_DINGLE && npc.variant == DANGLE) || npc.type == ENTITY_BROWNIE; for (int i = 0; i < dips; i++) { @@ -1476,6 +1470,11 @@ void rebirth_item_effect_run(ItemUse& use) return d4_use(use); case COLLECTIBLE_D10: return d10_use(use); + case COLLECTIBLE_D12: + return d12_use(use); + case COLLECTIBLE_WE_NEED_TO_GO_DEEPER: + case COLLECTIBLE_MOMS_SHOVEL: + return deeper_use(use); case COLLECTIBLE_BLANK_CARD: return blank_card_use(use); case COLLECTIBLE_BOOK_OF_SECRETS: diff --git a/src/entity_player_actives_repentance.cpp b/src/entity_player_actives_repentance.cpp index 6353daa..d192698 100644 --- a/src/entity_player_actives_repentance.cpp +++ b/src/entity_player_actives_repentance.cpp @@ -211,7 +211,11 @@ void game_charm_fart(const Vector& position, float radius, Entity* source) if (entity->type == ENTITY_PLAYER && source && source->IsDescendantOf(entity)) continue; entity->AddCharmed(EntityRef(source), CHARM_FART_FRAMES, false, false); - if (multiplier > 1) reconstruction_missing("Game::CharmFart 00703f90: Gigante Bean's knockback (Entity::AddKnockback)"); + if (multiplier > 1) + entity->AddKnockback( + EntityRef(source), + vector_scale(vector_normalized(vector_sub(entity->pos, position)), GIGANTE_KNOCKBACK_SPEED), + GIGANTE_KNOCKBACK_FRAMES, false); if (multiplier > 2) entity->AddConfusion(EntityRef(source), CHARM_FART_CONFUSION_FRAMES, false); } @@ -532,6 +536,122 @@ static void urn_of_souls_use(ItemUse& use) use.isAddEffect = false; } +// The kind of clot a heart turns into (Lua's ClotSubType), by the heart Sumptorium takes. +enum ClotKind : int +{ + CLOT_RED, + CLOT_SOUL, + CLOT_BLACK, + CLOT_ETERNAL, + CLOT_GOLD, + CLOT_BONE, + CLOT_ROTTEN +}; + +// The heart SpawnClot takes from the soul side: a bone heart, the last soul heart (all of them at no health), or a +// black heart's half, and the clot it makes. +static ClotKind clot_soul_take(Entity_Player& player, bool isFromItem) +{ + int soul = player.soulHearts; + if (player.boneHearts > 0 && player.IsBoneHeart((soul + 1) / 2 + player.boneHearts - 1)) + { + player.AddBoneHearts(-1); + return CLOT_BONE; + } + if (player.GetHealthType() == HEALTH_NO_HEALTH && isFromItem) + { + player.soulHearts = 0; + return CLOT_SOUL; + } + bool isBlack = soul > 0 && player.IsBlackHeart(soul % 2 == 1 ? soul : soul - 1); + if (isBlack && soul % 2 == 1) player.RemoveBlackHeart(soul); + player.AddSoulHearts(-1, false); + return isBlack ? CLOT_BLACK : CLOT_SOUL; +} + +// 007da810 Turns half a heart into a clot familiar thrown out of a spot, with a splat of its blood: a golden heart +// first, an eternal one, red ones while soul or bone hearts are left (rotten ones first), else the soul side unless +// only the reds can pay. From an item (Sumptorium) the player may give its last heart, which can start Astral +// Projection. +void Entity_Player::SpawnClot(Vector position, bool isFromItem) +{ + constexpr int CLOT_ROTTEN_COST = 2; + constexpr int CLOT_ROTTEN_VERSUS_COST = 16; + constexpr float CLOT_THROW_SPEED = 2; + constexpr float CLOT_SPLAT_RISE = -6; + constexpr float CLOT_SPLAT_DEPTH = 10; + constexpr int BLOOD_EXPLOSION_MEDIUM = 2; + HealthType health = GetHealthType(); + bool isCoin = health == HEALTH_COIN; + ClotKind kind = CLOT_RED; + + if (goldenHearts > 0) + { + goldenHearts--; + if (!g_game->deathmatchManager.is_active() && !isDead && goldenHearts > 0) + { + int hearts = (std::min(redHearts, maxHearts) + 1) / 2 + (soulHearts + 1) / 2 + boneHearts; + if (hearts < goldenHearts) + { + BreakGoldenHearts(goldenHearts - hearts); + goldenHearts = hearts; + } + } + kind = CLOT_GOLD; + } + else if (eternalHearts > 0) + { + eternalHearts--; + UpdateHeartDependentEffects(); + kind = CLOT_ETERNAL; + } + else + { + bool isRedFirst = redHearts >= 1 && boneHearts + soulHearts >= 1; + int keptRed = isFromItem ? 0 : (isCoin ? 2 : 1); + if (!isRedFirst && redHearts - rottenHearts <= keptRed) + { + if (boneHearts + soulHearts <= (isFromItem ? 0 : 1)) return; + kind = clot_soul_take(*this, isFromItem); + } + else if (rottenHearts < 1) + { + redHearts -= scale_for_hard_difficulty(isCoin ? 2 : 1); + UpdateHeartDependentEffects(); + } + else + { + rottenHearts--; + redHearts -= g_game->deathmatchManager.is_active() ? CLOT_ROTTEN_VERSUS_COST : CLOT_ROTTEN_COST; + UpdateHeartDependentEffects(); + kind = CLOT_ROTTEN; + } + } + + uint32_t seed = Random(); + Vector direction = random_direction(); + Entity* clot = g_game->Spawn({.position = position, + .velocity = vector_scale(direction, CLOT_THROW_SPEED), + .spawner = this, + .subType = kind, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::BLOOD_BABY, + .seed = seed}); + clot->ClearEntityFlags(FLAG_APPEAR); + clot->Update(); + sound_play(SOUND_MEAT_JUMPS); + Entity* splat = g_game->Spawn({.position = position, + .subType = BLOOD_EXPLOSION_MEDIUM, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splat->SetColor(clot->splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->sprite.offset = vector_make(0, CLOT_SPLAT_RISE); + splat->renderDepthOffset = CLOT_SPLAT_DEPTH; + splat->Update(); + if (isFromItem) try_trigger_astral_projection(); +} + // Sumptorium: a blood clot from the player's health, or for Tainted Eve the clots called back. static void sumptorium_use(ItemUse& use) { @@ -1152,7 +1272,7 @@ static void d7_use(ItemUse& use) RoomConfig_Room* data = room.descriptor->data; bool isBossDungeon = room.roomType == ROOM_DUNGEON && data && (data->subtype == D7_DUNGEON_GIDEON || data->subtype == D7_DUNGEON_ROTGUT); if (room.roomType == ROOM_BOSS || room.IsBeastDungeon() || isBossDungeon || g_game->stage == STAGE_HOME) return; - reconstruction_missing("Room::RespawnEnemies 0081fd60 (the D7's respawn)"); + room.RespawnEnemies(); g_game->isRoomRespawned = true; } @@ -1219,10 +1339,69 @@ static void genesis_use(ItemUse& use) timer->parent = player.GetMainTwin(); } -// R Key's restart a frame after its use: the run starts over from the first floor, items kept. +// 00707ad0 R Key's restart (r_key_timer_callback): the game resets, every stage seed steps on, the stage before the +// backwards path is saved, and the run begins again at the first floor, the stage bar too. A teleport under way lands +// in the start room, any other transition stops. Held items are dropped, and the screen fades in with the players' +// controls off. static void r_key_restart(Entity_Effect*) { - reconstruction_missing("r_key_timer_callback 00707ad0 (R Key's restart of the run)"); + constexpr int STAGE_LAST_SAVED = 8; + constexpr int GREED_STAGE_ICON = -3; + constexpr int BOSS_RUSH_PAR = 36000; + constexpr int BOSS_RUSH_ALT_PAR = 45000; + constexpr float R_KEY_FADE_SPEED = 0.04f; + constexpr float INSTANT_FADE_ALPHA = 1e-5f; + Game& game = *g_game; + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + + game.ResetState(); + for (int stage = 0; stage < STAGE_SEED_COUNT; stage++) game.seedEffects.ForgetStageSeed(stage); + int stage = (int)game.stage; + if (stage > 0 && (stage > STAGE_WOMB_II || !(game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH))) + { + if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) stage++; + if (stage < STAGE_LAST_SAVED) Game::SaveBackwardsStage(stage); + } + game.stage = 0; + game.stageType = STAGETYPE_ORIGINAL; + g_manager->nightmareScene.isDogma = false; + g_manager->nightmareScene.stageIcons[0] = isGreed ? GREED_STAGE_ICON : 0; + bool isAltPar = !isGreed && (int)game.stage <= STAGE_WOMB_II && + (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B); + game.bossRushParTime = isAltPar ? BOSS_RUSH_ALT_PAR : BOSS_RUSH_PAR; + game.SetNextStage(); + game.Init(true); + + RoomTransition& transition = game.roomTransition; + if (transition.mode != TRANSITION_NONE) + { + RoomTransitionAnim animation = transition.animation; + bool isTeleport = animation == TRANSITION_TELEPORT || animation == TRANSITION_GLOWING_HOURGLASS || + animation == TRANSITION_D7 || animation == TRANSITION_WOMB_TELEPORT; + if (isTeleport) + game.StartRoomTransition({.player = game.playerManager.roomTransitionPlayer, + .animation = TRANSITION_TELEPORT, + .roomIndex = game.startingRoomIdx}); + else + { + transition.mode = TRANSITION_NONE; + transition.frame = 0; + transition.progress = 0; + transition.direction = {}; + transition.animation = TRANSITION_WALK; + transition.flags = 0; + game.playerManager.roomTransitionPlayer = nullptr; + } + } + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->IsHoldingItem()) player->heldSprite.Reset(); + player->queuedItem = {}; + } + game.fadeInColor = kcolor_rgba(0, 0, 0, game.isInstantFadeIn ? INSTANT_FADE_ALPHA : 1); + game.fadeSpeed = R_KEY_FADE_SPEED; + game.isFadeInIconShown = true; + for (Entity_Player* player : game.playerManager.playerList) player->isControlsEnabled = false; } // R Key's item raised again a few frames after its use, once the restart has begun. @@ -1572,6 +1751,6 @@ void repentance_item_effect_run(ItemUse& use) case COLLECTIBLE_MOMS_SHOVEL: return rebirth_item_effect_run(use); default: - return active_missing_report(use); + return afterbirth_item_effect_run(use); } } diff --git a/src/entity_player_cards.cpp b/src/entity_player_cards.cpp index 3dace13..e633a91 100644 --- a/src/entity_player_cards.cpp +++ b/src/entity_player_cards.cpp @@ -930,6 +930,120 @@ static Entity* card_poof_spawn(const Vector& position, Entity* spawner) .seed = Random()}); } +// Hagalaz: the rock enemies a broken rock kills, and those it bares into a fleshier form. +constexpr std::array, 27> HAGALAZ_KILLED = { + {{821, 0}, {23, 3}, {859, 0}, {41, 3}, {818, 0}, {818, 1}, {818, 2}, {302, 0}, {302, 10}, + {826, 0}, {42, 0}, {42, 1}, {42, 2}, {201, 0}, {202, 0}, {202, 10}, {203, 0}, {235, 0}, + {236, 0}, {804, 0}, {809, 0}, {44, 0}, {44, 1}, {877, 0}, {893, 0}, {852, 0}, {915, 1}}}; +constexpr std::array, 10> HAGALAZ_BARED = {{{ENTITY_HOST, 0, ENTITY_HOST, 1}, + {ENTITY_HOST, 3, ENTITY_HOST, 1}, + {ENTITY_MOBILE_HOST, 0, ENTITY_FLESH_MOBILE_HOST, 0}, + {ENTITY_KNIGHT, 0, ENTITY_BRAIN, 0}, + {ENTITY_KNIGHT, 2, ENTITY_PON, 0}, + {ENTITY_KNIGHT, 4, ENTITY_PON, 0}, + {ENTITY_FLOATING_KNIGHT, 0, ENTITY_BRAIN, 0}, + {ENTITY_BONE_KNIGHT, 0, ENTITY_BRAIN, 0}, + {ENTITY_DEATHS_HEAD, 0, ENTITY_FLESH_DEATHS_HEAD, 0}, + {ENTITY_DEATHS_HEAD, 3, ENTITY_FLESH_DEATHS_HEAD, 0}}}; +constexpr std::array HAGALAZ_SHIFTS = {5, 27, 25}; +constexpr float HAGALAZ_SHELL_DAMAGE = 40; +constexpr int HAGALAZ_DUST_MIN = 6; +constexpr uint32_t HAGALAZ_DUST_RANGE = 6; +constexpr float HAGALAZ_DUST_SPEED = 5; +constexpr float HAGALAZ_DUST_SPREAD = 20; +constexpr float HAGALAZ_DUST_SPIN_MIN = 2; +constexpr float HAGALAZ_DUST_SPIN_RANGE = 10; +constexpr int HAGALAZ_DUST_FRAMES = 15; +constexpr float HAGALAZ_DUST_ALPHA_MIN = 0.2f; +constexpr float HAGALAZ_DUST_ALPHA_RANGE = 0.5f; +constexpr float HAGALAZ_QUIET_VOLUME = 0.8f; + +// A puff of dust thrown from a bared rock enemy, spinning away from where it flies. +static void hagalaz_dust_spawn(Entity& npc) +{ + Vector heading = random_direction(); + Vector velocity = vector_scale(heading, random_unit() * HAGALAZ_DUST_SPEED); + uint32_t seed = Random(); + Vector away = random_direction(); + Vector position = vector_add(npc.pos, vector_scale(away, random_unit() * HAGALAZ_DUST_SPREAD)); + auto* dust = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + Vector offset = vector_sub(dust->pos, npc.pos); + float side = offset.x * velocity.y - offset.y * velocity.x < 0 ? -1.0f : 1.0f; + dust->rotation = (random_unit() * HAGALAZ_DUST_SPIN_RANGE + HAGALAZ_DUST_SPIN_MIN) * side; + dust->timeout = (int)(Random() % HAGALAZ_DUST_FRAMES) + HAGALAZ_DUST_FRAMES; + dust->lifespan = dust->timeout; + dust->sprite.scale = vector_make(1, 1); + float alpha = random_unit() * HAGALAZ_DUST_ALPHA_RANGE + HAGALAZ_DUST_ALPHA_MIN; + dust->SetColor({{1, 1, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->Update(); +} + +// What Hagalaz does to a rock enemy: the ones made of rock die, the armored ones lose their shell (with dust), and +// Larry Jr.'s shelled variants take a hit. +static void hagalaz_enemy_break(Entity_Player& player, Entity_NPC& npc) +{ + for (auto [type, variant] : HAGALAZ_KILLED) + { + if (npc.type != type || npc.variant != variant) continue; + npc.Kill(EntityRef()); + sound_play(SOUND_ROCK_CRUMBLE); + break; + } + for (const std::array& bared : HAGALAZ_BARED) + { + if (npc.type != bared[0] || npc.variant != bared[1]) continue; + if (npc.type == ENTITY_DEATHS_HEAD) npc.isInvincible = false; + npc.Morph(bared[2], bared[3], 0, CHAMPION_NONE); + g_manager->sfxManager.Play(SOUND_DEATH_BURST_SMALL, + {.volume = player.config->gibsAmount < 1 ? HAGALAZ_QUIET_VOLUME : 1.0f}); + uint32_t dust = Random() % HAGALAZ_DUST_RANGE + HAGALAZ_DUST_MIN; + for (uint32_t i = 0; i < dust; i++) hagalaz_dust_spawn(npc); + sound_play(SOUND_ROCK_CRUMBLE); + break; + } + if (npc.type == ENTITY_LARRYJR && (npc.variant == 2 || npc.variant == 3) && npc.i2 == 0) + { + sound_play(SOUND_ROCK_CRUMBLE); + npc.TakeDamage(HAGALAZ_SHELL_DAMAGE, DAMAGE_EXPLOSION, EntityRef(), DAMAGE_COUNTDOWN_FRAMES); + } +} + +// 005b23f0 Hagalaz: every grid entity inside the walls but doors is destroyed (a superstition rock twice), and every +// rock enemy broken, with its giant book. Given a generator (a Rune Shard), only one in four of each is, the rest of +// the grid hurt once, drawn from a copy of the generator. +void Entity_Player::use_card_hagalaz(RNG* rng) +{ + Room& room = *g_game->room; + RNG draw = {rng ? rng->_seed : 0, HAGALAZ_SHIFTS[0], HAGALAZ_SHIFTS[1], HAGALAZ_SHIFTS[2]}; + auto isPicked = [&]() { + return !rng || (draw.Next() & 3) == 0; + }; + + for (int x = 1; x < room.gridWidth - 1; x++) + for (int y = 1; y < room.gridHeight - 1; y++) + { + GridEntity* grid = room.GetGridEntity(room.GetGridIndexByTile(x, y)); + if (!grid || grid->type == GRID_DOOR) continue; + if (!isPicked()) + { + grid->Hurt(1, EntityRef(this)); + continue; + } + grid->Destroy(false, EntityRef(this)); + if (grid->type == GRID_ROCK_SS) grid->Destroy(false, EntityRef(this)); + } + + EntityList_EL& entities = room.GetEntities()->updateEL; + for (size_t i = 0; i < entities.size(); i++) + if (Entity::is_enemy_type(entities[i]->type) && isPicked()) + hagalaz_enemy_break(*this, *static_cast(entities[i])); + if (!rng) g_game->itemOverlay.Show(GIANTBOOK_HAGALAZ, 4, nullptr); +} + // Blank Rune: another rune's effect at random (one a versus match allows), and a quarter of the time a new Blank Rune // unless the use is mimicked. static PocketUseEnd blank_rune_use(PocketUse& use) diff --git a/src/entity_player_costumes.cpp b/src/entity_player_costumes.cpp index 586182e..b681aca 100644 --- a/src/entity_player_costumes.cpp +++ b/src/entity_player_costumes.cpp @@ -6,6 +6,7 @@ #include "weapon_umbilical_whip.h" #include #include +#include #include #include @@ -31,6 +32,37 @@ constexpr int MAGGY_HUG_SQUASH_FRAMES = 8; constexpr int MAGGY_HUG_SQUASH_LAST = 6; constexpr float MAGGY_HUG_LIFT = 4; +constexpr float ADRENALINE_FULL_HEARTS = 24; +constexpr float ADRENALINE_RATE_GROWTH = 9; +constexpr float ADRENALINE_PERIOD_FRAMES = 30; +constexpr float ADRENALINE_BEAT_SCALE = 1.2f; +constexpr float ADRENALINE_BEAT_FLOOR = 0.2f; +constexpr float ADRENALINE_HEAD_SQUASH = 0.1f; +constexpr int ADRENALINE_ECHO_LAG = 3; +constexpr int ADRENALINE_LIFT_LEAD = 10; +constexpr int ADRENALINE_HEAD_LEAD = 20; +constexpr float CHARGE_PULSE_RATE = 0.2f; +constexpr int AZAZELS_RAGE_FULL = 4; +constexpr int MARS_FLASH_PERIOD = 30; +constexpr int REVERSE_CHARIOT_SLOW_FROM = 24; +constexpr int REVERSE_CHARIOT_FLASH_STEPS = 4; +constexpr float BERSERK_SHAKE_RATE = 1.5707964f; +constexpr float BERSERK_THROB_RATE = 1.2566371f; +constexpr float BERSERK_FADE = 0.3f; +constexpr float BERSERK_RED = 0.4f; +constexpr float JELLY_BELLY_FRAMES = 20; +constexpr float JELLY_BELLY_PERIOD = 10; +constexpr float JELLY_BELLY_DEPTH = 0.4f; +constexpr float JELLY_BELLY_LIFT = 3; +// Reverse Chariot's sideways shake by frames left (the exe's table at 00babc60). +constexpr float REVERSE_CHARIOT_SHAKE[] = {0, -0.5f, -1, 0.5f, 2, 1, 0}; +constexpr int REVERSE_CHARIOT_SHAKE_LAST = 6; +// The effects' tints, with the exe's values: Midas' gold statue (00c811cc), Mars' ready flash and Reverse Chariot's +// red. +constexpr ColorMod MIDAS_GOLD = {{1, 1, 1, 1}, {2, 1.5f, 0.1f, 1}, {0.1f, 0.02f, 0}}; +constexpr ColorMod MARS_READY_FLASH = {{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0.3f, 0, 0}}; +constexpr ColorMod REVERSE_CHARIOT_RED = {{1, 0.6f, 0.6f, 1}, {0, 0, 0, 0}, {0.3f, 0, 0}}; + // 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. @@ -53,9 +85,122 @@ 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. +// Adrenaline's heartbeat, faster and stronger the more red hearts are missing (a quarter of them in the versus mode): +// the body pulses, the head bobs and squashes a few frames apart. +static void adrenaline_look_read(Entity_Player& player, LayerLook& look) +{ + int missing = (player.boneHearts * 2 - player.redHearts + player.maxHearts) / 2; + if (g_game->deathmatchManager.is_active()) missing = (int)((uint32_t)missing >> 2); + float strength = (float)missing / ADRENALINE_FULL_HEARTS; + float reach = 1 - (1 - strength) * (1 - strength); + float rate = + ((strength * ADRENALINE_RATE_GROWTH * strength + 1) * 2 * std::numbers::pi_v) / ADRENALINE_PERIOD_FRAMES; + float swing = reach * 0.5f; + int frame = g_game->frameCount; + auto beat = [rate](int at) { + float wave = (std::sin((float)at * rate) * 0.5f + 0.5f) * ADRENALINE_BEAT_SCALE; + return std::pow(wave, 2.0f) - ADRENALINE_BEAT_FLOOR; + }; + + float pulse = beat(frame) * swing + 1; + float echo = beat(frame - ADRENALINE_ECHO_LAG) * strength * strength; + look.bodySquash = vector_make((1 / pulse - 1) * 0.5f + 1 + echo, echo * 0.5f + pulse); + look.headLift = beat(frame + ADRENALINE_LIFT_LEAD) * swing; + float headY = beat(frame + ADRENALINE_HEAD_LEAD) * reach * ADRENALINE_HEAD_SQUASH + 1; + look.headSquash = vector_make(1 / headY, headY); +} + +// The head tints of a charge: red as it fills, pulsing once full. +static float charge_tint_get(float filled, bool isFull) +{ + if (!isFull) return filled; + return (std::sin((float)g_game->frameCount * CHARGE_PULSE_RATE) * 0.25f + 0.75f) * filled; +} + +// The tints the effects lay on the head and body: Midas' gold on a statue, the bladder's and IBS's red charge and +// the damage flash (or Azazel's Rage's full charge) on the head, Mars' ready flash, Reverse Chariot's red fading in +// over its last frames and Berserk!'s red throb. +static void tint_look_read(Entity_Player& player, LayerLook& look) +{ + TemporaryEffects& effects = player.temporaryEffects; + int frame = g_game->frameCount; + auto tint_both = [&look](const ColorMod& tint) { + color_multiply(look.headColor, tint); + color_multiply(look.bodyColor, tint); + }; + + bool isStatue = (player.HasCollectible(COLLECTIBLE_GNAWED_LEAF) && player.mass == STATUE_MASS) || + effects.HasNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE); + if (player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH) && isStatue) tint_both(MIDAS_GOLD); + + float charge = 0; + if (player.bladderCharge > 0) + { + float filled = (float)player.bladderCharge / (float)player.maxBladderCharge; + charge = charge_tint_get(filled, player.bladderCharge >= player.maxBladderCharge); + } + else if (player.ibsChargeBar > 0) charge = charge_tint_get(player.ibsChargeBar, player.ibsChargeBar >= 1); + if (player.bladderCharge > 0 || player.ibsChargeBar > 0) + color_multiply(look.headColor, {{1, 1 - charge, 1 - charge, 1}, {0, 0, 0, 0}, {0, 0, 0}}); + + if (player.flashCountdown > 0 || effects.GetCollectibleEffectNum(COLLECTIBLE_AZAZELS_RAGE) == AZAZELS_RAGE_FULL) + { + float flash = std::sin((float)frame * CHARGE_PULSE_RATE) * 0.5f + 0.5f; + color_multiply(look.headColor, {{1, 1 - flash * 0.75f, 1 - flash, 1}, {0, 0, 0, 0}, {0, 0, 0}}); + } + if (player.HasCollectible(COLLECTIBLE_MARS) && player.marsCooldown < 1 && + player.FrameCount() % MARS_FLASH_PERIOD < 2) + color_multiply(look.headColor, MARS_READY_FLASH); + + if (TemporaryEffect* chariot = effects.GetNullEffect(NULLITEM_REVERSE_CHARIOT); + chariot && chariot->cooldown < REVERSE_CHARIOT_FLASH_FRAMES) + { + int step = chariot->cooldown >= REVERSE_CHARIOT_SLOW_FROM ? chariot->cooldown % 16 : chariot->cooldown % 8; + if (step <= REVERSE_CHARIOT_FLASH_STEPS) + tint_both(color_lerp(COLOR_DEFAULT, REVERSE_CHARIOT_RED, (float)step * 0.25f)); + } + if (effects.HasCollectibleEffect(COLLECTIBLE_BERSERK)) + { + look.headOffset.x += std::sin(player.updateTime * BERSERK_SHAKE_RATE); + float throb = std::sin(player.updateTime * BERSERK_THROB_RATE) * 0.5f + 0.5f; + tint_both( + {{1, throb * BERSERK_FADE, throb * BERSERK_FADE, 1}, {0, 0, 0, 0}, {(1 - throb) * BERSERK_RED, 0, 0}}); + } +} + +// The squashes of a bounce: Tainted Magdalene's hug and Jelly Belly's wobble, and Reverse Chariot's shake sideways. +static void squash_look_read(Entity_Player& player, LayerLook& look) +{ + auto squash = [&look](float body, float head, float lift) { + look.bodySquash = vector_make(look.bodySquash.x * (2 - body), look.bodySquash.y * body); + look.headSquash = vector_make(look.headSquash.x * (2 - head), look.headSquash.y * head); + look.headLift += (head - 1) * lift; + }; + + if (player.maggySwingCooldown > 0) + { + if (!player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) player.maggySwingCooldown--; + int step = std::clamp(MAGGY_HUG_SQUASH_FRAMES - player.maggySwingCooldown, 0, MAGGY_HUG_SQUASH_LAST); + squash(MAGGY_HUG_SQUASH[step], MAGGY_HUG_SQUASH[step], MAGGY_HUG_LIFT); + } + if (player.jellyBellyBounceTimer > 0) + { + float timer = std::max(player.jellyBellyBounceTimer - player.speedMultiplier, 0.0f); + player.jellyBellyBounceTimer = timer; + auto wobble = [](float at) { + return 1 - (at / JELLY_BELLY_FRAMES) * + std::sin((at + at) * std::numbers::pi_v / JELLY_BELLY_PERIOD) * JELLY_BELLY_DEPTH; + }; + squash(wobble(timer), wobble(timer + 1), JELLY_BELLY_LIFT); + } + if (player.reverseChariotMoveCooldown > 1) + look.offsetX = REVERSE_CHARIOT_SHAKE[std::min(player.reverseChariotMoveCooldown, REVERSE_CHARIOT_SHAKE_LAST)]; +} + +// Reads how the player's layers draw this frame: the head's size from the head costume's frame (Pluto's and Inner +// Child's heads keep theirs), Adrenaline's heartbeat, the head's offset and size from the body costume's HeadTransform +// null (lower under Tainted Lilith's Gello, riding Tainted Forgotten's height), the effects' tints and squashes, and a +// bleeding out player reddening. Hot Potato's bomb head and a remote player's fading stop the game until reached. static void layer_look_read(Entity_Player& player, LayerLook& look) { PlayerCostumeMap& head = player.playerCostumeMap[PLAYER_LAYER_HEAD]; @@ -68,34 +213,9 @@ static void layer_look_read(Entity_Player& player, LayerLook& look) 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.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)"); - if (player.maggySwingCooldown > 0) - { - if (!player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) player.maggySwingCooldown--; - int step = std::clamp(MAGGY_HUG_SQUASH_FRAMES - player.maggySwingCooldown, 0, MAGGY_HUG_SQUASH_LAST); - float squash = MAGGY_HUG_SQUASH[step]; - look.headSquash = vector_make(look.headSquash.x * (2 - squash), look.headSquash.y * squash); - look.bodySquash = vector_make(look.bodySquash.x * (2 - squash), look.bodySquash.y * squash); - look.headLift += (squash - 1) * MAGGY_HUG_LIFT; - } + bool isAdrenaline = player.HasCollectible(COLLECTIBLE_ADRENALINE) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ADRENALINE); + if (isAdrenaline && player.IsExtraAnimationFinished()) adrenaline_look_read(player, look); PlayerCostumeMap& body = player.playerCostumeMap[PLAYER_LAYER_BODY]; if (body.index >= 0) @@ -106,15 +226,23 @@ static void layer_look_read(Entity_Player& player, LayerLook& look) look.headSize = transform->scale; if (player.playerType == PLAYER_LILITH_B) look.headOffset.y -= (float)(gello_look_get(player) * 2); } + + tint_look_read(player, look); + squash_look_read(player, look); + if (g_game->challenge == CHALLENGE_HOT_POTATO && player.playerType == PLAYER_THEFORGOTTEN_B) + reconstruction_missing("Entity_Player::Update 00782af0 (Hot Potato's bomb head)"); 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); + if (isBleeding) + { + 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); + } + if (!player.IsLocalPlayer()) reconstruction_missing("Entity_Player::Update 00782af0 (a remote player's fading)"); } // Poses the player's own layers: the body ones tinted and squashed by the body's scale, the head ones tinted, sized by @@ -174,7 +302,7 @@ void Entity_Player::costume_layers_update() 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); + bool isWhole = isPlayingExtraAnimation && !IsItemCostumeVisible(megaMush, -1); player_layers_pose(*this, look, isWhole); std::set worn; diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index 46e5e50..b68e336 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -37,6 +37,7 @@ constexpr int ZODIAC = 392; constexpr int ENTITY_SEGMENTED_WORM = 903; constexpr int ENTITY_DAMAGE_RELAY = 966; +constexpr int SIREN_CHARM_SPARE_FRAMES = 29; constexpr int SEGMENTED_WORM_VARIANT = 10; constexpr int WHITE_FIRE_VARIANT = 4; constexpr int EFFECT_SELF_DAMAGE = 19; @@ -490,6 +491,17 @@ static bool hit_items_check(Entity_Player& player, int amount, const ItemsHit& h return isHurtShown; } +// Whether the hit comes from a familiar the Siren charmed under 30 frames ago, or from a relay of its hits. +static bool is_siren_charm_fresh(const EntityRef& source) +{ + Entity* hitter = source.type == ENTITY_DAMAGE_RELAY && source.entity ? source.entity->parent.get() : nullptr; + if (source.type == ENTITY_FAMILIAR) hitter = source.entity; + if (!hitter || hitter->type != ENTITY_FAMILIAR) return false; + + int frames = static_cast(hitter)->sirenCharmFrames; + return frames >= 1 && frames <= SIREN_CHARM_SPARE_FRAMES; +} + // 007729d0 The player takes a hit: the hit is ignored or turned by many items, then costs its hearts, plays the hurt // grunt and the Hit animation, starts the invincibility frames, and kills the player out of hearts. True when it hurt. bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) @@ -502,8 +514,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if (twin->itemState == COLLECTIBLE_GLASS_CANNON) twin->bodySprite.Reset(); return twin->TakeDamage(damage, damageFlags, source, damageCountdown); } - if (source.entity && (source.type == ENTITY_DAMAGE_RELAY || source.type == ENTITY_FAMILIAR)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a familiar or relay source)"); + if (is_siren_charm_fresh(source)) return false; if (is_wisp_shield_present(*this)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (wisp shields)"); if (source.type == ENTITY_FIREPLACE && source.variant == WHITE_FIRE_VARIANT) { @@ -993,3 +1004,10 @@ void Entity_Player::ResetItemState() PlayExtraAnimation("HideItem"); itemState = 0; } + +// 006dad80 Notes the last damage the player took, as a deal or a trinket's price does without a hit. +void Entity_Player::set_last_damage(uint64_t damageFlags, const EntityRef& source) +{ + lastDamageFlags = damageFlags; + lastDamageSource = source; +} diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index 20a12f2..b74b9d4 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -203,12 +203,8 @@ static void voice_play(int sound, float pitch) // Mysterious Paper's chance of Missing Poster), the held entity is thrown, the ghost shows, and a run lost forgets its // save. The player slows to a halt, cries out on the animation's DeathSound, takes its twin down with it once the // animation shows, and vanishes when it ends. -// Update returns into this before its base entity update, which the original runs for the dead too, so it runs here. void Entity_Player::death_update() { - Entity::Update(); - if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) bodySprite.Update(); - Game& game = *g_game; std::string_view animation = GetDeathAnimName(); bool isTransitioning = game.roomTransition.mode != TRANSITION_NONE || game.stageTransition.state != 0; @@ -274,7 +270,8 @@ void Entity_Player::death_update() // 007a6680 Leaves the room: the queued item is added, room-long states end (Holy Mantle's unless kept), the compass, // Metronome's item, Bat Wing's wings and Wavy Cap's trip wear off, the temporary effects clear, the costumes of actives -// no longer worn come off, a held item is put away, and a soul player of the Forgotten or Jacob leaves. +// no longer worn come off, a held item is put away, the room's trail is kept for the Void's hallucinations when it is +// the longest walked, and a soul player of the Forgotten or Jacob leaves. // The after-images and the deathmatch's damage are not modeled. void Entity_Player::room_exit(bool isKeepHolyMantle) { @@ -332,6 +329,12 @@ void Entity_Player::room_exit(bool isKeepHolyMantle) ResetItemState(); itemStateCooldown = 0; } + if (roomTrail.distance > hallucinationTrail.distance) + { + hallucinationTrail.frames = roomTrail.frames; + hallucinationTrail.distance = roomTrail.distance; + } + hallucinationTrail.current = 0; bool isSoulPlayer = temporaryEffects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN) || temporaryEffects.HasNullEffect(NULLITEM_SOUL_JACOB); diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index ebae5ee..e120d65 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -81,7 +81,6 @@ constexpr int BLOOD_LUST_COLOR_CAP = 6; constexpr float BLOOD_LUST_COLOR_STEP = 0.125f; constexpr float BERSERK_CHARGE_FULL = 100000; constexpr float HOLOGRAM_ALPHA = 0.2f; -constexpr float COLOR_OFFSET_UNIT = 0.003921569f; constexpr float HELD_THROW_SCALE = 0.1f; constexpr float TAINTED_BETHANY_STAT_SCALE = 0.75f; constexpr float SAMSONS_LOCK_CAP = 5; @@ -105,12 +104,6 @@ constexpr int DAILY_LUCKY = 23; constexpr int DAILY_SLOW = 43; constexpr float DAILY_LUCK_BONUS = 50; -// Whether the player owns any of the listed collectibles. -static bool is_owning_any(Entity_Player& player, std::span collectibles) -{ - return std::ranges::any_of(collectibles, [&](int id) { return player.HasCollectible(id); }); -} - // Whether the player has a collectible, or its temporary effect. static bool is_having(Entity_Player& p, int collectible) { @@ -160,12 +153,12 @@ static void bulbs_apply(Entity_Player& p, float& stat, float dimScale, float vib if (p.HasTrinket(TRINKET_VIBRANT_BULB) && isFull) stat = trinket_num(p, TRINKET_VIBRANT_BULB) * vibrantScale + stat; } -// The temporary effects the frame (00782af0) and its items' (00794e50), shooting (0077b020) and body (00779b40) parts -// ask about by id but do not run yet: collectible effects, null effects and Faded Polaroid's. An effect the frame -// never asks about only counts down there. -constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {28, 65, 130, 147, 160, 181, 282, 325, 326, 409, 475, 478, 493, 497, 522, - 543, 550, 593, 625, 632, 640, 673, 688, 699, 704, 705, 713, 714, 726, 729}; -constexpr int FRAME_NULL_EFFECTS[] = {48, 50, 55, 59, 60, 61, 62, 63, 66, 69, 70, 111, 114, 116, 117, 122, 128}; +// The temporary effects the items' frame (update_effects 00794e50) and the shooting part (0077b020) ask about by id +// but do not run yet: collectible effects, null effects and Faded Polaroid's. An effect the frame never asks about +// only counts down there. The frame's own part (00782af0) runs or stops on its own. +constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {28, 65, 130, 147, 160, 181, 325, 326, 409, 475, 497, 522, 543, + 550, 593, 625, 640, 673, 688, 699, 704, 705, 713, 714, 726, 729}; +constexpr int FRAME_NULL_EFFECTS[] = {48, 50, 59, 60, 61, 62, 66, 69, 70, 111, 114, 116, 122, 128}; constexpr int FRAME_TRINKET_EFFECTS[] = {TRINKET_FADED_POLAROID}; // Whether the frame runs a temporary effect: the effects written for it, and those it never asks about. @@ -180,16 +173,6 @@ static bool is_frame_effect_known(const TemporaryEffect& effect) return std::ranges::find(unwritten, effect.item->id) == unwritten.end(); } -// Whether the character and run are ones the frame is reconstructed for, with only temporary effects it runs. -bool Entity_Player::is_character_plain() -{ - Game& game = *g_game; - return is_character_reconstructed(*this) && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && !hasCurseMistEffect && - game.challenge == 0 && game.dailyChallenge._id == 0 && game.seedEffects.CountSeedEffects() == 0 && - !game.deathmatchManager.is_active() && std::ranges::all_of(temporaryEffects.effects, is_frame_effect_known) && - proceduralItems.empty(); -} - // What every section of the evaluation starts from: the bonuses Experimental Treatment, Binge Eater's foods, Candy // Heart and Soul Locket give (damage, tears, range, shot speed, speed and luck), Cracked Crown's scale, and whether // the curse mist or a co-op ghost drops the pills and stat modifiers. @@ -1513,19 +1496,32 @@ void Entity_Player::EvaluateItems() cacheFlags = 0; } -// The collectibles the frame (00782af0) and its items' part (update_effects 00794e50) look at, which the plain path -// does not cover yet: Judas's kept Book of Belial among them, Jupiter and Berserk!, and the auras and timers of Linger -// Bean, Dad's Ring, 2Spooky, 120 Volt, Monstrance, Venus, Purgatory, Tooth and Nail and IBS. The weapon items are not: -// the frame never asks for them, their weapons do. Midas' Touch only tints a Gnawed Leaf statue or a frozen player. -constexpr int FRAME_ITEMS[] = {465, 493, 497, 575, 593, 619, 632, 641, 59, 399, 594, 704, - 447, 546, 554, 559, 574, 591, 634, 663, 725}; +// The collectibles the items' part of the frame (update_effects 00794e50) looks at, which the plain path does not +// cover yet: Analog Stick's aim, Camo Undies, Mars, the Birthright, Akeldama, Judas's kept Book of Belial, Berserk!, +// and the auras and timers of Linger Bean, Dad's Ring, 2Spooky, 120 Volt, Monstrance, Venus, Purgatory, Tooth and Nail +// and IBS. The weapon items are not: the frame never asks for them, their weapons do. +constexpr int FRAME_ITEMS[] = {465, 497, 593, 619, 641, 59, 704, 447, 546, 554, 559, 574, 591, 634, 663, 725}; // The trinkets the items' frame (00794e50) looks at that it does not run yet: Faded Polaroid and Extension Cord. constexpr std::array FRAME_TRINKETS = {69, 125}; -// Whether the player's frame runs its plain path: a plain character holding none of the items the frame handles. -bool Entity_Player::is_frame_plain() +// What the player's frame does not run yet, empty when it runs its plain path: a character or run it is not +// reconstructed for, a temporary effect it asks about but does not run, or an item or trinket it handles. +std::string Entity_Player::frame_gap() { - return is_character_plain() && !is_owning_any(*this, FRAME_ITEMS) && - std::ranges::none_of(FRAME_TRINKETS, [this](int trinket) { return HasTrinket(trinket); }); + Game& game = *g_game; + if (!is_character_reconstructed(*this)) return "character " + std::to_string(playerType); + if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost || hasCurseMistEffect) return "a co-op baby, ghost or the mist"; + if (game.challenge != 0 || game.dailyChallenge._id != 0) return "a challenge or daily run"; + if (game.seedEffects.CountSeedEffects() != 0 || game.deathmatchManager.is_active()) return "a seeded or versus run"; + if (!proceduralItems.empty()) return "a glitched item"; + for (const TemporaryEffect& effect : temporaryEffects.effects) + if (!is_frame_effect_known(effect)) + return "update_effects 00794e50: the effect of item " + std::to_string(effect.item->type) + "." + + std::to_string(effect.item->id); + for (int id : FRAME_ITEMS) + if (HasCollectible(id)) return "update_effects 00794e50: collectible " + std::to_string(id); + for (int id : FRAME_TRINKETS) + if (HasTrinket(id)) return "update_effects 00794e50: trinket " + std::to_string(id); + return {}; } diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index cb6e6cf..118ad25 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -17,9 +17,14 @@ #include "lua_engine.h" #include "manager.h" #include "menu_manager.h" +#include "fx_layers.h" #include "npc_ai.h" +#include "npc_basement.h" #include "npc_depths.h" +#include "active_items.h" #include "platform.h" +#include "player_hud.h" +#include "hud.h" #include "room.h" #include "weapon_lasers.h" #include @@ -33,16 +38,39 @@ constexpr float HELD_OFFSET_SCALE = 0.65f; constexpr float MOVE_SPEED_BASE = 0.75f; constexpr float MOVE_SPEED_SCALE = 0.25f; constexpr float SLIPPERY_FRAMES = 60; +constexpr float SLIPPERY_DOT_MIN = -3; +constexpr float SLIPPERY_SPEED_MAX = 3; +constexpr float SLIPPERY_SPEED_CAP = 4; constexpr float WALK_FAST_SPEED = 6; constexpr float WALK_FASTEST_SPEED = 10; constexpr float WALK_SLOW_SPEED = 2.3f; constexpr int DAMAGE_BLINK_PERIOD = 6; constexpr int DAMAGE_BLINK_HIDDEN = 3; -constexpr int COLLECTIBLE_INTRUDER = 575; constexpr float EMOTE_HEIGHT = 52; +constexpr float STATUS_EFFECT_RISE = -35; +constexpr float TARGET_MARKER_RISE = -40; +constexpr float HUD_BUBBLE_RISE = -30; +constexpr float HUD_BUBBLE_HEART_STEP = 5; +constexpr int HUD_BUBBLE_HEARTS_PER_ROW = 6; +constexpr float GUSH_RISE_JUPITER = -15; +constexpr float GUSH_RISE_MEGA_MUSH = -65; constexpr float EMOTE_MOVING_SPEED = 0.1f; constexpr float GRAVITY_PULL = 0.225f; constexpr int MARS_TAP_FRAMES_MAX = 10000; +constexpr int MARS_DOUBLE_TAP_FRAMES = 11; +constexpr float JUPITER_CHARGE_FRAMES = 60; +constexpr float JUPITER_FART_INTERVAL = 2; +constexpr float JUPITER_LOUD_CHARGE = 0.3f; +constexpr int JUPITER_FART_DELAY = 5; +constexpr float JUPITER_MOVING = 0.01f; +constexpr float JUPITER_SPRAY_ARC = 40; +constexpr float JUPITER_SPLASH_BACK = 4; +constexpr float JUPITER_SPLASH_SPEED_RANGE = 20; +constexpr float JUPITER_SPLASH_SPEED_MIN = 6; +constexpr float JUPITER_GAS_SPEED_RANGE = 10; +constexpr float JUPITER_GAS_SPEED_MIN = 10; +constexpr uint32_t JUPITER_GAS_EXTRA_FRAMES = 30; +constexpr int JUPITER_GAS_FRAMES = 60; constexpr float FIRE_DIRECTION_MIN = 0.01f; constexpr float SHOOT_CHARGE_DEAD_ZONE = 0.5f; @@ -120,29 +148,6 @@ static bool is_overlay_pass() return mode == RENDER_NORMAL || mode == RENDER_WATER_ABOVE; } -// 00a15640's mapping, as the walk speed scales the animation: a value from one range to another, clamped. -static float range_map(float value, float inMin, float inMax, float outMin, float outMax) -{ - float t = std::clamp((value - inMin) / (inMax - inMin), 0.0f, 1.0f); - return (outMax - outMin) * t + outMin; -} - -// How far an action is pushed on a controller, or on any device for -1, as the input manager reads it offline. -static float action_value(ButtonAction action, int controllerIndex) -{ - KAGE::Input::Manager& input = KAGE::Input::manager; - float value = 0; - - for (int i = 0; i < input.get_device_count(); i++) - { - std::shared_ptr device = input.get_device(i); - if (!device || !device->isConnected || (controllerIndex != -1 && device->id != controllerIndex)) continue; - for (int button : g_manager->keyConfigs.binding_get(*device, action)) - if (button != KAGE::Input::BUTTON_NONE) value = std::max(value, device->button_value(button)); - } - return value; -} - // Whether an action is held on a controller, or on any device for -1, as the input manager's pressed test reads it. static bool is_action_held(ButtonAction action, int controllerIndex) { @@ -204,11 +209,14 @@ Vector Entity_Player::GetMovementJoystick() bool isFollower = playerType == PLAYER_ESAU || (parent && parent->is_player()) || ((playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B) && twin && twin->playerIndex != -1 && twin->playerIndex < playerIndex && twin != this); - if (isFollower && isControlsEnabled && controlsCooldown < 1 && action_value(ACTION_DROP, controllerIndex) > 0) + if (isFollower && isControlsEnabled && controlsCooldown < 1 && + input_action_value_get(ACTION_DROP, controllerIndex, this) > 0) return {}; - Vector input = vector_make(action_value(ACTION_RIGHT, controllerIndex) - action_value(ACTION_LEFT, controllerIndex), - action_value(ACTION_DOWN, controllerIndex) - action_value(ACTION_UP, controllerIndex)); + Vector input = vector_make(input_action_value_get(ACTION_RIGHT, controllerIndex, this) - + input_action_value_get(ACTION_LEFT, controllerIndex, this), + input_action_value_get(ACTION_DOWN, controllerIndex, this) - + input_action_value_get(ACTION_UP, controllerIndex, this)); if (game.deathmatchManager.is_active() && HasEntityFlags(FLAG_CONFUSION)) input = vector_make(-input.x, -input.y); if (game.seedEffects.HasSeedEffect(SEED_CONTROLS_REVERSED)) input = vector_make(-input.x, -input.y); if (game.seedEffects.HasSeedEffect(SEED_AXIS_ALIGNED_CONTROLS)) input = axis_snap(input); @@ -231,9 +239,10 @@ Vector Entity_Player::GetShootingJoystick() } else { - input = vector_make( - action_value(ACTION_SHOOT_RIGHT, controllerIndex) - action_value(ACTION_SHOOT_LEFT, controllerIndex), - action_value(ACTION_SHOOT_DOWN, controllerIndex) - action_value(ACTION_SHOOT_UP, controllerIndex)); + input = vector_make(input_action_value_get(ACTION_SHOOT_RIGHT, controllerIndex, this) - + input_action_value_get(ACTION_SHOOT_LEFT, controllerIndex, this), + input_action_value_get(ACTION_SHOOT_DOWN, controllerIndex, this) - + input_action_value_get(ACTION_SHOOT_UP, controllerIndex, this)); if (game.seedEffects.HasSeedEffect(SEED_CONTROLS_REVERSED)) input = vector_make(-input.x, -input.y); } if (game.seedEffects.HasSeedEffect(SEED_AXIS_ALIGNED_CONTROLS)) input = axis_snap(input); @@ -306,6 +315,101 @@ bool Entity_Player::IsFullSpriteRendering() return !IsHoldingItem() || IsHeldItemVisible(); } +// One of Jupiter's farts, out of the player's back (its last movement, or the way it faces). +static void jupiter_fart(Entity_Player& p) +{ + if (p.jupiterCharge > JUPITER_LOUD_CHARGE) + { + uint32_t delay = Random(); + npc_sound_play(SOUND_FART, p.jupiterCharge, (int)(delay & 7) + JUPITER_FART_DELAY, 1); + } + Vector& recent = p.recentMovementVector; + Vector facing = recent.x * recent.x + recent.y * recent.y <= JUPITER_MOVING + ? vector_from_direction(p.moveDirection == DIRECTION_NONE ? DIRECTION_DOWN : p.moveDirection) + : vector_normalized(recent); + Vector back = vector_make(-facing.x, -facing.y); + auto spray_get = [&back](float speedRange, float speedMin) { + float angle = (random_unit() * JUPITER_SPRAY_ARC - JUPITER_SPRAY_ARC * 0.5f) * DEGREES_TO_RADIANS; + Vector turned = vector_make(std::cos(angle) * back.x - std::sin(angle) * back.y, + std::sin(angle) * back.x + std::cos(angle) * back.y); + return vector_scale(turned, random_unit() * speedRange + speedMin); + }; + + uint32_t seed = Random(); + Vector velocity = spray_get(JUPITER_SPLASH_SPEED_RANGE, JUPITER_SPLASH_SPEED_MIN); + Entity* splash = g_game->Spawn({.position = vector_add(p.pos, vector_scale(back, JUPITER_SPLASH_BACK)), + .velocity = velocity, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = seed}); + splash->sprite.scale = vector_scale(splash->sprite.scale, random_unit() * 1.5f + 1); + splash->sprite.color = {{0.3f, 0.42f, 0.25f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + splash->Update(); + + velocity = spray_get(JUPITER_GAS_SPEED_RANGE, JUPITER_GAS_SPEED_MIN); + seed = Random(); + Vector at = vector_add(p.pos, vector_scale(back, random_unit() * 3 + 2)); + auto* gas = static_cast(g_game->Spawn({.position = at, + .velocity = velocity, + .spawner = &p, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = seed})); + gas->SetTimeout((int)(Random() % JUPITER_GAS_EXTRA_FRAMES) + JUPITER_GAS_FRAMES); + float size = (random_unit() * 0.4f + 0.6f) * (p.HasTrinket(TRINKET_GIGANTE_BEAN) ? 2.0f : 1.0f); + gas->sprite.scale = vector_make(size, size); + gas->SetCollisionDamage(p.meleeDamage * 0.5f); + gas->Update(); +} + +// Jupiter's gas: standing still fills its charge over a second (scaled by time), walking spends it, and while it lasts +// every 2 ticks the player farts behind it, loudly past 0.3, a puff of green spray and a gas cloud hurting at half its +// melee damage, bigger with Gigante Bean. A changed charge asks for the speed. +static void jupiter_update(Entity_Player& p, Vector input) +{ + if (!p.HasCollectible(COLLECTIBLE_JUPITER)) + { + p.jupiterCharge = 0; + return; + } + float before = p.jupiterCharge; + float step = p.speedMultiplier / JUPITER_CHARGE_FRAMES; + if (is_zero(input)) + { + if (p.velocity.x * p.velocity.x + p.velocity.y * p.velocity.y < 1) + p.jupiterCharge = std::min(before + step, 1.0f); + } + else + { + p.jupiterCharge = std::max(before - step, 0.0f); + if (p.jupiterCharge > 0 && p.GetIntervalTicks(JUPITER_FART_INTERVAL, 0) != 0) jupiter_fart(p); + } + if (p.jupiterCharge == before) return; + p.cacheFlags |= CACHE_SPEED; + p.temporaryEffects.isEvaluateCachePending = true; +} + +// Mars: tapping a direction twice within 11 frames, its cooldown over, starts its dash that way. +static void mars_taps_read(Entity_Player& p) +{ + for (int direction = 0; direction < 4; direction++) + { + if (!input_is_action_triggered((ButtonAction)(ACTION_LEFT + direction), p.controllerIndex, &p)) continue; + bool isDoubleTap = p.marsLastTapDirection == direction && p.marsTapFrames < MARS_DOUBLE_TAP_FRAMES; + if (isDoubleTap && p.HasCollectible(COLLECTIBLE_MARS) && p.marsCooldown < 1) + { + if (ItemConfig_Item* mars = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MARS)) + p.temporaryEffects.AddEffect(TemporaryEffect(mars), false, 1); + p.marsDashDirection = p.marsLastTapDirection; + p.marsCooldown = p.marsDashCooldown; + p.isMarsDashReady = false; + } + p.marsLastTapDirection = direction; + p.marsTapFrames = 0; + } +} + // 00779b40 Moves the player by its input: speed and friction from its speed stat, a slippery floor's drift and the // facing it walks in. A doubled Duct Tape's drop button turns the familiars' formation. The items that change walking // stop the game until reached. @@ -348,11 +452,8 @@ void Entity_Player::update_body_animations() if (temporaryEffects.HasNullEffect(NULLITEM_SPIN_TO_WIN)) reconstruction_missing("Entity_Player::update_body_animations 00779b40 (Spin to Win)"); if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) walking_items_animate(*this); - if (HasCollectible(COLLECTIBLE_JUPITER)) - reconstruction_missing("Entity_Player::update_body_animations 00779b40 (Jupiter)"); - jupiterCharge = 0; - if (HasCollectible(COLLECTIBLE_MARS) && isControlsEnabled) - reconstruction_missing("Entity_Player::update_body_animations 00779b40 (Mars)"); + jupiter_update(*this, input); + if (HasCollectible(COLLECTIBLE_MARS) && isControlsEnabled) mars_taps_read(*this); marsTapFrames = std::min(marsTapFrames + 1, MARS_TAP_FRAMES_MAX); if (!HasTrinket(TRINKET_DUCT_TAPE) || GetTrinketMultiplier(TRINKET_DUCT_TAPE) < 2) ductTapeMode = 0; else if (isControlsEnabled && input_is_action_triggered(ACTION_DROP, controllerIndex, this)) @@ -459,7 +560,6 @@ void Entity_Player::walk_animation_update() bool isLifted = isHolding && held_item_pose_update(*this); bool isFlushDue = isHolding ? (isHeldItemVisible && !isLifted) || g_game->room->GetFrameCount() == 0 : IsExtraAnimationFinished(); - isHeldItemVisible = IsHeldItemVisible(); if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || (!IsExtraAnimationFinished() && !isHolding)) return; if (isFlushDue) FlushQueueItem(); @@ -488,9 +588,16 @@ void Entity_Player::walk_animation_update() if (sprite.IsPlaying()) { float length = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); - if (length < WALK_SLOW_SPEED) speed = range_map(length, 1, WALK_SLOW_SPEED, 0.5f, 1); - 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)"); + if (length < WALK_SLOW_SPEED) speed = lerp_range(length, {1, WALK_SLOW_SPEED, 0.5f, 1}); + if (length > WALK_FAST_SPEED) speed = lerp_range(length, {WALK_FAST_SPEED, WALK_FASTEST_SPEED, 1, 2}); + if (slipperyTimer > 0) + { + float along = recentMovementVector.x * velocity.x + recentMovementVector.y * velocity.y; + float push = std::sqrt(recentMovementVector.x * recentMovementVector.x + + recentMovementVector.y * recentMovementVector.y); + speed = std::min(std::max(lerp_range(along, {SLIPPERY_DOT_MIN, 1, SLIPPERY_SPEED_MAX, 1}) * push, 0.5f), + SLIPPERY_SPEED_CAP); + } } sprite.playbackSpeed = speed * speedFactor; body_costumes_speed_set(sprite.playbackSpeed); @@ -1177,104 +1284,34 @@ void Entity_Player::update_shooting() while (shootDirectionHistory.size() > SHOOT_HISTORY_SIZE) shootDirectionHistory.pop_front(); } -// The temporary effects' part of 00782af0: Mars' dash, a pony's charge and Recall ignore knockback, the stats are -// evaluated when the effects changed, and the timed ones count down. The items' frame (update_effects) is not reached -// by a plain player, but its closing PostPEffectUpdate callback is. -static void temporary_effects_update(Entity_Player& player) +// 0084a870 A co-op player's hearts over its head, centered on the columns its filled slots take (6 to a row). +static void hud_bubble_render(PlayerHUD& hud, Vector at) { - TemporaryEffects& effects = player.temporaryEffects; - bool isDashing = effects.HasCollectibleEffect(COLLECTIBLE_MARS) || player.ponyCharge >= 1 || - effects.HasCollectibleEffect(COLLECTIBLE_RECALL); - if (isDashing) player.AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); - else player.ClearEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); - if (effects.isEvaluateCachePending) - { - player.cacheFlags |= effects.cacheFlags; - player.EvaluateItems(); - } - effects.isEvaluateCachePending = false; - if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; - - tainted_frame_update(player); - effects.Update(); - character_frame_update(player); - passives_frame_update(player); - trinkets_frame_update(player); - lua_engine_get().PostPEffectUpdate(&player); -} - -// 00782af0 The player's frame. Only the frame of a plain character is reconstructed: the base entity moves it, it walks -// by its input, uses its bomb, active, pocket and drop buttons, shoots, its temporary effects count down and its body -// animates. Items and effects the plain frame does not know and the held entity stop the game until reached. -void Entity_Player::Update() -{ - equality_update(*this); - if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; - if (isPlayingItemAnimation && bodySprite.IsFinished() && !bodySprite.IsFinished("LiftItem")) - { - isPlayingItemAnimation = false; - bodySprite.Reset(); - heldSprite.Reset(); - } - update_pitfall(); - trinket_teleports_update(*this); - if (activeItems[ACTIVE_SLOT_SECONDARY].item != 0 && !HasCollectible(COLLECTIBLE_SCHOOLBAG) && !isCoopGhost) - reconstruction_missing("Entity_Player::Update 00782af0 (the second active dropped without the Schoolbag)"); - if (isHurtPending && !isPlayingExtraAnimation) - { - isHurtPending = false; - if (HasCollectible(COLLECTIBLE_INTRUDER) && !temporaryEffects.HasNullEffect(NULLITEM_INTRUDER)) - reconstruction_missing("Entity_Player::Update 00782af0 (the spiders a hurt sets loose)"); - } - book_of_belial_passive_update(*this); - if (isDead) return death_update(); - if (!is_frame_plain()) - reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and item animations)"); - held_entity_follow(); - height_update(); - - Entity::Update(); - if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) - { - bodySprite.Update(); - heldSprite.Update(); - } - sprite_scale_update(); - costume_layers_update(); - lastActionTriggers = 0; - update_body_animations(); - update_bomb_input(); - ControlActiveItem(ACTIVE_SLOT_PRIMARY); - pocket_use_input(); - update_shooting(); - tractor_beam_update(*this); - pockets_rotate(); - gnawed_leaf_update(*this); - temporary_effects_update(*this); - walk_animation_update(); - if (damageCooldown > 0) damageCooldown--; - if (controlsCooldown > 0) controlsCooldown--; - if (fireBlockCooldown > 0) fireBlockCooldown--; - if (itemHoldCooldown > 0) itemHoldCooldown--; - if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && HasCollectible(COLLECTIBLE_HOST_HAT) && - IsCollectibleAnimFinished(COLLECTIBLE_HOST_HAT, "")) - ClearCollectibleAnim(COLLECTIBLE_HOST_HAT); - update_footprints(); - moms_hand_player_release_update(*this); - lua_engine_get().PostPlayerUpdate(this); + int columns = 0; + for (int slot = 0; slot < PLAYER_HUD_HEART_COUNT; slot++) + if (hud.hearts[slot].isVisible) columns = std::max(columns, slot % HUD_BUBBLE_HEARTS_PER_ROW); + Vector extent{}; + hud.RenderHearts(extent, g_game->hud.heartsSprite, HUD_LAYOUT_NORMAL, 1, + vector_make(at.x - (float)columns * HUD_BUBBLE_HEART_STEP, at.y)); } // 0078ca00 Draws the player at its place, lifted by its flight and its offset: blinking while hurt, the held entity -// in front or behind, its after-images, then its overlays (the co-op indicator, charge bars and status effect) in the -// room's pass. Netplay's shadows and colors are offline. +// in front or behind, then its overlays (the co-op indicator, charge bars, status effect and the Void's hallucination +// of its past walk) in the room's pass. A player following a target shows only a marker. Netplay's shadows and colors +// are offline, and nothing fills the after-images the original keeps. void Entity_Player::Render(const Vector& offset) { - if (variant == PLAYER_VARIANT_EXTRA || target) + if (target) { - if (target && variant != PLAYER_VARIANT_EXTRA) - reconstruction_missing("Entity_Player::Render 0078ca00 (a player following a target)"); + FontSettings settings; + settings.alignment = ALIGN_TOP_CENTER; + Vector marker = vector_add(render_position_get(pos, RENDER_SNAPPED), offset); + g_manager->font6_PFTempestaSevenCondensed.DrawString("v", vector_make(marker.x, marker.y + TARGET_MARKER_RISE), + vector_make(1, 1), kcolor_rgba(1, 0.6f, 0.6f, 1), + settings); return; } + if (variant == PLAYER_VARIANT_EXTRA) return; Vector renderOffset = offset; if (!HasEntityFlags(FLAG_HELD)) @@ -1295,7 +1332,9 @@ void Entity_Player::Render(const Vector& offset) lua_engine_get().PostPlayerRender(this, offset); if (!is_overlay_pass()) return; - if (playerHUD) reconstruction_missing("Entity_Player::Render 0078ca00 (the player's HUD bubble)"); + if (playerHUD) + hud_bubble_render(*playerHUD, + vector_make(renderPosition.x, renderPosition.y + playerSpriteScale.y * HUD_BUBBLE_RISE)); if (g_game->playerManager.playerList.size() > 1 && g_game->roomTransition.mode == TRANSITION_NONE) coop_indicator_render(); if (!isDead) @@ -1303,10 +1342,14 @@ void Entity_Player::Render(const Vector& offset) render_charge_bars(renderPosition); if (statusEffectSprite.isLoaded && statusEffectSprite.animState.animData && statusEffectSprite.animState.isPlaying) - reconstruction_missing("Entity_Player::Render 0078ca00 (the status effect sprite)"); + { + float size = std::min(playerSpriteScale.x, playerSpriteScale.y); + statusEffectSprite.scale = vector_make(size, size); + Vector above = vector_make(renderPosition.x, renderPosition.y + playerSpriteScale.y * STATUS_EFFECT_RISE); + statusEffectSprite.Render(SpriteDraw{above, {}, {}}); + } } - if (g_game->hallucinationTimer > 0) - reconstruction_missing("Entity_Player::Render 0078ca00 (the hallucination overlay)"); + if (!hallucinationTrail.frames.empty() && g_game->hallucinationTimer > 0) hallucination_trail_render(*this, offset); if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Player::Render 0078ca00 (the deathmatch overlay)"); } @@ -1383,13 +1426,14 @@ void Entity_Player::render_back(const Vector& position) layer_sprite(PLAYER_LAYER_BACK).RenderLayer(layer_id(PLAYER_LAYER_BACK), SpriteDraw{position, {}, {}}); } -// 0078dde0 Draws the body layers, the costumes' where they cover them, and the blood gush of a headless player. -// Flying costumes cover the body only while flying. +// 0078dde0 Draws the body layers, the costumes' where they cover them, and the blood gush of a headless player, raised +// over Jupiter's and Mega Mush's bodies. Flying costumes cover the body only while flying. void Entity_Player::RenderBody(const Vector& position) { if (!isVisible || IsFullSpriteRendering()) return; bool isBodyRendered = false; + float gushRise = 0; for (int layer = PLAYER_LAYER_BODY; layer <= PLAYER_LAYER_BODY1; layer++) { int index = playerCostumeMap[layer].index; @@ -1401,13 +1445,23 @@ void Entity_Player::RenderBody(const Vector& position) } CostumeSpriteDesc& costume = costumeSpriteDescs[index]; if (canFly && !costume.isFlying) continue; + ItemConfig_Item* item = costume.item; + bool isJupiter = item && item->type == ITEM_NULL && item->id >= NULLITEM_JUPITER_BODY && + item->id <= NULLITEM_JUPITER_BODY_WHITEPONY; + bool isMegaMush = item && item->IsCollectible() && item->id == COLLECTIBLE_MEGA_MUSH; + if (layer == PLAYER_LAYER_BODY && (isJupiter || isMegaMush)) + gushRise = + std::min(gushRise, costume.sprite.scale.y * (isJupiter ? GUSH_RISE_JUPITER : GUSH_RISE_MEGA_MUSH)); + int layerId = playerCostumeMap[layer].layerId; costume.sprite.RenderLayer(layerId, SpriteDraw{position, {}, {}}); const AnimationFrame* frame = costume.sprite.animState.animData ? costume.sprite.animState.GetLayerFrame(layerId) : nullptr; if (frame && frame->isVisible) isBodyRendered = true; } - if (isBodyRendered && IsHeadless()) reconstruction_missing("Entity_Player::RenderBody 0078dde0 (the blood gush)"); + if (!isBodyRendered || !IsHeadless()) return; + Vector gush = vector_make(position.x, position.y + gushRise * HELD_OFFSET_SCALE); + bloodGushSprite.RenderLayer(0, SpriteDraw{gush, {}, {}}); } // 0078dff0 Draws the head layers, the costumes' where they cover them, and the crowns of Dark Prince's Crown and Crown diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index f7e28f2..95de1ee 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -744,6 +744,38 @@ void Entity_Player::AddKeys(int amount) hud_refresh_players(); } +// 00759620 Gives the golden key, which opens every lock for free. +void Entity_Player::AddGoldenKey() +{ + hasGoldenKey = true; + ConsumableCountChanged(CONSUMABLE_GOLDEN_KEY); + hud_refresh_players(); +} + +// 00759660 Takes the golden key away. +void Entity_Player::RemoveGoldenKey() +{ + hasGoldenKey = false; + ConsumableCountChanged(CONSUMABLE_GOLDEN_KEY); + hud_refresh_players(); +} + +// 007c8f80 Gives the golden bomb, which never runs out. +void Entity_Player::AddGoldenBomb() +{ + hasGoldenBomb = true; + ConsumableCountChanged(CONSUMABLE_GOLDEN_BOMB); + hud_refresh_players(); +} + +// 007c8fc0 Takes the golden bomb away. +void Entity_Player::RemoveGoldenBomb() +{ + hasGoldenBomb = false; + ConsumableCountChanged(CONSUMABLE_GOLDEN_BOMB); + 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() diff --git a/src/entity_player_hits.cpp b/src/entity_player_hits.cpp index 60cbd08..090f4ab 100644 --- a/src/entity_player_hits.cpp +++ b/src/entity_player_hits.cpp @@ -48,7 +48,6 @@ constexpr int CARTRIDGE_ODDS = 20; constexpr float CARTRIDGE_LUCK = 0.5f; constexpr int CRACKED_DICE_CHANCES[] = {50, 75, 100}; constexpr int CRACKED_DICE_ITEMS[] = {105, 166, 386, 406, 285}; -constexpr int BLEED_OUT_FRAMES = 600; constexpr int SHARD_HEART_ODDS = 4; constexpr int VARICOSE_ANEMIC_ODDS = 5; constexpr int VARICOSE_ANEMIC_FRAMES = 60; diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 940b4b2..a64cf8a 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -1612,10 +1612,28 @@ void Entity_Player::AddCostume(ItemConfig_Item* item, bool isItemStateOnly) // the costume of highest priority winning. void Entity_Player::costume_layers_map(SkinColors& colors) { + EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType); + int characterCostume = playerConfig ? playerConfig->costumeID : -1; + auto is_item = [](const CostumeSpriteDesc& costume, int id) { + return costume.item && costume.item->IsCollectible() && costume.item->id == id; + }; + bool isMegaMushWorn = std::ranges::any_of(costumeSpriteDescs, [](const CostumeSpriteDesc& costume) { + return costume.item && costume.item->type == ITEM_ACTIVE && costume.item->id == COLLECTIBLE_MEGA_MUSH; + }); + bool isLazarus = playerType == PLAYER_LAZARUS || playerType == PLAYER_LAZARUS2; + auto is_mapped = [&](const CostumeSpriteDesc& costume) { + bool isCharacter = costume.item && costume.item->type == ITEM_NULL && costume.item->id == characterCostume; + bool isTranscendent = is_item(costume, COLLECTIBLE_TRANSCENDENCE) && + temporaryEffects.HasCollectibleEffect(COLLECTIBLE_TRANSCENDENCE); + if (hasCurseMistEffect && !isCharacter && !isTranscendent) return false; + if (isMegaMushWorn && + !(costume.item && costume.item->type == ITEM_ACTIVE && costume.item->id == COLLECTIBLE_MEGA_MUSH)) + return false; + return !(is_item(costume, COLLECTIBLE_ANEMIC) && isLazarus); + }; int headPriority = -1; int bodyPriority = -1; - auto color_take = [](const CostumeSpriteDesc& costume, int& color, int& priority) - { + auto color_take = [](const CostumeSpriteDesc& costume, int& color, int& priority) { if (costume.priority < priority) return; color = costume.defaultSkinColor; priority = costume.priority; @@ -1624,6 +1642,7 @@ void Entity_Player::costume_layers_map(SkinColors& colors) for (int index = 0; index < (int)costumeSpriteDescs.size(); index++) { CostumeSpriteDesc& costume = costumeSpriteDescs[index]; + if (!is_mapped(costume)) continue; int headIndex = index; int bodyIndex = index; int matched = 0; @@ -1715,28 +1734,67 @@ void Entity_Player::costume_skin_apply(CostumeSpriteDesc& costume, int skinColor if (!state.animData || costume.sprite.GetAnimation() != animation || isStopped) costume.sprite.Play(animation, PLAY_FORCED); } -// 0075bf00 Lays the worn costumes over the player's layers by priority, dresses each for the character, poses them -// at the first frame of HeadDown or WalkDown with their SubAnim overlay, and recolors the player for its skin. -// Jupiter's and Berserk's costumes, the cursed mist, Mega Mush and skin colors other than the character's stop the -// game until reached. +// Whether a costume is one of Jupiter's bodies. +static bool is_jupiter_body(const CostumeSpriteDesc& costume) +{ + return costume.item && costume.item->id >= NULLITEM_JUPITER_BODY && + costume.item->id <= NULLITEM_JUPITER_BODY_WHITEPONY; +} + +// The UpdateCostumes part that puts on the bodies items ask for: Jupiter's (a pony's under A Pony or White Pony, the +// angel's under a worn flying costume, swapped when it changes, taken off without Jupiter) and Tainted Samson's +// Berserk! one while Berserk!'s costume is on. A costume of another kind with the same ids counts as the original does. +void Entity_Player::costume_items_dress() +{ + ItemConfig& items = g_manager->itemConfig; + bool isJupiter = false; + bool isBerserk = false; + bool isBerserkWorn = false; + int wanted = NULLITEM_JUPITER_BODY; + int worn = -1; + + for (const CostumeSpriteDesc& costume : costumeSpriteDescs) + { + if (ItemConfig_Item* item = costume.item; item && item->IsCollectible()) + { + if (item->id == COLLECTIBLE_JUPITER) isJupiter = true; + else if (item->id == COLLECTIBLE_PONY) wanted = NULLITEM_JUPITER_BODY_PONY; + else if (item->id == COLLECTIBLE_WHITE_PONY) wanted = NULLITEM_JUPITER_BODY_WHITEPONY; + else if (item->id == COLLECTIBLE_BERSERK) isBerserk = true; + } + else if (item && item->type == ITEM_NULL) + { + if (is_jupiter_body(costume)) worn = item->id; + if (item->id == NULLITEM_BERSERK_SAMSON) isBerserkWorn = true; + } + if (canFly && costume.isFlying && !is_jupiter_body(costume) && wanted == NULLITEM_JUPITER_BODY) + wanted = NULLITEM_JUPITER_BODY_ANGEL; + } + if (!isJupiter) wanted = -1; + if (wanted != worn) + { + std::erase_if(costumeSpriteDescs, [](const CostumeSpriteDesc& costume) { + return costume.item && costume.item->type == ITEM_NULL && is_jupiter_body(costume); + }); + if (wanted != -1) AddCostume(items.GetNullItem(wanted), false); + } + + bool isBerserkWanted = isBerserk && playerType == PLAYER_SAMSON_B; + if (isBerserkWanted == isBerserkWorn) return; + if (isBerserkWanted) AddCostume(items.GetNullItem(NULLITEM_BERSERK_SAMSON), false); + else RemoveCostume(items.GetNullItem(NULLITEM_BERSERK_SAMSON)); +} + +// 0075bf00 Puts on the bodies items ask for, lays the worn costumes over the player's layers by priority (only the +// character's under the cursed mist, only Mega Mush's while it is on), dresses each for the character, poses them at +// the first frame of HeadDown or WalkDown with their SubAnim overlay, and recolors the player for its skin. void Entity_Player::UpdateCostumes() { static bool isUpdating = false; - constexpr int COLLECTIBLE_JUPITER_COSTUME = 594; - constexpr int COLLECTIBLE_MEGA_MUSH_COSTUME = 625; - constexpr int COLLECTIBLE_BERSERK_COSTUME = 704; if (variant == PLAYER_VARIANT_COOP_BABY || isUpdating) return; - for (CostumeSpriteDesc& costume : costumeSpriteDescs) - { - int id = costume.item && costume.item->IsCollectible() ? costume.item->id : 0; - if (id == COLLECTIBLE_JUPITER_COSTUME || id == COLLECTIBLE_MEGA_MUSH_COSTUME || id == COLLECTIBLE_BERSERK_COSTUME) - reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (Jupiter, Mega Mush and Berserk)"); - } - if (!costumeSpriteDescs.empty() && hasCurseMistEffect) - reconstruction_missing("Entity_Player::UpdateCostumes 0075bf00 (the cursed mist)"); - isUpdating = true; + costume_items_dress(); EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType); if (!playerConfig) log_printf(LOG_ASSERT, "Could not load config for player type %d\n", playerType); int skinColor = playerConfig ? playerConfig->skinColor : -1; diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index e5513c2..ec46ddf 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -3,20 +3,13 @@ void Entity_Player::StopExtraAnimation() { reconstruction_missing("Entity_Player::StopExtraAnimation 0058e230"); } void Entity_Player::moms_bracelet_grab() { reconstruction_missing("Entity_Player::moms_bracelet_grab 005b1a20"); } -void Entity_Player::use_card_hagalaz(RNG*) { reconstruction_missing("Entity_Player::use_card_hagalaz 005b23f0"); } void Entity_Player::ResetDamageCooldown() { reconstruction_missing("Entity_Player::ResetDamageCooldown 0060d090"); } Vector Entity_Player::SpriteScale() { reconstruction_missing("Entity_Player::SpriteScale 0060d0a0"); } -void Entity_Player::set_last_damage(uint64_t, const EntityRef&) -{ - reconstruction_missing("Entity_Player::set_last_damage 006dad80"); -} void Entity_Player::QueueExtraAnimation(std::string_view) { reconstruction_missing("Entity_Player::QueueExtraAnimation 007539c0"); } void Entity_Player::cycle_spectate_target() { reconstruction_missing("Entity_Player::cycle_spectate_target 007585b0"); } -void Entity_Player::AddGoldenKey() { reconstruction_missing("Entity_Player::AddGoldenKey 00759620"); } -void Entity_Player::RemoveGoldenKey() { reconstruction_missing("Entity_Player::RemoveGoldenKey 00759660"); } void Entity_Player::RemoveBlueFly() { reconstruction_missing("Entity_Player::RemoveBlueFly 00759b80"); } void Entity_Player::AddLeprosy() { reconstruction_missing("Entity_Player::AddLeprosy 00759b90"); } Entity* Entity_Player::AddBoneOrbital(Vector) { reconstruction_missing("Entity_Player::AddBoneOrbital 00759bc0"); } @@ -24,15 +17,10 @@ Entity* Entity_Player::AddSwarmFlyOrbital(Vector) { reconstruction_missing("Entity_Player::AddSwarmFlyOrbital 00759bf0"); } -void Entity_Player::AddNullCostume(int) { reconstruction_missing("Entity_Player::AddNullCostume 0075d800"); } void Entity_Player::RespawnFamiliars() { reconstruction_missing("Entity_Player::RespawnFamiliars 00770600"); } void Entity_Player::GetNPCTarget() { reconstruction_missing("Entity_Player::GetNPCTarget 00770610"); } bool Entity_Player::VoidHasCollectible(int) { reconstruction_missing("Entity_Player::VoidHasCollectible 007711a0"); } bool Entity_Player::replace_trinket() { reconstruction_missing("Entity_Player::replace_trinket 00772530"); } -void Entity_Player::RemoveCollectibleByHistoryIndex(int, bool) -{ - reconstruction_missing("Entity_Player::RemoveCollectibleByHistoryIndex 0078fec0"); -} void Entity_Player::update_effects() { reconstruction_missing("Entity_Player::update_effects 00794e50"); } void Entity_Player::update_ladder() { reconstruction_missing("Entity_Player::update_ladder 0079f3c0"); } void Entity_Player::ReviveFromTrinket(uint32_t) { reconstruction_missing("Entity_Player::ReviveFromTrinket 007a3430"); } @@ -76,11 +64,8 @@ void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Pl void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } 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"); } -void Entity_Player::RemoveGoldenBomb() { reconstruction_missing("Entity_Player::RemoveGoldenBomb 007c8fc0"); } Entity* Entity_Player::ShootRedCandle(Vector) { reconstruction_missing("Entity_Player::ShootRedCandle 007c9130"); } Entity* Entity_Player::ShootBlueCandle(Vector) { reconstruction_missing("Entity_Player::ShootBlueCandle 007c9350"); } -void Entity_Player::DoZitEffect(Vector) { reconstruction_missing("Entity_Player::DoZitEffect 007c9590"); } void Entity_Player::apply_victory_lap_penalty(uint32_t) { reconstruction_missing("Entity_Player::apply_victory_lap_penalty 007c97f0"); @@ -130,7 +115,6 @@ void Entity_Player::AttachMinecart(Entity_NPC*) { reconstruction_missing("Entity void Entity_Player::RevivePlayerGhost() { reconstruction_missing("Entity_Player::RevivePlayerGhost 007d93b0"); } void Entity_Player::MorphToCoopGhost() { reconstruction_missing("Entity_Player::MorphToCoopGhost 007d96f0"); } void Entity_Player::reset_body_sprite() { reconstruction_missing("Entity_Player::reset_body_sprite 007d9b70"); } -void Entity_Player::SpawnClot(Vector, bool) { reconstruction_missing("Entity_Player::SpawnClot 007da810"); } void Entity_Player::ResetPlayer() { reconstruction_missing("Entity_Player::ResetPlayer 007daed0"); } void Entity_Player::twins_duplicate_familiars(int) { diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index 1b896f0..4d02210 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -10,7 +10,6 @@ #include "room.h" #include -constexpr int TRINKET_DOOR_STOP = 124; constexpr int COLLECTIBLE_BROKEN_WATCH = 337; constexpr int COLLECTIBLE_DOG_TOOTH = 445; constexpr int COLLECTIBLE_BELIAL_PARTNER = 474; @@ -219,7 +218,7 @@ static void room_items_apply(Entity_Player& player) int cell = room.gridWidth * row + column; GridEntity* poop = isInside && cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; if (poop && poop->type == GRID_POOP && !player.canFly) - reconstruction_missing("Entity_Player::room_enter 007a6c50: Room::RemoveGridEntity 0081e930 on the poop entered on"); + room.RemoveGridEntity(cell, GRID_PATH_FREED, DECORATION_KEPT); else if (poop && poop->type == GRID_POOP && poop->variant == 1) reconstruction_missing("Entity_Player::room_enter 007a6c50: the red poop flown over drops to its last state"); } @@ -228,7 +227,7 @@ static void room_items_apply(Entity_Player& player) // Dogma in the living room, the Twins and Judas's Belial, then the player stands at its entry with its motion, held // throw and pit fall reset, and its items react to the room. Friendly enemies follow it in, and Used Diaper, Lil Clot, // the Forgotten's body and the item sounds come last. -// The original also clears the list at +0x1b34 and the words at +0x1c54..+0x1c60, which this player does not have. +// The room's trail starts over and the hallucination's replays from its start. void Entity_Player::room_enter() { Game& game = *g_game; @@ -337,6 +336,8 @@ void Entity_Player::room_enter() if (HasTrinket(TRINKET_LIL_CLOT)) spawn_lil_clot_familiars(); if (playerType == PLAYER_THESOUL) spawn_forgotten_body(); preload_item_sounds(); + roomTrail = {}; + hallucinationTrail.current = 0; } // A teleport takes a twin within 52 along, 10 beyond the spot. Its poof shows the player's layer 12 rising, and the diff --git a/src/entity_player_tears.cpp b/src/entity_player_tears.cpp index dff2811..85899ac 100644 --- a/src/entity_player_tears.cpp +++ b/src/entity_player_tears.cpp @@ -134,7 +134,6 @@ constexpr int COLLECTIBLE_8_INCH_NAILS = 359; constexpr int COLLECTIBLE_HOLY_LIGHT = 374; constexpr int COLLECTIBLE_PUPULA_DUPLEX = 379; constexpr int COLLECTIBLE_GODS_FLESH = 398; -constexpr int COLLECTIBLE_MAW_OF_THE_VOID = 399; constexpr int COLLECTIBLE_EXPLOSIVO = 401; constexpr int COLLECTIBLE_COMPOUND_FRACTURE = 453; constexpr int COLLECTIBLE_SINUS_INFECTION = 459; diff --git a/src/entity_player_update.cpp b/src/entity_player_update.cpp new file mode 100644 index 0000000..63c47e4 --- /dev/null +++ b/src/entity_player_update.cpp @@ -0,0 +1,883 @@ +#include "entity_player.h" +#include "entity_player_characters.h" +#include "entity_player_passives.h" +#include "entity_player_trinkets.h" +#include "tainted_characters.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_tear.h" +#include "game.h" +#include "kage_input.h" +#include "key_configs.h" +#include "log.h" +#include "lua_engine.h" +#include "player_hud.h" +#include "manager.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "npc_depths.h" +#include "entity_combat.h" +#include "active_items.h" +#include "room.h" +#include "sfx_manager.h" +#include "temporary_effects.h" +#include "weapon_lasers.h" +#include +#include + +constexpr int SIREN_COPY_SPAWNER = 904; +constexpr float LEADER_PUSH_REACH = 12; +constexpr float LEADER_PUSH_MAX = 2; +constexpr float SALVATION_HALO_SCALE = 1.2f; +constexpr float SALVATION_HALO_RISE = -15; +constexpr int SALVATION_TURN_FRAMES = 360; +constexpr float SALVATION_GROWTH = 0.1f; +constexpr float SALVATION_SCALE_MAX = 2; +constexpr float BREATH_OF_LIFE_RISE = -15; +constexpr float FX_POOF_DEPTH = -10; +constexpr float FX_POOF_RISE = -20; +constexpr int FX_POOF_SUBTYPE = 10; + +constexpr int POISON_BUILDUP_FRAMES = 30; +constexpr int POISON_FLASH_FROM = 20; +constexpr int POISON_SOUND_DELAY = 1; +constexpr int POISON_HURT_COUNTDOWN = 30; +constexpr int POISON_STATIC_FRAME = 3; +constexpr int INTRUDER_LUCK_ODDS = 5; +constexpr uint32_t INTRUDER_SPIDERS_RANGE = 3; +constexpr int INTRUDER_GIBS = 14; +constexpr float INTRUDER_GIB_SPREAD = 40; +constexpr uint32_t INTRUDER_GIB_FLAGS = 13; +constexpr int INTRUDER_SOUND_DELAY = 20; +constexpr float AKELDAMA_INTERVAL = 3; +constexpr uint32_t AKELDAMA_FEW_TEARS = 12; +constexpr uint32_t AKELDAMA_MANY_TEARS = 20; +constexpr float AKELDAMA_SPEED = 3; +constexpr float AKELDAMA_DAMAGE = 3.5f; +constexpr float AKELDAMA_SCALE_RANGE = 0.2f; +constexpr float AKELDAMA_SCALE_MIN = 0.9f; +constexpr float AKELDAMA_HEIGHT = -6; +constexpr float AKELDAMA_FALL_ACCEL = -0.03f; +constexpr int CAMO_BOOST_FRAMES = 30; +constexpr int CAMO_REVEAL_ROOM_FRAME = 6; +constexpr int CAMO_SHAKE_FRAMES = 10; +constexpr float CAMO_POOF_SIZE = 0.8f; +constexpr float CAMO_DAMAGE = 15; +constexpr float CAMO_RADIUS = 80; +constexpr float CAMO_PLAYER_THRESHOLD = 50; +constexpr int SLIPPERY_SLIDE_FRAMES = 60; +constexpr int HOW_TO_JUMP_SPECIAL_DAILY = 33; +constexpr float HOW_TO_JUMP_WAVE_REACH = 90; +constexpr int HOW_TO_JUMP_WAVE_FRAMES = 10; +constexpr float DASH_GRID_REACH = 40; +constexpr float MEGA_SATAN_BOUNCE = -10; +constexpr int MEGA_SATAN_PONY_SHAKE = 8; +constexpr float MOVEMENT_DECAY_MAX = 2; +constexpr float MOVEMENT_REST = 0.01f; +constexpr float MOVE_TO_TARGET_RATE = 0.18f; +constexpr int BLEED_OUT_FLASH_FROM = 30; +constexpr int BLEED_OUT_HURT_COUNTDOWN = 30; +constexpr int HALF_HEART_FLOORS = 2; +constexpr int HALF_HEART_DEEP_STAGE = 9; +constexpr int HALF_HEART_LAST_STAGE = 12; +constexpr int HALF_HEART_FLOOR_CAP = 10; +constexpr int ACHIEVEMENT_HALF_HEART_FLOORS = 329; +constexpr int TRAIL_FRAMES_MAX = 900; +constexpr int VOID_STAGE = 12; +constexpr int VOID_HALLUCINATION_PERIOD = 150; +constexpr int VOID_HALLUCINATION_ODDS = 75; +constexpr int VOID_HALLUCINATION_ODDS_PER_ROOM = 105; +constexpr int VOID_HALLUCINATION_FRAMES = 30; +constexpr int VOID_HALLUCINATION_BACKDROP = 63; + +// The damage a bleeding out player takes when its time runs out: red hearts first, through invincibility, with no +// modifiers, as the IV Bag's. +constexpr uint64_t BLEED_OUT_DAMAGE_FLAGS = DAMAGE_RED_HEARTS | DAMAGE_INVINCIBLE | DAMAGE_IV_BAG | DAMAGE_NO_MODIFIERS; +// The seeds the frame reads: the slippery floor, the music following the player's speed, the tints, the grid's +// footsteps and the timed deaths. +constexpr int FRAME_SEEDS[] = {1, 2, 14, 24, 26, 27, 28, 37, 52, 53}; +// The poisonous gas's tints (green) and a static's (white), building up and flashing, with the exe's values. +constexpr ColorMod POISON_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 1, 0}}; +constexpr ColorMod STATIC_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 1, 0.6f}}; +constexpr ColorMod BLEED_OUT_FLASH = {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +// The ghost a hallucination replays: half transparent and greyed (008391a0). +constexpr ColorMod TRAIL_COLOR = {{1, 1, 1, 0.5f}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; +// The status effects the player's head shows, by the entity flag that shows it, first match first. +constexpr std::pair STATUS_EFFECT_ANIMS[] = { + {FLAG_CHARM, "Charm"}, {FLAG_CONFUSION, "Confuse"}, {FLAG_BURN, "Burning"}, + {FLAG_POISON, "Poison"}, {FLAG_FEAR, "Fear"}, {FLAG_BLEED_OUT, "BleedingOut"}}; + +// Whether neither a room nor a stage transition runs. +static bool is_transition_idle() +{ + Game& game = *g_game; + return !game.roomTransition.is_active() && game.stageTransition.state == STAGE_TRANSITION_NONE; +} + +// A joined co-op player gets its own small HUD, which follows it each frame. +static void hud_update(Entity_Player& player) +{ + if (player.parent && player.variant == PLAYER_VARIANT_PLAYER && !player.playerHUD) + player.playerHUD = PlayerHUD::make_ref(&g_game->hud, &player); + if (player.playerHUD) player.playerHUD->Update(); +} + +// 007d4340 Salvation's halo grows a tenth for each room its effect counts, up to twice. +static float salvation_scale_get(Entity_Player& player) +{ + TemporaryEffect* effect = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_SALVATION); + float count = effect ? (float)effect->count : 0; + return std::clamp(count * SALVATION_GROWTH + 1, 1.0f, SALVATION_SCALE_MAX); +} + +// Salvation's halo floats above the player at its size, turning a degree a frame. +static void salvation_halo_update(Entity_Player& player) +{ + auto* halo = static_cast(player.salvationEffect.get()); + if (!halo) return; + + halo->scale = salvation_scale_get(player) * SALVATION_HALO_SCALE; + halo->posOffset = vector_make(0, SALVATION_HALO_RISE); + float half = player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) ? 0.5f : 0; + halo->sprite.rotation = (float)((g_game->frameCount - player.spawnFrame) % SALVATION_TURN_FRAMES) + half; +} + +// Tainted Lazarus's Birthright keeps both forms out at once: splitting them and joining them back stop the game until +// reached. +static void lazarus_twins_update(Entity_Player& player) +{ + if (player.playerType != PLAYER_LAZARUS_B && player.playerType != PLAYER_LAZARUS2_B) return; + Entity_Player* backup = player.backupPlayer; + bool isBirthright = player.HasCollectible(COLLECTIBLE_BIRTHRIGHT); + if (backup && !backup->isValid && (isBirthright || backup->HasCollectible(COLLECTIBLE_BIRTHRIGHT))) + reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lazarus's Birthright split)"); + + Entity_Player* twin = player.twinPlayer ? player.twinPlayer->ToPlayer() : nullptr; + if (twin && !isBirthright && !twin->HasCollectible(COLLECTIBLE_BIRTHRIGHT) && !player.IsHologram()) + reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lazarus's twins joined again)"); +} + +// A changed damage multiplier asks for the damage, and a floor start left pending (a twin's) runs once nothing +// transitions. +static void pending_starts_update(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + if (player.damageMultiplierStacks != player.lastDamageMultiplierStacks) + { + player.cacheFlags |= CACHE_DAMAGE; + player.lastDamageMultiplierStacks = player.damageMultiplierStacks; + player.temporaryEffects.isEvaluateCachePending = true; + } + if (player.isValid && is_transition_idle() && player.isLevelStartPending) player.level_start(true); +} + +// The cursed mist's effect follows the room's. +static void curse_mist_update(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || !is_transition_idle()) return; + bool isMist = g_game->room->HasCurseMist(); + if (isMist == player.hasCurseMistEffect) return; + if (isMist) player.AddCurseMistEffect(); + else player.RemoveCurseMistEffect(); +} + +// The entities that ride on the player: Breath of Life's glow above it, Salvation's halo, and the Dark Esau chasing +// it with its speed. +static void riders_update(Entity_Player& player) +{ + if (Entity* breath = player.breathOfLifeEffect) + { + breath->posOffset = vector_make(0, BREATH_OF_LIFE_RISE); + breath->pos = player.pos; + breath->velocity = {}; + } + if (Entity* halo = player.salvationEffect) + { + halo->pos = player.pos; + halo->velocity = {}; + } + if (Entity* esau = player.darkEsau; esau && esau->target.get() == &player) + { + esau->pos = player.pos; + esau->velocity = player.velocity; + } +} + +// The poisonous gas (and a static's) builds up on a player standing in it: each frame it hits for nothing adds to the +// build-up, which tints the player and every 30 frames hurts it (a gas) or strikes it with lightning (a static from +// Dogma). Out of it the build-up fades after a few frames. Evil Charm keeps it off. +static void poison_buildup_update(Entity_Player& player) +{ + SFXManager& sounds = g_manager->sfxManager; + if (player.HasCollectible(COLLECTIBLE_EVIL_CHARM) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_EVIL_CHARM)) + player.pendingDamageFlags &= ~(uint64_t)DAMAGE_POISON_BURN; + + EntityRef source; + if (player.pendingDamageFlags & DAMAGE_POISON_BURN) + { + bool isStatic = false; + std::erase_if(player.damageEvents, [&](const DamageEvent& event) { + if (event.damage != 0 || !(event.damageFlags & DAMAGE_POISON_BURN)) return false; + if (event.source.type != 0) source = event.source; + if (event.source.spawnerType == ENTITY_DOGMA) isStatic = true; + return true; + }); + player.pendingDamageFlags &= ~(uint64_t)DAMAGE_POISON_BURN; + player.poisonDamageFrames++; + if (!isStatic) + { + player.AddEntityFlags(FLAG_POISON); + if (!sounds.IsPlaying(SOUND_POISON_WARN)) + sounds.Play(SOUND_POISON_WARN, {.frameDelay = POISON_SOUND_DELAY}); + } + } + else if (player.poisonDamageFrames > 0 && player.IsFrame(3, 0)) + { + player.poisonDamageFrames = 0; + sounds.Stop(SOUND_POISON_WARN); + } + if (player.poisonDamageFrames < 1 || player.isDead) return; + + float buildup = std::min((float)player.poisonDamageFrames / POISON_BUILDUP_FRAMES, 1.0f); + bool isPoison = player.HasEntityFlags(FLAG_POISON); + if (isPoison) player.SetColor({{1, 1, 1, 1}, {0, 1, 0, buildup}, {0, buildup * 0.5f, 0}}, 2, 0, false, true); + else + player.SetColor({{1, 1, 1, 1}, {1.6f, 1.6f, 0.8f, buildup}, {buildup * 0.5f, buildup * 0.5f, buildup * 0.8f}}, + 2, 0, false, true); + if (player.poisonDamageFrames > POISON_FLASH_FROM && player.IsFrame(2, 0)) + player.SetColor(isPoison ? POISON_FLASH : STATIC_FLASH, 3, -1, true, true); + if (player.poisonDamageFrames <= POISON_BUILDUP_FRAMES) return; + + player.damageCooldown = 0; + player.poisonDamageFrames -= POISON_BUILDUP_FRAMES; + if (isPoison) + { + player.TakeDamage(1, 0, source, POISON_HURT_COUNTDOWN); + npc_sound_play(SOUND_POISON_HURT, 1, 2, 1); + return; + } + Entity* strike = g_game->Spawn( + {.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_CRACK_THE_SKY, .seed = Random()}); + strike->spawnerType = source.spawnerType; + strike->spawnerVariant = (int)source.spawnerVariant; + strike->sprite.SetFrame((float)POISON_STATIC_FRAME); + strike->Update(); +} + +// The sprite's FX event puffs a cloud off the player's head that follows it. +static void fx_event_update(Entity_Player& player) +{ + if (!player.sprite.IsEventTriggered("FX")) return; + + auto* poof = static_cast(g_game->Spawn({.position = player.pos, + .subType = FX_POOF_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_TEAR_POOF_A, + .seed = Random()})); + poof->FollowParent(&player); + poof->renderDepthOffset = FX_POOF_DEPTH; + poof->sprite.scale = player.sprite.scale; + poof->posOffset = vector_add(vector_make(0, poof->sprite.scale.y * FX_POOF_RISE), player.GetFlyingOffset()); + poof->AddEntityFlags(FLAG_TRANSITION_UPDATE); + poof->Update(); + poof->rotation = 0; +} + +// A controller that went away pauses the game for its player, or lets a joined co-op player go. Offline the keyboard +// never goes, so it stops the game until reached. +static void controller_check(Entity_Player& player) +{ + bool isConnected = KAGE::Input::manager.is_device_connected(player.controllerIndex); + if (!isConnected && g_game->stageTransition.state == STAGE_TRANSITION_NONE) + reconstruction_missing("Entity_Player::Update 00782af0 (a disconnected controller)"); +} + +// The Intruder: a hurt sets spiders loose from the player's head (always at a red heart or less, else one time in +// 5 less luck), once a room. +static void intruder_hurt(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_INTRUDER) || player.temporaryEffects.HasNullEffect(NULLITEM_INTRUDER)) + return; + int odds = player.redHearts <= 1 ? 1 : std::max(1, (int)((float)INTRUDER_LUCK_ODDS - player.luck)); + if (player.GetCollectibleRNG(COLLECTIBLE_INTRUDER).RandomInt((uint32_t)odds) != 0) return; + + npc_sound_play(SOUND_BOIL_HATCH, 1, INTRUDER_SOUND_DELAY, 1); + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + gibs_spawn({.position = player.pos, + .spawner = &player, + .spread = INTRUDER_GIB_SPREAD, + .amount = INTRUDER_GIBS, + .gibFlags = INTRUDER_GIB_FLAGS}); + for (uint32_t spiders = Random() % INTRUDER_SPIDERS_RANGE + 1; spiders > 0; spiders--) + player.ThrowBlueSpider(player.pos, {}); + player.temporaryEffects.AddNullEffect(NULLITEM_INTRUDER, true, 1); + player.EvaluateItems(); +} + +// Akeldama: in a room with enemies, every 3 ticks while fewer than 12 of its chained tears are out one time in two +// (and up to 20, one time in 5) the player drips a spectral blood tear that falls behind it on a chain. +static void akeldama_update(Entity_Player& player) +{ + Room& room = *g_game->room; + if (!player.HasCollectible(COLLECTIBLE_AKELDAMA) || room.GetAliveEnemiesCount() < 1 || + player.GetIntervalTicks(AKELDAMA_INTERVAL, 0) == 0) + return; + + uint32_t chained = 0; + for (Entity* entity : room.entityList.updateEL) + if (Entity_Tear* tear = entity->ToTear(); tear && tear->tearFlags[TEAR_CHAIN] && tear->parent.get() == &player) + chained++; + bool isDripping = chained < AKELDAMA_FEW_TEARS && random_below(2) == 0; + if (!isDripping && (chained >= AKELDAMA_MANY_TEARS || random_below(5) != 0)) return; + + Vector behind = + player.moveDirection == DIRECTION_NONE ? vector_make(0, 1) : vector_from_direction(player.moveDirection); + uint32_t seed = Random(); + Vector velocity = vector_add(player.velocity, vector_scale(behind, AKELDAMA_SPEED)); + Entity_Tear* tear = g_game + ->Spawn({.position = player.pos, + .velocity = velocity, + .spawner = &player, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = seed}) + ->ToTear(); + tear->isFireSoundMuted = true; + tear->SetCollisionDamage(AKELDAMA_DAMAGE); + tear->SetTearFlags(TearFlags().set(TEAR_CHAIN).set(TEAR_SPECTRAL)); + tear->parent = &player; + tear->SetScale(random_unit() * AKELDAMA_SCALE_RANGE + AKELDAMA_SCALE_MIN); + tear->height = AKELDAMA_HEIGHT; + tear->fallingSpeed = 0; + tear->fallingAccel = AKELDAMA_FALL_ACCEL; + tear->SetColor({{1, 1, 1, 1}, {2.7f, 1.6f, 1.6f, random_unit()}, {0, 0, 0}}, -1, 255, false, true); + tear->Update(); +} + +// The second active is dropped as a pedestal without the Schoolbag, unless the player is a co-op ghost. +static void schoolbag_drop_check(Entity_Player& player) +{ + if (player.activeItems[ACTIVE_SLOT_SECONDARY].item != 0 && !player.HasCollectible(COLLECTIBLE_SCHOOLBAG) && + !player.isCoopGhost) + reconstruction_missing("Entity_Player::Update 00782af0 (the second active dropped without the Schoolbag)"); +} + +// The floor turns slippery under the seed or a slippery flag, the slide lasting a second after it. +static void slippery_update(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_SLIPPERY_PHYSICS)) player.slipperyTimer = SLIPPERY_SLIDE_FRAMES; + else player.slipperyTimer = std::max(player.slipperyTimer - 1, 0); +} + +// Camo Undies' cloak drops at the first shot (or mouse aim): past the room's first frames it leaves a speed boost, a +// puff and a burst that hurts enemies around. +static void camo_undies_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + if (!effects.HasCollectibleEffect(COLLECTIBLE_CAMO_UNDIES)) return; + + bool isShooting = false; + for (ButtonAction action : {ACTION_SHOOT_LEFT, ACTION_SHOOT_UP, ACTION_SHOOT_RIGHT, ACTION_SHOOT_DOWN}) + isShooting |= input_is_action_triggered(action, player.controllerIndex, nullptr); + Vector aim{}; + bool isAiming = g_manager->optionsConfig.isMouseControlEnabled && player.GetMouseAimTarget(aim, false); + if (!isShooting && !isAiming) return; + + effects.RemoveCollectibleEffect(COLLECTIBLE_CAMO_UNDIES, 1); + if (g_game->room->GetFrameCount() <= CAMO_REVEAL_ROOM_FRAME) return; + effects.RemoveNullEffect(NULLITEM_CAMO_BOOST, -1); + effects.AddNullEffect(NULLITEM_CAMO_BOOST, false, CAMO_BOOST_FRAMES); + npc_sound_play(SOUND_BLACK_POOF, 1, 2, 1); + game_shake_screen(CAMO_SHAKE_FRAMES); + player.MakeGroundPoofAtSelf(COLOR_DEFAULT, CAMO_POOF_SIZE); + damage_radius({.position = player.pos, + .source = &player, + .damage = CAMO_DAMAGE, + .playerDamageThreshold = CAMO_PLAYER_THRESHOLD, + .radius = CAMO_RADIUS}); + player.cacheFlags |= effects.cacheFlags; + player.EvaluateItems(); + effects.isEvaluateCachePending = false; +} + +// Pause's frozen room thaws at the player's first shot, or in a versus match when the player's pause timer runs out. +static void pause_thaw_update(Entity_Player& player) +{ + Room& room = *g_game->room; + bool isTimeUp = false; + bool isVersus = g_game->deathmatchManager.is_active(); + if (!player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && isVersus && player.versusPauseTimer != 0) + isTimeUp = --player.versusPauseTimer == 0; + + bool isShooting = player.fireDirection != DIRECTION_NONE || (player.lastActionTriggers & ACTION_TRIGGER_SHOOT); + if (!(room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_PAUSE) && isShooting) && !isTimeUp) return; + room.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_PAUSE, 1); + room.isPacifist = false; + player.versusPauseTimer = 0; +} + +// The sprites that animate with the player: the held item, the crowns, the charge bars and the blood gush. +static void attached_sprites_update(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + player.heldSprite.Update(); + player.crownOfLightSprite.Update(); + player.darkPrincesCrownSprite.Update(); + for (ANM2& bar : player.chargeBarSprites) bar.Update(); + player.bloodGushSprite.Update(); +} + +// How to Jump's leap carries the player toward its landing spot, faster at first, and in the leaping daily its +// landing sends out a shockwave. +static void how_to_jump_update(Entity_Player& player) +{ + TemporaryEffect* jump = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOW_TO_JUMP); + if (!jump) return; + + float frames = (float)g_manager->itemConfig.GetCollectible(COLLECTIBLE_HOW_TO_JUMP)->maxCooldown; + float half = player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) ? 0.5f : 0; + float progress = 1 - (((float)jump->cooldown - half) - 1) / (frames - 2); + Vector leap = vector_scale(vector_sub(player.targetPosition, player.pos), progress * progress); + player.pos = vector_add(player.pos, leap); + player.velocity = {}; + if (g_game->dailyChallenge._specialDailyId != HOW_TO_JUMP_SPECIAL_DAILY || jump->cooldown != 1) return; + + auto* wave = static_cast(g_game->Spawn({.position = player.pos, + .spawner = &player, + .type = ENTITY_EFFECT, + .variant = EFFECT_SHOCKWAVE, + .seed = Random()})); + wave->parent = &player; + wave->SetRadii(player.size, HOW_TO_JUMP_WAVE_REACH); + wave->SetTimeout(HOW_TO_JUMP_WAVE_FRAMES); +} + +// Judas's Birthright aura (the Book of Belial kept as a passive) burns around a leaping or reviving player, and Dark +// Arts' dash ends at the next shot: both stop the game until reached. +static void leap_auras_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + bool isLeaping = effects.HasCollectibleEffect(COLLECTIBLE_HOW_TO_JUMP) || + effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && isLeaping) + reconstruction_missing("Entity_Player::Update 00782af0 (the Book of Belial's burning aura)"); + if (effects.HasCollectibleEffect(COLLECTIBLE_DARK_ARTS)) + reconstruction_missing("Entity_Player::Update 00782af0 (Dark Arts ended by a shot)"); +} + +// The timers the frame counts down: the hurt, controls, fire and item hold cooldowns, and the co-op babies' buffs, +// each asking for the stats it raised once over. +static void cooldowns_update(Entity_Player& player) +{ + constexpr uint32_t BUFF_CACHES[] = {CACHE_DAMAGE, CACHE_FIREDELAY, CACHE_SPEED, CACHE_SHOTSPEED | CACHE_RANGE, + CACHE_LUCK, CACHE_SIZE, CACHE_SIZE}; + for (int* cooldown : {&player.damageCooldown, &player.controlsCooldown, &player.fireBlockCooldown, + &player.itemHoldCooldown, &player.flashCountdown}) + if (*cooldown > 0) (*cooldown)--; + for (size_t buff = 0; buff < std::size(BUFF_CACHES); buff++) + if (player.coopBabyBuffTimers[buff] > 0 && --player.coopBabyBuffTimers[buff] == 0) + { + player.cacheFlags |= BUFF_CACHES[buff]; + player.EvaluateItems(); + } + int& last = player.coopBabyBuffTimers[std::size(BUFF_CACHES)]; + if (last > 0) last--; +} + +// The charges that break what they run into: My Little Unicorn's, the Gamekid's and Taurus's rage hurt the grid +// cell 40 ahead. +static void charge_grid_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + TemporaryEffect* taurus = effects.GetCollectibleEffect(COLLECTIBLE_TAURUS); + bool isCharging = effects.HasCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN) || + effects.HasCollectibleEffect(COLLECTIBLE_GAMEKID) || (taurus && taurus->cooldown != 0); + if (!isCharging) return; + + Room& room = *g_game->room; + int cell = + room.GetGridIndex(vector_add(player.pos, vector_scale(vector_normalized(player.velocity), DASH_GRID_REACH))); + if (cell < 0 || cell >= ROOM_GRID_CELLS) return; + if (GridEntity* grid = room.gridEntities[cell]) grid->Hurt(1, EntityRef(&player)); +} + +// Mega Satan's room holds the player below its line: a dash of Mars or a pony that crosses it ends there, bouncing +// back. +static void mega_satan_line_update(Entity_Player& player) +{ + if (g_game->room->bossId != BOSS_ID_MEGA_SATAN || player.pos.y >= HORSEMAN_MEGA_SATAN_FLOOR) return; + + TemporaryEffects& effects = player.temporaryEffects; + player.pos.y = HORSEMAN_MEGA_SATAN_FLOOR; + if (effects.HasCollectibleEffect(COLLECTIBLE_MARS)) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_MARS, -1); + player.marsDashDirection = -1; + player.dash_impact(); + player.AddVelocity(vector_make(0, MEGA_SATAN_BOUNCE), false); + } + if (effects.HasCollectibleEffect(COLLECTIBLE_PONY) || effects.HasCollectibleEffect(COLLECTIBLE_WHITE_PONY)) + { + player.ponyCharge = 0; + effects.RemoveCollectibleEffect(COLLECTIBLE_PONY, -1); + effects.RemoveCollectibleEffect(COLLECTIBLE_WHITE_PONY, -1); + game_shake_screen(MEGA_SATAN_PONY_SHAKE); + player.AddVelocity(vector_make(0, MEGA_SATAN_BOUNCE), false); + } +} + +// The end of a living frame's motion: a slowed player slides less, Mega Satan's line holds, and the last movement +// fades with the speed. +static void motion_settle(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_SLOW)) player.friction *= std::sqrt(player.slowingAmount); + mega_satan_line_update(player); + if (vector_is_zero(player.recentMovementVector)) return; + + float length = std::sqrt(player.velocity.x * player.velocity.x + player.velocity.y * player.velocity.y); + player.recentMovementVector = + vector_scale(player.recentMovementVector, std::min(std::max(length, 1.0f), MOVEMENT_DECAY_MAX) * 0.5f); + Vector& recent = player.recentMovementVector; + if (recent.x * recent.x + recent.y * recent.y < MOVEMENT_REST) recent = {}; +} + +// The items whose own animation ends with it: the Host Hat's, the Maw of the Void's and Hemoptysis's (whose costume +// then comes off). +static void item_animations_update(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + for (int collectible : {COLLECTIBLE_HOST_HAT, COLLECTIBLE_MAW_OF_THE_VOID}) + if (player.HasCollectible(collectible) && player.IsCollectibleAnimFinished(collectible, "")) + player.ClearCollectibleAnim(collectible); + if (player.temporaryEffects.HasNullEffect(NULLITEM_HEMOPTYSIS)) + reconstruction_missing("Entity_Player::Update 00782af0 (Hemoptysis's animation)"); +} + +// A delayed sound plays once its delay runs out. +static void delayed_sound_update(Entity_Player& player) +{ + if (player.delayedSfxDelay < 1 || --player.delayedSfxDelay != 0) return; + int sound = player.delayedSfxId; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = player.delayedSfxVolume}); + player.delayedSfxId = 0; +} + +// Bleeding out from its own wound drains the player's time while it has red hearts to lose (more than one, or two +// for Keeper's coins, with no soul or bone hearts): out of time it loses a red heart and the time restarts, near the +// end it flashes red. With none left to lose the bleeding stops. +static void bleed_out_update(Entity_Player& player) +{ + if (!player.HasEntityFlags(FLAG_BLEED_OUT) || player.bleedSource.entity != &player) return; + + int red = player.redHearts - player.rottenHearts; + int lasting = player.GetHealthType() == HEALTH_COIN ? 2 : 1; + bool isLosable = red > 0 && (player.soulHearts > 0 || player.boneHearts > 0 || red > lasting); + if (!isLosable) + { + player.ClearEntityFlags(FLAG_BLEED_OUT); + player.bleedOutHealth = 0; + return; + } + if (player.HasInstantDeathCurse()) return; + + player.bleedOutHealth -= (int)player.updateTime - (int)player.prevUpdateTime; + if (player.bleedOutHealth < 1) + { + player.bleedOutHealth = BLEED_OUT_FRAMES; + player.TakeDamage(1, BLEED_OUT_DAMAGE_FLAGS, EntityRef(), BLEED_OUT_HURT_COUNTDOWN); + } + else if (player.bleedOutHealth < BLEED_OUT_FLASH_FROM && player.bleedOutHealth % 4 == 0) + player.SetColor(BLEED_OUT_FLASH, 4, 2, true, true); +} + +// A player carried somewhere eases there, nearly a fifth of the way a frame. +static void move_to_target_update(Entity_Player& player) +{ + if (vector_is_zero(player.moveToTarget)) return; + Vector gap = vector_sub(player.moveToTarget, player.pos); + bool isFar = std::sqrt(gap.x * gap.x + gap.y * gap.y) > 1; + player.pos = isFar ? vector_add(player.pos, vector_scale(gap, MOVE_TO_TARGET_RATE)) : player.moveToTarget; +} + +// Three floors in a row on half a heart or less (the deep floors counted short) unlock the achievement. Greed mode +// does not count. +static void half_heart_floors_update(Entity_Player& player) +{ + Game& game = *g_game; + if (game.IsGreedMode()) return; + int stage = (int)game.stage; + if (player.soulHearts + player.redHearts >= 2) + { + game.lastLevelWithoutHalfHp = stage; + return; + } + int floors = stage - game.lastLevelWithoutHalfHp; + if (stage > HALF_HEART_DEEP_STAGE) + floors = stage < HALF_HEART_LAST_STAGE ? floors - 1 : HALF_HEART_FLOOR_CAP - game.lastLevelWithoutHalfHp; + if (floors > HALF_HEART_FLOORS) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_HALF_HEART_FLOORS); +} + +// The status effect over the player's head, by its first flag: charmed, confused, burning, poisoned, afraid or +// bleeding out, none otherwise. +static void status_effect_update(Entity_Player& player) +{ + ANM2& status = player.statusEffectSprite; + auto shown = + std::ranges::find_if(STATUS_EFFECT_ANIMS, [&](const auto& anim) { return player.HasEntityFlags(anim.first); }); + if (shown == std::end(STATUS_EFFECT_ANIMS)) + { + status.Stop(); + return; + } + if (!status.isLoaded) status.Load("gfx/StatusEffects.anm2", GRAPHICS_LOAD); + if (status.IsPlaying()) status.Update(); + status.Play(shown->second); +} + +// Records the frame into the room's trail (900 frames at most), and in the Void, every 150 frames, a hallucination +// may replay the longest trail walked, one in 75 plus 105 per room from Delirium. A hallucination steps through it. +static void trail_update(Entity_Player& player) +{ + PlayerTrail& trail = player.roomTrail; + bool isWalking = player.IsExtraAnimationFinished(); + TrailFrame frame{.position = player.pos, + .velocity = player.velocity, + .animation = player.sprite.animState.GetAnimationIndex(), + .frame = player.sprite.GetFrame(), + .overlayAnimation = isWalking ? player.sprite.overlayAnimState.GetAnimationIndex() : -1, + .overlayFrame = + player.sprite.overlayAnimState.animData ? (int)player.sprite.overlayAnimState.animFrame : -1}; + if (!trail.frames.empty()) + trail.distance += std::sqrt( + (frame.position.x - trail.frames.back().position.x) * (frame.position.x - trail.frames.back().position.x) + + (frame.position.y - trail.frames.back().position.y) * (frame.position.y - trail.frames.back().position.y)); + trail.frames.push_back(frame); + while (trail.frames.size() > TRAIL_FRAMES_MAX) + { + trail.frames.pop_front(); + if (trail.current > 0) trail.current--; + } + + Game& game = *g_game; + PlayerTrail& ghost = player.hallucinationTrail; + if (ghost.frames.empty()) return; + if (game.stage == VOID_STAGE && player.IsFrame(VOID_HALLUCINATION_PERIOD, 0) && + random_below(game.room->GetDeliriumDistance() * VOID_HALLUCINATION_ODDS_PER_ROOM + VOID_HALLUCINATION_ODDS) == + 0 && + game.hallucinationTimer < 1) + game.ShowHallucination(VOID_HALLUCINATION_FRAMES, VOID_HALLUCINATION_BACKDROP); + if (game.hallucinationTimer > 0 && ghost.current < ghost.frames.size()) ghost.current++; +} + +// The rest of a frame once alive or dead: the damage multiplier is spent, a co-op ghost passes through enemies in +// the versus mode and over the grid, a hologram touches nothing. +static void frame_finish(Entity_Player& player) +{ + if (!player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) player.damageMultiplierStacks = 0; + if (player.isCoopGhost) player.entityGridCollisionClass = GRIDCOLL_WALLS; + if (player.IsHologram()) player.entityCollisionClass = ENTCOLL_NONE; +} + +// A player led by another (a soul stone's twin, the hologram by Tainted Lazarus) is pushed off its leader and the +// leader's other followers, half a unit over the squared distance from each within 12, at most 2 a frame. +static void players_push_apart(Entity_Player& player) +{ + Entity_Player* leader = player.parent ? player.parent->ToPlayer() : nullptr; + if (player.IsHologram()) leader = player.twinPlayer ? player.twinPlayer->ToPlayer() : nullptr; + if (!leader || !is_transition_idle()) return; + + Vector push{}; + for (Entity_Player* other : g_game->playerManager.playerList) + { + if (other == &player || (other != leader && other->parent.get() != leader)) continue; + Vector away = vector_sub(player.pos, other->pos); + float lengthSquared = away.x * away.x + away.y * away.y; + if (lengthSquared > 0 && lengthSquared < LEADER_PUSH_REACH * LEADER_PUSH_REACH) + push = vector_add(push, vector_scale(away, 0.5f / lengthSquared)); + } + if (vector_length(push) > LEADER_PUSH_MAX) push = vector_resized(push, LEADER_PUSH_MAX); + player.AddVelocity(push, false); +} + +// The temporary effects' part of 00782af0: Mars' dash, a pony's charge and Recall ignore knockback, the stats are +// evaluated when the effects changed, and the timed ones count down. The items' frame (update_effects) runs only +// its written pieces, closed by the PostPEffectUpdate callback. +static void temporary_effects_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + bool isDashing = effects.HasCollectibleEffect(COLLECTIBLE_MARS) || player.ponyCharge >= 1 || + effects.HasCollectibleEffect(COLLECTIBLE_RECALL); + if (isDashing) player.AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + else player.ClearEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + if (effects.isEvaluateCachePending) + { + player.cacheFlags |= effects.cacheFlags; + player.EvaluateItems(); + } + effects.isEvaluateCachePending = false; + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + + tainted_frame_update(player); + effects.Update(); + character_frame_update(player); + passives_frame_update(player); + trinkets_frame_update(player); + lua_engine_get().PostPEffectUpdate(&player); +} + +// The living player's frame: it walks, uses its buttons and shoots, its effects and costumes update, its leaps, +// charges and timers run, and its body animates. +static void living_frame_update(Entity_Player& player) +{ + if (player.variant == PLAYER_VARIANT_COOP_BABY && player.isGlitchBaby && player.IsExtraAnimationFinished()) + reconstruction_missing("Entity_Player::Update 00782af0 (the glitched co-op baby's animation)"); + player.held_entity_follow(); + camo_undies_update(player); + player.update_body_animations(); + player.update_bomb_input(); + player.ControlActiveItem(ACTIVE_SLOT_PRIMARY); + player.pocket_use_input(); + player.update_shooting(); + player.pockets_rotate(); + players_push_apart(player); + if (player.variant == PLAYER_VARIANT_PLAYER && !player.isCoopGhost) + { + tractor_beam_update(player); + pause_thaw_update(player); + } + gnawed_leaf_update(player); + temporary_effects_update(player); + if (player.montezumaLaser) reconstruction_missing("Entity_Player::Update 00782af0 (Montezuma's Revenge's spray)"); + + attached_sprites_update(player); + player.sprite_scale_update(); + player.costume_layers_update(); + if (player.variant == PLAYER_VARIANT_PLAYER && !player.isCoopGhost) how_to_jump_update(player); + leap_auras_update(player); + if (player.HasCollectible(COLLECTIBLE_LADDER) && player.variant == PLAYER_VARIANT_PLAYER) player.update_ladder(); + cooldowns_update(player); + player.walk_animation_update(); + if (!player.queuedExtraAnimation.empty() && player.IsExtraAnimationFinished()) + { + player.PlayExtraAnimation(player.queuedExtraAnimation); + player.queuedExtraAnimation.clear(); + } + charge_grid_update(player); + motion_settle(player); + moms_hand_player_release_update(player); +} + +// 00782af0 The player's frame. It rides along with what it carries, catches up with the room's mist and pending floor +// starts, falls, builds up poison, moves as an entity, reacts to hurts, then runs its living frame or its death, its +// items' animations, footprints, sounds, bleeding, status effect and the Void's hallucination, and calls +// PostPlayerUpdate. The parts the plain path does not run yet stop the game until reached. +void Entity_Player::Update() +{ + Game& game = *g_game; + if (game.deathmatchManager.is_active()) reconstruction_missing("Entity_Player::Update 00782af0 (the versus mode)"); + if (std::ranges::any_of(FRAME_SEEDS, [&game](int seed) { return game.seedEffects.HasSeedEffect(seed); })) + reconstruction_missing("Entity_Player::Update 00782af0 (the seeds the frame reads)"); + hud_update(*this); + salvation_halo_update(*this); + lazarus_twins_update(*this); + pending_starts_update(*this); + if (!isValid && spawnerType == SIREN_COPY_SPAWNER) + { + if (bodySprite.isLoaded) bodySprite.Update(); + return; + } + curse_mist_update(*this); + equality_update(*this); + if (variant == PLAYER_VARIANT_EXTRA) reconstruction_missing("Entity_Player::Update 00782af0 (an extra player)"); + if (!isExists) return; + + riders_update(*this); + speedMultiplier = game.room->GetTimeScale(this); + height_update(); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) + { + poison_buildup_update(*this); + if (HasEntityFlags(FLAG_POISON) && poisonDamageFrames < 1) ClearEntityFlags(FLAG_POISON); + } + + Entity::Update(); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) + { + bodySprite.Update(); + fx_event_update(*this); + } + controller_check(*this); + if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; + if (isHurtPending && !isPlayingExtraAnimation) + { + isHurtPending = false; + intruder_hurt(*this); + } + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) akeldama_update(*this); + if (isPlayingItemAnimation && bodySprite.IsFinished() && !bodySprite.IsFinished("LiftItem")) + { + isPlayingItemAnimation = false; + bodySprite.Reset(); + heldSprite.Reset(); + } + update_pitfall(); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && (suplexState != 0 || HasCollectible(COLLECTIBLE_SUPLEX))) + update_suplex(); + trinket_teleports_update(*this); + schoolbag_drop_check(*this); + book_of_belial_passive_update(*this); + slippery_update(*this); + lastActionTriggers = 0; + + if (!isDead) + { + if (std::string gap = frame_gap(); !gap.empty()) + reconstruction_missing(("Entity_Player::Update 00782af0 (" + gap + ")").c_str()); + living_frame_update(*this); + } + else death_update(); + + item_animations_update(*this); + update_footprints(); + if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost) update_baby_skin_effects(); + delayed_sound_update(*this); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) ClearEntityFlags(FLAG_SLIPPERY_PHYSICS); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) bleed_out_update(*this); + isHeldItemVisible = IsHeldItemVisible(); + move_to_target_update(*this); + half_heart_floors_update(*this); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !isDead) + { + status_effect_update(*this); + trail_update(*this); + } + frame_finish(*this); + lua_engine_get().PostPlayerUpdate(this); +} + +// 0078ca00's hallucination part (HallucinationOverlay::Render 00839550): the replayed frame of the longest trail +// walked, its body and then its head, where the player stood then. +void hallucination_trail_render(Entity_Player& player, Vector offset) +{ + PlayerTrail& ghost = player.hallucinationTrail; + if (ghost.current >= ghost.frames.size() || ghost.frames[ghost.current].animation < 0) return; + + const TrailFrame& frame = ghost.frames[ghost.current]; + if (!ghost.sprite.isLoaded) + { + ghost.sprite.Load(g_manager->entityConfig.GetEntity(ENTITY_PLAYER, 0, 0)->anm2Path, GRAPHICS_LOAD); + ghost.sprite.color = TRAIL_COLOR; + } + Vector at = vector_add(render_position_get(frame.position, RENDER_SNAPPED), offset); + ghost.sprite.PlayIndex(frame.animation); + if (ghost.sprite.animState.animData) ghost.sprite.animState.SetFrameFloat((float)frame.frame); + ghost.sprite.Render(SpriteDraw{at, {}, {}}); + if (frame.overlayAnimation < 0) return; + ghost.sprite.PlayIndex(frame.overlayAnimation); + if (ghost.sprite.animState.animData) ghost.sprite.animState.SetFrameFloat((float)frame.overlayFrame); + ghost.sprite.Render(SpriteDraw{at, {}, {}}); +} diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index 05be56b..bfab369 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -22,7 +22,6 @@ constexpr int PLAYER_HEAD_LAYER = 4; constexpr const char* NULL_OFFSET_NAMES[] = {"LeftEye", "RightEye", "Forehead", "Mouth", "Mouth", "MomsEye", "Tractor"}; constexpr float CROSS_EYED_ANGLE = 0.7853982f; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float DEGREES_PER_RADIAN = 57.295776f; constexpr float DUNGEON_TEAR_HEIGHT_MAX = -5.1f; constexpr float DUNGEON_TEAR_OFFSET_Y = -18; @@ -70,6 +69,16 @@ constexpr float TECH_X_RING_LIFT = -20; constexpr int COLLECTIBLE_BRIMSTONE_WEAPON = 118; constexpr int COLLECTIBLE_CURSED_EYE_WEAPON = 316; constexpr int COLLECTIBLE_DEAD_TOOTH = 446; +constexpr float DEAD_TOOTH_RING_SCALE = 0.8f; +constexpr int LARGE_ZIT_INTERVAL = 30; +constexpr uint32_t LARGE_ZIT_ODDS = 3; +constexpr uint32_t ZIT_CREEP_MAX = 3; +constexpr float ZIT_CREEP_REACH = 75; +constexpr float ZIT_CREEP_MIN = 10; +constexpr float ZIT_TEAR_SPEED = 10; +constexpr float ZIT_TEAR_SCALE = 0.5f; +// Large Zit's tear: a pale white, with the exe's values (00bac330, 00bac340). +constexpr ColorMod ZIT_TEAR_COLOR = {{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0.7f, 0.7f, 0.7f}}; constexpr int COLLECTIBLE_EYE_SORE = 558; // The items GetWeaponModifiers turns into modifier bits, in the order it asks. @@ -90,8 +99,6 @@ static Vector vector_rotate(Vector v, float radians) return vector_make(v.x * cosine - v.y * sine, v.y * cosine + v.x * sine); } -static Vector vector_scale(Vector v, float scale) { return vector_make(v.x * scale, v.y * scale); } - // The weapon in charge: the one overriding the rest, or the main one. static Weapon* weapon_main(std::array& weapons) { @@ -162,16 +169,29 @@ void Entity_Player::stop_costume_item_anims() if (map.index >= 0) costumeSpriteDescs[map.index].isItemAnimPlay = false; } -// 007826d0 What firing does each frame: the items that react to shots (not written yet), then the weapon in charge -// fires, or every weapon does. Offline every player is local, so the deathmatch's check is not written yet. +// 007826d0 What firing does each frame: a shot opens Dead Tooth's ring if none is out and squeezes Large Zit one time +// in three every 30 frames, then the weapon in charge fires, or every weapon does. Offline every player is local, so +// the versus mode's remote players are not written. void Entity_Player::trigger_fire_item_effects(Vector direction, bool isShotFired) { - if (g_game->deathmatchManager.is_active()) + Game& game = *g_game; + if (game.deathmatchManager.is_active()) reconstruction_missing("Entity_Player::trigger_fire_item_effects 007826d0 (deathmatch)"); - if (HasCollectible(COLLECTIBLE_DEAD_TOOTH) || HasCollectible(COLLECTIBLE_LARGE_ZIT)) - reconstruction_missing("Entity_Player::trigger_fire_item_effects 007826d0 (Dead Tooth and Large Zit)"); bool isInterpolated = HasEntityFlags(FLAG_INTERPOLATION_UPDATE); + if (HasCollectible(COLLECTIBLE_DEAD_TOOTH) && isShotFired && !deadToothRing) + { + Entity* ring = game.Spawn( + {.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_FART_RING, .seed = Random()}); + ring->sprite.scale = vector_make(DEAD_TOOTH_RING_SCALE, DEAD_TOOTH_RING_SCALE); + deadToothRing = ring; + ring->parent = this; + ring->Update(); + } + if (HasCollectible(COLLECTIBLE_LARGE_ZIT) && isShotFired && !isInterpolated && !game.IsPaused() && + game.frameCount % LARGE_ZIT_INTERVAL == 0 && Random() % LARGE_ZIT_ODDS == 0) + DoZitEffect(direction); + if (weapons[0]) { weapons[0]->Fire(direction, isShotFired, isInterpolated); @@ -181,6 +201,39 @@ void Entity_Player::trigger_fire_item_effects(Vector direction, bool isShotFired if (weapons[slot]) weapons[slot]->Fire(direction, isShotFired, isInterpolated); } +// 007c9590 Large Zit squirts: one to three white creep puddles 10 to 85 along the direction, then a slowing white tear +// of half size and double damage. +void Entity_Player::DoZitEffect(Vector direction) +{ + Game& game = *g_game; + + for (uint32_t puddles = Random() % ZIT_CREEP_MAX + 1; puddles > 0; puddles--) + { + uint32_t seed = Random(); + float reach = (float)Random() * RANDOM_UNIT * ZIT_CREEP_REACH + ZIT_CREEP_MIN; + float length = std::sqrt(direction.x * direction.x + direction.y * direction.y); + Vector offset = length > 0 ? vector_scale(direction, reach / length) : direction; + game.Spawn({.position = vector_add(pos, offset), + .spawner = this, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_WHITE, + .seed = seed}); + } + + Vector inherited = GetTearMovementInheritance(direction, INHERIT_CHECKED); + Vector velocity = vector_scale(vector_add(vector_scale(direction, ZIT_TEAR_SPEED), inherited), shotSpeed); + Entity_Tear* tear = + game.Spawn({.position = pos, .velocity = velocity, .spawner = this, .type = ENTITY_TEAR, .seed = Random()}) + ->ToTear(); + tear->SetColor(ZIT_TEAR_COLOR, -1, 255, false, true); + tear->SetCollisionDamage(damage + damage); + tear->SetTearFlags(TearFlags().set(TEAR_SLOW)); + tear->baseScale = ZIT_TEAR_SCALE; + tear->fScale = ZIT_TEAR_SCALE; + tear->ResetSpriteScale(); + tear->Update(); +} + // 007aaea0 The share of the player's movement its shots carry: twice six tenths of its last velocity, without the part // against the shot. None while Marked aims or tears leave from a shifted head, unless always asked. Vector Entity_Player::GetTearMovementInheritance(const Vector& shotDirection, InheritMode mode) diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index f23c62d..eac46ed 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -261,6 +261,13 @@ constexpr ColorMod PUKE_POOF_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {124 / 255.0f, constexpr ColorMod FCUK_POOF_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr float EXPLOSION_DAMAGE = 50; constexpr float EXPLOSION_RADIUS = 60; + +// The Heretic's fireball bursts into six purple fire shots. +constexpr int HERETIC_BURST_SHOTS = 6; +constexpr float HERETIC_BURST_STEP = 60; +constexpr float HERETIC_BURST_SPEED = 8; +constexpr float HERETIC_BURST_FALL = 0.05f; +constexpr ColorMod HERETIC_BURST_COLOR = {{1, 1, 1, 1}, {1.3f, 1, 2, 1}, {0, 0, 0}}; constexpr float ACID_SCALE = 3; constexpr float ACID_GHOST_SCALE = 1.5f; constexpr int ACID_GHOST_TIMEOUT = 10; @@ -378,24 +385,11 @@ static bool is_crawlspace() return g_game->room->roomType == ROOM_DUNGEON; } -// Vector::Rotated: v turned by an angle in degrees. -static Vector vector_rotated(Vector v, float degrees) -{ - Vector turn = vector_from_angle(degrees); - return vector_make(v.x * turn.x - v.y * turn.y, v.x * turn.y + v.y * turn.x); -} - static float lerp(float from, float to, float t) { return from + (to - from) * t; } -// Math::timescale_factor: how much of a per-tick factor is left over a step of timeScale ticks. -static float timescale_factor(float factor, float timeScale) -{ - return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale); -} - // The phase of a wave of WAVE_FRAMES frames at a time, in radians. static float wave_phase(float time) { @@ -1018,6 +1012,25 @@ void Entity_Projectile::fire_spawn() .timeoutRange = RED_FLAME_TIMEOUT_RANGE}); } +// Part of 00653070: a Heretic's fireball bursts into six purple fire shots. +void Entity_Projectile::heretic_burst_spawn() +{ + for (int i = 0; i < HERETIC_BURST_SHOTS; i++) + { + Vector velocity = vector_scale(vector_from_angle((float)i * HERETIC_BURST_STEP + 0), HERETIC_BURST_SPEED); + auto* shot = static_cast(g_game->Spawn({.position = pos, + .velocity = velocity, + .spawner = parent, + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_FIRE, + .seed = Random()})); + shot->spawnerType = spawnerType; + shot->spawnerVariant = spawnerVariant; + shot->fallingAccel = HERETIC_BURST_FALL; + shot->SetColor(HERETIC_BURST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } +} + // The poof of a dead shot by its variant, or the explosion of an exploding one, tinted its color. void Entity_Projectile::death_poof_spawn() { @@ -1032,8 +1045,9 @@ void Entity_Projectile::death_poof_spawn() .damage = EXPLOSION_DAMAGE, .radius = EXPLOSION_RADIUS}); projectileFlags &= ~PROJECTILE_EXPLODE; - if (spawnerType == ENTITY_HERETIC || (spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL)) - reconstruction_missing("Entity_Projectile::Update 00653070: a late boss's exploding shot"); + if (spawnerType == ENTITY_HERETIC) heretic_burst_spawn(); + if (spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL) + reconstruction_missing("Entity_Projectile::Update 00653070: the Beast's exploding shot"); } else if (is_listed(POOF_VARIANTS, variant)) { diff --git a/src/entity_projectile.h b/src/entity_projectile.h index e27a07c..f2ab5dd 100644 --- a/src/entity_projectile.h +++ b/src/entity_projectile.h @@ -186,6 +186,7 @@ private: void trails_update(); void death_update(); void death_poof_spawn(); + void heretic_burst_spawn(); void death_flags_apply(); void death_bursts_spawn(); void grid_splash(); diff --git a/src/entity_status.cpp b/src/entity_status.cpp index 2bd6dcc..c6db75a 100644 --- a/src/entity_status.cpp +++ b/src/entity_status.cpp @@ -287,6 +287,28 @@ void Entity::AddConfusion(const EntityRef& source, int duration, bool isIgnoreBo if (head.confusionCountdown > 0 && !wasConfused) path_reset(head); } +// 006b7a80 Pushes the entity (or the body it shares status with) for a while unless a friend did it or it ignores +// status effects while not frozen in ice. Heavy entities are pushed less and for less long, by the log of their mass. +void Entity::AddKnockback(const EntityRef& source, Vector push, int duration, bool isImpactDamage) +{ + constexpr float KNOCKBACK_LIGHT_MASS = 10; + if (IsDamageSourceFriendly(source)) return; + Entity& head = *GetStatusEffectTarget(); + bool isIceFrozen = head.HasEntityFlags(FLAG_ICE_FROZEN); + if (duration == 0 || (head.HasEntityFlags(FLAG_NO_STATUS_EFFECTS) && !isIceFrozen)) return; + + head.knockbackCountdown = duration; + head.knockbackDirection = push; + if (head.mass > KNOCKBACK_LIGHT_MASS && !isIceFrozen) + { + float scale = 1 / (float)std::log10((double)head.mass); + head.knockbackDirection = vector_scale(push, scale); + head.knockbackCountdown = std::max(1, (int)((float)duration * scale)); + } + head.AddEntityFlags(isImpactDamage ? FLAG_KNOCKED_BACK | FLAG_APPLY_IMPACT_DAMAGE : FLAG_KNOCKED_BACK); + head.CopyStatusEffects(); +} + // 006adf40 Turns the entity to gold for a while unless a friend did it or it already is: frozen and tinted gold. // A poop turns golden instead. void Entity::AddMidasFreeze(const EntityRef& source, int duration, bool isIgnoreBossCooldown) diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 0786b3a..7410f3b 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -365,12 +365,6 @@ static void unhandled_check(const TearFlags& flags, const std::array= LAUNCH_DRAG_TIME) ClearEntityFlags(FLAG_NO_SPIKE_DAMAGE); - else friction *= lerp_clamped(updateTime, 0, LAUNCH_DRAG_TIME, LAUNCH_DRAG_FRICTION, 1); + else friction *= lerp_range(updateTime, {0, LAUNCH_DRAG_TIME, LAUNCH_DRAG_FRICTION, 1}); } pop_update(); @@ -863,8 +857,10 @@ void Entity_Tear::ludovico_refresh(Entity_Player* player, float speed, int ticks if (variant != params.tearVariant) variant_switch(params.tearVariant, true); if ((subtype & LUDOVICO_FAST) && speed > LUDOVICO_FAST_SPEED_MIN) { - params.tearDamage *= lerp_clamped(speed, LUDOVICO_FAST_SPEED_MIN, LUDOVICO_FAST_SPEED_MAX, 1, LUDOVICO_FAST_DAMAGE_MAX); - params.tearDamage += lerp_clamped(speed, LUDOVICO_FAST_SPEED_MIN, LUDOVICO_FAST_BONUS_SPEED, 0, LUDOVICO_FAST_DAMAGE_MAX); + params.tearDamage *= + lerp_range(speed, {LUDOVICO_FAST_SPEED_MIN, LUDOVICO_FAST_SPEED_MAX, 1, LUDOVICO_FAST_DAMAGE_MAX}); + params.tearDamage += + lerp_range(speed, {LUDOVICO_FAST_SPEED_MIN, LUDOVICO_FAST_BONUS_SPEED, 0, LUDOVICO_FAST_DAMAGE_MAX}); params.tearFlags.set(TEAR_SPECTRAL); } collisionDamage = params.tearDamage; @@ -978,8 +974,8 @@ float Entity_Tear::ludovico_update() } if (parent && parent->IsFamiliar()) scaleFactor *= LUDOVICO_FAMILIAR_SCALE; if (subtype & LUDOVICO_FAST) - scaleFactor *= lerp_clamped(speed, LUDOVICO_FAST_SPEED_MIN, LUDOVICO_FAST_SPEED_MAX, LUDOVICO_FAST_SCALE_MIN, - LUDOVICO_FAST_SCALE_MAX); + scaleFactor *= lerp_range(speed, {LUDOVICO_FAST_SPEED_MIN, LUDOVICO_FAST_SPEED_MAX, LUDOVICO_FAST_SCALE_MIN, + LUDOVICO_FAST_SCALE_MAX}); int ticks = GetIntervalTicks(player ? player->maxFireDelay : LUDOVICO_INTERVAL_DEFAULT, 0); if (ticks != 0) ludovico_refresh(player, speed, ticks); diff --git a/src/entity_tear_flags.cpp b/src/entity_tear_flags.cpp index f679c6a..ab9a3a5 100644 --- a/src/entity_tear_flags.cpp +++ b/src/entity_tear_flags.cpp @@ -284,7 +284,8 @@ void entities_attract(const Attraction& attraction) float pull = strength / reach; if (reach < ATTRACT_NEAR) { - entity->velocity = vector_scale(entity->velocity, npc_friction_scaled(ATTRACT_NEAR_DRAG, entity->speedMultiplier)); + entity->velocity = + vector_scale(entity->velocity, timescale_factor(ATTRACT_NEAR_DRAG, entity->speedMultiplier)); pull = reach / ATTRACT_NEAR_SHARE; } if (entity->mass != 0) @@ -414,7 +415,8 @@ void Entity_Tear::orbit_plain_update(Entity* center) float pullScale = ORBIT_PULL_SHARE; if (tearFlags[TEAR_BOOMERANG]) { - float t = lerp_clamped(height, ORBIT_BOOMERANG_HIGH, ORBIT_BOOMERANG_LOW, ORBIT_BOOMERANG_MIN, ORBIT_BOOMERANG_MAX); + float t = + lerp_range(height, {ORBIT_BOOMERANG_HIGH, ORBIT_BOOMERANG_LOW, ORBIT_BOOMERANG_MIN, ORBIT_BOOMERANG_MAX}); if (tearFlags[TEAR_EXPLOSIVE]) t = std::max(t, ORBIT_EXPLOSIVE_MIN); radius = t * ORBIT_DISTANCE; pullScale = (ORBIT_PULL_BASE - t) * ORBIT_PULL_SHARE; @@ -549,7 +551,7 @@ void Entity_Tear::fetus_update() float dragFactor = std::min(FETUS_DRAG_BASE - vector_dot(vector_normalized(velocity), away) * FETUS_DRAG_DOT + near, FETUS_DRAG_MAX); velocity = vector_sub(velocity, vector_scale(away, speedMultiplier * pull)); - velocity = vector_scale(velocity, npc_friction_scaled(dragFactor, speedMultiplier)); + velocity = vector_scale(velocity, timescale_factor(dragFactor, speedMultiplier)); float turn = (tearFlags[TEAR_HOMING] ? FETUS_TURN_HOMING : FETUS_TURN) * speedMultiplier; float angle = angle_approach(vector_angle(velocity), vector_angle(vector_scale(fromTarget, -1)), turn); velocity = vector_scale(vector_from_angle(angle), vector_length(velocity)); @@ -643,10 +645,9 @@ void Entity_Tear::glow_burn() void Entity_Tear::speed_flags_update() { if (tearFlags[TEAR_ABSORB] || tearFlags[TEAR_LUDOVICO] || tearFlags[TEAR_POP]) return; - if (tearFlags[TEAR_DECELERATE]) - friction *= lerp_clamped(updateTime, 0, SPEED_FLAG_FRAMES, 1, DECELERATE_END); + if (tearFlags[TEAR_DECELERATE]) friction *= lerp_range(updateTime, {0, SPEED_FLAG_FRAMES, 1, DECELERATE_END}); if (!tearFlags[TEAR_ACCELERATE]) return; - float factor = lerp_clamped(updateTime, 0, SPEED_FLAG_FRAMES, ACCELERATE_START, ACCELERATE_END); + float factor = lerp_range(updateTime, {0, SPEED_FLAG_FRAMES, ACCELERATE_START, ACCELERATE_END}); velocity = vector_resized(velocity, std::min(vector_length(velocity) * factor, ACCELERATE_MAX)); } @@ -982,8 +983,8 @@ void Entity_Tear::fire_update() if (variant != TEAR_FIRE) return; float damage = baseDamage; if (spawnerEntity) - damage = lerp_clamped(vector_length(vector_sub(spawnerEntity->pos, pos)), 0, FIRE_FAR, baseDamage, - baseDamage * FIRE_FAR_DAMAGE); + damage = lerp_range(vector_length(vector_sub(spawnerEntity->pos, pos)), + {0, FIRE_FAR, baseDamage, baseDamage * FIRE_FAR_DAMAGE}); collisionDamage = damage; float scale = std::clamp(updateTime / FIRE_FRAMES, FIRE_SCALE_MIN, 1.0f); sprite.scale = vector_make(scale, scale); diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index d63504e..c0d1148 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -5,6 +5,7 @@ #include "entity_player.h" #include "entity_tear.h" #include "familiar_gello.h" +#include "familiar_variants.h" #include "game.h" #include "item_pool.h" #include "log.h" @@ -370,16 +371,19 @@ Entity* Entity_Player::AddBlueFlies(int amount, Vector spawnPos, Entity* chased) // A charger dashing: its look, and how it stops on a wall or out of the room, breaking what it hits (part of 006174c0). void Entity_Familiar::charger_dash() { - if (variant == JAW_BONE || variant == LIL_PORTAL || variant == KNIFE_FULL) + if (variant == LIL_PORTAL) return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger's dash)"); + if (variant == JAW_BONE) return jaw_bone_dash(*this); - bool isShowingDash = variant == LITTLE_CHUBBY || variant == BIG_CHUBBY; + bool isShowingDash = + variant == LITTLE_CHUBBY || variant == BIG_CHUBBY || (variant == KNIFE_FULL && fireCooldown == -1); if (std::fabs(velocity.y) < std::fabs(velocity.x)) { if (isShowingDash) sprite.Play("FloatShootSide"); sprite.isFlipX = velocity.x < 0; } else if (isShowingDash) sprite.Play(velocity.y >= 0 ? "FloatShootDown" : "FloatShootUp"); + if (variant == KNIFE_FULL) return knife_dash(*this); Room& room = *g_game->room; if (isCollidesWithGrid || fireCooldown < -1 || !room.IsPositionInRoom(pos, CHARGE_ROOM_MARGIN)) @@ -453,15 +457,16 @@ void Entity_Familiar::ai_charger() if (fireCooldown < 0) return charger_dash(); FollowParent(); - if (variant == JAW_BONE || variant == LIL_PORTAL || variant == KNIFE_PIECE_1 || variant == KNIFE_PIECE_2 || - variant == KNIFE_FULL) - return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger)"); - if (!sprite.IsPlaying("Float")) sprite.Play("Float"); + if (variant == LIL_PORTAL) return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger)"); + bool isKnifePiece = variant == KNIFE_PIECE_1 || variant == KNIFE_PIECE_2; + if (variant == JAW_BONE) jaw_bone_follow(*this); + else if (isKnifePiece || variant == KNIFE_FULL) knife_follow(*this); + else if (!sprite.IsPlaying("Float")) sprite.Play("Float"); if (fireCooldown > 0) fireCooldown--; - if (direction != DIRECTION_NONE) + if (direction != DIRECTION_NONE && !isKnifePiece) { - sprite.isFlipX = direction == DIRECTION_LEFT; + if (variant != JAW_BONE) sprite.isFlipX = direction == DIRECTION_LEFT; bool isFree = true; if (variant == BOBS_BRAIN) for (Entity_Familiar* brain : familiar_query(BOBS_BRAIN)) @@ -472,7 +477,7 @@ void Entity_Familiar::ai_charger() } if (fireCooldown < 1 && isFree) charger_start(aim, direction); } - entityCollisionClass = ENTCOLL_NONE; + entityCollisionClass = variant == JAW_BONE ? ENTCOLL_ALL : ENTCOLL_NONE; } // The pickup a sack drops on a clear, or none (part of 0062aab0). Lil Chest and Mystery Sack roll theirs, Bumbo counts @@ -567,8 +572,7 @@ void Entity_Familiar::TriggerRoomClear() } if (variant == GB_BUG && subtype != 0) state = 1; - if (variant == PASCHAL_CANDLE) - reconstruction_missing("Entity_Familiar::TriggerRoomClear 0062aab0 (Paschal Candle)"); + if (variant == PASCHAL_CANDLE) paschal_candle_room_clear(*this); if (variant == WISP && !isDead && g_game->frameCount - spawnFrame > 1) wisp_room_clear(*this); } @@ -576,9 +580,10 @@ void Entity_Familiar::TriggerRoomClear() // Hallowed Ground's hop, Intruder's revenge and the Paschal Candle's dimming stop the game. void Entity_Familiar::trigger_player_damage(const DamageEvent& hit) { - if (variant == HALLOWED_GROUND || variant == INTRUDER || variant == PASCHAL_CANDLE) - reconstruction_missing("Entity_Familiar::trigger_player_damage 0062b750 " - "(this familiar's reaction)"); + if (variant == INTRUDER) + reconstruction_missing("Entity_Familiar::trigger_player_damage 0062b750 (this familiar's reaction)"); + if (variant == HALLOWED_GROUND) hallowed_ground_player_hurt(*this); + if (variant == PASCHAL_CANDLE) paschal_candle_player_hurt(*this, hit.damageFlags); if (variant == SMART_FLY) subtype = 1; else if (variant == MYSTERY_EGG && state == 0) @@ -605,12 +610,14 @@ void Entity_Familiar::level_start() if (variant == GUPPYS_HAIRBALL) subtype >>= 1; else if (variant == BUDDY_IN_A_BOX || variant == BUM_FRIEND) subtype = 0; else if (variant == UMBILICAL_BABY) Remove(); - else if ((variant == LOST_SOUL && !g_game->isStartingFromState) || variant == BLOOD_OATH || - variant == PASCHAL_CANDLE || variant == STAR_OF_BETHLEHEM) + else if (variant == BLOOD_OATH) blood_oath_level_start(*this); + else if (variant == PASCHAL_CANDLE) paschal_candle_sync_effects(); + else if (variant == LOST_SOUL && lost_soul_level_start(*this)) return; + else if (variant == STAR_OF_BETHLEHEM) reconstruction_missing("Entity_Familiar::level_start 0062b360 (this familiar's new floor)"); pos = GetFollowTargetPosition(FOLLOW_EXACT); - if (variant == BLOOD_PUPPY) reconstruction_missing("Entity_Familiar::level_start 0062b360 (Blood Puppy)"); + if (variant == BLOOD_PUPPY) blood_puppy_level_start(*this); if (variant == VANISHING_TWIN) state = 0; } @@ -700,9 +707,13 @@ void Entity_Familiar::room_enter() case PUNCHING_BAG: case SPIDER_MOD: case SPIDER_BABY: - case STAR_OF_BETHLEHEM: case LOST_SOUL: + lost_soul_room_enter(*this); + break; case BLOOD_PUPPY: + blood_puppy_room_enter(*this); + break; + case STAR_OF_BETHLEHEM: case VANISHING_TWIN: reconstruction_missing("Entity_Familiar::room_enter 0062bb70 (this familiar's new room)"); case UMBILICAL_BABY: umbilical_baby_room_enter(*this); break; case WISP: diff --git a/src/familiar_body.cpp b/src/familiar_body.cpp new file mode 100644 index 0000000..329b284 --- /dev/null +++ b/src/familiar_body.cpp @@ -0,0 +1,232 @@ +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" + +// The player layers Isaac's body copies, and the blood gush on its neck. +constexpr int BODY_PART_LAYERS[BODY_PART_COUNT] = { + PLAYER_LAYER_BODY, PLAYER_LAYER_BODY0, PLAYER_LAYER_BODY1, PLAYER_LAYER_TOP0}; +constexpr std::string_view BLOOD_GUSH_ANM2 = "gfx/characters/blood gush.anm2"; + +// Transcendence's costume, which the body swaps for Dead Dove's, and how high a flying body floats. +constexpr int COLLECTIBLE_DEAD_DOVE_COSTUME = 185; +constexpr float BODY_FLYING_HEIGHT = -4; + +// How the body walks to its player or its target: the reach and frame interval of its search, how near counts as +// arrived, and its pace (by its player's speed). +constexpr float BODY_REACH_PER_DAMAGE = 15; +constexpr float BODY_REACH_BASE = 65; +constexpr int BODY_SEARCH_INTERVAL = 13; +constexpr float BODY_SEARCH_CONE = 15; +constexpr float BODY_NEAR_PLAYER_SQUARED = 6400; +constexpr float BODY_NEAR_TARGET_SQUARED = 400; +constexpr float BODY_PACE_PLAYER = 1.5f; +constexpr float BODY_PACE_TARGET = 2; +constexpr float BODY_PACE_TARGET_VERSUS = 1.75f; +constexpr float BODY_FRICTION = 0.85f; + +// When the body counts as walking, the speed its legs slow under, and its blood drops (one frame in four). +constexpr float BODY_MOVING_SPEED = 1; +constexpr float BODY_SLOW_WALK_SPEED = 2.3f; +constexpr float BODY_SLOW_ANIM_SPEED = 0.5f; +constexpr float BODY_PLAIN_WALK_SPEED = 2; +constexpr float BODY_DRIP_SCALE_RANGE = 0.5f; +constexpr float BODY_DRIP_SCALE_MIN = 0.2f; +constexpr uint32_t BODY_DRIP_ODDS_MASK = 3; + +// How the detached head drags, and how much lower Decap Attack's draws. +constexpr float HEAD_FRICTION = 0.8f; +constexpr float DECAP_HEAD_DROP = 8.45f; + +// Part of 0060de70: Isaac's body copies the sprites drawing its player's body parts (a flying player's ground costumes +// left out), wears a blood gush, and floats with a flying player. +void isaacs_body_init(Entity_Familiar& body) +{ + Entity_Player& player = *body.player; + auto data = std::make_unique(); + for (int i = 0; i < BODY_PART_COUNT; i++) + { + int layer = BODY_PART_LAYERS[i]; + const PlayerCostumeMap& map = player.playerCostumeMap[layer]; + ANM2& part = data->parts[i]; + if (map.index < 0) + { + part = player.sprite; + data->partLayers[i] = layer; + continue; + } + + CostumeSpriteDesc& costume = player.costumeSpriteDescs[map.index]; + if (player.canFly && !costume.isFlying) continue; + + bool isTranscendence = costume.item && costume.item->type == ITEM_PASSIVE && + costume.item->id == COLLECTIBLE_TRANSCENDENCE; + if (!isTranscendence) part = costume.sprite; + else if (ItemConfig_Item* dove = g_manager->itemConfig.GetCollectible(COLLECTIBLE_DEAD_DOVE_COSTUME)) + part.Load(dove->costume.anm2Path, GRAPHICS_LOAD); + data->partLayers[i] = map.layerId; + } + data->bloodGush.Load(BLOOD_GUSH_ANM2, GRAPHICS_LOAD); + body.extraData = std::move(data); + + if (player.entityGridCollisionClass <= GRIDCOLL_WALLS) + { + body.entityGridCollisionClass = GRIDCOLL_WALLS; + body.posOffset.y = BODY_FLYING_HEIGHT; + } + else body.entityGridCollisionClass = GRIDCOLL_GROUND; +} + +// The walk a body part shows for a velocity: up, down, left or right by its larger axis, down when standing. +static std::string_view body_walk_anim(const Vector& velocity, bool isMoving) +{ + if (!isMoving) return "WalkDown"; + if (std::abs(velocity.y) > std::abs(velocity.x)) return velocity.y >= 0 ? "WalkDown" : "WalkUp"; + return velocity.x >= 0 ? "WalkRight" : "WalkLeft"; +} + +// Its parts walk as it moves (or always, floating), at half speed when slow. Standing parts hold the walk's first +// frame. +static void body_parts_walk(Entity_Familiar& body, IsaacsBodyData& data) +{ + float speed = vector_length(body.velocity); + bool isMoving = speed > BODY_MOVING_SPEED; + std::string_view anim = body_walk_anim(body.velocity, isMoving); + + // The original clamps the slowdown between swapped bounds, so it is always a flat half or whole speed. + if (speed == BODY_MOVING_SPEED) + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + float animSpeed = speed < BODY_SLOW_WALK_SPEED ? BODY_SLOW_ANIM_SPEED : 1; + + for (int i = 0; i < BODY_PART_COUNT; i++) + { + if (data.partLayers[i] < 0) continue; + + ANM2& part = data.parts[i]; + if (!isMoving && body.entityGridCollisionClass != GRIDCOLL_WALLS) + { + part.SetFrame(anim, 0); + continue; + } + part.Play(anim); + part.playbackSpeed = animSpeed; + } +} + +// 00616770 (part of 0061da10) Isaac's body walks back to its player, or to the enemy it picks to trample, its parts +// walking along and its neck gushing blood. +void isaacs_body_update(Entity_Familiar& body) +{ + Vector goal = body.player->pos; + body.PickEnemyTarget({.coneAngle = BODY_SEARCH_CONE, + .range = body.collisionDamage * BODY_REACH_PER_DAMAGE + BODY_REACH_BASE, + .frameInterval = BODY_SEARCH_INTERVAL}); + Entity* target = body.target; + if (target) goal = target->pos; + float near = target ? BODY_NEAR_TARGET_SQUARED : BODY_NEAR_PLAYER_SQUARED; + if (vector_length_squared(vector_sub(goal, body.pos)) > near) + { + float pace = familiar_versus() ? BODY_PACE_TARGET_VERSUS : BODY_PACE_TARGET; + if (!target) pace = BODY_PACE_PLAYER; + body.pathfinder.FindGridPath(goal, pace * body.player->moveSpeed, 0, DIRECT_PATH_FAR); + } + body.friction *= BODY_FRICTION; + + auto* data = dynamic_cast(body.extraData.get()); + if (!data) + { + if (vector_length(body.velocity) < BODY_PLAIN_WALK_SPEED) return body.sprite.SetFrame("WalkVert", 0); + bool isSideways = std::abs(body.velocity.y) < std::abs(body.velocity.x); + body.sprite.Play(isSideways ? "WalkHori" : "WalkVert"); + if (isSideways) body.sprite.isFlipX = body.velocity.x < 0; + return; + } + + data->bloodGush.Play("Idle"); + if (body.sprite.animState.animData) body_parts_walk(body, *data); + for (int i = 0; i < BODY_PART_COUNT; i++) + if (data->partLayers[i] >= 0) data->parts[i].Update(); + data->bloodGush.Update(); + + if ((Random() & BODY_DRIP_ODDS_MASK) != 0) return; + + float scale = random_unit() * BODY_DRIP_SCALE_RANGE + BODY_DRIP_SCALE_MIN; + Entity* drip = g_game->Spawn({.position = body.pos, .spawner = &body, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + drip->sprite.scale = vector_make(scale, scale); + drip->Update(); +} + +// Part of 00624e10: Isaac's body draws its parts in its own colour, then the blood gush on top. Without its data it +// draws as a plain entity. +bool isaacs_body_render(Entity_Familiar& body, const Vector& offset) +{ + auto* data = dynamic_cast(body.extraData.get()); + if (!data) return false; + + body.renderPosition = vector_add(render_position_get(vector_add(body.pos, body.posOffset), RENDER_SNAPPED), offset); + SpriteDraw draw{body.renderPosition, {}, {}}; + for (int i = 0; i < BODY_PART_COUNT; i++) + { + if (data->partLayers[i] < 0) continue; + + data->parts[i].color = body.sprite.color; + data->parts[i].RenderLayer(data->partLayers[i], draw); + } + data->bloodGush.RenderLayer(0, draw); + return true; +} + +// Part of 0061da10: the detached head holds still where it is (Scissors, Decap Attack) or circles its player +// (Guillotine, hidden under Decap Attack), and the player's tears leave from it. +void detached_head_update(Entity_Familiar& head) +{ + Entity_Player& player = *head.player; + if (head.variant == Entity_Familiar::GUILLOTINE) + { + Vector orbit = head.GetOrbitPosition(player.pos); + head.velocity = vector_sub(orbit, head.pos); + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DECAP_ATTACK)) + { + head.isVisible = false; + head.entityCollisionClass = ENTCOLL_NONE; + return; + } + head.entityCollisionClass = ENTCOLL_ALL; + head.isVisible = !player.IsFullSpriteRendering(); + player.tearsOffset = vector_sub(orbit, player.pos); + return; + } + + head.friction *= HEAD_FRICTION; + head.velocity = {}; + if (head.state == 0) head.state = 1; + player.tearsOffset = vector_sub(head.pos, player.pos); +} + +// Part of 00624e10: the detached head draws its player's glow, back and head at its own spot in the player's colour +// (Decap Attack's a little lower), Scissors' even while the player is hidden. Guillotine's draws only while shown. +void detached_head_render(Entity_Familiar& head, const Vector& offset) +{ + if (head.variant == Entity_Familiar::GUILLOTINE && !head.isVisible) return; + + head.renderPosition = vector_add(render_position_get(vector_add(head.pos, head.posOffset), RENDER_SNAPPED), offset); + if (head.variant == Entity_Familiar::DECAP_ATTACK) head.renderPosition.y += DECAP_HEAD_DROP; + + Entity_Player& player = *head.player; + ColorMod saved = player.sprite.color; + ColorMod shown = saved; + shown._tint[3] = 1; + player.SetColor(shown, -1, COLOR_PRIORITY_DEFAULT, false, true); + + bool isPlayerVisible = player.isVisible; + if (head.variant != Entity_Familiar::GUILLOTINE) player.isVisible = true; + player.RenderGlow(head.renderPosition); + player.render_back(head.renderPosition); + player.RenderHead(head.renderPosition); + player.isVisible = isPlayerVisible; + player.SetColor(saved, -1, COLOR_PRIORITY_DEFAULT, false, true); +} diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index 225be3b..9cbcd85 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -6,6 +6,7 @@ #include "entity_pickup.h" #include "entity_player.h" #include "entity_projectile.h" +#include "familiar_variants.h" #include "game.h" #include "log.h" #include "lua_engine.h" @@ -25,7 +26,7 @@ constexpr int CONTACT_VARIANTS[] = {33, 60, 15, 14, 79, 77, 3, 104, 44, 4 32, 83, 121, 126, 226, 224, 210, 218, 206, 237, 229, 204}; // The familiars whose touch, block or hit has an effect of its own not reconstructed yet. -constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 200, 105, 127, 131, 204, 231, 93}; +constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 200, 204, 231, 93}; constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {228, 238, 201, 216, 217, 231}; constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201, 216, 217}; constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 216, 217, 229, 234, 201, 238}; @@ -447,6 +448,29 @@ static void spider_curse(Entity_Familiar& spider, Entity& collider) spider.fireCooldown = (int)(Random() % SPIDER_REST_STEPS + SPIDER_REST_STEPS) * SPIDER_REST_STEP_FRAMES; } +// Depression's beam: one touch in a hundred calls it down on the enemy, as hard as its player, and Depression flashes +// red. +constexpr uint32_t DEPRESSION_BEAM_ODDS = 100; +constexpr ColorMod DEPRESSION_FLASH = {{1, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int DEPRESSION_FLASH_FRAMES = 30; + +// Part of 006261f0: now and then Depression calls a beam of light down on the enemy it touches. +static void depression_touch(Entity_Familiar& depression, Entity& collider) +{ + if (Random() % DEPRESSION_BEAM_ODDS != 0 || !collider.IsVulnerableEnemy(nullptr) || + depression.IsDescendantOf(&collider)) + return; + + Entity* beam = g_game->Spawn({.position = collider.pos, + .spawner = &depression, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACK_THE_SKY, + .seed = Random()}); + beam->SetCollisionDamage(depression.player->damage + beam->collisionDamage); + beam->parent = depression.player; + depression.SetColor(DEPRESSION_FLASH, DEPRESSION_FLASH_FRAMES, 1, true, true); +} + // Part of 006261f0: Sissy Longlegs charms each enemy it touches, once a hit list, and never blocks. static bool sissy_charm(Entity_Familiar& sissy, Entity& collider) { @@ -494,8 +518,10 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) } if (familiar_listed(UNWRITTEN_TOUCH_VARIANTS, variant) || sirenHelper) reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's touch)"); + if (variant == DEPRESSION) depression_touch(*this, *collider); float damageMultiplier = collision_multiplier(*collider); + if (variant == POINTY_RIB) pointy_rib_touch(*this, *collider, damageMultiplier); bool isSpider = variant == SPIDER_MOD || variant == SPIDER_BABY; if (isSpider && fireCooldown < 1 && collider->IsVulnerableEnemy(nullptr) && !IsDescendantOf(collider)) spider_curse(*this, *collider); @@ -508,6 +534,11 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) if (--fireCooldown < CHARGER_BUMP_LIMIT) fireCooldown = CHARGER_BUMP_RECOVER; } if (variant == SISSY_LONGLEGS) return sissy_charm(*this, *collider); + if (variant == MY_SHADOW) + { + my_shadow_touch(*this, *collider); + return true; + } if (isLow && HasEntityFlags(FLAG_SPIN) && collider->IsVulnerableEnemy(nullptr) && !EntityList::HitListContains(hitList, *collider)) @@ -573,21 +604,24 @@ bool Entity_Familiar::solid_check(Entity& collider, bool isIgnored) } // 0062cdc0 A hit on a familiar: shielded from friends, spikes and poop (Isaac's Heart excepted), Isaac's Heart passing -// it to its player, the Punching Bag knocked back, a Dip squeaking. The wisps, the Lost Soul and Milk stop the game. +// it to its player, the Punching Bag knocked back, a Dip squeaking, the Lost Soul losing its mantle or dying. Milk +// stops the game. bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) { if (IsDamageSourceFriendly(source) || source.IsFriendly()) return false; if ((damageFlags & (DAMAGE_SPIKES | DAMAGE_POOP)) && variant != ISAACS_HEART) return false; - if (variant == LOST_SOUL || variant == MILK) - reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0 (this familiar's hit)"); + if (variant == MILK) reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0 (this familiar's hit)"); bool isWisp = variant == WISP || variant == ITEM_WISP; if (isWisp && !wisp_take_damage(source, damageFlags)) return false; if (isWisp) damageCountdown = wisp_hit_countdown(damageCountdown); if (variant == BLOOD_BABY && counter > 0) return false; bool isPassed = variant == ISAACS_HEART || (g_game->challenge == CHALLENGE_GUARDIAN && variant == PUNCHING_BAG); - bool isDamaged = isPassed ? player->TakeDamage(damage, damageFlags | DAMAGE_ISAACS_HEART, source, damageCountdown) - : Entity::TakeDamage(damage, damageFlags | DAMAGE_COUNTDOWN, source, damageCountdown); + bool isDamaged = + isPassed + ? player->TakeDamage(damage, damageFlags | DAMAGE_ISAACS_HEART, source, damageCountdown) + : Entity::TakeDamage(damage, damageFlags | DAMAGE_COUNTDOWN | (variant == LOST_SOUL ? DAMAGE_NOKILL : 0), + source, damageCountdown); if (!isDamaged || damage <= 0) return isDamaged; if (variant == PUNCHING_BAG && friction != 0) @@ -598,6 +632,7 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit if (variant == DIP && (Random() & 1) == 0) familiar_sound_play(SOUND_DIP_HURT, {.volume = DIP_HURT_VOLUME, .frameDelay = DIP_HURT_DELAY}); if (isWisp) wisp_countdown_share(*this); + if (variant == LOST_SOUL) lost_soul_hurt(*this); return isDamaged; } diff --git a/src/familiar_dip.cpp b/src/familiar_dip.cpp index 43a3bf7..bc5ac5b 100644 --- a/src/familiar_dip.cpp +++ b/src/familiar_dip.cpp @@ -1,4 +1,6 @@ +#include "entity_effect.h" #include "entity_familiar.h" +#include "entity_npc.h" #include "entity_player.h" #include "game.h" #include "grid_entity_poop.h" @@ -18,11 +20,82 @@ constexpr float DIP_SPOT_DISTANCE = 80; constexpr float DIP_LANDING_SPREAD = 20; constexpr float DIP_THROW_SPEED = 0.04f; constexpr float DIP_THROW_LIFT = -8; -constexpr int DIP_THROWN_STATE = 2; // The share of a versus player's color a Dip's glow takes, and the color slot of a player without one. constexpr float DIP_VERSUS_GLOW = 0.25f; constexpr int DIP_VERSUS_NO_SLOT = 5; +// The Dips the familiar AI tells apart (Lua's DipSubType). +enum DipSubtype +{ + DIP_SUBTYPE_RED = 1, + DIP_SUBTYPE_GOLDEN = 3, + DIP_SUBTYPE_RAINBOW = 4, + DIP_SUBTYPE_BLACK = 5, + DIP_SUBTYPE_WHITE = 6, + DIP_SUBTYPE_STONE = 12, + DIP_SUBTYPE_FLAMING = 13, + DIP_SUBTYPE_STINKY = 14 +}; + +// A Dip's states: idling, scooting, and thrown. +enum DipState +{ + DIP_STATE_IDLE, + DIP_STATE_MOVING, + DIP_STATE_THROWN +}; + +// A Dip's scoots: their odds by subtype (one in ten, Stone one in twenty, Flaming one in three), their speed, how far +// around its player it wanders, the red one's charge, the golden one's slowness, and the drag of each state. +constexpr uint32_t DIP_SCOOT_ODDS = 10; +constexpr uint32_t DIP_SCOOT_ODDS_STONE = 20; +constexpr uint32_t DIP_SCOOT_ODDS_FLAMING = 3; +constexpr float DIP_SCOOT_SPEED = 5; +constexpr float DIP_WANDER = 80; +constexpr float DIP_RED_CHARGE = 2; +constexpr float DIP_GOLDEN_SLOWNESS = 0.8f; +constexpr float DIP_IDLE_DRAG = 0.8f; +constexpr float DIP_MOVING_DRAG = 0.95f; +constexpr int DIP_PATH_THRESHOLD = 999; + +// The enemies a Dip looks for: the red one far and often, the others near and seldom, and on landing. +constexpr TargetSearch DIP_RED_SEARCH = {.range = 240, .frameInterval = 4}; +constexpr TargetSearch DIP_NEAR_SEARCH = {.range = 40, .frameInterval = 4}; +constexpr TargetSearch DIP_LANDING_SEARCH = {.range = 80}; +constexpr uint32_t DIP_RED_SEARCH_ODDS = 3; +constexpr uint32_t DIP_NEAR_SEARCH_ODDS = 10; + +// A thrown Dip's fall and the heights its grid collision changes at. +constexpr float DIP_FALL = 0.7f; +constexpr float DIP_HIGH = -26; +constexpr float DIP_LOW = -3; + +// The explosions a Dip shrugs off past 3.5, its splats, the red one's regrowth and lifetime, the rainbow one's colors, +// the white one's aura (reach, size, height and sorting), the black one's creep and the stinky one's gas. +constexpr float DIP_EXPLOSION_CAP = 3.5f; +constexpr uint32_t DIP_SPLAT_ODDS = 20; +constexpr float DIP_SPLAT_MIN = 0.2f; +constexpr float DIP_SPLAT_RANGE = 0.5f; +constexpr float DIP_RED_REGROWTH = 0.03f; +constexpr int DIP_RED_LIFETIME = 450; +constexpr uint8_t DIP_RAINBOW_COLORS[][3] = {{154, 40, 45}, {170, 45, 147}, {41, 79, 175}, + {39, 171, 177}, {90, 180, 37}, {181, 170, 36}}; +constexpr int DIP_AURA_INTERVAL = 3; +constexpr float DIP_AURA_REACH = 23.33f; +constexpr int DIP_AURA_FRAMES = 4; +constexpr uint32_t DIP_AURA_CACHE = 99; +constexpr float DIP_AURA_SCALE = 0.33f; +constexpr float DIP_AURA_HEIGHT = -8; +constexpr int DIP_AURA_DEPTH = 10000; +constexpr int DIP_CREEP_INTERVAL = 4; +constexpr int DIP_CREEP_FRAMES = 90; +constexpr float DIP_CREEP_SCALE = 0.4f; +constexpr int DIP_GAS_INTERVAL = 8; +constexpr uint32_t DIP_GAS_ODDS = 3; +constexpr int DIP_GAS_FRAMES = 60; +constexpr float DIP_GAS_SCALE = 0.5f; +constexpr float DIP_TRAIL_SCALE_RANGE = 0.2f; + // 00639000 Spawns a Dip of a subtype for its owner (the poop variants without a Dip of their own give a plain one), // first killing the owner's least worth keeping while it has more than 32. In versus it takes its player's color. Entity* Entity_Familiar::ThrowDip(int subType, const Vector& position, Entity* spawner) @@ -36,9 +109,8 @@ Entity* Entity_Familiar::ThrowDip(int subType, const Vector& position, Entity* s { if (dip->isDead || dip->player != spawner) continue; - float score = dip->subtype >= 0 && dip->subtype < (int)std::size(DIP_KEEP_SCORES) - ? DIP_KEEP_SCORES[dip->subtype] - : 0; + float score = + dip->subtype >= 0 && dip->subtype < (int)std::size(DIP_KEEP_SCORES) ? DIP_KEEP_SCORES[dip->subtype] : 0; score -= (float)(g_game->frameCount - dip->spawnFrame); if (score < worstScore) { @@ -85,8 +157,8 @@ Entity* spawn_dip_at(int subType, const Vector* position, Entity* spawner, const if (vector_is_zero(target)) { Vector direction = random_direction(); - Vector probe = vector_make(direction.x * DIP_SPOT_DISTANCE + position->x, - direction.y * DIP_SPOT_DISTANCE + position->y); + Vector probe = + vector_make(direction.x * DIP_SPOT_DISTANCE + position->x, direction.y * DIP_SPOT_DISTANCE + position->y); Vector spot = room_free_pickup_position_find( {.position = probe, .step = DIP_SPOT_DISTANCE, .isAvoidActiveEntities = true}); Vector landing = random_direction(); @@ -102,6 +174,235 @@ Entity* spawn_dip_at(int subType, const Vector* position, Entity* spawner, const dip.velocity = velocity; dip.orbitSpeed = DIP_THROW_LIFT; dip.orbitDistance = velocity; - dip.state = DIP_THROWN_STATE; + dip.state = DIP_STATE_THROWN; return &dip; } + +// The white Dip's holy aura: every third frame the players beside it are blessed with Hallowed Ground's tears, and it +// keeps the aura effect under itself. +static void dip_aura_update(Entity_Familiar& dip) +{ + if (!dip.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && + g_game->frameCount % DIP_AURA_INTERVAL == 0) + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (familiar_versus() && !dip.IsDescendantOf(player)) continue; + if (vector_length(vector_sub(dip.pos, player->pos)) >= player->size + DIP_AURA_REACH) continue; + + int before = player->hallowedGroundCountdown; + player->hallowedGroundCountdown = std::min(before + DIP_AURA_FRAMES, DIP_AURA_FRAMES); + if ((before > 0) != (player->hallowedGroundCountdown > 0)) + { + player->cacheFlags |= DIP_AURA_CACHE; + player->EvaluateItems(); + } + } + if (dip.child) return; + + auto* aura = static_cast(g_game->Spawn( + {.position = dip.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HALLOWED_GROUND, .seed = Random()})); + aura->parent = &dip; + aura->isFollowing = true; + aura->sprite.offset = vector_make(0, DIP_AURA_HEIGHT); + aura->parentOffset = vector_sub(aura->pos, dip.pos); + aura->renderZOffset = DIP_AURA_DEPTH; + aura->sprite.scale = vector_make(DIP_AURA_SCALE, DIP_AURA_SCALE); + aura->Update(); + dip.child = aura; +} + +// A Dip at rest now and then scoots: toward its target (dropped now and then), else around its player, by the grid +// path when the way is blocked. The red one charges its target. +static void dip_scoot(Entity_Familiar& dip, float speedScale) +{ + dip.sprite.Play("Idle"); + uint32_t odds = dip.subtype == DIP_SUBTYPE_STONE ? DIP_SCOOT_ODDS_STONE + : dip.subtype == DIP_SUBTYPE_FLAMING ? DIP_SCOOT_ODDS_FLAMING + : DIP_SCOOT_ODDS; + if (Random() % odds == 0 && dip.isVisible) + { + if (dip.subtype != DIP_SUBTYPE_RED && dip.target && dip.headFrameDelay == 0 && (Random() & 3) == 0) + dip.target = nullptr; + Entity* goal = dip.target ? dip.target.get() : dip.player; + Vector destination = goal->pos; + if (!room_check_line(dip.pos, goal->pos, 1, DIP_PATH_THRESHOLD)) + { + Vector savedVelocity = dip.velocity; + float savedFriction = dip.friction; + dip.pathfinder.Reset(); + dip.pathfinder.FindGridPath(goal->pos, 1, 0, DIRECT_PATH_FAR); + destination = vector_add(dip.pos, dip.velocity); + dip.velocity = savedVelocity; + dip.friction = savedFriction; + } + else if (goal == dip.player) + destination = vector_add(destination, vector_scale(random_direction(), random_unit() * DIP_WANDER)); + else if (dip.subtype == DIP_SUBTYPE_RED) speedScale = DIP_RED_CHARGE; + + Vector heading = vector_is_zero(vector_sub(destination, dip.pos)) + ? vector_from_angle(random_unit() * RANDOM_HALF_TURN * 2 * RADIANS_TO_DEGREES) + : vector_normalized(vector_sub(destination, dip.pos)); + float speed = random_unit() * DIP_SCOOT_SPEED + DIP_SCOOT_SPEED; + dip.velocity = vector_add(dip.velocity, vector_scale(heading, speed * speedScale / dip.friction)); + dip.state = DIP_STATE_MOVING; + } + dip.friction *= DIP_IDLE_DRAG; +} + +// A thrown Dip arcs down. Thrown at nothing it bounces where it lands, its grid collision rising with it, and dies in a +// pit; at a spot it flies straight there. Landed, it goes for an enemy near and thuds. +static void dip_fall(Entity_Familiar& dip) +{ + dip.sprite.Play("Move"); + bool isFree = vector_is_zero(dip.targetPosition); + if (!isFree) + { + dip.entityGridCollisionClass = GRIDCOLL_WALLS; + dip.entityCollisionClass = ENTCOLL_NONE; + dip.velocity = dip.orbitDistance; + } + dip.orbitSpeed += DIP_FALL; + dip.posOffset.y += dip.orbitSpeed; + if (isFree) + dip.entityGridCollisionClass = dip.posOffset.y < DIP_HIGH + ? GRIDCOLL_WALLS + : (dip.posOffset.y < DIP_LOW ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND); + if (dip.posOffset.y <= -dip.orbitSpeed) return; + + if (isFree) + { + if (room_grid_collision_at(dip.pos) == COLLISION_PIT) + { + g_game->Spawn( + {.position = dip.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + return dip.Remove(); + } + if (!dip.target) dip.PickEnemyTarget(DIP_LANDING_SEARCH); + if (dip.target) dip.headFrameDelay = 1; + } + dip.posOffset.y = 0; + dip.orbitSpeed = 0; + dip.targetPosition = {}; + dip.state = DIP_STATE_IDLE; + familiar_sound_play(dip.subtype == DIP_SUBTYPE_STONE ? SOUND_STONE_IMPACT : SOUND_SPLATTER); +} + +// A Dip's trail as it lives: the black one's creep, the stinky one's gas, the red one's regrowth until it rots. +static void dip_trail(Entity_Familiar& dip) +{ + bool isActing = !dip.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused(); + int tick = g_game->frameCount + (int)dip.index; + if (dip.subtype == DIP_SUBTYPE_RED) + { + if (g_game->frameCount - dip.spawnFrame < DIP_RED_LIFETIME) + dip.health = std::min(dip.health + DIP_RED_REGROWTH, dip.maxHitPoints); + else dip.Kill(EntityRef{}); + return; + } + + Entity* trail = nullptr; + if (dip.subtype == DIP_SUBTYPE_BLACK && isActing && tick % DIP_CREEP_INTERVAL == 0 && (Random() & 1) == 0) + { + trail = g_game->Spawn({.position = dip.pos, + .spawner = &dip, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_BLACK, + .seed = Random()}); + float scale = random_unit() * DIP_TRAIL_SCALE_RANGE + DIP_CREEP_SCALE; + static_cast(trail)->timeout = DIP_CREEP_FRAMES; + static_cast(trail)->lifespan = DIP_CREEP_FRAMES; + trail->sprite.scale = vector_make(scale, scale); + } + else if (dip.subtype == DIP_SUBTYPE_STINKY && isActing && tick % DIP_GAS_INTERVAL == 0 && + Random() % DIP_GAS_ODDS == 0) + { + trail = g_game->Spawn({.position = dip.pos, + .spawner = dip.player, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()}); + float scale = random_unit() * DIP_TRAIL_SCALE_RANGE + DIP_GAS_SCALE; + static_cast(trail)->timeout = DIP_GAS_FRAMES; + static_cast(trail)->lifespan = DIP_GAS_FRAMES; + trail->sprite.scale = vector_make(scale, scale); + trail->SetCollisionDamage(dip.player->meleeDamage * 0.5f); + } + if (trail) trail->Update(); +} + +// 006414c0 A Dip's frame (ZHL's misfit name): it shrugs off big blasts, scoots about after enemies or its player, +// arcs down when thrown, splats, and acts on its kind: the red one hunts and regrows until it rots, the golden one is +// slow, the rainbow one shimmers, the white one blesses, the black one leaves creep, the stinky one gas. BFFS! halves +// its hurts. +void Entity_Familiar::zhl_misfit_006414c0() +{ + float speedScale = 1; + entityGridCollisionClass = GRIDCOLL_GROUND; + entityCollisionClass = ENTCOLL_ALL; + if (pendingDamage > 0) + { + pendingDamage = 0; + for (DamageEvent& hit : damageEvents) + { + if (hit.damageFlags & DAMAGE_EXPLOSION) hit.damage = std::min(hit.damage, DIP_EXPLOSION_CAP); + pendingDamage += hit.damage; + } + } + + switch (subtype) + { + case DIP_SUBTYPE_RED: + if (Random() % DIP_RED_SEARCH_ODDS == 0) PickEnemyTarget(DIP_RED_SEARCH); + break; + case DIP_SUBTYPE_GOLDEN: + speedScale = DIP_GOLDEN_SLOWNESS; + break; + case DIP_SUBTYPE_RAINBOW: + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && (g_game->frameCount & 1) == 0) + { + const uint8_t* rgb = DIP_RAINBOW_COLORS[Random() % std::size(DIP_RAINBOW_COLORS)]; + for (int i = 0; i < 3; i++) splatColor._offset[i] = (float)rgb[i] * COLOR_OFFSET_UNIT; + } + break; + case DIP_SUBTYPE_WHITE: + dip_aura_update(*this); + break; + } + if (subtype != DIP_SUBTYPE_RED && Random() % DIP_NEAR_SEARCH_ODDS == 0) PickEnemyTarget(DIP_NEAR_SEARCH); + if (!target) headFrameDelay = 0; + + if (state == DIP_STATE_IDLE) dip_scoot(*this, speedScale); + else if (state == DIP_STATE_MOVING) + { + sprite.Play("Move"); + if (vector_length_squared(velocity) < 1) state = DIP_STATE_IDLE; + friction *= DIP_MOVING_DRAG; + } + else if (state == DIP_STATE_THROWN) + { + dip_fall(*this); + if (!isExists) return; + } + + if (Random() % DIP_SPLAT_ODDS == 0 && subtype != DIP_SUBTYPE_STONE) + { + Entity* splat = g_game->Spawn( + {.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float size = random_unit() * DIP_SPLAT_RANGE + DIP_SPLAT_MIN; + splat->sprite.scale = vector_make(size, size); + splat->Update(); + splat->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + if (!isDead) dip_trail(*this); + + if (pendingDamage > 0 && player->HasCollectible(COLLECTIBLE_BFFS)) + { + pendingDamage = 0; + for (DamageEvent& hit : damageEvents) + { + hit.damage *= 0.5f; + pendingDamage += hit.damage; + } + } + sprite.isFlipX = velocity.x < 0; +} diff --git a/src/familiar_follow.cpp b/src/familiar_follow.cpp index 415f18c..0a66c65 100644 --- a/src/familiar_follow.cpp +++ b/src/familiar_follow.cpp @@ -1,6 +1,7 @@ #include "entity_familiar.h" #include "entity_effect.h" #include "familiar_gello.h" +#include "familiar_variants.h" #include "weapon_umbilical_whip.h" #include "entity_player.h" #include "entity_tear.h" @@ -24,6 +25,11 @@ constexpr float FOLLOW_PULL = 0.2f; constexpr float FOLLOW_FRICTION = 0.8f; constexpr float FOLLOW_POSITION_PULL = 0.1f; +// How a delayed familiar steers toward its leader's old position, and how hard My Shadow snaps there. +constexpr float DELAYED_PULL = 0.1f; +constexpr float DELAYED_FRICTION = 0.7f; +constexpr float MY_SHADOW_PULL = 0.5f; + // Tainted Lilith's Birthright: the familiars ride Gello in a ring as wide as the riders behind each one and a few // more (BFFS! wider) past a share of Gello's size, the knife pieces straight ahead. Each rider's spot comes from its // seed through two steps of two generators. @@ -204,25 +210,27 @@ static void ride_gello(Entity_Familiar& rider) rider.velocity = vector_sub(spot, rider.pos); } +// Whether a familiar already stands in a line (following or delayed): behind a familiar of its player's in the same +// line, or behind its player. +static bool is_line_joined(Entity_Familiar& familiar, bool Entity_Familiar::* line) +{ + Entity* parent = familiar.parent; + if (!(familiar.*line) || !parent) return false; + + auto* leader = parent->type == ENTITY_FAMILIAR ? dynamic_cast(parent) : nullptr; + if (leader && leader->*line && leader->player == familiar.player) return true; + return parent->type == ENTITY_PLAYER && parent == familiar.player; +} + // 0062db20 Joins its player's following line by priority: behind the first familiar of higher or equal rank, ahead of // the first lower one, at the end otherwise. The first follower starts a line of its own. void Entity_Familiar::AddToFollowers() { if (isSubtype55555) return; - if (variant == TWISTED_BABY) - return reconstruction_missing("Entity_Familiar::AddToFollowers 0062db20 (Twisted Pair)"); + if (variant == TWISTED_BABY) return twisted_baby_pair(*this); - if (isFollower && parent) - { - Entity_Familiar* leader = - parent->type == ENTITY_FAMILIAR ? dynamic_cast(parent.get()) : nullptr; - bool isFamiliarLeader = leader && leader->isFollower && leader->player == player; - if (isFamiliarLeader || (parent->type == ENTITY_PLAYER && parent == player)) - { - KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] Tried to add familiar %d to followers again!\n"); - return; - } - } + if (is_line_joined(*this, &Entity_Familiar::isFollower)) + return KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] Tried to add familiar %d to followers again!\n"); isFollower = true; int priority = GetFollowerPriority(); @@ -267,13 +275,30 @@ static void chain_unlink(Entity& entity) // 0062d7e0 Leaves the following line, its neighbours closing the gap. void Entity_Familiar::RemoveFromFollowers() { - if (variant == TWISTED_BABY && parent) - return reconstruction_missing("Entity_Familiar::RemoveFromFollowers 0062d7e0 (Twisted Pair)"); + if (variant == TWISTED_BABY && parent) return twisted_baby_unpair(*this); if (isFollower) chain_unlink(*this); isFollower = false; } +// 00613fe0 Joins its player's delayed line behind the first delayed familiar with none behind it yet. +void Entity_Familiar::AddToDelayed() +{ + if (isSubtype55555) return; + if (is_line_joined(*this, &Entity_Familiar::isDelayed)) + return KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] Tried to add familiar %d to delayed again!\n"); + + isDelayed = true; + for (Entity_Familiar* other : familiar_query(-1)) + { + if (!other->isExists || other->child || !other->isDelayed || other->player != player || other == this) continue; + + other->child = this; + parent = other; + return; + } +} + // 006141e0 Leaves the delayed line, its neighbours closing the gap. void Entity_Familiar::RemoveFromDelayed() { @@ -281,6 +306,45 @@ void Entity_Familiar::RemoveFromDelayed() isDelayed = false; } +// 00631050 Trails its leader (the familiar ahead, else its player) numFrames behind, steering toward where the leader +// was that long ago. A permanent familiar stays put, Duct Tape holds it in place, and a fresh start or a familiar +// leaving its formation fills the history with the leader's position. My Shadow snaps halfway there each frame. +void Entity_Familiar::MoveDelayed(int numFrames) +{ + if (isSubtype55555) + { + pos = formationOffset; + velocity = {}; + return; + } + if (player->HasTrinket(TRINKET_DUCT_TAPE)) return move_to_parent_offset(); + + // The original overruns its history past 60 frames and divides by zero at none, so the delay is clamped. + numFrames = std::clamp(numFrames, 1, (int)MOVE_HISTORY_SIZE); + int last = moveDelayNum; + if (!vector_is_zero(formationOffset)) + { + reset_follow_target(); + last = -1; + } + Entity* leader = parent ? parent.get() : player; + if (last == -1) + { + moveDelayNum = 0; + std::fill_n(moveHistory.begin(), numFrames, leader->pos); + } + else + { + moveDelayNum = (last + 1) % numFrames; + moveHistory[moveDelayNum] = leader->pos; + } + + Vector toward = vector_sub(moveHistory[(moveDelayNum + 1) % numFrames], pos); + if (variant == MY_SHADOW) velocity = vector_scale(toward, MY_SHADOW_PULL); + else velocity = vector_add(velocity, vector_scale(toward, DELAYED_PULL)); + friction *= DELAYED_FRICTION; +} + // 00613910 Drifts toward a position, or stays pinned in place when permanent. void Entity_Familiar::FollowPosition(const Vector& position) { diff --git a/src/familiar_gello.cpp b/src/familiar_gello.cpp index 2aefded..1122504 100644 --- a/src/familiar_gello.cpp +++ b/src/familiar_gello.cpp @@ -384,27 +384,6 @@ static void cord_grid_hits(Entity_Familiar& gello, const Capsule& cord) } } -// EntityList::query_player_capsule_hits 0041ab50: the tears, enemies, shots (when asked) and pickups the cord's capsule -// touches. -static EntityList_EL cord_hits_query(const Capsule& cord, bool isShotsHit) -{ - EntityList& list = g_game->room->entityList; - EntityList_EL found; - Vector low{}; - Vector high{}; - cord.get_bounding_box(low, high); - Vector center = vector_scale(vector_add(low, high), 0.5f); - Vector extent = vector_scale(vector_sub(high, low), 0.5f); - list.partitions[PARTITION_SHOTS].query_box(found, center, extent); - list.partitions[PARTITION_ENEMIES].query_box(found, center, extent); - if (isShotsHit) list.partitions[PARTITION_PROJECTILES].query_box(found, center, extent); - list.partitions[PARTITION_PICKUPS].query_box(found, center, extent); - std::erase_if(found, [&](Entity* entity) { - return entity->HasEntityFlags(FLAG_NO_QUERY) || !Capsule::Collide(cord, entity->GetCollisionCapsule({})); - }); - return found; -} - // What the fling's hits carry between entities: the cord, its damage, the hit point nearest Gello and whether any enemy // was struck. struct CordStrike @@ -529,7 +508,9 @@ static void gello_fling_hits(Entity_Familiar& gello, UmbilicalBabyData& data) cord_grid_hits(gello, strike.cord); bool isVersus = g_game->deathmatchManager.state >= DEATHMATCH_INTRO; - for (Entity* entity : cord_hits_query(strike.cord, data.tearFlags[TEAR_SHIELDED])) + uint32_t partitions = QUERY_TEARS | QUERY_ENEMIES | QUERY_PICKUPS; + if (data.tearFlags[TEAR_SHIELDED]) partitions |= QUERY_PROJECTILES; + for (Entity* entity : entity_query_capsule(strike.cord, partitions)) { if (entity->size == 0 || entity->entityCollisionClass == ENTCOLL_NONE) continue; @@ -570,12 +551,12 @@ static void gello_reel(Entity_Familiar& gello, UmbilicalBabyData& data, const Ve float timer = data.reelTimer - gello.speedMultiplier * (isInterpolated ? 0.5f : 1); if (!isInterpolated) data.reelTimer = timer; - float left = lerp_clamped(timer, 0, REEL_FRAMES, 0, 1); + float left = lerp_range(timer, {0, REEL_FRAMES, 0, 1}); float out = (1 - left) * left + left; Vector end = vector_add(playerPos, vector_scale(data.reelOffset, out)); Vector side = tear_vector_rotate(vector_normalized(data.reelOffset), 90); float wave = (REEL_FRAMES - timer) * REEL_WAVE; - float settle = npc_friction_scaled(1 - left * REEL_SETTLE, gello.speedMultiplier); + float settle = timescale_factor(1 - left * REEL_SETTLE, gello.speedMultiplier); auto& points = data.points; points[0].x = anchor.x; points[0].y = anchor.y; @@ -684,7 +665,7 @@ static void gello_hold(Entity_Familiar& gello, UmbilicalBabyData& data, const Ve float distance = vector_length(toPlayer); float pull = std::max((distance - GELLO_LEASH) * (1 / distance), 0.0f); float speed = gello.speedMultiplier; - float drag = npc_friction_scaled(BABY_DRAG, speed); + float drag = timescale_factor(BABY_DRAG, speed); gello.velocity = vector_add(vector_scale(gello.velocity, drag), vector_scale(toPlayer, speed * pull * GELLO_LEASH_PULL)); if (isShooting) { @@ -778,7 +759,7 @@ void umbilical_baby_room_enter(Entity_Familiar& gello) for (int i = 0; i < CORD_POINT_COUNT; i++) { - float u = lerp_clamped((float)i, 0, (float)(CORD_POINT_COUNT - 1), 0, 1); + float u = lerp_range((float)i, {0, (float)(CORD_POINT_COUNT - 1), 0, 1}); data->points[i] = {.x = gello.player->pos.x, .y = gello.player->pos.y, .z = CORD_HEIGHT_MIDDLE - u * CORD_ROOM_ENTER_DROP}; } } diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp index fc03ea0..f139759 100644 --- a/src/familiar_missing.cpp +++ b/src/familiar_missing.cpp @@ -27,12 +27,6 @@ void Entity_Familiar::ai_mega_blast_wisp() // 0043eb10 -// 005ae490 -void Entity_Familiar::ai_buddy_inbox() -{ - reconstruction_missing("Entity_Familiar::ai_buddy_inbox 005ae490"); -} - // 0060d180 KColor* Entity_Familiar::GetPlayerSlot(KColor*, Entity_Player*) { @@ -45,24 +39,6 @@ void Entity_Familiar::set_locust_config_index(int) reconstruction_missing("Entity_Familiar::set_locust_config_index 0060ddd0"); } -// 00613fe0 -void Entity_Familiar::AddToDelayed() -{ - reconstruction_missing("Entity_Familiar::AddToDelayed 00613fe0"); -} - -// 0061a240 -void Entity_Familiar::ai_blue_babys_only_friend() -{ - reconstruction_missing("Entity_Familiar::ai_blue_babys_only_friend 0061a240"); -} - -// 0061c150 -void Entity_Familiar::ai_orbital_variant_50() -{ - reconstruction_missing("Entity_Familiar::ai_orbital_variant_50 0061c150"); -} - // 0062c8d0 A pill's effect on the player's familiars: only Acid Baby and Lil Spewer react, which is not written yet. void Entity_Familiar::farting_baby_fart() { @@ -70,24 +46,12 @@ void Entity_Familiar::farting_baby_fart() reconstruction_missing("Entity_Familiar::farting_baby_fart 0062c8d0 (Acid Baby and Lil Spewer)"); } -// 0062e120 -void Entity_Familiar::ai_samsons_chains() -{ - reconstruction_missing("Entity_Familiar::ai_samsons_chains 0062e120"); -} - // 0062ee30 void Entity_Familiar::ai_lil_gurdy() { reconstruction_missing("Entity_Familiar::ai_lil_gurdy 0062ee30"); } -// 00631050 -void Entity_Familiar::MoveDelayed(int) -{ - reconstruction_missing("Entity_Familiar::MoveDelayed 00631050"); -} - // 00631850 void Entity_Familiar::move_to_parent_offset() { @@ -112,24 +76,12 @@ void Entity_Familiar::init_lil_harbinger_sprite() reconstruction_missing("Entity_Familiar::init_lil_harbinger_sprite 006322f0"); } -// 00632820 -void Entity_Familiar::ai_lil_monstro() -{ - reconstruction_missing("Entity_Familiar::ai_lil_monstro 00632820"); -} - // 00632d90 void Entity_Familiar::ai_variant_111() { reconstruction_missing("Entity_Familiar::ai_variant_111 00632d90"); } -// 00633500 -void Entity_Familiar::update_angry_fly() -{ - reconstruction_missing("Entity_Familiar::update_angry_fly 00633500"); -} - // 00634b10 void Entity_Familiar::ai_lil_spewer() { @@ -148,12 +100,6 @@ Entity_Laser* Entity_Familiar::sprinkler_shoot_laser(float, float) reconstruction_missing("Entity_Familiar::sprinkler_shoot_laser 0063aef0"); } -// 0063b340 -void Entity_Familiar::update_idle_anim_by_size() -{ - reconstruction_missing("Entity_Familiar::update_idle_anim_by_size 0063b340"); -} - // 0063b8b0 void Entity_Familiar::RemoveFromPlayer(uint8_t) { @@ -178,30 +124,12 @@ void Entity_Familiar::minisaac_find_target() reconstruction_missing("Entity_Familiar::minisaac_find_target 0063dd60"); } -// 0063f9f0 -void Entity_Familiar::ai_blood_oath() -{ - reconstruction_missing("Entity_Familiar::ai_blood_oath 0063f9f0"); -} - -// 006402f0 -void Entity_Familiar::paschal_candle_sync_effects() -{ - reconstruction_missing("Entity_Familiar::paschal_candle_sync_effects 006402f0"); -} - // 00640ca0 void Entity_Familiar::ai_boiled_baby() { reconstruction_missing("Entity_Familiar::ai_boiled_baby 00640ca0"); } -// 006414c0 -void Entity_Familiar::zhl_misfit_006414c0() -{ - reconstruction_missing("Entity_Familiar::zhl_misfit_006414c0 006414c0"); -} - // 006424d0 void Entity_Familiar::ai_bird_cage() { @@ -214,12 +142,6 @@ void Entity_Familiar::ai_bot_fly() reconstruction_missing("Entity_Familiar::ai_bot_fly 006431d0"); } -// 006437a0 -void Entity_Familiar::ai_stitches() -{ - reconstruction_missing("Entity_Familiar::ai_stitches 006437a0"); -} - // 006444d0 Entity* Entity_Familiar::aim_reflected_projectile() { diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp index 47b9f76..2a554b0 100644 --- a/src/familiar_shoot.cpp +++ b/src/familiar_shoot.cpp @@ -12,9 +12,15 @@ // The items and trinkets the familiars' shots read. constexpr int COLLECTIBLE_HIVE_MIND = 248; -constexpr int TRINKET_FORGOTTEN_LULLABY = 141; constexpr int TRINKET_ISAACS_HEAD_ID = 54; +// Fruity Plum's fruit tears: their damage, their two sizes (the tear scales of sizes 2 and 3), how much bigger, and +// their slow fall. +constexpr float FRUITY_PLUM_SHOT_DAMAGE = 3; +constexpr float FRUITY_PLUM_SHOT_SIZES[] = {0.5f, 0.625f}; +constexpr float FRUITY_PLUM_SHOT_SCALE = 1.25f; +constexpr float FRUITY_PLUM_SHOT_FALL = -0.025f; + // The config tags that make a familiar a fly or a spider, which Hive Mind strengthens. constexpr uint64_t TAG_FAMILIAR_FLY = 1 << 0; constexpr uint64_t TAG_FAMILIAR_SPIDER = 1 << 1; @@ -460,7 +466,14 @@ static bool shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, in shot.tearVariant = TEAR_BLOOD; shot.damage = 7.5f; } - else if (variant == Entity_Familiar::INTRUDER || variant == Entity_Familiar::FRUITY_PLUM) return false; + else if (variant == Entity_Familiar::INTRUDER) return false; + else if (variant == Entity_Familiar::FRUITY_PLUM) + { + shot.damage = FRUITY_PLUM_SHOT_DAMAGE; + shot.scale *= FRUITY_PLUM_SHOT_SIZES[Random() & 1] * FRUITY_PLUM_SHOT_SCALE; + shot.fallingSpeed = 0; + shot.fallingAccel = FRUITY_PLUM_SHOT_FALL; + } else if (variant == Entity_Familiar::FREEZER_BABY || (variant != Entity_Familiar::ABEL && mimic == 11)) { shot.tearVariant = TEAR_ICE; diff --git a/src/familiar_sprinkler.cpp b/src/familiar_sprinkler.cpp new file mode 100644 index 0000000..3941483 --- /dev/null +++ b/src/familiar_sprinkler.cpp @@ -0,0 +1,182 @@ +#include "entity_player.h" +#include "entity_tear.h" +#include "familiar_variants.h" +#include "game.h" +#include "log.h" +#include "npc_ai.h" +#include "room.h" +#include "weapon.h" +#include +#include + +// The Sprinkler: its eight facings (Top clockwise) and the step between them, the speed of its shots, the extra shots +// with Loki's Horns (three more, a right angle apart) or Mom's Eye (one behind), its shot flags, its look's prefix with +// Mom's Eye, and how it marks the grid it stands on so enemies path around it. +constexpr std::string_view SPRINKLER_FACINGS[] = {"Top", "Top Right", "Right", "Bottom Right", + "Down", "Bottom Left", "Left", "Top Left"}; +constexpr int SPRINKLER_FACING_COUNT = 8; +constexpr int SPRINKLER_FACING_LEAD = 2; +constexpr float SPRINKLER_STEP = 45; +constexpr float SPRINKLER_SHOT_SPEED = 10; +constexpr int SPRINKLER_HORN_SHOTS = 4; +constexpr float SPRINKLER_HORN_TURN = 90; +constexpr float SPRINKLER_EYE_TURN = 180; +constexpr uint32_t SPRINKLER_TEAR_FLAGS = TEAR_FIRE_NO_EVIL_EYE | TEAR_FIRE_EXTRA_SHOT; +constexpr std::string_view SPRINKLER_MOMS_EYE = "MomsEye "; +constexpr int SPRINKLER_GRID_PATH = 700; +constexpr int SPRINKLER_GRID_PATH_LIMIT = 951; +constexpr float SPRINKLER_FRICTION = 0.5f; +constexpr float SPRINKLER_SLOW_FIRE = 3; +constexpr WeaponType SPRINKLER_UNWRITTEN_WEAPONS[] = {WEAPON_ROCKETS, WEAPON_KNIFE, WEAPON_BOMBS, + WEAPON_TECH_X, WEAPON_LASER, WEAPON_BRIMSTONE}; + +// Monstro's Lung through the Sprinkler: the tears per eye (12 and 2.4 per extra tear, spread over the eyes), their +// scatter, fall, lift and size. +constexpr float SPRINKLER_LUNG_TEARS_BASE = 12; +constexpr float SPRINKLER_LUNG_TEARS_STEP = 2.4f; +constexpr float SPRINKLER_LUNG_SCATTER = 3.5f; +constexpr float SPRINKLER_LUNG_FALL = 0.5f; +constexpr float SPRINKLER_LUNG_LIFT_RANGE = 15; +constexpr float SPRINKLER_LUNG_LIFT = 5; +constexpr float SPRINKLER_LUNG_SCALE_BIG = 0.4f; +constexpr float SPRINKLER_LUNG_SCALE_BASE = 0.9f; +constexpr float SPRINKLER_LUNG_SCALE_RANGE = 0.05f; +constexpr float SPRINKLER_LUNG_SCALE_MIN = 0.01f; + +// A shot direction of the Sprinkler's turn plus an angle. +static Vector sprinkler_direction(Entity_Familiar& sprinkler, float turn) +{ + return vector_from_angle(normalize_angle_degrees((float)sprinkler.state * SPRINKLER_STEP + turn)); +} + +// Fires one of the player's tears from the Sprinkler. +static void sprinkler_tear(Entity_Familiar& sprinkler, const PosVel& shot) +{ + sprinkler.TryFireTear(sprinkler.player->FireTear(shot, SPRINKLER_TEAR_FLAGS, nullptr, 1)); +} + +// Monstro's Lung through the Sprinkler: each eye coughs a scattered burst of tears, lifted and sized at random. +static void sprinkler_lung(Entity_Familiar& sprinkler, Vector aim, const Weapon_MultiShotParams& params) +{ + int perEye = + (int)std::ceil((SPRINKLER_LUNG_TEARS_BASE + (float)(int)((float)params.numTears * SPRINKLER_LUNG_TEARS_STEP)) / + (float)params.numEyesActive); + for (int eye = 0; eye < params.numEyesActive; eye++) + { + float angle = 0; + if (params.numEyesActive > 1) + { + float share = std::clamp((float)eye / ((float)params.numEyesActive - 1), 0.0f, 1.0f); + angle = (params.multiEyeAngle + params.multiEyeAngle) * share - params.multiEyeAngle; + } + Vector eyeAim = vector_from_angle(vector_angle(aim) + angle); + for (int i = 0; i < perEye; i++) + { + float turn = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit(); + Vector velocity = + vector_add(vector_scale(vector_make(std::cos(turn), std::sin(turn)), reach * SPRINKLER_LUNG_SCATTER), + vector_scale(eyeAim, SPRINKLER_SHOT_SPEED)); + Entity_Tear* tear = sprinkler.player->FireTear({.position = sprinkler.pos, .velocity = velocity}, + SPRINKLER_TEAR_FLAGS, nullptr, 1); + tear->fallingAccel += SPRINKLER_LUNG_FALL; + tear->fallingSpeed = tear->fallingSpeed - random_unit() * SPRINKLER_LUNG_LIFT_RANGE + SPRINKLER_LUNG_LIFT; + float big = (float)(Random() & 1) * SPRINKLER_LUNG_SCALE_BIG; + float scale = + std::max((big + SPRINKLER_LUNG_SCALE_BASE + random_unit() * SPRINKLER_LUNG_SCALE_RANGE) * tear->fScale, + SPRINKLER_LUNG_SCALE_MIN); + tear->baseScale = scale; + tear->fScale = scale; + tear->ResetSpriteScale(); + sprinkler.TryFireTear(tear); + } + } +} + +// The Sprinkler's tear volley (tears, Monstro's Lung, the bone tears): the extra shots of Loki's Horns or Mom's Eye, +// then the volley along its turn. +static void sprinkler_tears(Entity_Familiar& sprinkler, const Weapon_MultiShotParams& params) +{ + Entity_Player& player = *sprinkler.player; + if (player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) + for (int i = 1; i < SPRINKLER_HORN_SHOTS; i++) + sprinkler_tear(sprinkler, + {.position = sprinkler.pos, + .velocity = vector_scale(sprinkler_direction(sprinkler, (float)i * SPRINKLER_HORN_TURN), + SPRINKLER_SHOT_SPEED)}); + else if (player.HasCollectible(COLLECTIBLE_MOMS_EYE)) + sprinkler_tear(sprinkler, {.position = sprinkler.pos, + .velocity = vector_scale(sprinkler_direction(sprinkler, SPRINKLER_EYE_TURN), + SPRINKLER_SHOT_SPEED)}); + + Vector aim = sprinkler_direction(sprinkler, 0); + if (player.weaponTypes[WEAPON_MONSTROS_LUNGS]) return sprinkler_lung(sprinkler, aim, params); + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_TEARS, aim, SPRINKLER_SHOT_SPEED, params); + shot.position = vector_add(shot.position, sprinkler.pos); + sprinkler_tear(sprinkler, shot); + } +} + +// Turns the Sprinkler to its next facing: Loki's two looks, Mom's Eye's or its plain eight. +static void sprinkler_face(Entity_Familiar& sprinkler) +{ + Entity_Player& player = *sprinkler.player; + if (player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) + sprinkler.sprite.Play((sprinkler.state & 1) == 0 ? "Loki Down" : "Loki Bottom Right"); + else + { + std::string_view facing = + SPRINKLER_FACINGS[(sprinkler.state + SPRINKLER_FACING_LEAD) & (SPRINKLER_FACING_COUNT - 1)]; + if (player.HasCollectible(COLLECTIBLE_MOMS_EYE)) + sprinkler.sprite.Play(std::string(SPRINKLER_MOMS_EYE) + std::string(facing)); + else sprinkler.sprite.Play(facing); + } + sprinkler.state = (sprinkler.state + 1) & (SPRINKLER_FACING_COUNT - 1); +} + +// 00635390 FamiliarAI::sprinkler: the Sprinkler stays where it landed, marking its tile for pathing. Once it appeared +// (in Loki's or Mom's Eye's look) it fires the player's weapon at the player's rate (a third of it for Epic Fetus and +// C Section), turning an eighth each volley. Tears, Monstro's Lung and the bone tears are written, the other weapons +// stop the game. +void sprinkler_update(Entity_Familiar& sprinkler) +{ + if (vector_is_zero(sprinkler.targetPosition)) sprinkler.targetPosition = sprinkler.pos; + sprinkler.pos = sprinkler.targetPosition; + sprinkler.friction *= SPRINKLER_FRICTION; + + Room& room = *g_game->room; + int column = (int)((sprinkler.pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((sprinkler.pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + int index = row * room.gridWidth + column; + bool isOnGrid = + column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight && index < ROOM_GRID_CELLS; + if (isOnGrid && room.gridPaths[index] < SPRINKLER_GRID_PATH_LIMIT) room.gridPaths[index] = SPRINKLER_GRID_PATH; + + Entity_Player& player = *sprinkler.player; + if (sprinkler.subtype == 0) + { + if (player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) sprinkler.sprite.Play("Loki Appear"); + else sprinkler.sprite.Play(player.HasCollectible(COLLECTIBLE_MOMS_EYE) ? "MomsEye Appear" : "Appear"); + if (!sprinkler.sprite.IsPlaying()) sprinkler.subtype = 1; + return; + } + + float fireDelay = player.maxFireDelay; + if (player.weaponTypes[WEAPON_ROCKETS] || player.weaponTypes[WEAPON_FETUS]) fireDelay *= SPRINKLER_SLOW_FIRE; + if (sprinkler.GetIntervalTicks(fireDelay, 0) == 0) return; + + Weapon_MultiShotParams params = player.GetMultiShotParams(WEAPON_TEARS); + ::Weapon* tearWeapon = player.weapons[1].get(); + for (WeaponType type : SPRINKLER_UNWRITTEN_WEAPONS) + if (player.weaponTypes[type]) + return reconstruction_missing("FamiliarAI::sprinkler 00635390 (this weapon through the Sprinkler)"); + if (tearWeapon && tearWeapon->weaponType == WEAPON_FETUS) + return reconstruction_missing("FamiliarAI::sprinkler 00635390 (C Section through the Sprinkler)"); + + if (player.weaponTypes[WEAPON_TEARS] || player.weaponTypes[WEAPON_MONSTROS_LUNGS] || + player.weaponTypes[WEAPON_BONE]) + sprinkler_tears(sprinkler, params); + sprinkler_face(sprinkler); +} diff --git a/src/familiar_update.cpp b/src/familiar_update.cpp new file mode 100644 index 0000000..deb30d0 --- /dev/null +++ b/src/familiar_update.cpp @@ -0,0 +1,1202 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.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 "game.h" +#include "grid_entity_poop.h" +#include "log.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "pocket_items.h" +#include "room.h" +#include "room_grid.h" +#include "weapon.h" +#include +#include + +// Brown Nugget's fly: how often and how far it looks for an enemy, its shot's speed, damage and size (by BFFS!), its +// drag, and how long it lives in a versus match. +constexpr int NUGGET_FLY_SHOT_INTERVAL = 30; +constexpr float NUGGET_FLY_RANGE = 150; +constexpr float NUGGET_FLY_NEAREST_START = 40000; +constexpr float NUGGET_FLY_SHOT_SPEED = 10; +constexpr float NUGGET_FLY_SHOT_DAMAGE = 3.5f; +constexpr float NUGGET_FLY_SHOT_SCALE_STEP = 0.2f; +constexpr float NUGGET_FLY_SHOT_SCALE_BASE = 0.6f; +constexpr float NUGGET_FLY_SHOT_FALL = 1; +constexpr float NUGGET_FLY_FRICTION = 0.8f; +constexpr int NUGGET_FLY_VERSUS_FRAMES = 749; + +// Charged Baby: how often it may act (every 30 seconds by a coin flip, every minute for sure), how many batteries or +// charges it gives before it only stuns, and how its stun freezes. +constexpr int CHARGED_CHANCE_FRAMES = 900; +constexpr int CHARGED_SURE_FRAMES = 1800; +constexpr int CHARGED_GIFT_LIMIT = 2; +constexpr int CHARGED_STUN = 2; +constexpr int CHARGED_FREEZE_FRAMES = -40; + +// Lost Fly: its pace along the walls, its drag, and how far and how long it draws enemies' attention. +constexpr float LOST_FLY_STEP = 3; +constexpr float LOST_FLY_FRICTION = 0.6f; +constexpr float LOST_FLY_LURE_RANGE = 160; +constexpr float LOST_FLY_LURE_INTERVAL = 2; +constexpr int LOST_FLY_LURE_FRAMES = 90; + +// The Censer's aura: its reach, the slow it lays on enemies, and how much it slows shots passing through. +constexpr float CENSER_RANGE = 150; +constexpr int CENSER_SLOW_FRAMES = 2; +constexpr float CENSER_SLOW = 0.9f; +constexpr ColorMod CENSER_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}}; +constexpr float CENSER_SHOT_SLOW = 0.5f; + +// Papa Fly: how often and how far it looks for an enemy, how long it holds its attack look, and its shot's speed, fall +// and size (by BFFS!). Shots fired with no target left fly at the aim's slower speed. +constexpr int PAPA_FLY_SHOT_INTERVAL = 30; +constexpr float PAPA_FLY_RANGE = 150; +constexpr int PAPA_FLY_ATTACK_FRAMES = 12; +constexpr float PAPA_FLY_AIM_SPEED = 8; +constexpr float PAPA_FLY_SHOT_SPEED = 10; +constexpr float PAPA_FLY_SHOT_FALL = 1.2f; +constexpr float PAPA_FLY_SCALE_STEP = 0.2f; +constexpr float PAPA_FLY_SCALE_BASE = 0.7f; +constexpr float PAPA_FLY_SCALE_MIN = 0.01f; + +// Milk: the splash it leaves when it drops (a bright poof and a puddle), and how it stops. +constexpr ColorMod MILK_SPLASH_COLOR = {{1, 1, 1, 1}, {2, 2, 2, 1}, {0, 0, 0}}; +constexpr float MILK_FRICTION = 0.5f; + +// Shade: its walks (or flights, with a flying player), how its walk speeds up and slows down with its pace, how many +// chargers it bursts into, the damage it absorbs before (less in a versus match), and Black Judas's red shade. +constexpr std::string_view SHADE_WALKS[] = {"WalkDown", "WalkUp", "WalkHori"}; +constexpr std::string_view SHADE_FLIGHTS[] = {"FlyDown", "FlyUp", "FlyHori"}; +constexpr float SHADE_PACE_SHARE = 0.5f; +constexpr float SHADE_SLOW_PACE = 2.3f; +constexpr float SHADE_FAST_PACE = 6; +constexpr float SHADE_TOP_PACE = 10; +constexpr int SHADE_CHARGERS_MIN = 3; +constexpr int SHADE_ABSORB_LIMIT = 666; +constexpr int SHADE_ABSORB_LIMIT_VERSUS = 100; +constexpr float SHADE_BURST_STEP = 40; +constexpr float SHADE_FRICTION = 0.7f; +constexpr ColorMod SHADE_BLACK_JUDAS_COLOR = {{238 / 255.0f, 28 / 255.0f, 36 / 255.0f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Hushy: how it drifts, its drag while fighting, and its ring of eight shots every second. +constexpr float HUSHY_DRIFT_SPEED = 1.3f; +constexpr float HUSHY_FRICTION = 0.85f; +constexpr int HUSHY_SHOT_FRAMES = 30; +constexpr int HUSHY_SHOT_COUNT = 8; +constexpr float HUSHY_SHOT_STEP = 45; + +// King Baby: its drag while its player fires, and how far, how often and how it picks the enemy its line chases. +constexpr float KING_BABY_FRICTION = 0.7f; +constexpr float KING_BABY_RANGE = 800; +constexpr int KING_BABY_SEARCH_INTERVAL = 8; +constexpr float KING_BABY_SEARCH_CONE = 15; + +// The Finger: how far out it points, how it turns and drags, and its invisible poke (a tenth of its player's laser +// damage) every three frames, every two seconds in a versus match. +constexpr float FINGER_REACH = 50; +constexpr float FINGER_TURN = 0.3f; +constexpr float FINGER_PULL = 0.3f; +constexpr float FINGER_FRICTION = 0.7f; +constexpr float FINGER_FLIP_ROTATION = 1; +constexpr int FINGER_POKE_FRAMES = 3; +constexpr int FINGER_POKE_FRAMES_VERSUS = 60; +constexpr float FINGER_POKE_HEIGHT = -10; +constexpr float FINGER_POKE_DAMAGE = 0.1f; + +// Farting Baby: its three farts' reaches. +constexpr float FARTING_BABY_FART_RADIUS = 85; +constexpr float FARTING_BABY_PUSH_RADIUS = 120; +constexpr float FARTING_BABY_CHARM_RADIUS = 100; + +// Succubus: its aura's reach, how often it burns the enemies in it and how hard, and the reach of its damage boost. +constexpr int SUCCUBUS_BURN_INTERVAL = 7; +constexpr float SUCCUBUS_RANGE = 150; +constexpr float SUCCUBUS_BURN_DAMAGE = 2.5f; +constexpr int SUCCUBUS_BURN_COUNTDOWN = 30; +constexpr float SUCCUBUS_BOOST_RANGE_SQUARED = 10000; + +// Bloodshot Eye: its look's eight frames, how often it fires (sooner again when it found nothing), how far and how +// straight ahead it looks, and its shot's speed, damage, fall and size (by BFFS!). +constexpr int BLOODSHOT_FRAMES = 8; +constexpr int BLOODSHOT_SHOT_INTERVAL = 12; +constexpr int BLOODSHOT_RETRY_INTERVAL = 4; +constexpr float BLOODSHOT_RANGE = 200; +constexpr int BLOODSHOT_LINE_THRESHOLD = 900; +constexpr float BLOODSHOT_LOOK_TURN = 45; +constexpr float BLOODSHOT_CONE_DOT = 0.9f; +constexpr float BLOODSHOT_SHOT_SPEED = 10; +constexpr float BLOODSHOT_SHOT_FALL = 0.7f; +constexpr float BLOODSHOT_SHOT_DAMAGE = 3.5f; +constexpr float BLOODSHOT_SCALE_STEP = 0.35f; +constexpr float BLOODSHOT_SCALE_BASE = 0.7f; + +// Smart Fly: how far its angered form looks, how long it chases one enemy in a versus match and how long it then +// leaves it, its orbit layer, how it settles in its orbit, and its chase speed and drag. +constexpr float SMART_FLY_RANGE = 200; +constexpr int SMART_FLY_SEARCH_INTERVAL = 13; +constexpr float SMART_FLY_SEARCH_CONE = 15; +constexpr int SMART_FLY_CHASE_FRAMES = 599; +constexpr int SMART_FLY_GIVE_UP_FRAMES = -1200; +constexpr int SMART_FLY_ORBIT_LAYER = 1; +constexpr float SMART_FLY_SETTLE_DISTANCE = 20; +constexpr float SMART_FLY_SETTLE = 0.9f; +constexpr float SMART_FLY_STILL_DISTANCE = 0.1f; +constexpr float SMART_FLY_PULL = 0.15f; +constexpr float SMART_FLY_TOP_SPEED = 2; +constexpr float SMART_FLY_FRICTION = 0.8f; + +// Blue Baby's Only Friend: its drag against walls, its push along the aim (stronger the faster it goes, braked against +// its motion), its glide, and how hard the room's edge pushes it back. +constexpr float FRIEND_WALL_DRAG = 0.88f; +constexpr float FRIEND_CROSS_DRAG = 0.5f; +constexpr float FRIEND_SPEED_SHARE = 0.03f; +constexpr float FRIEND_BRAKE = 0.2f; +constexpr float FRIEND_PUSH_BASE = 3; +constexpr float FRIEND_PUSH_SCALE = 0.8f; +constexpr float FRIEND_GLIDE = 0.775f; +constexpr float FRIEND_EDGE_PUSH_MIN = 1; +constexpr float FRIEND_EDGE_PUSH_MAX = 10; + +// Angry Fly: how often it gives up on its player or on a target no longer worth it, its circle around its target (a +// boss's pulses in and out every five seconds), its spin, and its pull and top speed. +constexpr int ANGRY_FLY_PLAYER_FRAMES = 30; +constexpr int ANGRY_FLY_TARGET_FRAMES = 150; +constexpr int ANGRY_FLY_CULTIST_SKIPPED = 10; +constexpr float ANGRY_FLY_RADIUS = 65; +constexpr int ANGRY_FLY_PULSE_PERIOD = 150; +constexpr int ANGRY_FLY_PULSE_FRAMES = 30; +constexpr float ANGRY_FLY_SPIN = 3.6f; +constexpr float ANGRY_FLY_PULL = 0.22f; +constexpr float ANGRY_FLY_TOP_SPEED = 10; + +// Spider Mod's spiders: how long they rest (15 to 34 frames) and walk (15 to 74), their pace and drag. +constexpr uint32_t SPIDER_MOD_REST_RANGE = 20; +constexpr uint32_t SPIDER_MOD_WALK_RANGE = 60; +constexpr int SPIDER_MOD_PHASE_MIN = 15; +constexpr float SPIDER_MOD_PACE = 1; +constexpr float SPIDER_MOD_FRICTION = 0.7f; + +// Samson's Chains: the slack before the chain pulls, the hard pull past its length, the ball's glide, how the balls +// keep apart, the chain's full reach and the ball's speed held against a wall there, and the drawn links. +constexpr float SAMSON_CHAIN_SLACK = 70; +constexpr float SAMSON_CHAIN_SLACK_PULL = 0.1f; +constexpr float SAMSON_CHAIN_LENGTH = 100; +constexpr float SAMSON_CHAIN_LENGTH_PULL = 1.6f; +constexpr float SAMSON_CHAIN_GLIDE = 0.8836f; +constexpr float SAMSON_CHAIN_BALL_SPACING = 20; +constexpr float SAMSON_CHAIN_BALL_PUSH = 0.1f; +constexpr float SAMSON_CHAIN_REACH = 120; +constexpr float SAMSON_CHAIN_WALL_SPEED = 5; +constexpr float SAMSON_CHAIN_STILL_DISTANCE = 0.01f; +constexpr int SAMSON_CHAIN_LINKS = 8; +constexpr float SAMSON_CHAIN_LINK_SAG = 7; +constexpr float SAMSON_CHAIN_LINK_RISE = -5; + +// Gemini: its leash and its reach around its player (both longer with BFFS!), its rage after losing its target, how it +// chases, how close twins push apart and how hard, and the cord it draws. +constexpr float GEMINI_LEASH = 150; +constexpr float GEMINI_REACH = 180; +constexpr float GEMINI_LEASH_BFFS = 187.5f; +constexpr float GEMINI_REACH_BFFS = 225; +constexpr int GEMINI_RAGE_FRAMES = 15; +constexpr float GEMINI_LEASH_PULL = 0.9f; +constexpr float GEMINI_DRAG = 0.9f; +constexpr float GEMINI_TWIN_RANGE = 24; +constexpr float GEMINI_TWIN_PUSH = 10; +constexpr float GEMINI_TWIN_PUSH_MAX = 4; +constexpr int GEMINI_CORD_LINKS = 9; +constexpr float GEMINI_CORD_HEIGHT = -16; + +// Sissy Longlegs: how long it rests (15 to 34 frames) and wanders (15 to 44), its pace and drag, how often it lays a +// spider while enemies remain (2.5 to 7.5 seconds, 2 to 5.5 with BFFS!), and its spider limits (Mom's Wig doubles it). +constexpr uint32_t SISSY_WANDER_RANGE = 30; +constexpr float SISSY_PACE = 0.8f; +constexpr float SISSY_FRICTION = 0.7f; +constexpr float SISSY_SPAWN_FRICTION = 0.6f; +constexpr uint32_t SISSY_LAY_RANGE = 300; +constexpr int SISSY_LAY_MIN = 150; +constexpr uint32_t SISSY_LAY_RANGE_BFFS = 210; +constexpr int SISSY_LAY_MIN_BFFS = 120; +constexpr int SISSY_SPIDER_LIMIT = 4; +constexpr int SISSY_SPIDER_LIMIT_WIG = 9; + +// Punching Bag: the subtype of a bag knocked out in the Guardian challenge, and how near it shies away from danger. +constexpr int PUNCHING_BAG_GONE = 0xdead; +constexpr float PUNCHING_BAG_SHY_RANGE = 50; +constexpr int PUNCHING_BAG_PROBES = 8; +constexpr float PUNCHING_BAG_FRICTION = 0.8f; + +// Part of 0061da10: Brown Nugget's fly hovers where it appeared, and every half second spits a blood tear at the +// nearest enemy in reach, leading its motion. In a versus match it dies after a while, taking the nugget's effect. +void brown_nugget_update(Entity_Familiar& fly) +{ + if (vector_is_zero(fly.targetPosition)) fly.targetPosition = fly.pos; + if (fly.sprite.IsFinished()) fly.sprite.Play("Fly"); + + if (fly.IsFrame(NUGGET_FLY_SHOT_INTERVAL, fly.index)) + { + Entity* nearest = nullptr; + float nearestDistance = NUGGET_FLY_NEAREST_START; + for (Entity* enemy : entity_query_radius(fly.pos, NUGGET_FLY_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(&fly) || enemy == fly.spawnerEntity) continue; + + float distance = vector_length_squared(vector_sub(enemy->pos, fly.pos)); + if (distance >= nearestDistance) continue; + + nearestDistance = distance; + nearest = enemy; + } + if (nearest) + { + fly.sprite.Play("Attack", PLAY_FORCED); + fly.sprite.isFlipX = fly.pos.x > nearest->pos.x; + uint32_t seed = Random(); + Vector aim = vector_sub(vector_add(nearest->pos, nearest->velocity), fly.pos); + Vector shot = vector_resized(aim, NUGGET_FLY_SHOT_SPEED); + auto* tear = static_cast(g_game->Spawn({.position = fly.pos, + .velocity = shot, + .spawner = &fly, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = seed})); + float multiplier = fly.GetMultiplier(); + float scale = fly.GetMultiplier() * NUGGET_FLY_SHOT_SCALE_STEP + NUGGET_FLY_SHOT_SCALE_BASE; + tear->SetCollisionDamage(multiplier * NUGGET_FLY_SHOT_DAMAGE); + tear->SetScale(scale); + tear->fallingSpeed = NUGGET_FLY_SHOT_FALL; + fly.TryFireTear(tear); + tear->Update(); + fly.shot_owner_convert(tear); + } + } + + if (g_game->deathmatchManager.is_active() && ++fly.counter > NUGGET_FLY_VERSUS_FRAMES) + { + if (fly.player) fly.player->temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_BROWN_NUGGET, 1); + fly.Kill(EntityRef{}); + } + fly.velocity = vector_sub(fly.targetPosition, fly.pos); + fly.friction *= NUGGET_FLY_FRICTION; +} + +// Charged Baby's turn: a battery beside it, a charge for its player's active item, or a stun on every enemy. After two +// gifts it only stuns, and in a versus match it never stuns. A stun does not count. +static void charged_baby_act(Entity_Familiar& baby) +{ + bool isVersus = g_game->deathmatchManager.is_active(); + uint32_t act = baby.coins < CHARGED_GIFT_LIMIT ? baby.dropRNG.RandomInt(3) : CHARGED_STUN; + if (act == CHARGED_STUN && !isVersus) + { + for (Entity* enemy : g_game->room->GetEntities()->updateEL) + if (enemy->IsVulnerableEnemy(nullptr)) enemy->AddFreeze(EntityRef(&baby), CHARGED_FREEZE_FRAMES, false); + baby.sprite.Play("Act", PLAY_FORCED); + familiar_sound_play(SOUND_CHARGEDBABY_STUN); + return; + } + if (act == 0) + { + Vector spot = room_free_pickup_position_find({.position = baby.pos}); + g_game->Spawn({.position = spot, .spawner = &baby, .type = ENTITY_PICKUP, .variant = PICKUP_LIL_BATTERY, + .seed = Random()}); + baby.sprite.Play("Spawn", PLAY_FORCED); + familiar_sound_play(SOUND_CHARGEDBABY_BATTERY); + } + else if (act == 1) + { + baby.player->AddActiveCharge(1, -1, false, false, false); + baby.sprite.Play("Act", PLAY_FORCED); + familiar_sound_play(SOUND_CHARGEDBABY_CHARGE); + } + baby.coins++; +} + +// Part of 0061da10: Charged Baby follows, and while enemies remain (always in a versus match) acts now and then. +void charged_baby_update(Entity_Familiar& baby) +{ + if (!g_game->room->IsClear() || g_game->deathmatchManager.is_active()) + { + int age = baby.FrameCount(); + bool isChance = age % CHARGED_CHANCE_FRAMES == 0 && random_below(2) == 0; + if (age > 0 && (isChance || age % CHARGED_SURE_FRAMES == 0)) charged_baby_act(baby); + } + baby.FollowParent(); + if (baby.sprite.IsFinished()) baby.sprite.Play("Idle"); +} + +// Whether a cell lets Lost Fly pass: open floor or a pit. +static bool is_lost_fly_passable(uint32_t collision) +{ + return collision == COLLISION_NONE || collision == COLLISION_PIT; +} + +// Part of 0061da10 (0062e9c0): Lost Fly crawls along the walls, keeping its right side on them (it turns left at a +// wall ahead, and right where the wall beside it ends), and draws the attention of the enemies that can see it. +void lost_fly_update(Entity_Familiar& fly) +{ + Room& room = *g_game->room; + if (vector_is_zero(fly.targetPosition)) + { + fly.targetPosition = fly.pos; + fly.state = room.GetGridIndex(fly.pos); + } + fly.friction *= LOST_FLY_FRICTION; + fly.pos = fly.targetPosition; + + Vector step = vector_scale(direction_unit(fly.moveDirection), LOST_FLY_STEP); + int ahead = room.GetGridIndex(vector_add(fly.pos, step)); + if (ahead != fly.state) + { + if (!is_lost_fly_passable(room.GetGridCollision(ahead))) + { + fly.moveDirection = (fly.moveDirection + 3) % 4; + return; + } + Vector side = vector_add(fly.pos, vector_scale(direction_unit((fly.moveDirection + 1) % 4), LOST_FLY_STEP)); + if (is_lost_fly_passable(room.GetGridCollision(room.GetGridIndex(vector_add(side, step)))) && + !is_lost_fly_passable(room_grid_collision_at(side))) + fly.moveDirection = (fly.moveDirection + 1) % 4; + } + fly.velocity = step; + fly.targetPosition = vector_add(fly.targetPosition, step); + + if (!fly.GetIntervalTicks(LOST_FLY_LURE_INTERVAL, 0)) return; + + for (Entity* entity : entity_query_radius(fly.pos, LOST_FLY_LURE_RANGE, QUERY_ENEMIES)) + { + auto* enemy = dynamic_cast(entity); + if (!entity->IsVulnerableEnemy(nullptr) || !enemy || entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) + continue; + if (room_check_line(fly.pos, enemy->pos, LINE_MODE_PROJECTILE, 0)) + enemy->TryForceTarget(&fly, LOST_FLY_LURE_FRAMES); + } +} + +// Part of 0061da10: the Censer follows, slowing the enemies around it, and halves once the speed of the tears (marked +// with Lump of Coal's growth) and, in a versus match, the enemy shots passing through. +void censer_update(Entity_Familiar& censer) +{ + uint32_t partitions = QUERY_TEARS | QUERY_ENEMIES; + if (g_game->deathmatchManager.is_active()) partitions |= QUERY_PROJECTILES; + for (Entity* entity : entity_query_radius(censer.pos, CENSER_RANGE, partitions)) + { + if (entity->HasEntityFlags(FLAG_FRIENDLY)) continue; + + if (entity->IsVulnerableEnemy(nullptr)) + entity->AddSlowing(EntityRef(&censer), CENSER_SLOW_FRAMES, CENSER_SLOW, CENSER_SLOW_COLOR, false); + else if (auto* shot = entity->type == ENTITY_PROJECTILE ? dynamic_cast(entity) : nullptr) + { + if (shot->projectileFlags & PROJECTILE_SLOWED) continue; + + shot->velocity = vector_scale(shot->velocity, CENSER_SHOT_SLOW); + shot->AddProjectileFlags(PROJECTILE_SLOWED); + } + else if (auto* tear = entity->IsTear() ? dynamic_cast(entity) : nullptr) + { + if (tear->tearFlags.test(TEAR_GROW) || tear->IsDescendantOf(censer.spawnerEntity)) continue; + + tear->velocity = vector_scale(tear->velocity, CENSER_SHOT_SLOW); + tear->SetTearFlags(TearFlags(tear->tearFlags).set(TEAR_GROW)); + } + } + censer.FollowParent(); +} + +// 00632820 Papa Fly's attack (the database's name for it): every half second it aims at the last enemy in reach it can +// see, plays its attack, and on the attack's Shoot event fires a tear as hard as its player's. It faces its motion. +void Entity_Familiar::ai_lil_monstro() +{ + if (IsFrame(familiar_lullaby_delay(*this, PAPA_FLY_SHOT_INTERVAL), 0)) + { + Entity* aimed = nullptr; + for (Entity* enemy : entity_query_radius(pos, PAPA_FLY_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || IsDescendantOf(enemy) || + enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) + continue; + if (room_check_line(pos, enemy->pos, LINE_MODE_PROJECTILE, 0)) aimed = enemy; + } + if (aimed) + { + Vector toward = vector_sub(aimed->pos, pos); + headFrameDelay = PAPA_FLY_ATTACK_FRAMES; + sprite.Play("Attack"); + sprite.isFlipX = toward.x < 0; + targetPosition = vector_scale(vector_normalized(toward), PAPA_FLY_AIM_SPEED); + target = aimed; + } + } + if (headFrameDelay > 0) headFrameDelay--; + else if (!sprite.animState.animData || !sprite.animState.isPlaying) sprite.Play("Fly"); + + if (sprite.animState.animData && sprite.animState.IsEventTriggered("Shoot")) + { + Vector shot = targetPosition; + if (target) shot = vector_scale(vector_normalized(vector_sub(target->pos, pos)), PAPA_FLY_SHOT_SPEED); + auto* tear = static_cast(g_game->Spawn( + {.position = pos, .velocity = shot, .spawner = this, .type = ENTITY_TEAR, .seed = Random()})); + tear->fallingSpeed = PAPA_FLY_SHOT_FALL; + float multiplier = GetMultiplier(); + float scale = std::max(GetMultiplier() * PAPA_FLY_SCALE_STEP + PAPA_FLY_SCALE_BASE, PAPA_FLY_SCALE_MIN); + TearParams hit = player->GetTearHitParams(WEAPON_TEARS, 1, (Random() & 1) * 2 - 1, nullptr); + tear->SetCollisionDamage(multiplier * hit.tearDamage); + tear->baseScale = scale; + tear->fScale = scale; + tear->ResetSpriteScale(); + TryFireTear(tear); + shot_owner_convert(tear); + } + if (sprite.animState.animData && sprite.animState.animData->isLooping) sprite.isFlipX = velocity.x < 0; +} + +// Part of 0061da10: Milk follows until its player's damage tops it up to its drink, then drops: on its Drop event it +// splashes, gives its player Milk's effect and loses its shadow, and once dropped it hides at the room's corner. +void milk_update(Entity_Familiar& milk) +{ + if ((uint32_t)milk.subtype < (uint32_t)milk.maxSubtype) return milk.FollowParent(); + + if (milk.sprite.IsEventTriggered("Drop")) + { + milk.shadowSize = 0; + familiar_sound_play(SOUND_GLASS_BREAK); + familiar_sound_play(SOUND_GASCAN_POUR); + milk.player->temporaryEffects.AddCollectibleEffect(COLLECTIBLE_MILK, true, 1); + Entity* poof = g_game->Spawn({.position = milk.pos, .spawner = &milk, .type = ENTITY_EFFECT, + .variant = EFFECT_TEAR_POOF_B, .seed = Random()}); + poof->SetColor(MILK_SPLASH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + g_game->Spawn({.position = milk.pos, .type = ENTITY_EFFECT, .variant = EFFECT_PLAYER_CREEP_PUDDLE_MILK, + .seed = Random()})->Update(); + } + milk.friction *= MILK_FRICTION; + if (!milk.sprite.IsFinished()) return; + + milk.sprite.Play("Idle"); + milk.isVisible = false; + milk.pos = {}; + milk.velocity = {}; +} + +// Shade's charm: it vanishes into three or four charmed, unseen chargers around it, then waits on its leader. +static void shade_burst(Entity_Familiar& shade) +{ + if (shade.isVisible) + { + shade.isVisible = false; + for (int count = random_below(2) + SHADE_CHARGERS_MIN; count > 0; count--) + { + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = shade.pos, .step = SHADE_BURST_STEP}); + Entity* charger = g_game->Spawn({.position = spot, .spawner = &shade, .subType = 1, + .type = ENTITY_CHARGER, .seed = seed}); + charger->AddCharmed(EntityRef{}, -1, false, false); + charger->isVisible = false; + charger->Update(); + } + } + if (!shade.isVisible) + { + shade.velocity = {}; + shade.pos = (shade.parent ? shade.parent.get() : static_cast(shade.player))->pos; + } + shade.friction *= SHADE_FRICTION; +} + +// Part of 0061da10: Shade trails its leader 20 frames behind, walking (or flying with a flying player) at a pace its +// legs follow, red for Black Judas. Once it absorbed enough it bursts into chargers. +void shade_update(Entity_Familiar& shade) +{ + if (shade.subtype != 0) return shade_burst(shade); + + bool isFlying = shade.player->IsFlying(); + const std::string_view* anims = isFlying ? SHADE_FLIGHTS : SHADE_WALKS; + shade.MoveDelayed(DELAYED_FOLLOW_FRAMES); + int direction = shade.get_velocity_direction(); + if (vector_length_squared(shade.velocity) >= 1) + { + if (direction == DIRECTION_DOWN) shade.sprite.Play(anims[0]); + else if (direction == DIRECTION_UP) shade.sprite.Play(anims[1]); + else + { + shade.sprite.Play(anims[2]); + shade.sprite.isFlipX = direction == DIRECTION_LEFT; + } + } + else if (isFlying) shade.sprite.Play(anims[0]); + else shade.sprite.SetFrame(anims[0], 0); + + if (shade.sprite.IsPlaying()) + { + float pace = vector_length(shade.velocity) * SHADE_PACE_SHARE; + float speed = 1; + if (pace < SHADE_SLOW_PACE) speed = lerp_range(pace, {1, SHADE_SLOW_PACE, 0.5f, 1}); + if (pace > SHADE_FAST_PACE) speed = lerp_range(pace, {SHADE_FAST_PACE, SHADE_TOP_PACE, 1, 2}); + shade.sprite.playbackSpeed = speed; + } + bool isBlackJudas = shade.player->playerType == PLAYER_BLACKJUDAS; + const ColorMod& shown = isBlackJudas ? SHADE_BLACK_JUDAS_COLOR : COLOR_DEFAULT; + std::ranges::copy(shown._tint, shade.sprite.color._tint); + + int limit = g_game->deathmatchManager.is_active() ? SHADE_ABSORB_LIMIT_VERSUS : SHADE_ABSORB_LIMIT; + if (shade.state > limit) shade.subtype = 1; +} + +// Part of 0061da10: Hushy bounces about in its second phase while its player holds fire. While the player fires it sits +// still, ringing out eight shots every second. +void hushy_update(Entity_Familiar& hushy) +{ + bool isFiring = hushy.player->fireDirection != DIRECTION_NONE; + if (hushy.subtype == 0) + { + if (hushy.sprite.IsFinished()) hushy.sprite.Play("Phase2"); + hushy.MoveDiagonally(HUSHY_DRIFT_SPEED); + if (!isFiring) return; + + hushy.subtype = 1; + hushy.sprite.Play("RevertToPhase1"); + hushy.fireCooldown = HUSHY_SHOT_FRAMES; + return; + } + if (hushy.subtype != 1) return; + + if (hushy.sprite.IsFinished()) hushy.sprite.Play("Idle"); + if (!isFiring) + { + hushy.subtype = 0; + hushy.sprite.Play("Phase2Start"); + } + hushy.friction *= HUSHY_FRICTION; + hushy.pos = g_game->room->GetClampedPosition(hushy.pos, hushy.size); + if (hushy.fireCooldown-- > 0) return; + + hushy.fireCooldown = HUSHY_SHOT_FRAMES; + for (int i = 0; i < HUSHY_SHOT_COUNT; i++) + hushy.FireProjectile(tear_vector_rotate(vector_make(0, 1), (float)i * HUSHY_SHOT_STEP), FIRE_INHERIT_MOTION); + hushy.sprite.Play("RevertToPhase1"); +} + +// Part of 0061da10: King Baby leads its line. While its player fires it stays put (or rides Gello) and picks a far, +// healthy enemy for its line to chase, else it follows and forgets it. +void king_baby_update(Entity_Familiar& king) +{ + if (king.player->fireDirection == DIRECTION_NONE) + { + king.FollowParent(); + king.target = nullptr; + } + else + { + if (king.IsLilithBirthrightIncubus()) king.FollowParent(); + else + { + king.friction *= KING_BABY_FRICTION; + king.pos = g_game->room->GetClampedPosition(king.pos, 0); + } + king.PickEnemyTarget({.coneAngle = KING_BABY_SEARCH_CONE, + .range = KING_BABY_RANGE, + .frameInterval = KING_BABY_SEARCH_INTERVAL, + .flags = TARGET_RETARGET | TARGET_NOT_NEAR_PLAYER | TARGET_NO_STICKINESS}); + } + int direction = vector_length_squared(king.velocity) < 1 ? DIRECTION_DOWN : king.get_velocity_direction(); + king.PlayFloatAnim(direction); +} + +// Part of 0061da10: the Finger circles its player on the side the player aims (or faces), pointing outward, and pokes +// whatever lies that way with an invisible one-hit laser. +void finger_update(Entity_Familiar& finger) +{ + Entity_Player& player = *finger.player; + Vector aim = player.aimDirection; + if (vector_is_zero(aim)) aim = direction_unit(player.headDirection); + if (vector_is_zero(aim)) aim = vector_make(0, 1); + finger.orbitAngleOffset = angle_lerp(finger.orbitAngleOffset, vector_angle(aim), FINGER_TURN); + Vector spot = vector_add(player.pos, vector_scale(vector_from_angle(finger.orbitAngleOffset), FINGER_REACH)); + finger.velocity = vector_add(finger.velocity, vector_scale(vector_sub(spot, finger.pos), FINGER_PULL)); + finger.friction *= FINGER_FRICTION; + + Vector outward = vector_sub(finger.pos, player.pos); + finger.sprite.rotation = angle_wrap(vector_angle(outward) - 90); + finger.sprite.GetLayer(0)->isFlipX = finger.sprite.rotation > FINGER_FLIP_ROTATION; + + int interval = g_game->deathmatchManager.is_active() ? FINGER_POKE_FRAMES_VERSUS : FINGER_POKE_FRAMES; + if (!finger.IsFrame(interval, 0)) return; + + Entity_Laser* poke = player.FireTechLaser({.direction = vector_normalized(outward), + .position = finger.pos, + .source = &finger, + .offsetId = LASER_OFFSET_TECH5, + .isOneHit = true}); + poke->posOffset = vector_make(0, FINGER_POKE_HEIGHT); + poke->isVisible = false; + TearParams hit = player.GetTearHitParams(WEAPON_LASER, 1, 1, &finger); + poke->SetCollisionDamage(hit.tearDamage * FINGER_POKE_DAMAGE * finger.GetMultiplier()); + poke->entityGridCollisionClass = GRIDCOLL_WALLS; + poke->tearFlags.reset(); + poke->isPlayerParams = true; + poke->mass = 0; + poke->Update(); +} + +// Part of 0061da10: Farting Baby, once its hit plays out, lets out a poison fart with a push, a push alone, or a charm +// fart, by a third each. It follows, counting its cooldown down. +void farting_baby_update(Entity_Familiar& baby) +{ + if (baby.sprite.IsFinished("Hit")) + { + baby.sprite.Play("Idle"); + int fart = random_below(3); + if (fart == 0) + { + game_fart({.position = baby.pos, .source = &baby, .radius = FARTING_BABY_FART_RADIUS}); + game_butter_bean_fart({.position = baby.pos, .source = baby.player, .radius = FARTING_BABY_PUSH_RADIUS, + .isShowEffect = false}); + } + else if (fart == 1) + game_butter_bean_fart({.position = baby.pos, .source = baby.player, .radius = FARTING_BABY_PUSH_RADIUS}); + else game_charm_fart(baby.pos, FARTING_BABY_CHARM_RADIUS, &baby); + } + baby.FollowParent(); + if (baby.fireCooldown > 0) baby.fireCooldown--; +} + +// Part of 0061da10: Succubus bounces about burning the enemies in its aura every seven frames, and stacks a damage +// boost on each player inside it (only its own player in a versus match). +void succubus_update(Entity_Familiar& succubus) +{ + if (succubus.IsFrame(SUCCUBUS_BURN_INTERVAL, succubus.index)) + for (Entity* enemy : entity_query_radius(succubus.pos, SUCCUBUS_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || succubus.IsDescendantOf(enemy) || + enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) + continue; + enemy->TakeDamage(SUCCUBUS_BURN_DAMAGE, 0, EntityRef(&succubus), SUCCUBUS_BURN_COUNTDOWN); + } + + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (g_game->deathmatchManager.is_active() && !succubus.IsDescendantOf(player)) continue; + if (vector_length_squared(vector_sub(player->pos, succubus.pos)) < SUCCUBUS_BOOST_RANGE_SQUARED) + player->damageMultiplierStacks++; + } + succubus.MoveDiagonally(1); +} + +// Part of 0061da10: Bloodshot Eye orbits its player looking outward, and fires a blood tear at the enemy it sees ahead. +void bloodshot_eye_update(Entity_Familiar& eye) +{ + Vector outward = vector_sub(eye.pos, eye.player->pos); + float look = angle_wrap(vector_angle(outward) + BLOODSHOT_LOOK_TURN); + int frame = (int)((1 - (look + 180) / 360) * BLOODSHOT_FRAMES); + if (eye.fireCooldown > 0) eye.fireCooldown--; + int interval = familiar_lullaby_delay(eye, BLOODSHOT_SHOT_INTERVAL); + if (eye.fireCooldown < 1) + { + Entity* seen = nullptr; + Vector ahead = vector_from_angle(vector_angle(outward) - BLOODSHOT_LOOK_TURN); + for (Entity* enemy : entity_query_radius(eye.pos, BLOODSHOT_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + if (!room_check_line(eye.pos, enemy->pos, LINE_MODE_PROJECTILE, BLOODSHOT_LINE_THRESHOLD)) continue; + Vector toward = vector_normalized(vector_sub(enemy->pos, eye.pos)); + if (vector_dot(toward, ahead) > BLOODSHOT_CONE_DOT) seen = enemy; + } + eye.fireCooldown = seen ? interval : BLOODSHOT_RETRY_INTERVAL; + if (seen) + { + uint32_t seed = Random(); + Vector shot = vector_scale(vector_normalized(vector_sub(seen->pos, eye.pos)), BLOODSHOT_SHOT_SPEED); + auto* tear = static_cast(g_game->Spawn({.position = eye.pos, .velocity = shot, + .spawner = &eye, .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, .seed = seed})); + tear->fallingSpeed = BLOODSHOT_SHOT_FALL; + float multiplier = eye.GetMultiplier(); + float scale = eye.GetMultiplier() * BLOODSHOT_SCALE_STEP + BLOODSHOT_SCALE_BASE; + tear->SetCollisionDamage(multiplier * BLOODSHOT_SHOT_DAMAGE); + tear->SetScale(scale); + eye.TryFireTear(tear); + eye.shot_owner_convert(tear); + } + } + eye.sprite.SetFrame((float)frame); + eye.velocity = vector_sub(eye.GetOrbitPosition(eye.player->pos), eye.pos); +} + +// 0061c150 Smart Fly (the database's orbital variant 50) circles its player, and once angered (subtype 1) leaves its +// orbit to chase an enemy, giving up on one it chased ten seconds in a versus match. +void Entity_Familiar::ai_orbital_variant_50() +{ + if (subtype == 1) + PickEnemyTarget( + {.coneAngle = SMART_FLY_SEARCH_CONE, .range = SMART_FLY_RANGE, .frameInterval = SMART_FLY_SEARCH_INTERVAL}); + if (familiar_versus() && target) + { + int& frames = targetFrames[target->index]; + if (frames > SMART_FLY_CHASE_FRAMES) frames = SMART_FLY_GIVE_UP_FRAMES; + } + + if (!target) + { + if (orbitLayer == -1) + { + orbitLayer = SMART_FLY_ORBIT_LAYER; + orbitDistance = GetOrbitDistance(SMART_FLY_ORBIT_LAYER); + RecalculateOrbitOffset(SMART_FLY_ORBIT_LAYER, ORBIT_JOIN); + } + targetPosition = GetOrbitPosition(player->pos); + Vector toward = vector_sub(targetPosition, pos); + if (vector_length(toward) < SMART_FLY_SETTLE_DISTANCE) velocity = vector_scale(toward, SMART_FLY_SETTLE); + } + else + { + targetPosition = target->pos; + if (orbitLayer >= 0) + { + RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + orbitLayer = -1; + } + } + + Vector toward = vector_sub(targetPosition, pos); + float distance = vector_length(toward); + float pull = 0; + if (distance >= SMART_FLY_STILL_DISTANCE) + pull = std::min(distance * SMART_FLY_PULL, SMART_FLY_TOP_SPEED) / distance; + velocity = vector_add(velocity, vector_scale(toward, pull)); + friction *= SMART_FLY_FRICTION; +} + +// 0061a240 Blue Baby's Only Friend is pushed along its player's aim, braked across it, and pushed back in from the +// room's edges. +void Entity_Familiar::ai_blue_babys_only_friend() +{ + Vector aim = player->GetShootingJoystick(); + if (isCollidesWithGrid) velocity = vector_scale(velocity, FRIEND_WALL_DRAG); + + float along = 0; + if (aim.x == 0 && aim.y != 0) + { + along = std::abs(velocity.y); + velocity.x *= FRIEND_CROSS_DRAG; + } + else if (aim.x != 0 && aim.y == 0) + { + along = std::abs(velocity.x); + velocity.y *= FRIEND_CROSS_DRAG; + } + float brake = std::max(-vector_dot(velocity, aim) * FRIEND_BRAKE, 0.0f); + float push = (along * FRIEND_SPEED_SHARE + brake + FRIEND_PUSH_BASE) * FRIEND_PUSH_SCALE; + velocity = vector_scale(vector_add(vector_scale(aim, push), velocity), FRIEND_GLIDE); + + Vector inside = vector_sub(g_game->room->GetClampedPositionImpl(pos, 0, 0, 0, 0), pos); + if (vector_is_zero(inside)) return; + + Vector normal = vector_normalized(inside); + float back = std::clamp(-vector_dot(normal, velocity), FRIEND_EDGE_PUSH_MIN, FRIEND_EDGE_PUSH_MAX); + velocity = vector_add(velocity, vector_scale(normal, back * speedMultiplier)); +} + +// Whether Angry Fly may pick an entity: any living enemy or prop but the fireplaces, shopkeepers, moving TNT, poop, +// rail props and one cultist, or a rival player in a versus match. +static bool is_angry_fly_target(Entity& entity) +{ + if (entity.isDead) return false; + if (familiar_versus() && entity.type == ENTITY_PLAYER) return true; + + int type = entity.type; + if (type < ENTITY_FIRST_ENEMY || type >= ENTITY_EFFECT || type == ENTITY_FIREPLACE || type == ENTITY_SHOPKEEPER || + type == ENTITY_MOVABLE_TNT || type == ENTITY_POOP || type == ENTITY_GENERIC_PROP || type == ENTITY_MINECART) + return false; + return type != ENTITY_CULTIST || entity.variant != ANGRY_FLY_CULTIST_SKIPPED; +} + +// Whether Spider Baby's spider goes straight for an entity: a living, touchable, hittable enemy (Blood Puppy and Dark +// Esau even untargetable), or a rival player in a versus match. +static bool is_spider_prey(Entity& entity) +{ + bool isRival = familiar_versus() && entity.type == ENTITY_PLAYER; + if (!isRival && (entity.type < ENTITY_FIRST_ENEMY || entity.type >= ENTITY_EFFECT)) return false; + if (entity.entityCollisionClass == ENTCOLL_NONE || entity.entityCollisionClass == ENTCOLL_PLAYERONLY) return false; + if (entity.isInvincible || entity.isDead) return false; + bool isAlwaysPrey = entity.type == ENTITY_BLOOD_PUPPY || entity.type == ENTITY_DARK_ESAU; + return !entity.HasEntityFlags(FLAG_NO_TARGET) || isAlwaysPrey; +} + +// Part of 0061da10 (00630c90): Spider Mod's spiders rest, then walk a while to a random spot, Spider Baby's to the +// first enemy fit to attack (else the last one Angry Fly would pick). +void spider_update(Entity_Familiar& spider) +{ + if (spider.subtype == 0) + { + if (spider.counter-- < 1) + { + spider.subtype = 1; + spider.counter = (int)(Random() % SPIDER_MOD_WALK_RANGE) + SPIDER_MOD_PHASE_MIN; + Entity* prey = nullptr; + if (spider.variant == Entity_Familiar::SPIDER_BABY) + for (Entity* entity : g_game->room->GetEntities()->updateEL) + { + if (is_spider_prey(*entity)) + { + prey = entity; + break; + } + if (is_angry_fly_target(*entity)) prey = entity; + } + spider.targetPosition = prey ? prey->pos : g_game->room->GetRandomPosition(0); + } + } + else if (spider.subtype == 1) + { + spider.pathfinder.FindGridPath(spider.targetPosition, SPIDER_MOD_PACE, 0, DIRECT_PATH_FAR); + if (spider.counter-- < 1) + { + spider.subtype = 0; + spider.counter = (int)(Random() % SPIDER_MOD_REST_RANGE) + SPIDER_MOD_PHASE_MIN; + spider.pathfinder.Reset(); + } + } + spider.sprite.Play(vector_length_squared(spider.velocity) <= 1 ? "Idle" : "Walk"); + spider.sprite.isFlipX = spider.velocity.x < 0; + spider.friction *= SPIDER_MOD_FRICTION; + if (spider.fireCooldown > 0) spider.fireCooldown--; +} + +// 00633500 Angry Fly circles its target with the other flies on it, spaced evenly and spinning. It picks a random +// target among the room's enemies (its player when there are none) and picks again when its target dies or now and +// then while it circles its player. +void Entity_Familiar::update_angry_fly() +{ + bool isRetargeting = !target; + if (target) + { + bool isPlayerTimeUp = target == player && IsFrame(ANGRY_FLY_PLAYER_FRAMES, index); + isRetargeting = isPlayerTimeUp || + (!target->IsVulnerableEnemy(nullptr) && IsFrame(ANGRY_FLY_TARGET_FRAMES, index)); + } + if (isRetargeting) + { + std::vector candidates; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (is_angry_fly_target(*entity)) candidates.push_back(entity); + target = candidates.empty() ? static_cast(player) : candidates[Random() % candidates.size()]; + } + if (!target) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"[err] Angry Fly - Got a null target!\n"); + + int slot = 0; + int sharing = 1; + std::vector flies = familiar_query(variant); + for (int i = 0; i < (int)flies.size(); i++) + { + if (flies[i] == this) slot = i; + else if (flies[i]->target == target) sharing++; + } + float angle = (float)slot * 360 / (float)sharing; + if (std::abs(angle) > 360) angle = std::fmod(angle, 360.0f); + if (angle > 180) angle -= 360; + else if (angle < -180) angle += 360; + + float radius = ANGRY_FLY_RADIUS; + int pulse = g_game->frameCount % ANGRY_FLY_PULSE_PERIOD; + if (target->IsBoss() && pulse < ANGRY_FLY_PULSE_FRAMES) + radius = std::abs((float)pulse / ANGRY_FLY_PULSE_FRAMES - 0.5f) * 2 * ANGRY_FLY_RADIUS; + Vector around = vector_scale(vector_from_angle((float)g_game->frameCount * ANGRY_FLY_SPIN + angle), radius); + velocity = vector_scale(vector_sub(vector_add(target->pos, around), pos), ANGRY_FLY_PULL); + if (vector_length_squared(velocity) > ANGRY_FLY_TOP_SPEED * ANGRY_FLY_TOP_SPEED) + velocity = vector_resized(velocity, ANGRY_FLY_TOP_SPEED); +} + +// 0062e120 Samson's Chains' ball is dragged by its chain (along the floor only in a crawlspace), glides, keeps off the +// other balls, and is pulled to the chain's full reach behind its player, held back by a wall there. +void Entity_Familiar::ai_samsons_chains() +{ + Vector toPlayer = vector_sub(player->pos, pos); + float distanceSquared = vector_length_squared(toPlayer); + float distance = std::sqrt(distanceSquared); + if (distance > SAMSON_CHAIN_STILL_DISTANCE) + { + float pull = std::max((distance - SAMSON_CHAIN_SLACK) * SAMSON_CHAIN_SLACK_PULL, 0.0f) + + std::max((distance - SAMSON_CHAIN_LENGTH) * SAMSON_CHAIN_LENGTH_PULL, 0.0f); + Vector along = vector_scale(vector_normalized(toPlayer), pull); + if (g_game->room->roomType == ROOM_DUNGEON) along.y = 0; + velocity = vector_add(velocity, along); + } + velocity = vector_scale(velocity, SAMSON_CHAIN_GLIDE); + + for (Entity_Familiar* other : familiar_query(variant)) + { + if (other == this) continue; + + Vector apart = vector_sub(pos, other->pos); + float gap = vector_length(apart); + float push = std::max(SAMSON_CHAIN_BALL_SPACING - gap, 0.0f) * SAMSON_CHAIN_BALL_PUSH; + if (gap > 0) apart = vector_scale(apart, push / gap); + velocity = vector_add(velocity, apart); + } + + if (distanceSquared <= SAMSON_CHAIN_REACH * SAMSON_CHAIN_REACH) return; + + Vector chain = distance > 0 ? vector_scale(toPlayer, SAMSON_CHAIN_REACH / distance) : toPlayer; + Vector reach = vector_sub(player->pos, chain); + Room& room = *g_game->room; + if (room.GetGridCollision(room.GetGridIndex(reach)) == COLLISION_NONE) + { + pos = reach; + velocity = {}; + } + else if (vector_length(velocity) > 0) + velocity = vector_resized(velocity, std::min(vector_length(velocity), SAMSON_CHAIN_WALL_SPEED)); +} + +// Part of 00624e10: the chain's links hang between the ball and its player, sagging in the middle (upside down in a +// water reflection). +void samsons_chains_links_place(Entity_Familiar& ball) +{ + Vector span = vector_sub(render_position_get(ball.player->pos, RENDER_SNAPPED), + render_position_get(ball.pos, RENDER_SNAPPED)); + if (g_game->room->entityList.renderMode == RENDER_WATER_REFLECT) span.y = -span.y; + for (int link = 1; link <= SAMSON_CHAIN_LINKS; link++) + { + float share = (float)link / SAMSON_CHAIN_LINKS; + float sag = 1 - share; + LayerState* layer = ball.sprite.GetLayer(link); + float height = SAMSON_CHAIN_LINK_RISE - sag * sag * SAMSON_CHAIN_LINK_SAG + share * span.y; + layer->pos = vector_scale(vector_make(share * span.x, height), 1 / ball.sprite.scale.x); + } +} + +// Gemini's animation: raging while it has had a target lately, easing out of it, and floating otherwise. +static void gemini_animate(Entity_Familiar& gemini, int previousCooldown) +{ + bool isPlaying = gemini.sprite.animState.animData && gemini.sprite.animState.isPlaying; + bool isRaging = gemini.fireCooldown > 0; + bool wasRaging = previousCooldown > 0; + if (isRaging && !wasRaging) gemini.sprite.Play("Rage"); + else if (!isRaging && wasRaging) gemini.sprite.Play("RageEnd"); + else if (!isPlaying) gemini.sprite.Play(isRaging ? "FloatDownRage" : "FloatDown"); +} + +// Part of 0061da10 (0061d030, the database's lil_haunt): Gemini follows until an enemy comes within reach of its +// player, then charges it on its leash, dropping it once it strays out of reach. Twins keep apart. +void gemini_update(Entity_Familiar& gemini) +{ + Entity_Player& player = *gemini.player; + bool isBffs = player.HasCollectible(COLLECTIBLE_BFFS); + float leash = isBffs ? GEMINI_LEASH_BFFS : GEMINI_LEASH; + float reach = isBffs ? GEMINI_REACH_BFFS : GEMINI_REACH; + Vector own = gemini.pos; + float distance = vector_length(vector_sub(player.pos, own)); + Vector toPlayer = vector_scale(vector_sub(player.pos, own), 1 / distance); + int previousCooldown = gemini.fireCooldown; + + gemini.pos = player.pos; + gemini.PickEnemyTarget({.coneAngle = 15, .range = reach, .frameInterval = 1}); + gemini.pos = own; + if (!gemini.target) + { + if (gemini.fireCooldown > 0) gemini.fireCooldown--; + gemini.FollowParent(); + } + else + { + gemini.fireCooldown = GEMINI_RAGE_FRAMES; + if (distance <= leash) + gemini.velocity = vector_add(gemini.velocity, vector_normalized(vector_sub(gemini.target->pos, own))); + else + { + Vector leashed = vector_sub(player.pos, vector_resized(toPlayer, leash)); + gemini.velocity = vector_add(gemini.velocity, vector_scale(vector_sub(leashed, own), GEMINI_LEASH_PULL)); + float away = vector_dot(gemini.velocity, vector_scale(toPlayer, -1)) / vector_length(gemini.velocity); + if (away >= 0) + gemini.velocity = vector_add(gemini.velocity, vector_scale(toPlayer, away / vector_length(toPlayer))); + if (vector_length(vector_sub(player.pos, gemini.target->pos)) > reach) gemini.target = nullptr; + } + gemini.velocity = vector_scale(gemini.velocity, GEMINI_DRAG); + } + gemini_animate(gemini, previousCooldown); + if (gemini.target) gemini.sprite.GetLayer(0)->isFlipX = gemini.target->pos.x - gemini.pos.x < 0; + + Vector push{}; + for (Entity* twin : entity_query_radius(gemini.pos, GEMINI_TWIN_RANGE, QUERY_FAMILIARS)) + { + auto* other = twin->type == ENTITY_FAMILIAR ? static_cast(twin) : nullptr; + if (!other || other->variant != gemini.variant || other->player != gemini.player) continue; + + Vector apart = vector_sub(gemini.pos, other->pos); + if (!vector_is_zero(apart)) + push = vector_add(push, vector_scale(apart, GEMINI_TWIN_PUSH / vector_length_squared(apart))); + } + if (vector_length(push) > GEMINI_TWIN_PUSH_MAX) push = vector_resized(push, GEMINI_TWIN_PUSH_MAX); + gemini.velocity = vector_add(gemini.velocity, vector_scale(push, gemini.speedMultiplier)); +} + +// Part of 00624e10: Gemini's cord hangs from its player's body to it, rising with the player's height. +void gemini_cord_place(Entity_Familiar& gemini) +{ + Vector span = vector_sub(render_position_get(gemini.player->pos, RENDER_SNAPPED), + render_position_get(gemini.pos, RENDER_SNAPPED)); + if (g_game->room->entityList.renderMode == RENDER_WATER_REFLECT) span.y = -span.y; + float rise = -gemini.player->playerSpriteScale.y; + float peak = GEMINI_CORD_HEIGHT - rise; + for (int link = 1; link <= GEMINI_CORD_LINKS; link++) + { + float share = (float)link / GEMINI_CORD_LINKS; + float sag = 1 - share; + LayerState* layer = gemini.sprite.GetLayer(link); + layer->pos = vector_scale(vector_make(share * span.x, peak * sag * sag + rise + share * span.y), + 1 / gemini.sprite.scale.x); + } +} + +// The wander Sissy Longlegs and the Punching Bag share: a rest, then a walk of a while toward a random spot. +static void familiar_wander(Entity_Familiar& familiar) +{ + if (familiar.subtype == 0) + { + if (familiar.counter-- >= 1) return; + + familiar.subtype = 1; + familiar.counter = (int)(Random() % SISSY_WANDER_RANGE) + SPIDER_MOD_PHASE_MIN; + Room& room = *g_game->room; + float down = random_unit(); + float across = random_unit(); + Vector span = vector_sub(room.bottomRightPos, room.topLeftPos); + familiar.targetPosition = vector_add(room.topLeftPos, vector_make(across * span.x, down * span.y)); + } + else if (familiar.subtype == 1) + { + if (familiar.variant != Entity_Familiar::SISSY_LONGLEGS || !familiar.sprite.IsPlaying("Spawn")) + familiar.pathfinder.FindGridPath(familiar.targetPosition, SISSY_PACE, 0, DIRECT_PATH_FAR); + if (familiar.counter-- >= 1) return; + + familiar.subtype = 0; + familiar.counter = (int)(Random() % SPIDER_MOD_REST_RANGE) + SPIDER_MOD_PHASE_MIN; + familiar.pathfinder.Reset(); + } +} + +// Part of 0061da10 (0061c3f0, the database's variant_66): Sissy Longlegs wanders the room, resting between walks, +// and while enemies remain lays a blue spider now and then, up to its player's limit. +void sissy_longlegs_update(Entity_Familiar& sissy) +{ + bool isLaying = sissy.sprite.IsPlaying("Spawn"); + familiar_wander(sissy); + if (!isLaying) + { + if (vector_length_squared(sissy.velocity) <= 1) sissy.sprite.Play("Idle"); + else + { + sissy.sprite.Play("Walking"); + sissy.sprite.isFlipX = sissy.velocity.x < 0; + } + } + sissy.isVisible = true; + sissy.entityGridCollisionClass = GRIDCOLL_GROUND; + sissy.friction *= SISSY_FRICTION; + sissy.entityCollisionClass = ENTCOLL_ENEMIES; + + EntityList& entities = *g_game->room->GetEntities(); + if (entities.enemyCount + entities.pendingEnemyCount > 0 && --sissy.state < 0) + { + bool isBffs = sissy.GetMultiplier() > 1; + sissy.state = isBffs ? (int)(Random() % SISSY_LAY_RANGE_BFFS) + SISSY_LAY_MIN_BFFS + : (int)(Random() % SISSY_LAY_RANGE) + SISSY_LAY_MIN; + int spiders = sissy.player->numBlueSpiders; + bool isWig = sissy.player->HasCollectible(COLLECTIBLE_MOMS_WIG); + if (spiders <= SISSY_SPIDER_LIMIT || (isWig && spiders <= SISSY_SPIDER_LIMIT_WIG)) + { + sissy.sprite.Play("Spawn"); + sissy.friction *= SISSY_SPAWN_FRICTION; + } + } + if (!sissy.sprite.IsEventTriggered("Spawn")) return; + + sissy.player->numBlueSpiders++; + Entity* spider = g_game->Spawn({.position = sissy.pos, .spawner = sissy.player, .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::BLUE_SPIDER, .seed = Random()}); + spider->flags &= ~FLAG_APPEAR; + sissy.shot_owner_convert(spider); +} + +// Where the dangers around the Punching Bag gather: the enemies, fires and bombs near it, and the red poop beside it. +// None (only harmless entities near) gives nothing to shy from. +static std::optional punching_bag_danger(Entity_Familiar& bag, const EntityList_EL& nearby) +{ + Vector sum{}; + int count = 0; + for (Entity* entity : nearby) + { + bool isEnemy = entity->IsVulnerableEnemy(nullptr) && !entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET); + if (!isEnemy && entity->type != ENTITY_FIREPLACE && entity->type != ENTITY_BOMB) continue; + + sum = vector_add(sum, entity->pos); + count++; + } + Room& room = *g_game->room; + std::set cells; + for (int probe = 0; probe < PUNCHING_BAG_PROBES; probe++) + { + Vector around = vector_from_angle((float)probe * 360 / PUNCHING_BAG_PROBES); + Vector probed = vector_add(bag.pos, vector_scale(around, PUNCHING_BAG_SHY_RANGE)); + cells.insert((uint32_t)room.GetGridIndex(probed)); + } + for (uint32_t cell : cells) + { + GridEntity* grid = cell < ROOM_GRID_CELLS ? room.GetGridEntity(cell) : nullptr; + if (!grid || grid->type != GRID_POOP || grid->variant != POOP_RED) continue; + + sum = vector_add(sum, room.GetGridPosition(grid->gridIndex)); + count++; + } + // The original divides by a count of none too, steering toward nowhere, so that case is skipped. + if (count == 0) return std::nullopt; + return vector_scale(sum, 1.0f / (float)count); +} + +// Part of 0061da10 (0061c910): the Punching Bag wanders the room and shies away from the dangers near it. In the +// Guardian challenge it bursts when its player dies. +void punching_bag_update(Entity_Familiar& bag) +{ + if (bag.subtype == PUNCHING_BAG_GONE) + { + bag.isVisible = false; + bag.entityCollisionClass = ENTCOLL_NONE; + bag.entityGridCollisionClass = GRIDCOLL_NONE; + bag.velocity = {}; + bag.pos = {}; + } + if (bag.player->isDead && g_game->challenge == CHALLENGE_GUARDIAN) + { + bag.subtype = PUNCHING_BAG_GONE; + uint32_t seed = Random(); + g_game->Spawn({.position = bag.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); + familiar_sound_play(SOUND_DEATH_BURST_SMALL); + } + + EntityList_EL nearby = entity_query_radius(bag.pos, PUNCHING_BAG_SHY_RANGE, QUERY_ENEMIES); + if (!nearby.empty()) + { + if (bag.subtype == 1) + { + bag.subtype = 0; + bag.pathfinder.Reset(); + } + if (std::optional danger = punching_bag_danger(bag, nearby)) + bag.pathfinder.EvadeTarget(*danger, STATUS_OBEYED); + } + familiar_wander(bag); + + if (vector_length_squared(bag.velocity) <= 1) bag.sprite.Play("Idle"); + else bag.sprite.Play("Walk"); + bag.sprite.isFlipX = bag.velocity.x < 0; + bag.isVisible = true; + bag.entityGridCollisionClass = GRIDCOLL_GROUND; + bag.entityCollisionClass = ENTCOLL_ALL; + bag.friction *= PUNCHING_BAG_FRICTION; +} diff --git a/src/familiar_variants.cpp b/src/familiar_variants.cpp new file mode 100644 index 0000000..2c09021 --- /dev/null +++ b/src/familiar_variants.cpp @@ -0,0 +1,1670 @@ +#include "familiar_variants.h" +#include "entity_effect.h" +#include "entity_list.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity.h" +#include "grid_entity_poop.h" +#include "item_config.h" +#include "entity_tear.h" +#include "item_pool.h" +#include "kage_graphics.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "path_finder.h" +#include "boss_ai.h" +#include "entity_npc.h" +#include "room_render.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include +#include + +// Pointy Rib: how far it swings out from the player along the aim (by a sine over two seconds), how fast it turns and +// closes in, its drag, and how often it chips the grid under it. +constexpr float POINTY_RIB_NEAR = 20; +constexpr float POINTY_RIB_FAR = 120; +constexpr float POINTY_RIB_SWING_FRAMES = 30; +constexpr float POINTY_RIB_TURN = 0.4f; +constexpr float POINTY_RIB_PULL = 0.8f; +constexpr float POINTY_RIB_FRICTION = 0.7f; +constexpr int POINTY_RIB_GRID_INTERVAL = 7; + +// Hallowed Ground: its hop toward its spot, and the poop's fart. +constexpr float HALLOWED_HOP_PULL = 0.5f; +constexpr float HALLOWED_FART_RADIUS = 120; + +// My Shadow's look sizes (Idle0 to Idle4) against the player's shadow, how far they stretch, and how far behind it +// trails. The last look takes whatever outgrows the others. +constexpr float MY_SHADOW_SIZES[] = {8, 16, 32, 64, 120}; +constexpr float MY_SHADOW_SIZE_SPAN = 1.5f; +constexpr float MY_SHADOW_PERCENT = 100; +constexpr float MY_SHADOW_DEPTH = -10; +constexpr int MY_SHADOW_DELAY = 5; + +// Spin to Win: its charge while spinning, and the whir's volume and pitch by charge. +constexpr int SPIN_WHIR_CHARGE_MAX = 5; +constexpr float SPIN_WHIR_VOLUME_STEP = 0.2f; +constexpr float SPIN_WHIR_PITCH_STEP = 0.06f; +constexpr float SPIN_WHIR_PITCH_RAISE = 0.3f; +constexpr float SPIN_WHIR_PITCH_BASE = 0.7f; + +// Bone Spur: its eight looks and its generator's shifts, and how it slows to a stop over its first frames. +constexpr uint32_t BONE_SPUR_LOOKS = 8; +constexpr uint32_t BONE_SPUR_RNG_SHIFT = 13; +constexpr float BONE_SPUR_SLOW_FRAMES = 15; +constexpr float BONE_SPUR_SLOW_FRICTION = 0.8f; + +// Twisted Pair: how far beside the player each twin keeps, how fast it closes in (faster with Friendship Necklace, +// which spins them around the player), and how long a room runs before they pick their sides. +constexpr float TWISTED_SPACING = 26; +constexpr float TWISTED_PULL = 0.4f; +constexpr float TWISTED_NECKLACE_PULL = 0.8f; +constexpr float TWISTED_NECKLACE_SPEED = 3.5f; +constexpr int TWISTED_SIDE_ROOM_FRAMES = 30; +constexpr float TWISTED_FRICTION = 0.8f; +constexpr float RIGHT_TURN = -90; + +// The Lost Soul: how far behind the player it floats, its pull and speed limit, its drag, its reward's odds, how far +// apart rewards land, its death cry's pitch, and its mantle's flash (subtype, depth) and grace. +constexpr float LOST_SOUL_TRAIL = 48; +constexpr float LOST_SOUL_NEAR_SQUARED = 2304; +constexpr float LOST_SOUL_PLAYER_PULL = 0.4f; +constexpr float LOST_SOUL_PULL = 0.04f; +constexpr float LOST_SOUL_SPEED = 5; +constexpr float LOST_SOUL_FRICTION = 0.8f; +constexpr float LOST_SOUL_ANGEL_ODDS = 0.25f; +constexpr float LOST_SOUL_TREASURE_ODDS = 0.5f; +constexpr float LOST_SOUL_SOUL_ODDS = 0.75f; +constexpr int LOST_SOUL_SOUL_HEARTS = 3; +constexpr int LOST_SOUL_ETERNAL_HEARTS = 2; +constexpr float LOST_SOUL_REWARD_STEP = 40; +constexpr float LOST_SOUL_DEATH_PITCH = 1.5f; +constexpr int LOST_SOUL_MANTLE_FLASH = 11; +constexpr float LOST_SOUL_FLASH_DEPTH = 16; +constexpr int LOST_SOUL_MANTLE_FRAMES = 30; + +// The Lost Soul's states. +enum LostSoulState +{ + SOUL_START, + SOUL_FOLLOW, + SOUL_REWARD, + SOUL_SPAWNING, + SOUL_DEAD +}; + +// The Paschal Candle's looks by flame (Idle0 to Idle6), its brightest flame, the hits that do not snuff it, and its +// snuffed puff. +constexpr std::string_view PASCHAL_LOOKS[] = {"Idle0", "Idle1", "Idle2", "Idle3", "Idle4", "Idle5", "Idle6"}; +constexpr int PASCHAL_FLAME_MAX = 6; +constexpr uint64_t PASCHAL_HARMLESS_HITS = DAMAGE_RED_HEARTS | DAMAGE_FAKE | DAMAGE_NO_PENALTIES; +constexpr float PASCHAL_PUFF_SCALE = 0.65f; +constexpr float PASCHAL_PUFF_HEIGHT = -10; + +// Blood Oath's looks by stabs (of 23), its states, its stab's hit and the blood it spills. +constexpr std::string_view BLOOD_OATH_LOOKS[] = {"Idle", "Idle2", "Idle3", "Idle4"}; +constexpr int BLOOD_OATH_SPLAT_ODDS[] = {0, 0, 10, 4}; +constexpr float BLOOD_OATH_STAB_SCALE = 23; +constexpr float BLOOD_OATH_SPLAT_MIN = 0.2f; +constexpr float BLOOD_OATH_SPLAT_RANGE = 0.5f; +constexpr uint64_t BLOOD_OATH_STAB_FLAGS = + DAMAGE_NOKILL | DAMAGE_RED_HEARTS | DAMAGE_ISAAC_HURT | DAMAGE_INVINCIBLE | DAMAGE_FAKE | DAMAGE_NO_MODIFIERS; +constexpr int BLOOD_OATH_STAB_COUNTDOWN = 30; +constexpr int BLOOD_OATH_BFFS_BONUS = 4; +constexpr float BLOOD_OATH_SPRAY_SPREAD = 20; + +// Blood Oath's states. +enum BloodOathState +{ + BLOOD_OATH_START, + BLOOD_OATH_IDLE = 3, + BLOOD_OATH_STAB, + BLOOD_OATH_BACK +}; + +// The chargers' recharge after a dash. The knife pieces' and full knife's turn once drifting, and the full knife's +// dash: its speed, how squarely a wall must face it to stop it, its states stuck in a wall and fading through the +// strange door, its fade, and that door's variant and exit kind. +constexpr int CHARGE_RECOVERY = 30; +constexpr float KNIFE_FLIP_SPEED = 0.1f; +constexpr float KNIFE_SPEED = 17; +constexpr float KNIFE_WALL_FACING = 0.45f; +constexpr int KNIFE_STUCK = -2; +constexpr int KNIFE_FADING = -3; +constexpr float KNIFE_FADE_STEP = 0.1f; +constexpr int KNIFE_DOOR_VARIANT = 3; +constexpr int KNIFE_SECRET_EXIT = 4; + +// Jaw Bone: the pickups it fetches, how long a sticky nickel it shook stays put, how fast it must move to turn, its +// state coming back, how near its player it drops its catch, its speed back and how far outside the room it may fly. +constexpr int JAW_BONE_FETCHED[] = {PICKUP_HEART, PICKUP_COIN, PICKUP_LIL_BATTERY, PICKUP_BOMB, + PICKUP_KEY, PICKUP_PILL, PICKUP_TAROTCARD, PICKUP_TRINKET, + PICKUP_GRAB_BAG, PICKUP_THROWABLEBOMB, PICKUP_POOP}; +constexpr int JAW_BONE_NICKEL_COOLDOWN = 10; +constexpr float JAW_BONE_MOVING_SQUARED = 4; +constexpr int JAW_BONE_RETURNING = -2; +constexpr float JAW_BONE_CATCH_SQUARED = 1600; +constexpr float JAW_BONE_RETURN_SPEED = 10; +constexpr float JAW_BONE_ROOM_MARGIN = -100; + +// The Mystery Egg: the clears that grow its pool, the enemy pools by clears (the last for more), its hatchling's +// toughness, its plop's spread over frames, and its splash's look. +constexpr std::array MYSTERY_EGG_CLEARS = {1, 4, 7, 10, 13}; +constexpr int MYSTERY_EGG_POOL_0[] = {13, 18, 217, 85, 21, 231, 77}; +constexpr int MYSTERY_EGG_POOL_1[] = {80, 14, 214, 249, 61, 256, 94, 29, 11, 12, 281, 244, 92, 40}; +constexpr int MYSTERY_EGG_POOL_2[] = {220, 246, 228, 215, 206, 240, 255, 289, 16, 22, 205, 288, + 54, 10, 284, 226, 26, 248, 229, 208, 211, 15, 23, 32, + 89, 27, 53, 38, 24, 279, 280, 58, 243, 305, 234}; +constexpr int MYSTERY_EGG_POOL_3[] = {238, 251, 253, 25, 278, 227, 221, 252, 57, 59, 55, 56, 259, 258, 257, 254, + 41, 216, 210, 224, 219, 86, 90, 300, 283, 286, 35, 34, 304, 303, 301, 242}; +constexpr int MYSTERY_EGG_POOL_4[] = {87, 88, 230, 204, 60, 276, 213, 225, 282, 209, 277, 91}; +constexpr int MYSTERY_EGG_POOL_5[] = {285, 237, 223, 306, 241, 39}; +constexpr std::array, 6> MYSTERY_EGG_POOLS = {MYSTERY_EGG_POOL_0, MYSTERY_EGG_POOL_1, + MYSTERY_EGG_POOL_2, MYSTERY_EGG_POOL_3, + MYSTERY_EGG_POOL_4, MYSTERY_EGG_POOL_5}; +constexpr float MYSTERY_EGG_TOUGHNESS = 1.5f; +constexpr uint32_t MYSTERY_EGG_SOUND_SPREAD = 11; +constexpr ColorMod MYSTERY_EGG_SPLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.8f, 0.8f, 0.8f}}; +constexpr float MYSTERY_EGG_SPLASH_HEIGHT = -14; + +// Esau Jr.'s familiar: its generator's shifts and how far its centre strays. +constexpr uint32_t ESAU_JR_RNG_SHIFT = 19; +constexpr float ESAU_JR_CENTER_SPREAD = 30; + +// Stitches: its states, its swap's effect on the player, its bursts (the player's damage and the threshold for +// players), BFFS!'s tears, Book of Belial's trail and cut, how long the player is spared, and its drift's drag, push +// and bounce. +enum StitchesState +{ + STITCHES_START, + STITCHES_SWAP, + STITCHES_LANDING, + STITCHES_IDLE +}; +constexpr int STITCHES_EFFECT_FRAMES = 12; +constexpr float STITCHES_BURST_RADIUS = 30; +constexpr float STITCHES_BURST_RADIUS_BFFS = 45; +constexpr float STITCHES_PLAYER_BURST_SCALE = 3; +constexpr float STITCHES_PLAYER_BURST_BASE = 40; +constexpr float STITCHES_PLAYER_THRESHOLD = 50; +constexpr float STITCHES_BFFS_BONUS = 3; +constexpr int STITCHES_BFFS_TEARS = 8; +constexpr float STITCHES_TEAR_SPEED = 10; +constexpr ColorMod STITCHES_TRAIL_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float STITCHES_TRAIL_START = 0.08f; +constexpr float STITCHES_TRAIL_END = 0.04f; +constexpr float STITCHES_CUT_REACH = 25; +constexpr int STITCHES_CUT_COUNTDOWN = 30; +constexpr float STITCHES_CUT_PITCH = 1.5f; +constexpr float STITCHES_CUT_PITCH_RANGE = 0.2f; +constexpr int STITCHES_SHAKE = 6; +constexpr int STITCHES_SPARED_FRAMES = 30; +constexpr float STITCHES_WALL_DRAG = 0.88f; +constexpr float STITCHES_BRAKE = 0.2f; +constexpr float STITCHES_CARRY = 0.03f; +constexpr float STITCHES_PUSH = 3; +constexpr float STITCHES_PUSH_SCALE = 0.8f; +constexpr float STITCHES_DRAG = 0.775f; +constexpr float STITCHES_BOUNCE_MIN = 1; +constexpr float STITCHES_BOUNCE_MAX = 10; + +// Pointy Rib's cut: the fireplaces, barrels and poop it also cuts, how much the player's swing adds, and its hit +// countdown. +constexpr int RIB_FIREPLACE_TYPES[] = {ENTITY_FIREPLACE, ENTITY_MOVABLE_TNT, ENTITY_POOP}; +constexpr float RIB_SWING_SCALE = 0.1f; +constexpr int RIB_HIT_COUNTDOWN = 30; + +// My Shadow's Chargers: how many may be out, how far away they rise (four tries at a free spot), how long they chase +// their enemy, and their black fading in. +constexpr size_t MY_SHADOW_CHARGER_LIMIT = 15; +constexpr float MY_SHADOW_REACH = 40; +constexpr int MY_SHADOW_TRIES = 4; +constexpr int MY_SHADOW_FORCE_FRAMES = 90; +constexpr int MY_SHADOW_FADE_FRAMES = 6; +constexpr ColorMod MY_SHADOW_BLACK = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Cube Baby: its spin's eight frames and speed, its fall after a throw and the heights its grid collision changes at, +// its glide (frames, speed and what each wall bounce costs), its resting drag, its frost trail and its pale dust. +constexpr float CUBE_SPIN_FRAMES = 8; +constexpr float CUBE_SPIN_SPEED = 120; +constexpr float CUBE_SPIN_MAX = 0.125f; +constexpr float CUBE_FALL = 0.7f; +constexpr float CUBE_HIGH = -26; +constexpr float CUBE_LOW = -3; +constexpr int CUBE_GLIDE_FRAMES = 30; +constexpr float CUBE_GLIDE_SPEED = 10; +constexpr int CUBE_WALL_COST = 6; +constexpr float CUBE_SLIDE_SPAN = 6; +constexpr float CUBE_FRICTION_MIN = 0.94f; +constexpr float CUBE_FRICTION_RANGE = 0.060000002f; +constexpr float CUBE_FROST_MIN = 0.2f; +constexpr float CUBE_FROST_RANGE = 0.5f; +constexpr float CUBE_DUST_DRIFT = 0.14f; +constexpr float CUBE_DUST_SPIN_MIN = 2; +constexpr float CUBE_DUST_SPIN_RANGE = 10; +constexpr uint32_t CUBE_DUST_LIFE = 15; +constexpr ColorMod CUBE_DUST_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0.8f, 0.9f, 1}}; + +// Blood Puppy: its stages, the blood each needs, how long a versus chase lasts, its search, how near its player it +// heels, its speed and drag, its trot's threshold, its bleeding, and how far its body drops on a new floor. +enum PuppyStage +{ + PUPPY_PUP, + PUPPY_SMALL, + PUPPY_BIG +}; +constexpr int PUPPY_SMALL_BLOOD = 15; +constexpr int PUPPY_BIG_BLOOD = 40; +constexpr int PUPPY_VERSUS_CHASE_FRAMES = 599; +constexpr TargetSearch PUPPY_SEARCH = {.range = 120, .frameInterval = 6}; +constexpr float PUPPY_HEEL_SQUARED = 6400; +constexpr float PUPPY_SPEED = 1.328f; +constexpr float PUPPY_DRAG = 0.9f; +constexpr float PUPPY_TROT_SPEED = 2; +constexpr float PUPPY_SPLAT_MIN = 0.1f; +constexpr float PUPPY_SPLAT_RANGE = 0.3f; +constexpr float PUPPY_FLOOR_DROP = 80; + +// Fruity Plum: its states, its circle round the player, its searches, its dive (the diagonals, the lead on the +// target, the push, Forgotten Lullaby's, the drags), its tear spray, its bounce off walls and how long a dive lasts. +enum PlumState +{ + PLUM_START, + PLUM_CIRCLING = 3, + PLUM_DIVE_START, + PLUM_DIVING, + PLUM_DIVE_END +}; +constexpr float PLUM_CIRCLE = 40; +constexpr float PLUM_CIRCLE_PULL = 0.6f; +constexpr float PLUM_CIRCLE_DRAG = 0.8f; +constexpr TargetSearch PLUM_SEARCH = { + .range = 480, .frameInterval = 8, .flags = TARGET_RETARGET | TARGET_PREFER_HEALTHY}; +constexpr TargetSearch PLUM_RESEARCH = {.range = 480, .flags = TARGET_RETARGET | TARGET_PREFER_HEALTHY}; +constexpr int PLUM_DIAGONALS = 4; +constexpr float PLUM_DIAGONAL_TURN = 45; +constexpr float PLUM_LEAD = 0.1f; +constexpr float PLUM_BEST_START = -1e6f; +constexpr float PLUM_PUSH = 0.3f; +constexpr float PLUM_PUSH_FAST = 0.6f; +constexpr float PLUM_DIVE_DRAG = 0.9f; +constexpr float PLUM_DIVING_DRAG = 0.98f; +constexpr float PLUM_SPRAY_SPEED = 5; +constexpr float PLUM_SPRAY_MIN = 0.9f; +constexpr float PLUM_SPRAY_RANGE = 0.2f; +constexpr float PLUM_SPRAY_SPREAD = 60; +constexpr float PLUM_SPRAY_BACK = 8; +constexpr float PLUM_BOUNCE = 0.2f; +constexpr float PLUM_PAST = -10; +constexpr int PLUM_DIVE_MIN = 20; +constexpr int PLUM_DIVE_MAX = 60; + +// A blood splat under a familiar. +static void familiar_splat(Entity_Familiar& familiar, float size) +{ + Entity* splat = g_game->Spawn({.position = familiar.pos, + .spawner = &familiar, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_SPLAT, + .seed = Random()}); + splat->sprite.scale = vector_make(size, size); + splat->Update(); +} + +// Part of 0061da10 (Pointy Rib): it swings in and out along the player's aim (the head's way, else down), turned to +// face away from the player, chipping the grid under it every seventh frame. +void pointy_rib_update(Entity_Familiar& rib) +{ + Entity_Player& player = *rib.player; + Vector aim = player.aimDirection; + if (vector_is_zero(aim)) aim = direction_unit(player.headDirection); + if (vector_is_zero(aim)) aim = vector_make(0, 1); + + float swing = std::sin((float)g_game->frameCount / POINTY_RIB_SWING_FRAMES * PI_F); + float reach = lerp_range(swing, {.inMin = -1, .inMax = 1, .outMin = POINTY_RIB_NEAR, .outMax = POINTY_RIB_FAR}); + rib.orbitAngleOffset = angle_lerp(rib.orbitAngleOffset, vector_angle(aim), POINTY_RIB_TURN); + Vector spot = vector_add(player.pos, vector_scale(vector_from_angle(rib.orbitAngleOffset), reach)); + rib.velocity = vector_scale(vector_sub(spot, rib.pos), POINTY_RIB_PULL); + rib.friction *= POINTY_RIB_FRICTION; + + LayerState* layer = rib.sprite.GetLayer(0); + layer->rotation = normalize_angle_degrees(vector_angle(vector_sub(rib.pos, player.pos)) - RIGHT_ANGLE_DEGREES); + layer->isFlipX = rib.sprite.rotation > 1; + + if (!rib.IsFrame(POINTY_RIB_GRID_INTERVAL, 0)) return; + Room& room = *g_game->room; + int index = room.GetGridIndex(rib.pos); + if (index < 0) return; + if (GridEntity* grid = room.GetGridEntity((uint32_t)index)) grid->Hurt(1, EntityRef{}); +} + +// Part of 0061da10 (Hallowed Ground): it follows, and once its player was hurt it hops to its spot, leaves a white +// poop there (unless a grid entity other than a decoration or web is in the way, or in a crawlspace) with a fart, and +// hides once its hop plays out. +void hallowed_ground_update(Entity_Familiar& ground) +{ + if (!ground.isVisible) + { + ground.velocity = {}; + return; + } + if (vector_is_zero(ground.targetPosition)) return ground.FollowParent(); + + ground.velocity = vector_scale(vector_sub(ground.targetPosition, ground.pos), HALLOWED_HOP_PULL); + if (ground.sprite.IsEventTriggered("Spawn")) + { + Room& room = *g_game->room; + int index = room.GetGridIndex(ground.pos); + GridEntity* grid = room.GetGridEntity((uint32_t)index); + bool isFree = !grid || grid->type == GRID_DECORATION || grid->type == GRID_SPIDERWEB; + if (isFree && room.roomType != ROOM_DUNGEON) + { + room.SpawnGridEntity(index, GRID_POOP, POOP_WHITE, ground.dropRNG.Next(), 0); + game_butter_bean_fart({.position = ground.pos, + .source = ground.player, + .radius = HALLOWED_FART_RADIUS, + .isShowEffect = false}); + } + familiar_sound_play(SOUND_FART); + } + if (ground.sprite.IsFinished()) ground.isVisible = false; +} + +// Part of 0062b750: Hallowed Ground's player was hurt. Unless it is already hopping, it hops to the tile under it (or +// the nearest free spot when a grid entity other than a decoration or web is there, or in a crawlspace). +void hallowed_ground_player_hurt(Entity_Familiar& ground) +{ + if (ground.state != 0) return; + + ground.sprite.Play("Spawn"); + Room& room = *g_game->room; + int column = (int)((ground.pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((ground.pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + bool isOnGrid = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int index = isOnGrid ? row * room.gridWidth + column : -1; + GridEntity* grid = isOnGrid && index < ROOM_GRID_CELLS ? room.GetGridEntity((uint32_t)index) : nullptr; + bool isBlocked = grid && grid->type != GRID_DECORATION && grid->type != GRID_SPIDERWEB; + if (isBlocked || room.roomType == ROOM_DUNGEON) + ground.targetPosition = room_free_pickup_position_find({.position = ground.pos, .isAvoidActiveEntities = true}); + else + ground.targetPosition = vector_make((float)(index % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(index / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); + ground.state = 1; +} + +// Part of 0060de70 (My Shadow): drawn under the player and sized to its shadow. +void my_shadow_init(Entity_Familiar& shadow) +{ + shadow.renderDepthOffset = MY_SHADOW_DEPTH; + shadow.orbitSpeed = 0; + shadow.update_idle_anim_by_size(); +} + +// 0063b340 My Shadow's look and size follow its player's shadow: the smallest look it fits, stretched to it. The last +// size seen is kept in orbitSpeed. +void Entity_Familiar::update_idle_anim_by_size() +{ + float wanted = player->shadowSize * player->sprite.scale.x * MY_SHADOW_PERCENT; + if (orbitSpeed == wanted) return; + + int look = 0; + while (look < (int)std::size(MY_SHADOW_SIZES) - 1 && wanted >= MY_SHADOW_SIZES[look] * MY_SHADOW_SIZE_SPAN) look++; + char name[32]; + std::snprintf(name, sizeof(name), "Idle%d", look); + sprite.Play(name); + + float base = MY_SHADOW_SIZES[look]; + sprite.scale = vector_make(wanted / base, wanted / base); + orbitSpeed = wanted; + size = wanted; +} + +// Part of 0061da10 (My Shadow): it sizes itself and trails five frames behind. +void my_shadow_update(Entity_Familiar& shadow) +{ + shadow.update_idle_anim_by_size(); + shadow.MoveDelayed(MY_SHADOW_DELAY); +} + +// Part of 0061da10 (Spin to Win): it orbits, spinning while the player spins (charging the whir up) and idling +// otherwise (winding it down). +void spin_to_win_update(Entity_Familiar& spinner) +{ + spinner.velocity = vector_sub(spinner.GetOrbitPosition(spinner.player->pos), spinner.pos); + if (spinner.HasEntityFlags(FLAG_SPIN)) + { + spinner.sprite.Play("Spin"); + spinner.chargeLevel = std::min(spinner.chargeLevel + 1, SPIN_WHIR_CHARGE_MAX); + } + else + { + spinner.sprite.Play("Idle"); + spinner.chargeLevel = std::max(spinner.chargeLevel - 1, 0); + } + + float volume = std::min((float)spinner.chargeLevel * SPIN_WHIR_VOLUME_STEP, 1.0f); + float pitch = + std::min((float)spinner.chargeLevel * SPIN_WHIR_PITCH_STEP, SPIN_WHIR_PITCH_RAISE) + SPIN_WHIR_PITCH_BASE; + SFXManager& sfx = g_manager->sfxManager; + if (!sfx.IsPlaying(SOUND_SPIN_TO_WIN)) + { + if (spinner.chargeLevel > 0) + familiar_sound_play(SOUND_SPIN_TO_WIN, + {.volume = volume, .frameDelay = 0, .loop = SOUND_LOOP, .pitch = pitch}); + } + else if (spinner.chargeLevel < 1) sfx.Stop(SOUND_SPIN_TO_WIN); + else + { + sfx.AdjustVolume(SOUND_SPIN_TO_WIN, volume); + sfx.AdjustPitch(SOUND_SPIN_TO_WIN, pitch); + } +} + +// Part of 0060de70 (Bone Spur): one of eight looks, maybe flipped, hurting as the player's melee, and never in the +// following line. +void bone_spur_init(Entity_Familiar& spur) +{ + RNG rng; + rng.SetSeed(spur.dropRNG._seed, BONE_SPUR_RNG_SHIFT); + uint32_t look = rng.RandomInt(BONE_SPUR_LOOKS); + spur.subtype = (int)look + 1; + char name[32]; + std::snprintf(name, sizeof(name), "Idle%u", look); + spur.sprite.Play(name); + spur.sprite.isFlipX = rng.RandomInt(2) == 0; + spur.collisionDamage = spur.player->meleeDamage; + spur.isNotCountedAsFollower = true; +} + +// Part of 0061da10 (Bone Spur): it slides to a stop over its first frames. +void bone_spur_update(Entity_Familiar& spur) +{ + if (!spur.sprite.animState.IsLoopingAnimation()) return; + spur.friction *= + lerp_range(spur.updateTime, {.inMax = BONE_SPUR_SLOW_FRAMES, .outMin = 1, .outMax = BONE_SPUR_SLOW_FRICTION}); +} + +// Part of 0061da10 (Twisted Pair): each twin fires with its own weapon and keeps to one side of the player across the +// aim (the last aim while firing lingers, else down). Past a room's first second they take the sides nearest where +// they are heading. With Friendship Necklace they spin around the player instead. A twin riding another familiar keeps +// beside that one's parent. +void twisted_baby_update(Entity_Familiar& baby) +{ + Entity_Player& player = *baby.player; + baby.update_weapon(false); + + Vector aim = player.aimDirection; + bool isLingering = baby.headFrameDelay > 0 || baby.counter > 0; + if (isLingering && vector_is_zero(aim) && !vector_is_zero(baby.targetPosition)) aim = baby.targetPosition; + if (vector_is_zero(aim)) aim = vector_make(0, 1); + baby.targetPosition = aim; + + float pull = TWISTED_PULL; + bool isNecklace = player.HasTrinket(TRINKET_FRIENDSHIP_NECKLACE); + if (isNecklace) + { + baby.orbitDistance = vector_make(TWISTED_SPACING, TWISTED_SPACING); + baby.orbitSpeed = TWISTED_NECKLACE_SPEED; + aim = vector_from_angle((float)g_game->frameCount * baby.orbitSpeed - baby.orbitAngleOffset); + pull = TWISTED_NECKLACE_PULL; + } + Vector side = vector_scale(vector_rotated(aim, RIGHT_TURN), TWISTED_SPACING); + + if (!isNecklace && g_game->room->GetFrameCount() > TWISTED_SIDE_ROOM_FRAMES) + { + Entity* root = &baby; + while (root->parent.get() && root->parent.get()->type == ENTITY_FAMILIAR) root = root->parent.get(); + Vector heading = vector_add(root->prevPosition, vector_scale(root->velocity, (1 - pull) / pull)); + float rightDistance = vector_length_squared(vector_sub(heading, vector_add(player.pos, side))); + float leftDistance = vector_length_squared(vector_sub(heading, vector_sub(player.pos, side))); + if (leftDistance < rightDistance) side = vector_scale(side, -1); + } + + Entity* anchor = &player; + Entity* parent = baby.parent.get(); + if (parent && parent->type == ENTITY_FAMILIAR && parent->parent.get()) anchor = parent->parent.get(); + if (baby.subtype == 1) side = vector_scale(side, -1); + + baby.velocity = vector_scale(vector_sub(vector_add(anchor->pos, side), baby.pos), pull); + baby.friction *= TWISTED_FRICTION; +} + +// A Lost Soul's reward pickup, dropDelay counting its place in the batch. +static void lost_soul_pickup_spawn(Entity_Familiar& soul, RNG& rng, int subType, int order) +{ + Vector spot = room_free_pickup_position_find({.position = soul.pos, .step = LOST_SOUL_REWARD_STEP}); + Entity* pickup = g_game->Spawn( + {.position = spot, .subType = subType, .type = ENTITY_PICKUP, .variant = PICKUP_HEART, .seed = rng.Next()}); + static_cast(pickup)->dropDelay = order; +} + +// A Lost Soul's reward item from a pool. +static void lost_soul_item_spawn(Entity_Familiar& soul, RNG& rng, ItemPoolType pool) +{ + Vector spot = room_free_pickup_position_find({.position = soul.pos, .step = LOST_SOUL_REWARD_STEP}); + int item = g_game->itemPool.GetCollectible(pool, rng.Next(), 0, 0, 0); + g_game->Spawn( + {.position = spot, .subType = item, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, .seed = rng.Next()}); +} + +// 00645bc0 FamiliarAI::lost_soul: the Lost Soul floats behind the player where it aims. Brought to a boss room's end +// it rewards its player by the collectible's generator: an angel item, a treasure item, three soul hearts or two +// eternal hearts. Dead, it cries once and fades. Only while following can enemies touch it. +void lost_soul_update(Entity_Familiar& soul) +{ + if (soul.isDead) return; + + switch (soul.state) + { + case SOUL_START: + soul.sprite.Play("FloatDown"); + soul.state = SOUL_FOLLOW; + break; + case SOUL_FOLLOW: + { + soul.sprite.Play("FloatDown"); + Entity_Player& player = *soul.player; + Vector spot = vector_sub(player.pos, vector_scale(player.aimDirection, LOST_SOUL_TRAIL)); + Vector toward = vector_sub(spot, soul.pos); + Vector push = vector_scale(player.velocity, LOST_SOUL_PLAYER_PULL); + if (vector_length_squared(toward) > LOST_SOUL_NEAR_SQUARED) + { + push = vector_scale(toward, LOST_SOUL_PULL); + if (vector_length(push) > LOST_SOUL_SPEED) push = vector_resized(push, LOST_SOUL_SPEED); + } + soul.velocity = vector_add(soul.velocity, vector_scale(push, soul.speedMultiplier)); + soul.friction *= LOST_SOUL_FRICTION; + break; + } + case SOUL_REWARD: + { + soul.sprite.Play("PreSpawn"); + if (!soul.sprite.IsPlaying()) + { + soul.sprite.Play("Spawn"); + soul.state = SOUL_SPAWNING; + familiar_sound_play(SOUND_THUMBSUP); + RNG& rng = soul.player->GetCollectibleRNG(COLLECTIBLE_LOST_SOUL); + float roll = rng.RandomFloat(); + if (roll < LOST_SOUL_ANGEL_ODDS) lost_soul_item_spawn(soul, rng, POOL_ANGEL); + else if (roll < LOST_SOUL_TREASURE_ODDS) lost_soul_item_spawn(soul, rng, POOL_TREASURE); + else if (roll < LOST_SOUL_SOUL_ODDS) + for (int i = 0; i < LOST_SOUL_SOUL_HEARTS; i++) lost_soul_pickup_spawn(soul, rng, HEART_SOUL, i); + else + for (int i = 0; i < LOST_SOUL_ETERNAL_HEARTS; i++) + lost_soul_pickup_spawn(soul, rng, HEART_ETERNAL, i); + } + soul.friction *= LOST_SOUL_FRICTION; + break; + } + case SOUL_SPAWNING: + if (!soul.sprite.IsPlaying()) + { + soul.sprite.Play("FloatDown"); + soul.state = SOUL_FOLLOW; + } + soul.friction *= LOST_SOUL_FRICTION; + break; + case SOUL_DEAD: + soul.sprite.Play("Death"); + if (soul.sprite.IsEventTriggered("Sound") && soul.isVisible) + familiar_sound_play(SOUND_ISAACDIES, {.pitch = LOST_SOUL_DEATH_PITCH}); + if (!soul.sprite.IsPlaying()) soul.isVisible = false; + soul.velocity = {}; + break; + } + + soul.entityGridCollisionClass = GRIDCOLL_WALLS; + soul.entityCollisionClass = soul.state == SOUL_FOLLOW ? ENTCOLL_ALL : ENTCOLL_NONE; + soul.sprite.isFlipX = soul.velocity.x > 0; +} + +// Part of 0062b360 (Lost Soul): a new floor (not a continued run) brings a dead soul back to follow and sends a living +// one to its reward, just below the player. Whether the floor start is done with it. +bool lost_soul_level_start(Entity_Familiar& soul) +{ + if (g_game->isStartingFromState) return false; + + if (soul.state == SOUL_DEAD) + { + soul.isVisible = true; + soul.state = SOUL_FOLLOW; + } + else soul.state = SOUL_REWARD; + soul.pos = vector_add(soul.player->pos, vector_make(0, LOST_SOUL_TRAIL)); + return true; +} + +// Part of 0062bb70 (Lost Soul): a new room puts it on the player, wearing the mantle with BFFS!. +void lost_soul_room_enter(Entity_Familiar& soul) +{ + soul.pos = soul.player->pos; + soul.velocity = {}; + if (!soul.player->HasCollectible(COLLECTIBLE_BFFS)) return; + + soul.coins = 1; + soul.sprite.PlayOverlay("Mantle"); +} + +// 006402f0 The Paschal Candle's flames as its player's effects: one Paschal Candle effect for each flame past the +// first, then the stats. +void Entity_Familiar::paschal_candle_sync_effects() +{ + ItemConfig_Item* candle = g_manager->itemConfig.GetCollectible(COLLECTIBLE_PASCHAL_CANDLE); + if (candle) player->temporaryEffects.RemoveEffect(candle, -1); + + TemporaryEffect flame; + flame.item = candle; + for (int i = 1; i < hearts; i++) player->temporaryEffects.AddEffect(flame, true, 1); + player->EvaluateItems(); +} + +// 006401d0 The Paschal Candle follows, lit to its flame (one on its first frame). +void paschal_candle_update(Entity_Familiar& candle) +{ + if (candle.hearts == 0) + { + candle.hearts = 2; + candle.paschal_candle_sync_effects(); + } + candle.sprite.Play(PASCHAL_LOOKS[std::clamp(candle.hearts - 1, 0, PASCHAL_FLAME_MAX)]); + candle.FollowParent(); +} + +// Part of 0062aab0: a cleared room lights the Paschal Candle a flame brighter, up to six. +void paschal_candle_room_clear(Entity_Familiar& candle) +{ + if (candle.hearts >= PASCHAL_FLAME_MAX) return; + + candle.hearts++; + familiar_sound_play(SOUND_CANDLE_LIGHT); + candle.paschal_candle_sync_effects(); +} + +// Part of 0062b750: a real hit snuffs the Paschal Candle down to one flame with a puff of smoke. +void paschal_candle_player_hurt(Entity_Familiar& candle, uint64_t damageFlags) +{ + if (candle.hearts <= 1 || (damageFlags & PASCHAL_HARMLESS_HITS)) return; + + candle.hearts = 1; + familiar_sound_play(SOUND_STEAM_HALFSEC); + Entity* puff = + g_game->Spawn({.position = candle.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + puff->posOffset = vector_make(0, PASCHAL_PUFF_HEIGHT); + puff->sprite.scale = vector_make(PASCHAL_PUFF_SCALE, PASCHAL_PUFF_SCALE); + candle.paschal_candle_sync_effects(); +} + +// 00640050 Blood Oath's stabs as its player's effects: one Blood Oath null effect per stab, then the stats. +static void blood_oath_effects_sync(Entity_Familiar& oath) +{ + TemporaryEffects& effects = oath.player->temporaryEffects; + if (!effects.isDisabled) + effects.RemoveNullEffect(NULLITEM_BLOOD_OATH, effects.GetNullEffectNum(NULLITEM_BLOOD_OATH)); + + auto& nullItems = g_manager->itemConfig.nullItems; + TemporaryEffect stab; + stab.item = (int)nullItems.size() > NULLITEM_BLOOD_OATH ? nullItems[NULLITEM_BLOOD_OATH].get() : nullptr; + for (int i = 0; i < oath.hearts; i++) effects.AddEffect(stab, true, 1); + oath.player->EvaluateItems(); +} + +// 0062c8a0 Gives Blood Oath's stabs or Paschal Candle's flame back to its player's effects. +void familiar_room_effects_sync(Entity_Familiar& familiar) +{ + if (familiar.variant == Entity_Familiar::BLOOD_OATH) blood_oath_effects_sync(familiar); + else if (familiar.variant == Entity_Familiar::PASCHAL_CANDLE) familiar.paschal_candle_sync_effects(); +} + +// Blood Oath's stab lands: it bleeds its player of red hearts down to a half (a coin for the Keeper, none with soul or +// bone hearts), a hit each, sprays blood, and counts the hearts (four more with BFFS!). +static void blood_oath_stab(Entity_Familiar& oath) +{ + familiar_sound_play(SOUND_MEATY_DEATHS); + Entity_Player& player = *oath.player; + if (player.HasInvincibility(0, EntityRef{})) return; + + int kept = player.soulHearts + player.boneHearts <= 0 ? (player.GetHealthType() == HEALTH_COIN ? 2 : 1) : 0; + int stabs = player.redHearts - kept; + oath.hearts = 0; + for (int i = 0; i < stabs && player.redHearts > kept; i++) + { + player.damageCooldown = 0; + if (!player.TakeDamage(1, BLOOD_OATH_STAB_FLAGS, EntityRef(&oath), BLOOD_OATH_STAB_COUNTDOWN)) break; + oath.hearts++; + } + + if (oath.hearts > 0) + { + Vector spray = vector_scale(Entity_Pickup::GetRandomPickupVelocity(player.pos, nullptr, 0), 2); + g_game->Spawn({.position = player.pos, + .velocity = spray, + .subType = 3, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + uint32_t big = Random() % 3; + uint32_t drops = big + 8 + Random() % 6; + for (uint32_t i = 0; i < drops; i++) + { + float turn = random_unit() * BLOOD_OATH_SPRAY_SPREAD - BLOOD_OATH_SPRAY_SPREAD / 2; + Vector drop = vector_scale(vector_rotated(spray, turn), random_unit()); + Entity* particle = g_game->Spawn({.position = vector_add(player.pos, drop), + .velocity = drop, + .subType = (int)i < (int)big + 2 ? 0 : 99, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = Random()}); + particle->Update(); + } + if (player.HasCollectible(COLLECTIBLE_BFFS)) oath.hearts += BLOOD_OATH_BFFS_BONUS; + } + blood_oath_effects_sync(oath); +} + +// 0063f9f0 Blood Oath follows, its look and dripping by its stabs. When a floor starts it flies to its player and +// stabs, then goes back. +void Entity_Familiar::ai_blood_oath() +{ + int look = 0; + float stabbed = (float)hearts / BLOOD_OATH_STAB_SCALE; + if (stabbed > 0.5f) look = 3; + else if (stabbed > 0.25f) look = 2; + else if (stabbed > 0) look = 1; + + switch (state) + { + case BLOOD_OATH_START: + state = BLOOD_OATH_IDLE; + [[fallthrough]]; + case BLOOD_OATH_IDLE: + { + sprite.Play(BLOOD_OATH_LOOKS[look]); + int odds = BLOOD_OATH_SPLAT_ODDS[look]; + if (odds != 0 && Random() % (uint32_t)odds == 0) + familiar_splat(*this, random_unit() * BLOOD_OATH_SPLAT_RANGE + BLOOD_OATH_SPLAT_MIN); + break; + } + case BLOOD_OATH_STAB: + sprite.Play("Stab"); + velocity = vector_scale(vector_sub(player->pos, pos), 1 / friction); + if (!sprite.animState.animData) return; + if (sprite.IsEventTriggered("Hit")) return blood_oath_stab(*this); + if (sprite.IsEventTriggered("Back")) state = BLOOD_OATH_BACK; + return; + case BLOOD_OATH_BACK: + if (sprite.animState.animData && !sprite.animState.isPlaying && sprite.GetAnimation() == "Stab") + state = BLOOD_OATH_IDLE; + break; + default: + return; + } + FollowParent(); +} + +// Part of 0062b360 (Blood Oath): a new floor (not a continued run) forgets the stabs, and with more red hearts than it +// leaves it starts stabbing on its player. +void blood_oath_level_start(Entity_Familiar& oath) +{ + if (!g_game->isStartingFromState) + { + oath.hearts = 0; + int kept = oath.player->GetHealthType() == HEALTH_COIN ? 2 : 1; + if (oath.player->redHearts > kept) + { + oath.state = BLOOD_OATH_STAB; + oath.pos = oath.player->pos; + } + } + blood_oath_effects_sync(oath); +} + +// A knife piece or the full knife idles beside its player, turned the way it drifts (part of 006174c0). +void knife_follow(Entity_Familiar& knife) +{ + knife.sprite.Play("Idle"); + if (std::fabs(knife.velocity.x) > KNIFE_FLIP_SPEED) knife.sprite.isFlipX = knife.velocity.x < 0; +} + +// The full knife's own dash (part of 006174c0). Flying, it keeps its speed until it meets a wall. A wall with the +// strange door stabs it open: the knife flies through and fades away, its pieces leaving their owners. Any other wall +// stops it in its hit, after which it recharges. +void knife_dash(Entity_Familiar& knife) +{ + if (knife.fireCooldown == KNIFE_FADING) + { + knife.sprite.color._tint[3] = std::max(knife.sprite.color._tint[3] - KNIFE_FADE_STEP, 0.0f); + if (knife.sprite.color._tint[3] > 0) return; + + knife.Remove(); + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == 0) + { + player->cacheFlags |= CACHE_FAMILIARS; + player->temporaryEffects.isEvaluateCachePending = true; + } + return; + } + if (knife.fireCooldown == KNIFE_STUCK) + { + knife.velocity = vector_sub(knife.targetPosition, knife.pos); + if (!knife.sprite.IsPlaying()) knife.fireCooldown = CHARGE_RECOVERY; + return; + } + if (knife.fireCooldown != -1) return; + + knife.entityCollisionClass = ENTCOLL_ENEMIES; + Vector motion = knife.gridCollisionVelocity; + if (!knife.isCollidesWithGrid || + vector_dot(vector_normalized(motion), knife.gridCollisionNormal) <= KNIFE_WALL_FACING) + { + float speed = vector_length(knife.velocity); + if (speed < KNIFE_SPEED && speed > 0) knife.velocity = vector_resized(knife.velocity, KNIFE_SPEED); + return; + } + + Room& room = *g_game->room; + for (const Vector& point : knife.collisionPoints) + { + Vector probe = vector_add(vector_add(knife.pos, motion), point); + int column = (int)((probe.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((probe.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) continue; + int index = row * room.gridWidth + column; + GridEntity* grid = index < ROOM_GRID_CELLS ? room.GetGridEntity((uint32_t)index) : nullptr; + if (!grid || grid->type != GRID_DOOR) continue; + + auto* door = static_cast(grid); + if (door->variant != KNIFE_DOOR_VARIANT || door->get_secret_exit_kind() != KNIFE_SECRET_EXIT || + !door->TryBlowOpen(false, &knife)) + break; + + knife.entityGridCollisionClass = GRIDCOLL_NONE; + knife.fireCooldown = KNIFE_FADING; + knife.velocity = motion; + knife.pos = vector_add(knife.pos, vector_scale(motion, knife.speedMultiplier)); + for (int piece : {COLLECTIBLE_KNIFE_PIECE_1, COLLECTIBLE_KNIFE_PIECE_2}) + { + Entity_Player* owner = knife.player->HasCollectible(piece) + ? knife.player + : g_game->playerManager.FirstCollectibleOwner(piece, LAZARUS_SHARE_IGNORE); + if (owner) owner->RemoveCollectible(piece, false, 0, true); + } + return; + } + + knife.entityCollisionClass = ENTCOLL_NONE; + knife.entityGridCollisionClass = GRIDCOLL_NONE; + if (vector_is_zero(knife.gridCollisionNormal)) + { + knife.fireCooldown = CHARGE_RECOVERY; + return; + } + if (std::fabs(motion.y) < std::fabs(motion.x)) + { + knife.sprite.Play("HitSide"); + knife.sprite.isFlipX = motion.x < 0; + } + else knife.sprite.Play(motion.y < 0 ? "HitUp" : "HitDown"); + knife.targetPosition = knife.pos; + knife.velocity = {}; + familiar_sound_play(SOUND_GOOATTACH0); + knife.fireCooldown = KNIFE_STUCK; +} + +// Plays Jaw Bone's float the way it moves. +static void jaw_bone_face(Entity_Familiar& jaw) +{ + int direction = jaw.get_velocity_direction(); + if (direction == DIRECTION_DOWN) jaw.sprite.Play("FloatDown"); + else if (direction == DIRECTION_UP) jaw.sprite.Play("FloatUp"); + else + { + jaw.sprite.Play("FloatSide"); + jaw.sprite.isFlipX = direction == DIRECTION_LEFT; + } +} + +// Jaw Bone follows, facing the way it moves once it moves at all (part of 006174c0). +void jaw_bone_follow(Entity_Familiar& jaw) +{ + if (vector_length_squared(jaw.velocity) > JAW_BONE_MOVING_SQUARED) jaw_bone_face(jaw); +} + +// Jaw Bone's throw (part of 006174c0): it grabs the first free pickup it touches (a sticky nickel only wiggles) and +// carries it. Meeting a wall, leaving the room or carrying something turns it back, and near its player it drops what +// it carries and recharges. +void jaw_bone_dash(Entity_Familiar& jaw) +{ + jaw.sprite.Play("Throw"); + if (!jaw.target) + { + for (Entity* entity : entity_query_radius(jaw.pos, jaw.size, QUERY_PICKUPS)) + { + auto* pickup = static_cast(entity); + if (!entity || entity->type != ENTITY_PICKUP || !familiar_listed(JAW_BONE_FETCHED, entity->variant) || + pickup->price != 0) + continue; + if (entity->variant != PICKUP_COIN || entity->subtype != COIN_STICKYNICKEL) + { + jaw.target = entity; + continue; + } + if (entity->sprite.IsPlaying("Touched")) continue; + entity->sprite.Play("Touched"); + pickup->collisionCooldown = JAW_BONE_NICKEL_COOLDOWN; + } + } + else + { + jaw.target->pos = jaw.pos; + jaw.target->velocity = jaw.velocity; + jaw.target->entityGridCollisionClass = GRIDCOLL_NONE; + } + + if (jaw.fireCooldown == JAW_BONE_RETURNING) + { + Vector toPlayer = vector_sub(jaw.player->pos, jaw.pos); + if (vector_length_squared(toPlayer) < JAW_BONE_CATCH_SQUARED) + { + jaw.fireCooldown = CHARGE_RECOVERY; + if (jaw.target) + { + jaw.target->entityGridCollisionClass = jaw.IsLilithBirthrightIncubus() ? GRIDCOLL_NONE : GRIDCOLL_WALLS; + jaw.target = nullptr; + } + jaw_bone_face(jaw); + } + jaw.velocity = vector_scale(vector_normalized(toPlayer), JAW_BONE_RETURN_SPEED); + } + else if ((jaw.isCollidesWithGrid || !g_game->room->IsPositionInRoom(jaw.pos, JAW_BONE_ROOM_MARGIN) || jaw.target) && + !jaw.IsLilithBirthrightIncubus()) + { + jaw.entityGridCollisionClass = GRIDCOLL_NONE; + jaw.velocity = vector_scale(jaw.velocity, 0.5f); + jaw.fireCooldown = JAW_BONE_RETURNING; + } + jaw.entityCollisionClass = ENTCOLL_ALL; +} + +// Stitches' swap with Book of Belial: a dark trail from Stitches to its player, and a cut through every enemy (or +// versus player) along it on one side, the original testing the side without a bound on the other. +static void stitches_belial_cut(Entity_Familiar& stitches, float damage) +{ + Entity_Player& player = *stitches.player; + Entity* trail = g_game->Spawn({.position = stitches.pos, + .spawner = &stitches, + .type = ENTITY_EFFECT, + .variant = EFFECT_SPRITE_TRAIL, + .seed = Random()}); + auto* line = static_cast(trail); + line->parent = &player; + line->sprite.color = STITCHES_TRAIL_COLOR; + LayerState* layer = line->sprite.GetLayer(0); + layer->blendMode[BLEND_EQUATION] = BLEND_EQUATION_ADD; + layer->blendMode[BLEND_RGB_SOURCE] = + KAGE::Graphics::manager.isPremultipliedAlpha ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA; + layer->blendMode[BLEND_RGB_DEST] = BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + layer->blendMode[BLEND_ALPHA_SOURCE] = BLEND_FACTOR_ONE; + layer->blendMode[BLEND_ALPHA_DEST] = BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + line->sprite.scale = vector_make(1, 1); + line->minRadius = STITCHES_TRAIL_START; + line->maxRadius = STITCHES_TRAIL_START; + line->Update(); + line->pos = player.pos; + line->minRadius = STITCHES_TRAIL_END; + line->maxRadius = STITCHES_TRAIL_END; + line->sprite.scale = vector_make(2, 2); + line->Update(); + + Vector toPlayer = vector_sub(player.pos, stitches.pos); + float length = vector_length(toPlayer); + if (length > 0) + { + Vector along = vector_scale(toPlayer, 1 / length); + bool isVersus = familiar_versus(); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!entity || entity->entityCollisionClass == ENTCOLL_NONE || entity->IsFriendly()) continue; + bool isTarget = (isVersus && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY); + if (!isTarget) continue; + + Vector offset = vector_sub(entity->pos, stitches.pos); + float forward = vector_dot(along, offset); + float side = along.x * offset.y - along.y * offset.x; + if (side < entity->size + STITCHES_CUT_REACH && forward >= 0 && forward <= length) + entity->TakeDamage(damage, 0, EntityRef(&player), STITCHES_CUT_COUNTDOWN); + } + } + familiar_sound_play(SOUND_TOOTH_AND_NAIL, + {.frameDelay = 1, .pitch = random_unit() * STITCHES_CUT_PITCH_RANGE + STITCHES_CUT_PITCH}); + game_shake_screen(STITCHES_SHAKE); +} + +// The Mystery Egg's hatchling: a charmed enemy of a pool that grows with the rooms it lasted, a champion with BFFS!, +// half again as tough, hatched with a splash. +static void mystery_egg_hatch(Entity_Familiar& egg) +{ + int clears = egg.roomClearCount; + std::span pool = MYSTERY_EGG_POOLS.back(); + for (size_t i = 0; i < MYSTERY_EGG_CLEARS.size(); i++) + if (clears < MYSTERY_EGG_CLEARS[i]) + { + pool = MYSTERY_EGG_POOLS[i]; + break; + } + + int enemyType = pool[egg.dropRNG.RandomInt((uint32_t)pool.size())]; + auto* hatchling = dynamic_cast( + g_game->Spawn({.position = egg.pos, .spawner = &egg, .type = enemyType, .seed = egg.dropRNG._seed})); + hatchling->AddCharmed(EntityRef{}, -1, false, false); + if (egg.player->HasCollectible(COLLECTIBLE_BFFS)) hatchling->MakeChampion(egg.dropRNG._seed, -1, false); + hatchling->maxHitPoints *= MYSTERY_EGG_TOUGHNESS; + hatchling->health *= MYSTERY_EGG_TOUGHNESS; + + familiar_sound_play(SOUND_PLOP, {.frameDelay = (int)(egg.index % MYSTERY_EGG_SOUND_SPREAD)}); + egg.BloodExplode(); + Entity* splash = g_game->Spawn({.position = egg.pos, + .subType = 3, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splash->SetColor(MYSTERY_EGG_SPLASH, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->posOffset = vector_make(0, MYSTERY_EGG_SPLASH_HEIGHT); + splash->Update(); + egg.roomClearCount = 0; +} + +// 00638170 FamiliarAI::mystery_egg: the Mystery Egg follows. Cracked by its player's hit, it hatches on its Spawn event +// and hides once the crack plays out. +void mystery_egg_update(Entity_Familiar& egg) +{ + if (egg.sprite.animState.animData) + { + if (egg.sprite.IsEventTriggered("Spawn")) mystery_egg_hatch(egg); + if (egg.sprite.IsFinished("Crack")) + { + egg.isVisible = false; + return; + } + } + if (egg.isVisible) egg.FollowParent(); +} + +// Part of 0061da10 (Esau Jr.'s familiar): like Abel it mirrors the player across the room's centre, the centre moved by +// up to 30 the way its seed picks, and shoots. +void esau_jr_update(Entity_Familiar& esau) +{ + Vector center = Room::GetCenterPos(); + Vector fromCenter = vector_sub(esau.player->pos, center); + RNG rng; + rng.game_constructor(esau.initSeed, ESAU_JR_RNG_SHIFT); + center = vector_add(center, vector_scale(RandomVector(esau.initSeed), rng.RandomFloat() * ESAU_JR_CENTER_SPREAD)); + esau.FollowPosition(vector_sub(center, fromCenter)); + esau.Shoot(); +} + +// Stitches swaps places with its player: its ghost rises from its spot, the player lands there under a brief Stitches +// effect, and both spots burst (the player's harder, wider with BFFS!, which also rings eight tears). With Judas's +// Book of Belial a dark trail joins them and cuts what lies on one side of it. The player is spared hits for a second. +static void stitches_swap(Entity_Familiar& stitches) +{ + Entity_Player& player = *stitches.player; + Entity* ghost = + g_game->Spawn({.position = stitches.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + ghost->sprite = stitches.sprite; + ghost->sprite.Play("TeleportUp"); + ghost->Update(); + + Vector playerSpot = player.pos; + player.Teleport(stitches.pos, true, false); + stitches.pos = playerSpot; + TemporaryEffect swap(g_manager->itemConfig.GetCollectible(COLLECTIBLE_STITCHES)); + swap.count = 1; + swap.cooldown = STITCHES_EFFECT_FRAMES; + player.temporaryEffects.AddEffect(swap, false, 1); + + bool hasBffs = player.HasCollectible(COLLECTIBLE_BFFS); + float radius = hasBffs ? STITCHES_BURST_RADIUS_BFFS : STITCHES_BURST_RADIUS; + float playerBurst = player.meleeDamage * STITCHES_PLAYER_BURST_SCALE + STITCHES_PLAYER_BURST_BASE; + for (const Vector& spot : {player.pos, stitches.pos}) + g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()})->Update(); + RadiusDamage burst = {.source = &stitches, + .damageFlags = DAMAGE_EXPLOSION, + .playerDamageThreshold = STITCHES_PLAYER_THRESHOLD, + .radius = radius}; + burst.position = player.pos; + burst.damage = playerBurst; + damage_radius(burst); + float boosted = player.meleeDamage + player.meleeDamage + STITCHES_BFFS_BONUS; + burst.position = stitches.pos; + burst.damage = hasBffs ? boosted : player.meleeDamage; + damage_radius(burst); + + if (hasBffs) + for (int i = 0; i < STITCHES_BFFS_TEARS; i++) + { + Vector shot = vector_scale(vector_from_angle((float)i * FULL_TURN_DEGREES / STITCHES_BFFS_TEARS), + player.shotSpeed * STITCHES_TEAR_SPEED); + player.FireTear({.position = stitches.pos, .velocity = shot}, 0, nullptr, 1); + } + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) stitches_belial_cut(stitches, boosted); + + player.damageCooldown = std::max(player.damageCooldown, STITCHES_SPARED_FRAMES); + player.flags |= FLAG_NO_DAMAGE_BLINK; + stitches.velocity = {}; + stitches.sprite.Play("TeleportDown"); + stitches.state = STITCHES_LANDING; +} + +// 006437a0 Stitches drifts the way its player shoots (sideways shots damp the other axis), its speed kept within +// reach, braking against a reversal and bounced back into the room. Its active item sets it swapping places. +void Entity_Familiar::ai_stitches() +{ + entityGridCollisionClass = GRIDCOLL_WALLS; + switch (state) + { + case STITCHES_START: + spawnerType = ENTITY_PLAYER; + state = STITCHES_IDLE; + break; + case STITCHES_SWAP: + stitches_swap(*this); + break; + case STITCHES_LANDING: + sprite.Play("TeleportDown"); + if (!sprite.IsPlaying()) state = STITCHES_IDLE; + break; + case STITCHES_IDLE: + sprite.Play("Idle"); + break; + } + + Vector stick = player->GetShootingJoystick(); + if (isCollidesWithGrid) velocity = vector_scale(velocity, STITCHES_WALL_DRAG); + float alongX = velocity.x; + float carried = 0; + if (stick.x != 0 && stick.y == 0) + { + velocity.y *= 0.5f; + carried = std::fabs(alongX); + } + else if (stick.y != 0 && stick.x == 0) + { + carried = std::fabs(velocity.y); + alongX *= 0.5f; + } + float brake = std::max(-(velocity.y * stick.y + alongX * stick.x) * STITCHES_BRAKE, 0.0f); + float push = (brake + carried * STITCHES_CARRY + STITCHES_PUSH) * STITCHES_PUSH_SCALE; + velocity = vector_make((push * stick.x + alongX) * STITCHES_DRAG, (push * stick.y + velocity.y) * STITCHES_DRAG); + + Vector inside = vector_sub(g_game->room->GetClampedPositionImpl(pos, 0, 0, 0, 0), pos); + if (vector_is_zero(inside)) return; + Vector normal = vector_normalized(inside); + float bounce = std::clamp(-vector_dot(normal, velocity), STITCHES_BOUNCE_MIN, STITCHES_BOUNCE_MAX); + velocity = vector_add(velocity, vector_scale(normal, bounce * speedMultiplier)); +} + +// Part of 006261f0 (Pointy Rib): an enemy it touches (a vulnerable one, or a fireplace) is cut once per hit list, as a +// knife would, harder when the player swings it along its edge. +void pointy_rib_touch(Entity_Familiar& rib, Entity& collider, float damageMultiplier) +{ + if (!collider.IsEnemy() || collider.IsDescendantOf(rib.spawnerEntity)) return; + bool isFireplace = familiar_listed(RIB_FIREPLACE_TYPES, collider.type); + if (!collider.IsVulnerableEnemy(nullptr) && !isFireplace) return; + if (EntityList::HitListContains(rib.hitList, collider)) return; + + hit_list_insert(rib.hitList, collider); + Entity_Player& player = *rib.player; + Vector edge = vector_from_angle(rib.sprite.GetLayer(0)->rotation + RIGHT_ANGLE_DEGREES); + float swing = std::clamp(vector_dot(edge, player.velocity) * RIB_SWING_SCALE, 0.0f, 1.0f); + int displacement = (int)(Random() & 1) * 2 - 1; + TearParams params = player.GetTearHitParams(WEAPON_KNIFE, 1, displacement, nullptr); + collider.TakeDamage((swing + damageMultiplier) * params.tearDamage, 0, EntityRef(&rib), RIB_HIT_COUNTDOWN); +} + +// Part of 006261f0 (My Shadow): the first touch of each vulnerable enemy summons a charmed shadow Charger nearby (a +// free spot within 40, four tries) set on that enemy, while fewer than sixteen Chargers are out. Always ignored. +void my_shadow_touch(Entity_Familiar& shadow, Entity& collider) +{ + if (EntityList::HitListContains(shadow.hitList, collider)) return; + hit_list_insert(shadow.hitList, collider); + if (!collider.IsVulnerableEnemy(shadow.player)) return; + if (entity_query(ENTITY_CHARGER, 0).size() > MY_SHADOW_CHARGER_LIMIT) return; + + Vector spot = vector_add(shadow.pos, vector_scale(random_direction(), MY_SHADOW_REACH * random_unit())); + for (int i = 0; i < MY_SHADOW_TRIES && room_grid_collision_at(spot) != 0; i++) + { + float turn = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit() * MY_SHADOW_REACH; + spot = vector_add(shadow.pos, vector_make(std::cos(turn) * reach, std::sin(turn) * reach)); + } + if (room_grid_collision_at(spot) != 0) return; + + auto* charger = static_cast( + g_game->Spawn({.position = spot, + .spawner = shadow.player, + .subType = 1, + .type = ENTITY_CHARGER, + .seed = shadow.player->GetCollectibleRNG(COLLECTIBLE_MY_SHADOW).Next()})); + charger->flags &= ~FLAG_APPEAR; + charger->AddCharmed(EntityRef(&shadow), -1, false, false); + charger->TryForceTarget(&collider, MY_SHADOW_FORCE_FRAMES); + charger->isCanShutDoors = false; + charger->SetColor(MY_SHADOW_BLACK, MY_SHADOW_FADE_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + charger->Update(); + Entity* smoke = g_game->Spawn( + {.position = charger->pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_FIRE_JET, .seed = Random()}); + smoke->SetColor(MY_SHADOW_BLACK, -1, COLOR_PRIORITY_DEFAULT, false, true); + smoke->SetCollisionDamage(0); + smoke->Update(); +} + +// Part of 0062db20 (Twisted Pair): a twin pairs instead of joining the line. With no parent yet it rides its player, +// then hooks onto the end of another twin's chain as the other one of the pair, its look reloaded for its side. +void twisted_baby_pair(Entity_Familiar& baby) +{ + if (baby.parent) return; + + baby.parent = baby.player; + int side = 0; + for (Entity_Familiar* other : familiar_query(Entity_Familiar::TWISTED_BABY)) + { + if (other == &baby || !other->isExists || other->player != baby.player) continue; + + Entity* last = other; + while (last->child) last = last->child; + last->child = &baby; + baby.parent = last; + side = 1 - last->subtype; + break; + } + if (side == baby.subtype) return; + + baby.subtype = side; + baby.config = g_manager->entityConfig.GetEntity(baby.type, baby.variant, side); + baby.sprite.Load(baby.config->anm2Path, GRAPHICS_LOAD); + baby.sprite.Play(baby.sprite.GetDefaultAnimationName()); +} + +// Part of 0062d7e0 (Twisted Pair): a riding twin leaves with its partner, the line closing behind the pair. A twin +// without its partner leaves alone. +void twisted_baby_unpair(Entity_Familiar& baby) +{ + Entity* lead = baby.subtype == 0 ? &baby : (baby.parent->type == ENTITY_FAMILIAR ? baby.parent.get() : nullptr); + Entity* second = + baby.subtype != 0 ? &baby : (baby.child && baby.child->type == ENTITY_FAMILIAR ? baby.child.get() : nullptr); + if (!lead || !second) + { + KAGE_LogMessage(LOG_WARN, (uint8_t*)"Attempting to remove unpaired twisted baby!\n"); + lead = &baby; + second = &baby; + } + + Entity* before = lead->parent; + Entity* after = second->child; + if (before && before->type == ENTITY_FAMILIAR) before->child = after; + if (after) after->parent = before; + lead->parent = nullptr; + lead->child = nullptr; + second->parent = nullptr; + second->child = nullptr; +} + +// Part of 0060de70 (Cube Baby): it rests on the floor, its spin at a random frame. +void cube_baby_init(Entity_Familiar& cube) +{ + cube.entityGridCollisionClass = GRIDCOLL_GROUND; + cube.orbitAngleOffset = random_unit(); + cube.sprite.SetFrame("Spin", (int)(cube.orbitAngleOffset * CUBE_SPIN_FRAMES)); +} + +// 0064f860 FamiliarAI::cube_baby: Cube Baby spins as fast as it slides (unless held) and falls back after a throw. +// Freshly pushed it glides on, trailing frost and a pale dust, bouncing off walls (slower each time) and kept at a +// glide's speed. Resting, it slows the faster it went. +void cube_baby_update(Entity_Familiar& cube) +{ + float spin = std::min(vector_length(cube.velocity) / CUBE_SPIN_SPEED, CUBE_SPIN_MAX); + if (cube.velocity.x < 0) spin = -spin; + if (!cube.HasEntityFlags(FLAG_HELD)) + { + float turn = spin + 1 + cube.orbitAngleOffset; + cube.orbitAngleOffset = turn - std::floor(turn); + if (cube.sprite.animState.animData) + cube.sprite.animState.SetFrameFloat((float)(int)(cube.orbitAngleOffset * CUBE_SPIN_FRAMES)); + } + + if (cube.orbitSpeed < 0 || cube.posOffset.y < 0) + { + cube.orbitSpeed += CUBE_FALL; + cube.fireCooldown = CUBE_GLIDE_FRAMES; + cube.posOffset.y += cube.orbitSpeed; + float height = cube.posOffset.y; + cube.entityGridCollisionClass = + height < CUBE_HIGH ? GRIDCOLL_WALLS : (height < CUBE_LOW ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND); + if (height >= 0) + { + cube.posOffset.y = 0; + cube.orbitSpeed = 0; + cube.flags &= ~FLAG_THROWN; + cube.entityGridCollisionClass = GRIDCOLL_GROUND; + } + } + + if (cube.fireCooldown < 1) + { + float sliding = std::clamp(vector_length(cube.velocity) / CUBE_SLIDE_SPAN, 0.0f, 1.0f); + cube.friction = sliding * CUBE_FRICTION_RANGE + CUBE_FRICTION_MIN; + return; + } + + cube.friction = 1; + cube.fireCooldown += (int)cube.prevUpdateTime - (int)cube.updateTime; + if ((Random() & 1) == 0) + { + Entity* frost = g_game->Spawn({.position = cube.pos, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL, + .seed = Random()}); + float size = random_unit() * CUBE_FROST_RANGE + CUBE_FROST_MIN; + frost->sprite.scale = vector_make(size, size); + frost->Update(); + } + auto* dust = static_cast(g_game->Spawn({.position = cube.pos, + .velocity = vector_scale(cube.velocity, CUBE_DUST_DRIFT), + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = Random()})); + dust->rotation = random_unit() * CUBE_DUST_SPIN_RANGE + CUBE_DUST_SPIN_MIN; + int life = (int)(Random() % CUBE_DUST_LIFE) + (int)CUBE_DUST_LIFE; + dust->timeout = life; + dust->lifespan = life; + dust->posOffset = cube.posOffset; + dust->sprite.GetLayer(0)->color = CUBE_DUST_COLOR; + + float speed = vector_length(cube.velocity); + if (cube.isCollidesWithGrid) + { + if (speed > 0) cube.velocity = vector_scale(cube.velocity, vector_length(cube.gridCollisionVelocity) / speed); + cube.fireCooldown -= CUBE_WALL_COST; + return; + } + if (speed < CUBE_GLIDE_SPEED && speed > 0) cube.velocity = vector_resized(cube.velocity, CUBE_GLIDE_SPEED); +} + +// The body Blood Puppy's blood grows it into: none, the small one past 15, the big one past 40. +static int blood_puppy_stage(Entity_Familiar& puppy) +{ + if (puppy.coins >= PUPPY_BIG_BLOOD) return PUPPY_BIG; + return puppy.coins >= PUPPY_SMALL_BLOOD ? PUPPY_SMALL : PUPPY_PUP; +} + +// 0064fd40 FamiliarAI::blood_puppy: Blood Puppy grows into its body (a persistent enemy-side NPC riding along) as it +// drinks blood, starting over when that body dies. As a pup it chases enemies near or keeps by its player, bleeding, +// facing the way it trots. In a versus match it gives up a target it chased ten seconds. +void blood_puppy_update(Entity_Familiar& puppy) +{ + int stage = blood_puppy_stage(puppy); + if (stage == puppy.state && stage != PUPPY_PUP && !puppy.linkedEntity) + { + stage = PUPPY_PUP; + puppy.state = PUPPY_PUP; + puppy.coins = 0; + } + familiar_chase_limit(puppy, PUPPY_VERSUS_CHASE_FRAMES); + + if (stage != puppy.state) + { + Entity* body = puppy.linkedEntity; + int bodyVariant = stage - 1; + if (body && (stage == PUPPY_PUP || body->type != ENTITY_BLOOD_PUPPY || body->variant != bodyVariant)) + { + body->Remove(); + puppy.linkedEntity = nullptr; + body = nullptr; + } + if (!body && stage != PUPPY_PUP) + { + body = g_game->Spawn({.position = puppy.pos, + .spawner = puppy.player, + .type = ENTITY_BLOOD_PUPPY, + .variant = bodyVariant, + .seed = Random()}); + body->parent = &puppy; + body->Update(); + body->sprite.isFlipX = puppy.sprite.isFlipX; + g_game->room->entityList.AddPersistentEntity(body); + puppy.linkedEntity = body; + } + puppy.state = stage; + } + + if (Entity* body = puppy.linkedEntity) + { + puppy.isVisible = false; + puppy.entityCollisionClass = ENTCOLL_NONE; + puppy.entityGridCollisionClass = GRIDCOLL_NONE; + puppy.pos = body->pos; + puppy.velocity = {}; + return; + } + + puppy.isVisible = true; + puppy.entityCollisionClass = ENTCOLL_ALL; + puppy.entityGridCollisionClass = GRIDCOLL_GROUND; + puppy.PickEnemyTarget(PUPPY_SEARCH); + Vector goal = puppy.target ? puppy.target->pos : puppy.player->pos; + float near = puppy.target ? 0 : PUPPY_HEEL_SQUARED; + if (vector_length_squared(vector_sub(goal, puppy.pos)) > near) + puppy.pathfinder.FindGridPath(goal, PUPPY_SPEED, 0, DIRECT_PATH_FAR); + if ((Random() & 3) == 0) familiar_splat(puppy, random_unit() * PUPPY_SPLAT_RANGE + PUPPY_SPLAT_MIN); + puppy.friction *= PUPPY_DRAG; + + Vector motion = puppy.velocity; + if (vector_length(motion) >= PUPPY_TROT_SPEED) + { + if (std::fabs(motion.y) < std::fabs(motion.x)) + { + puppy.moveDirection = motion.x >= 0 ? DIRECTION_RIGHT : DIRECTION_LEFT; + puppy.sprite.Play("Move Hori"); + } + else + { + puppy.moveDirection = motion.y < 0 ? DIRECTION_UP : DIRECTION_DOWN; + puppy.sprite.Play(motion.y < 0 ? "Move Up" : "Move Down"); + } + } + else if (puppy.moveDirection == DIRECTION_UP) puppy.sprite.Play("Idle Up"); + else if (puppy.moveDirection == DIRECTION_DOWN) puppy.sprite.Play("Idle Down"); + else puppy.sprite.Play("Idle Hori"); + bool isSideways = puppy.moveDirection != DIRECTION_UP && puppy.moveDirection != DIRECTION_DOWN; + puppy.sprite.isFlipX = isSideways && puppy.moveDirection == DIRECTION_LEFT; +} + +// Part of 0062b360 (Blood Puppy): on a new floor its body comes along, a little below where it was. +void blood_puppy_level_start(Entity_Familiar& puppy) +{ + for (Entity* entity : g_game->room->entityList.persistentEL) + { + if (entity->type != ENTITY_BLOOD_PUPPY || entity->parent.get() != &puppy) continue; + + entity->pos.y += PUPPY_FLOOR_DROP; + if (entity == puppy.linkedEntity.get()) puppy.pos = entity->pos; + } +} + +// Part of 0062bb70 (Blood Puppy): in a new room its body stands where the pup is (any other body somewhere random +// beside it), still, an enemy-side one set to its special state. +void blood_puppy_room_enter(Entity_Familiar& puppy) +{ + for (Entity* entity : g_game->room->entityList.persistentEL) + { + if (entity->type != ENTITY_BLOOD_PUPPY || entity->parent.get() != &puppy) continue; + + if (entity == puppy.linkedEntity.get()) entity->pos = puppy.pos; + else + { + float turn = random_unit() * RANDOM_HALF_TURN * 2; + entity->pos = vector_add(puppy.pos, vector_make(std::cos(turn), std::sin(turn))); + } + entity->velocity = {}; + bool isFoe = (familiar_versus() && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY); + if (!isFoe) continue; + static_cast(entity)->state = NPC_STATE_SPECIAL; + entity->Update(); + } +} + +// Fruity Plum picks the diagonal nearest where its target is heading and dives along it. +static void fruity_plum_dive(Entity_Familiar& plum) +{ + Entity& target = *plum.target; + float distance = vector_length(vector_sub(plum.pos, target.pos)); + Vector lead = vector_sub(vector_add(target.pos, vector_scale(target.velocity, distance * PLUM_LEAD)), plum.pos); + float best = PLUM_BEST_START; + int diagonal = 0; + for (int i = 0; i < PLUM_DIAGONALS; i++) + { + float along = vector_dot(vector_from_angle((float)i * RIGHT_ANGLE_DEGREES + PLUM_DIAGONAL_TURN), lead); + if (along > best) + { + best = along; + diagonal = i; + } + } + plum.shootDirection = diagonal; + plum.targetPosition = vector_from_angle((float)diagonal * RIGHT_ANGLE_DEGREES + PLUM_DIAGONAL_TURN); + plum.state = PLUM_DIVE_START; + plum.sprite.isFlipX = plum.targetPosition.x < 0; +} + +// Plays Fruity Plum's attack look of a stage, its back turned when diving upward. +static void fruity_plum_attack_play(Entity_Familiar& plum, std::string_view front, std::string_view back) +{ + plum.sprite.Play(plum.targetPosition.y >= 0 ? back : front); +} + +// 006403f0 Fruity Plum circles its player until an enemy is near, then dives at it along a diagonal (faster with +// Baby-Bender's kin, Forgotten Lullaby), spraying fruit tears behind it and bouncing off walls, and comes back about +// when it passed the enemy or flew long enough. +void fruity_plum_update(Entity_Familiar& plum) +{ + bool isBounced = plum.isCollidesWithGrid; + if (isBounced) + { + Vector normal = plum.gridCollisionNormal; + if ((plum.targetPosition.x > 0 && normal.x > PLUM_BOUNCE) || + (plum.targetPosition.x < 0 && normal.x < -PLUM_BOUNCE)) + plum.targetPosition.x = -plum.targetPosition.x; + if ((plum.targetPosition.y > 0 && normal.y > PLUM_BOUNCE) || + (plum.targetPosition.y < 0 && normal.y < -PLUM_BOUNCE)) + plum.targetPosition.y = -plum.targetPosition.y; + float speed = vector_length(plum.velocity); + if (speed > 0) plum.velocity = vector_scale(plum.velocity, vector_length(plum.gridCollisionVelocity) / speed); + } + plum.entityGridCollisionClass = GRIDCOLL_WALLS; + + switch (plum.state) + { + case PLUM_START: + plum.sprite.Play("Fly"); + plum.state = PLUM_CIRCLING; + plum.shootDirection = -1; + return; + case PLUM_CIRCLING: + { + plum.sprite.Play("Fly"); + RNG rng = {plum.initSeed, 5, 9, 7}; + float turn = (float)(g_game->frameCount - plum.spawnFrame) * 2 + rng.RandomFloat() * FULL_TURN_DEGREES; + Vector spot = vector_add(plum.player->pos, vector_scale(vector_from_angle(turn), PLUM_CIRCLE)); + plum.velocity = vector_add(plum.velocity, + vector_scale(vector_normalized(vector_sub(spot, plum.pos)), PLUM_CIRCLE_PULL)); + plum.friction *= PLUM_CIRCLE_DRAG; + plum.PickEnemyTarget(PLUM_SEARCH); + if (plum.target) fruity_plum_dive(plum); + return; + } + case PLUM_DIVE_START: + fruity_plum_attack_play(plum, "AttackStart", "AttackBackStart"); + if (plum.sprite.animState.animData && plum.sprite.IsEventTriggered("Shoot")) + { + plum.state = PLUM_DIVING; + plum.fireCooldown = 0; + } + plum.friction *= PLUM_DIVE_DRAG; + return; + case PLUM_DIVING: + { + if (!plum.sprite.IsPlaying() || isBounced) + { + plum.sprite.isFlipX = plum.targetPosition.x < 0; + fruity_plum_attack_play(plum, "AttackLoop", "AttackBackLoop"); + } + float push = plum.player->HasTrinket(TRINKET_FORGOTTEN_LULLABY) ? PLUM_PUSH_FAST : PLUM_PUSH; + plum.velocity = vector_add(plum.velocity, vector_scale(plum.targetPosition, push)); + plum.friction *= PLUM_DIVING_DRAG; + if (++plum.fireCooldown % 2 == 0) + { + Vector spray = vector_scale(plum.targetPosition, + -PLUM_SPRAY_SPEED * (random_unit() * PLUM_SPRAY_RANGE + PLUM_SPRAY_MIN)); + spray = vector_rotated(spray, random_unit() * PLUM_SPRAY_SPREAD - PLUM_SPRAY_SPREAD / 2); + Entity_Tear* tear = plum.FireProjectile(spray, FIRE_EXACT); + tear->velocity = spray; + tear->pos = vector_sub(plum.pos, + vector_make(plum.targetPosition.x * PLUM_SPRAY_BACK, plum.targetPosition.y * 2)); + tear->Update(); + plum.shot_owner_convert(tear); + } + bool isPast = plum.target && (Random() & 3) == 0 && + vector_dot(vector_sub(plum.pos, plum.target->pos), plum.targetPosition) > PLUM_PAST; + if (plum.fireCooldown > PLUM_DIVE_MAX || (plum.fireCooldown > PLUM_DIVE_MIN && (!plum.target || isPast))) + plum.state = PLUM_DIVE_END; + return; + } + case PLUM_DIVE_END: + fruity_plum_attack_play(plum, "AttackEnd", "AttackBackEnd"); + plum.friction *= PLUM_DIVE_DRAG; + if (plum.sprite.IsPlaying()) return; + plum.PickEnemyTarget(PLUM_RESEARCH); + if (plum.target) return fruity_plum_dive(plum); + plum.state = PLUM_CIRCLING; + plum.fireCooldown = 0; + return; + } +} + +// Part of 0062cdc0 (Lost Soul): a hit while following breaks its mantle (from BFFS!) with a flash, else it dies. +void lost_soul_hurt(Entity_Familiar& soul) +{ + if (soul.state != SOUL_FOLLOW || soul.coins < 0) return; + if (soul.coins == 0) + { + familiar_sound_play(SOUND_DEATH_BURST_SMALL); + familiar_sound_play(SOUND_ISAAC_HURT_GRUNT, {.pitch = LOST_SOUL_DEATH_PITCH}); + soul.state = SOUL_DEAD; + return; + } + + familiar_sound_play(SOUND_HOLY_MANTLE); + auto* flash = static_cast(g_game->Spawn({.position = soul.pos, + .spawner = &soul, + .subType = LOST_SOUL_MANTLE_FLASH, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()})); + flash->FollowParent(&soul); + flash->posOffset = soul.posOffset; + flash->renderDepthOffset = LOST_SOUL_FLASH_DEPTH; + flash->Update(); + soul.coins = 0; + soul.damageCountdown = LOST_SOUL_MANTLE_FRAMES; + soul.sprite.overlayAnimState.SetAnimationData(nullptr); +} diff --git a/src/familiar_variants.h b/src/familiar_variants.h new file mode 100644 index 0000000..080ee5c --- /dev/null +++ b/src/familiar_variants.h @@ -0,0 +1,51 @@ +#pragma once + +#include "entity_familiar.h" + +// The familiars from Sprinkler (3.120) on, each variant's setup, frame and room hooks (familiar_variants.cpp, +// familiar_sprinkler.cpp, familiar_locust.cpp). + +// The variants Update 0061da10 has no case for, which only run the shared tail. +constexpr int IDLE_VARIANTS[] = {205, 215, 219, 227}; + +void my_shadow_init(Entity_Familiar& shadow); +void bone_spur_init(Entity_Familiar& spur); +void cube_baby_init(Entity_Familiar& cube); + +void pointy_rib_update(Entity_Familiar& rib); +void hallowed_ground_update(Entity_Familiar& ground); +void my_shadow_update(Entity_Familiar& shadow); +void spin_to_win_update(Entity_Familiar& spinner); +void bone_spur_update(Entity_Familiar& spur); +void twisted_baby_update(Entity_Familiar& baby); +void lost_soul_update(Entity_Familiar& soul); +void paschal_candle_update(Entity_Familiar& candle); +void mystery_egg_update(Entity_Familiar& egg); +void esau_jr_update(Entity_Familiar& esau); +void cube_baby_update(Entity_Familiar& cube); +void blood_puppy_update(Entity_Familiar& puppy); +void fruity_plum_update(Entity_Familiar& plum); + +void hallowed_ground_player_hurt(Entity_Familiar& ground); +void paschal_candle_player_hurt(Entity_Familiar& candle, uint64_t damageFlags); +void paschal_candle_room_clear(Entity_Familiar& candle); +void blood_oath_level_start(Entity_Familiar& oath); +void familiar_room_effects_sync(Entity_Familiar& familiar); +bool lost_soul_level_start(Entity_Familiar& soul); +void lost_soul_room_enter(Entity_Familiar& soul); +void lost_soul_hurt(Entity_Familiar& soul); +void blood_puppy_level_start(Entity_Familiar& puppy); +void blood_puppy_room_enter(Entity_Familiar& puppy); + +void pointy_rib_touch(Entity_Familiar& rib, Entity& collider, float damageMultiplier); +void my_shadow_touch(Entity_Familiar& shadow, Entity& collider); + +void twisted_baby_pair(Entity_Familiar& baby); +void twisted_baby_unpair(Entity_Familiar& baby); + +void knife_follow(Entity_Familiar& knife); +void knife_dash(Entity_Familiar& knife); +void jaw_bone_follow(Entity_Familiar& jaw); +void jaw_bone_dash(Entity_Familiar& jaw); + +void sprinkler_update(Entity_Familiar& sprinkler); diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index 95a4ea6..aee45bd 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -108,8 +108,6 @@ constexpr int VEIN_DEPTH_MAX = 4; constexpr float FULL_TURN = 360; constexpr float HALF_TURN = 180; constexpr float QUARTER_TURN = 90; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; -constexpr float RADIANS_TO_DEGREES = 57.29578f; // The vein and ray phase generator, seeded anew by every LoadConfig. static RNG fxRng = {}; diff --git a/src/game.cpp b/src/game.cpp index 387208d..746bcb7 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -279,40 +279,22 @@ bool Game::load_bossoverlays_xml(std::string_view path) return true; } -// A boss a Boss Rush spawn slot holds: its type and variant, and the segments of a segmented boss. -struct BossRushSpawn -{ - int chunks = 1; - int type = 0; - int variant = 0; -}; - -// ambush.xml's Boss Rush: the bosses of each spawn slot, how many waves it lasts and how many slots each wave draws. -// The original keeps them in Ambush, which classes.h holds as bytes. They move there with its takeover. -struct BossRushConfig -{ - std::vector> slots; - int numWaves = 0; - int spawnsPerWave = 0; -}; - -static BossRushConfig bossRushConfig; - // 00834680 Reads ambush.xml's into the Boss Rush: its wave counts, then from its first on, a slot // for each element, holding from its first on each element's boss count times. A missing file changes nothing. // The original crashes on a file without . Here that leaves the Boss Rush empty. void Game::LoadBossRushXml(std::string_view path) { + Ambush& ambush = g_game->ambush; Data data; data_load(data, path); if (!data.isLoaded) return; - bossRushConfig = {}; + ambush.bossRushWaves.clear(); std::optional root = root_find(data, "bossrush"); if (!root) return; - bossRushConfig.numWaves = std::atoi(node_attr(*root, "numWaves").data()); - bossRushConfig.spawnsPerWave = std::atoi(node_attr(*root, "spawnsPerWave").data()); + ambush.maxWaves = std::atoi(node_attr(*root, "numWaves").data()); + ambush.bossesPerWave = std::atoi(node_attr(*root, "spawnsPerWave").data()); bool isSlotStarted = false; for (DataNode slotNode : node_children(*root)) @@ -320,14 +302,14 @@ void Game::LoadBossRushXml(std::string_view path) isSlotStarted = isSlotStarted || node_tag(slotNode) == "spawn"; if (!isSlotStarted) continue; - std::vector& slot = bossRushConfig.slots.emplace_back(); + BossRushWave& slot = ambush.bossRushWaves.emplace_back(); bool isEnemyStarted = false; for (DataNode enemyNode : node_children(slotNode)) { isEnemyStarted = isEnemyStarted || node_tag(enemyNode) == "enemy"; if (!isEnemyStarted) continue; - BossRushSpawn spawn; + BossRushEntry spawn; int count = 1; spawn.type = std::atoi(node_attr(enemyNode, "type").data()); spawn.variant = std::atoi(node_attr(enemyNode, "variant").data()); diff --git a/src/game.h b/src/game.h index 28b3985..81f7cbf 100644 --- a/src/game.h +++ b/src/game.h @@ -2,6 +2,7 @@ #include "item_overlay.h" +#include "ambush.h" #include "anm2.h" #include "boss_pool.h" #include "challenge_params.h" @@ -37,6 +38,8 @@ #include #include +// The devil deals that unlock Azazel. +constexpr int AZAZEL_DEALS = 3; constexpr int GLOWING_HOURGLASS_SLOTS = 2; constexpr int GIANTBOOK_ENTRY_COUNT = 48; constexpr int BOSS_OVERLAY_COUNT = 5; diff --git a/src/game_restore.cpp b/src/game_restore.cpp index 7215de4..6837bf4 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 "music_manager.h" #include "npc_ai.h" #include "room.h" #include "texture_cache.h" @@ -30,6 +31,7 @@ constexpr uint32_t DEVIL_ANGEL_SHIFT = 2; constexpr uint8_t HOLY_MANTLE_SAVED = 2; constexpr const char* ITEM_POOLS_XML = "itempools.xml"; constexpr int DIMENSION_ALTERNATE = 1; +constexpr int AMBUSH_RESUME_COUNTDOWN = 30; constexpr float FAMILIAR_RESTORE_SCATTER = 20; constexpr int MINI_MUSH_STACKS_SECOND = 4; constexpr int MINI_MUSH_STACKS_THIRD = 7; @@ -75,6 +77,32 @@ RoomConfig_Room* room_config_ref_load(const RoomConfigRef& ref, const std::vecto return configs.mirrored_room_make(*room); } +// A fight saved in progress goes on: the Boss Rush drops the waves already called, a challenge starts over at its +// saved wave. The next wave comes in 30 frames to the fight's music, queued behind a start jingle still playing. +static void ambush_resume(Ambush& ambush, int wave) +{ + MusicManager& music = g_manager->musicManager; + bool isBossRush = g_game->room->roomType == ROOM_BOSSRUSH; + int track = isBossRush ? MUSIC_BOSS_RUSH : MUSIC_CHALLENGE_FIGHT; + + if (isBossRush) + { + ambush.shuffle_waves(); + for (int i = 0; i < (wave - 1) * ambush.bossesPerWave && !ambush.wavesLeft.empty(); i++) + ambush.wavesLeft.pop_back(); + } + else + { + ambush.isActive = false; + ambush.StartChallenge(); + ambush.currentWave = wave; + } + ambush.countdown = AMBUSH_RESUME_COUNTDOWN; + if (music.currentMusicId != MUSIC_GAME_START_JINGLE && music.currentMusicId != MUSIC_REVERSE_GENESIS_START) + music.Play(track, g_manager->optionsConfig.musicVolume); + else if (track < (int)music.tracks.size()) music.queuedMusicId = track; +} + // 006f8140 Rebuilds the run from a game state: its rules, counters and histories, then (continuing a saved run rather // than rewinding) the first player, the pools, the fortune generator and whether achievements may unlock. The // generators, pools, TMTRAINER items, the Ascent's stages, the versus rules, the players, the floor with the room the @@ -153,9 +181,9 @@ void Game::restore_game_state(GameState& state, GameRestore restore) Level::RestoreGameState(state); playerManager.RestoreGameState_PostLevelInit(state); manager.nightmareScene.stageIcons = state.nightmareStageIcons; - ambush._isActive = state.isAmbushActive; - ambush._currentWave = state.ambushWave; - if (ambush._isActive) reconstruction_missing("Game::restore_game_state 006f8140: an ambush in progress (Ambush)"); + ambush.isActive = state.isAmbushActive; + ambush.currentWave = state.ambushWave; + if (ambush.isActive) ambush_resume(ambush, state.ambushWave); scoreSheet.restore_state(state.scoreSheet); for (Entity_Player* player : playerManager.playerList) player->update_mini_mush_costume(); } @@ -505,7 +533,7 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) if (id < (int)items.collectibles.size()) voidedCollectibles.push_back(id); voidedPassives.clear(); for (VoidedPassive passive : saved.voidedPassives) - if (passive.id < (int)items.collectibles.size()) voidedPassives.push_back(passive.id); + if (passive.id < (int)items.collectibles.size()) voidedPassives.push_back(passive); movingBoxContents = saved.movingBoxContents; for (EntitySaveState& box : movingBoxContents) box.int64Storage = box.spawnerType; playerForms = saved.playerForms; @@ -582,6 +610,9 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) effectiveSoulCharge = saved.effectiveSoulCharge; urnSouls = saved.urnSouls; numGigaBombs = saved.numGigaBombs; + std::copy(saved.candyHeartStatUps.begin(), saved.candyHeartStatUps.end(), candyHeartStatUps.begin()); + std::copy(saved.soulLocketStatUps.begin(), saved.soulLocketStatUps.end(), soulLocketStatUps.begin()); + bonusDamageUps = saved.bonusDamageUps; rockBottomDamage = saved.rockBottomDamage; rockBottomMaxFireDelay = saved.rockBottomMaxFireDelay; rockBottomLuck = saved.rockBottomLuck; diff --git a/src/game_save.cpp b/src/game_save.cpp index a2bf386..e58b1d6 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -101,8 +101,8 @@ void Game::store_game_state(GameState& state) state.backwardsStages = backwardsStages; state.deathCertificateExitTimer = deathCertificateExitTimer; state.nightmareStageIcons = g_manager->nightmareScene.stageIcons; - state.isAmbushActive = ambush._isActive; - state.ambushWave = ambush._currentWave > 0 ? ambush._currentWave - 1 : ambush._currentWave; + state.isAmbushActive = ambush.isActive; + state.ambushWave = ambush.currentWave > 0 ? ambush.currentWave - 1 : ambush.currentWave; scoreSheet.store_state(state.scoreSheet); versus_store(deathmatchManager, state); } @@ -334,10 +334,9 @@ static bool is_familiar_saved(Entity_Familiar& familiar, bool isSaveTemporaryFam // 007b0be0 Copies the player into a saved player: its character, health and consumables, its sub player and the co-op // 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 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. +// The fields the curated player does not have yet keep their defaults: the soul charge, 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) { GameStatePlayer& state = *saveState; @@ -391,6 +390,9 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.effectiveSoulCharge = effectiveSoulCharge; state.urnSouls = urnSouls; state.numGigaBombs = numGigaBombs; + std::copy(candyHeartStatUps.begin(), candyHeartStatUps.end(), state.candyHeartStatUps.begin()); + std::copy(soulLocketStatUps.begin(), soulLocketStatUps.end(), state.soulLocketStatUps.begin()); + state.bonusDamageUps = bonusDamageUps; state.rockBottomDamage = rockBottomDamage; state.rockBottomMaxFireDelay = rockBottomMaxFireDelay; state.rockBottomLuck = rockBottomLuck; @@ -461,8 +463,7 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.playerFormsRewarded = playerFormsRewarded; state.collectibleCounts = collectibleCounts; state.voidedCollectibles = voidedCollectibles; - state.voidedPassives.clear(); - for (int passive : voidedPassives) state.voidedPassives.push_back({.id = passive}); + state.voidedPassives = voidedPassives; state.trinkets = trinkets; state.costumes.clear(); for (CostumeSpriteDesc& costume : costumeSpriteDescs) state.costumes.push_back({costume.item->id, costume.item->type}); diff --git a/src/game_state.cpp b/src/game_state.cpp index d6b9210..e196d58 100644 --- a/src/game_state.cpp +++ b/src/game_state.cpp @@ -399,7 +399,7 @@ void StateWriter::player_write(const GameStatePlayer& player) write(value); each_write(player.candyHeartStatUps); each_write(player.soulLocketStatUps); - write(player.unknownCounter); + write(player.bonusDamageUps); for (int value : {player.soulCharge, player.numGigaBombs, (int)player.urnSouls}) write(counter_byte(value)); for (float value : {player.rockBottomMoveSpeed, player.rockBottomMaxFireDelay, player.rockBottomDamage, player.rockBottomTearRange, player.rockBottomShotSpeed, player.rockBottomLuck}) @@ -1076,7 +1076,7 @@ bool StateReader::player_read(GameStatePlayer& player) fields_read(player.brittleBonesUpgrades, player.bleedOutHealth); player.greedsGulletHearts = read(); fields_read(player.greedsGulletOverflow, player.redStewBonusDuration, player.brokenHearts, player.rottenHearts, - player.effectiveSoulCharge, player.candyHeartStatUps, player.soulLocketStatUps, player.unknownCounter); + player.effectiveSoulCharge, player.candyHeartStatUps, player.soulLocketStatUps, player.bonusDamageUps); player.soulCharge = read(); player.numGigaBombs = read(); player.urnSouls = read(); diff --git a/src/game_state_player.h b/src/game_state_player.h index a619616..c96496e 100644 --- a/src/game_state_player.h +++ b/src/game_state_player.h @@ -50,13 +50,6 @@ struct CostumeItem int type = 0; }; -// A passive the Void absorbed. Its second word is only ever copied. -struct VoidedPassive -{ - int id = 0; - int value = 0; -}; - // A player as a saved run keeps it (GameStatePlayer): its character, health and consumables, its items and their RNGs, // stats and the counters items keep, the familiars and charmed enemies that follow it, and its co-op babies. // The first player also keeps PlayerManager's glitched baby seed and random babies. @@ -134,6 +127,7 @@ struct GameStatePlayer int blackHearts = 0; int bleedOutHealth = 0; int boneHearts = 0; + int bonusDamageUps = 0; int boneHeartsMask = 0; int brokenHearts = 0; int cambionConceptionState = 0; @@ -184,7 +178,6 @@ struct GameStatePlayer int speedModifier = 0; int strengthMaxHearts = 0; int tearRangeModifier = 0; - int unknownCounter = 0; int unknownTimer = -1; int unknownValue = 0; int wildCardItem = 0; diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index 735fe8a..68162e9 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -1047,8 +1047,7 @@ void GridEntity_Door::Open() { if (currentRoomType == ROOM_CHALLENGE) { - if (g_game->ambush._isActive && !isUnlockedByPlayer) - return; + if (g_game->ambush.isActive && !isUnlockedByPlayer) return; } else { diff --git a/src/grid_entity_poop.cpp b/src/grid_entity_poop.cpp index 204e836..6ac2827 100644 --- a/src/grid_entity_poop.cpp +++ b/src/grid_entity_poop.cpp @@ -754,7 +754,7 @@ void GridEntity_Poop::spawn_rewards(const PoopHit& hit) 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) player = main_player_nearest(position); if (player) spawn_dip_at(POOP_CHARMING, &position, player, &still); continue; } diff --git a/src/grid_entity_stairs.cpp b/src/grid_entity_stairs.cpp index 4c122f2..ea43cc9 100644 --- a/src/grid_entity_stairs.cpp +++ b/src/grid_entity_stairs.cpp @@ -1,16 +1,96 @@ #include "grid_entity_stairs.h" -#include "log.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_trap_door.h" +#include "npc_ai.h" +#include "room.h" +#include "room_descriptor.h" +#include "room_transition.h" +#include +#include -// 0099bad0 Loads the stairs. +constexpr std::string_view STAIRS_ANIM_CLOSED = "Closed"; +constexpr std::string_view STAIRS_ANIM_OPENING = "Open Animation"; +constexpr float STAIRS_PLAYER_FAR = 1e9f; +constexpr float STAIRS_CLEARANCE = 50; +constexpr float STAIRS_REACH = 21; +constexpr int STAIRS_OPENING_FRAME = 9; +constexpr int STAIRS_RETURN_ROOM_MIN = -20; +constexpr int STAIRS_RETURN_ROOM_MAX = 168; + +// 0099bad0 Loads the stairs closed (the secret shop's with its own sheet), or breaks them at once in cursed mist. void GridEntity_Stairs::subclass_init() { - reconstruction_missing("GridEntity_Stairs::subclass_init 0099bad0"); + if (g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CURSED_MIST) + { + Destroy(true, EntityRef()); + return; + } + sprite.Load("gfx/grid/door_20_secrettrapdoor.anm2", GRAPHICS_DEFER); + state = 0; + if (variant == STAIRS_SECRET_SHOP) sprite.ReplaceSpritesheet(0, "gfx/grid/secretshop_trapdoor.png"); + sprite.LoadGraphics(); + sprite.Play(STAIRS_ANIM_CLOSED); } -// 0099bd50 Takes a player stepping on it out of the crawlspace. +// 0099bd50 Stays shut while the nearest player stands within 50 of it or the Forgotten's body lies on it (and in an +// uncleared room, or a Greed wave), once past its ninth opening frame it keeps opening. The nearest player who walks +// onto the open stairs goes down, the way back kept: the room and the stairs, or from a negative room its last one. void GridEntity_Stairs::Update() { - reconstruction_missing("GridEntity_Stairs::Update 0099bd50"); + Game& game = *g_game; + Room& room = *game.room; + bool isCleared = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + bool isGreedLocked = isGreed && room.roomType == ROOM_DEFAULT && !isCleared; + Vector position = Position(); + Entity_Player* player = main_player_nearest(position); + float distance = player ? vector_length(vector_sub(position, player->pos)) : STAIRS_PLAYER_FAR; + bool isShut = (player && distance < STAIRS_CLEARANCE) || is_forgotten_body_on(position); + + bool isOpening = !isCleared || isShut ? sprite.animState.animData && + (int)std::floor(sprite.animState.animFrame) > STAIRS_OPENING_FRAME + : true; + if (isOpening && !isGreedLocked) + { + sprite.Play(STAIRS_ANIM_OPENING); + if (!sprite.animState.animData || !sprite.animState.isPlaying) state = 1; + } + else + { + sprite.Play(STAIRS_ANIM_CLOSED); + state = 0; + } + + bool isBusy = player && (player->isPlayingExtraAnimation || player->isPlayingItemAnimation); + bool isHoldingTwin = player && player->heldEntity && player->heldEntity == player->twinPlayer.get(); + if (player && distance < STAIRS_REACH && state == 1 && (!isBusy || isHoldingTwin)) + { + RoomTransitionRequest request = {.player = player, .animation = TRANSITION_PIXELATION}; + if (variant == STAIRS_START_ROOM) + { + request.roomIndex = game.startingRoomIdx; + return game.StartRoomTransition(request); + } + if (variant == STAIRS_CRAWLSPACE || variant == STAIRS_GIDEON || variant == STAIRS_SECRET_SHOP) + { + request.roomIndex = variant == STAIRS_CRAWLSPACE ? ROOM_DUNGEON_IDX + : variant == STAIRS_GIDEON ? ROOM_GIDEON_DUNGEON_IDX + : ROOM_SECRET_SHOP_IDX; + game.StartRoomTransition(request); + } + if (game.currentRoomIdx < 0) + { + game.dungeonReturnPosition = {}; + game.dungeonReturnRoomIndex = std::clamp(game.lastRoomIdx, STAIRS_RETURN_ROOM_MIN, STAIRS_RETURN_ROOM_MAX); + } + else + { + game.dungeonReturnPosition = position; + game.dungeonReturnRoomIndex = std::min(game.currentRoomIdx, STAIRS_RETURN_ROOM_MAX); + } + } + if (sprite.isLoaded) sprite.Update(); } // 00714750 Water lies flat over the stairs. diff --git a/src/grid_entity_stairs.h b/src/grid_entity_stairs.h index 0ecd95b..962545d 100644 --- a/src/grid_entity_stairs.h +++ b/src/grid_entity_stairs.h @@ -2,6 +2,15 @@ #include "grid_entity.h" +// Where stairs lead, by their variant: a crawlspace, Gideon's crawlspace, the secret shop, or the start room. +enum StairsVariant : int +{ + STAIRS_CRAWLSPACE, + STAIRS_GIDEON, + STAIRS_SECRET_SHOP, + STAIRS_START_ROOM +}; + // The stairs out of a crawlspace (Lua's GRID_STAIRS). struct GridEntity_Stairs : GridEntity { diff --git a/src/grid_entity_trap_door.cpp b/src/grid_entity_trap_door.cpp index 8fb2e44..4b446b4 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -45,7 +45,6 @@ constexpr float PLAYER_CLEARANCE = 50; constexpr float REACH = 21; constexpr float MOTHER_HOLE_REACH = 34; constexpr float FORGOTTEN_BODY_RADIUS = 20; -constexpr int SOUND_SHOVEL_HOLE_OPEN = 917; constexpr int VOID_SHOCKWAVE_FRAMES = 15; constexpr float VOID_SHOCKWAVE_AMPLITUDE = 0.05f; @@ -122,28 +121,8 @@ void GridEntity_TrapDoor::subclass_init() sprite.Play(ANIM_CLOSED); } -// (00703ab0) Game::GetNearestPlayerEx for the main players only: the nearest player itself (not a co-op ghost, baby, -// twin's hold or hologram) that collides with entities. -static Entity_Player* main_player_nearest(const Vector& position) -{ - Entity_Player* nearest = nullptr; - float best = 1e10f; - - for (Entity_Player* player : g_game->playerManager.playerList) - { - float distance = vector_length_squared(vector_sub(position, player->pos)); - if (distance >= best) continue; - if (player->variant != 0 || player->isCoopGhost || player->parent || player->IsHologram()) continue; - if (player->entityCollisionClass == ENTCOLL_NONE) continue; - - nearest = player; - best = distance; - } - return nearest; -} - // Whether The Forgotten's body lies on the trapdoor (EntityList::QueryRadius over the familiars). -static bool is_forgotten_body_on(const Vector& position) +bool is_forgotten_body_on(const Vector& position) { EntityList& list = g_game->room->entityList; EntityList_EL found; diff --git a/src/grid_entity_trap_door.h b/src/grid_entity_trap_door.h index 262b53e..6f3929d 100644 --- a/src/grid_entity_trap_door.h +++ b/src/grid_entity_trap_door.h @@ -18,3 +18,4 @@ struct GridEntity_TrapDoor : GridEntity }; void shockwave_make(const Vector& position, float amplitude, float speed, int duration); +bool is_forgotten_body_on(const Vector& position); diff --git a/src/hud.cpp b/src/hud.cpp index df3385a..9fe0db2 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -822,7 +822,7 @@ void HUD::Render() if (!game.deathmatchManager.is_active()) { game.minimap.Render(); - if (game.ambush._isActive && game.room->roomType == ROOM_BOSSRUSH) + if (game.ambush.isActive && game.room->roomType == ROOM_BOSSRUSH) { constexpr float WAVE_BOX_WIDTH = 64; constexpr float WAVE_BOX_HEIGHT = 32; @@ -840,7 +840,7 @@ void HUD::Render() bossHealthBarRushImage->Render(KAGE::Graphics::color_quad_rect(at, box, WHITE), WHITE); char waves[TEXT_BUFFER_SIZE]; - std::snprintf(waves, sizeof(waves), "%d/%d", game.ambush._currentWave, game.ambush._maxWaves); + std::snprintf(waves, sizeof(waves), "%d/%d", game.ambush.currentWave, game.ambush.maxWaves); float width = (float)(unsigned int)font6.GetStringWidth(waves); text_draw(font6, waves, at_make(at.x + WAVE_TEXT_RIGHT - width, at.y + WAVE_TEXT_Y)); } diff --git a/src/item_overlay.h b/src/item_overlay.h index f5a9ed6..452b7f7 100644 --- a/src/item_overlay.h +++ b/src/item_overlay.h @@ -26,6 +26,7 @@ enum GiantbookOverlay : int GIANTBOOK_HOURGLASS = 14, GIANTBOOK_NECRONOMICON = 12, GIANTBOOK_MISSING_PAGE_2 = 31, + GIANTBOOK_HAGALAZ = 20, GIANTBOOK_CLICKER = 39, GIANTBOOK_SLEEP_NIGHTMARE = 44, GIANTBOOK_MEGA_MUSH = 45, diff --git a/src/level.cpp b/src/level.cpp index 5d04f86..43885c1 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -15,6 +15,7 @@ #include "platform.h" #include "room.h" #include "room_config.h" +#include "room_render.h" #include "room_transition.h" #include "texture_cache.h" #include @@ -50,6 +51,11 @@ constexpr uint32_t CHALLENGE_XXXXXXXXL = 21; constexpr int ALT_PATH_LAYER_FIRST = 3; constexpr int DIMENSION_MINESHAFT = 2; constexpr int ENEMY_TYPE_LAST = 999; +// X-Ray Vision opening a hidden door: the wall crack turned to the door's side, and its sound. +constexpr int XRAY_DOOR_SIDES = 4; +constexpr float XRAY_WALL_TURN = 90; +constexpr float XRAY_SOUND_VOLUME = 0.75f; +constexpr int XRAY_SOUND_DELAY = 10; // The enemies' health that makes a room's music intense, growing with the floor (a Greed floor counting as two). constexpr float INTENSE_HEALTH_BASE = 40; @@ -117,7 +123,6 @@ 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; @@ -2687,8 +2692,16 @@ void Level::reveal_room_visibility(RoomDescriptor& target, RoomDescriptor* fromR GridEntity_Door& door = *room->doors[doorSlot]; if (is_xray() && door.variant == DOOR_HIDDEN) - reconstruction_missing("Level::reveal_room_visibility 0073f620: X-Ray Vision's hidden door opening " - "(Game::SpawnEx 006fe410)"); + { + uint32_t seed = Random(); + Entity* wall = g_game->Spawn( + {.position = door.Position(), .type = ENTITY_EFFECT, .variant = EFFECT_XRAY_WALL, .seed = seed}); + wall->sprite.rotation = (float)(doorSlot % XRAY_DOOR_SIDES - 1) * XRAY_WALL_TURN; + door.variant = DOOR_UNSPECIFIED; + int sound = SOUND_DEATH_CARD; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = XRAY_SOUND_VOLUME, .frameDelay = XRAY_SOUND_DELAY}); + } isShown = door.isBusted; } if (!isShown) isShown = is_xray() || is_spelunker(); @@ -3375,10 +3388,27 @@ void Level::InitializeDevilAngelRoom(bool isForceAngel, bool isForceDevil) if (!isDealsDaily) game.gameStateFlags |= 1ull << GAME_STATE_KRAMPUS_SPAWNED; } -// 0074ba00 Starts Mama Mega's explosion. -void Level::StartMamaMega(Vector&, Entity_Player*) +// 0074ba00 Starts Mama Mega's explosion where it was set off, remembering where the room lies on the floor (a room +// off the map somewhere far out, by its decoration seed) for the rooms its blast reaches. +void Level::StartMamaMega(Vector& position, Entity_Player* player) { - reconstruction_missing("Level::StartMamaMega 0074ba00"); + constexpr int MAP_COLUMNS = 13; + constexpr float MAP_ROOM_WIDTH = 600; + constexpr float MAP_ROOM_HEIGHT = 360; + constexpr float OFF_MAP_REACH = 5000; + constexpr float OFF_MAP_CENTER_X = 4200; + constexpr float OFF_MAP_CENTER_Y = 2520; + Vector offset = vector_make((float)(currentRoomIdx % MAP_COLUMNS * MAP_ROOM_WIDTH), + (float)(currentRoomIdx / MAP_COLUMNS) * MAP_ROOM_HEIGHT); + if (currentRoomIdx < 0) + { + Vector direction = RandomVector(GetRoomByIdx(currentRoomIdx, -1)->decorationSeed); + offset = + vector_make(direction.x * OFF_MAP_REACH + OFF_MAP_CENTER_X, direction.y * OFF_MAP_REACH + OFF_MAP_CENTER_Y); + } + g_game->mamaMegaPosition = vector_add(offset, position); + levelStateFlags |= 1u << LEVEL_STATE_MAMA_MEGA; + room->MamaMegaExplosion(position, player); } // 0074eaf0 A rail plate pressed on the mineshaft floor raises the entrance's next rail: the plate rooms and the diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp index b4db53e..9e23c5d 100644 --- a/src/lua_api_game.cpp +++ b/src/lua_api_game.cpp @@ -28,8 +28,6 @@ constexpr float FART_RADIUS = 85; // The last stage the run's stage counters keep. constexpr int STAGE_COUNTER_MAX = 13; // Making this many devil deals in one run unlocks Azazel. -constexpr int AZAZEL_DEALS = 3; -constexpr int ACHIEVEMENT_AZAZEL = 79; // A Greed run's waves, bosses and the devil's included (one more in Greedier). constexpr int GREED_WAVE_TOTAL = 11; // The argument past the last line HUD:ShowFortuneText reads. diff --git a/src/lua_api_room.cpp b/src/lua_api_room.cpp index 937bdff..c75aa8f 100644 --- a/src/lua_api_room.cpp +++ b/src/lua_api_room.cpp @@ -274,9 +274,9 @@ static void room_state_register(lua_State* state) lua_method(state, "TriggerClear", [](Room& room, bool isSilent) { room_clear_trigger(room, isSilent ? CLEAR_SOUND_SILENT : CLEAR_SOUND_PLAY); }); - lua_method(state, "RespawnEnemies", [](Room&) { reconstruction_missing("Room::RespawnEnemies 0081fd60"); }); + lua_method(state, "RespawnEnemies", [](Room& room) { room.RespawnEnemies(); }); lua_method(state, "MamaMegaExplosion", - [](Room&, Vector, Entity_Player*) { reconstruction_missing("Room::MamaMegaExplosion 00820910"); }); + [](Room& room, Vector position, Entity_Player* player) { room.MamaMegaExplosion(position, player); }); lua_method(state, "Update", [](Room& room) { room.Update(); }); lua_method(state, "Render", [](Room& room) { room.Render(); }); } @@ -323,7 +323,7 @@ static void room_register(lua_State* state) 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, "IsAmbushActive", [](Room&) { return g_game->ambush._isActive; }); + lua_method(state, "IsAmbushActive", [](Room&) { return g_game->ambush.isActive; }); lua_method(state, "HasTriggerPressurePlates", [](Room& room) { return room.isTriggerPressurePlates; }); lua_method(state, "GetTintedRockIdx", [](Room& room) { return room.tintedRockIdx; }); lua_method(state, "GetRenderMode", [](Room& room) { return room.entityList.renderMode; }); diff --git a/src/lua_api_vector.cpp b/src/lua_api_vector.cpp index 67aa2c5..cb4fee9 100644 --- a/src/lua_api_vector.cpp +++ b/src/lua_api_vector.cpp @@ -8,14 +8,6 @@ static Vector vector_clamped(const Vector& vector, float minX, float minY, float 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) diff --git a/src/lua_callbacks.cpp b/src/lua_callbacks.cpp index a2be448..4a01379 100644 --- a/src/lua_callbacks.cpp +++ b/src/lua_callbacks.cpp @@ -234,6 +234,19 @@ std::optional LuaEngine::InputAction(Entity* entity, int hook, int action) return value; } +// 00864d80 Runs MC_INPUT_ACTION for the action value hook. The value a mod answered, nothing when no mod did. +std::optional LuaEngine::InputActionValue(Entity* entity, int action) +{ + constexpr int INPUT_HOOK_VALUE = 2; + CallbackRun run = {"PreActionHookF", MC_INPUT_ACTION, INPUT_HOOK_VALUE}; + if (!callback_run(*this, run, entity, INPUT_HOOK_VALUE, action)) return std::nullopt; + + std::optional value; + if (!lua_isnil(state, -1)) value = (float)luaL_checknumber(state, -1); + lua_pop(state, 1); + return value; +} + // 00864ae0 Runs MC_POST_CURSE_EVAL for the curses a floor got. The curses a mod chose, or those. int LuaEngine::PostCurseEval(int curses) { diff --git a/src/lua_engine.h b/src/lua_engine.h index 003752b..989842a 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -167,6 +167,7 @@ struct LuaEngine int GetPillEffect(int pillEffect, int pillColor); int GetTrinket(int trinket, const RNG& rng); std::optional InputAction(Entity* entity, int hook, int action); + std::optional InputActionValue(Entity* entity, int action); int PostCurseEval(int curses); int PostGetCollectible(const LuaCollectibleDraw& draw); int PreGetCollectible(const LuaCollectibleDraw& draw); diff --git a/src/main.cpp b/src/main.cpp index 4d65581..6c0d50d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -71,7 +71,7 @@ int IsaacMain(int argc, uint8_t** argv) platform.frame_wait(); } - Isaac::Shutdown(); + isaac_shutdown(); platform.engine_shutdown(); return 0; } diff --git a/src/manager.cpp b/src/manager.cpp index 9952b71..839391d 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -571,6 +571,34 @@ void IsaacStartup(int argc, uint8_t** argv) manager.consecutiveResetCount = 0; } +// 009ab700 Shuts the game down when the window closes: an unended daily run counts as lost, the options and changed +// progress (backed up first) are saved, and a run in progress is saved through Game::Exit. +// Netplay's leaving is offline. The daily check's third word (Game 0x2673c) is not identified yet and counts as 0. +// The menus, run, manager, animation cache, shaders and Lua engine are left to the process's exit, as their destructors +// only free memory. +void isaac_shutdown() +{ + Manager& manager = *g_manager; + PersistentGameData& data = manager.persistentGameData; + log_printf(LOG_INFO, "Isaac is shutting down...\n"); + + if (g_game && g_game->dailyChallenge._id != 0 && !g_game->dailyChallenge._isPractice) + { + data.eventCounters[EVENT_COUNTER_DAILYS_STREAK] = 0; + data.IncreaseEventCounter(EVENT_COUNTER_DAILYS_LOSING_STREAK, 1); + data.Save(); + } + manager.optionsConfig.Save(); + if (manager.currentSaveSlot != 0 && data.isChangesMade && data.isFileLoaded) + { + data.isChangesMade = false; + data.BackupSaveFile(); + data.Save(); + } + if (manager.state == MANAGER_STATE_GAME) Game::Exit(true); + log_printf(LOG_INFO, "Isaac has shut down successfully \n"); +} + // The quad covering the screen, in one color. static KAGE::Graphics::ColorQuad screen_quad(KColor color) { diff --git a/src/manager.h b/src/manager.h index 104545b..ca504c3 100644 --- a/src/manager.h +++ b/src/manager.h @@ -202,6 +202,7 @@ public: }; void IsaacStartup(int argc, uint8_t** argv); +void isaac_shutdown(); bool input_poll_active_device(); void loading_images_load(uint32_t seed); void seed_fart_sound_override(int* soundId); diff --git a/src/menu_character.cpp b/src/menu_character.cpp index c7c1b06..f9f1a05 100644 --- a/src/menu_character.cpp +++ b/src/menu_character.cpp @@ -162,7 +162,6 @@ constexpr float FULL_TURN = 360; constexpr float HALF_TURN = 180; constexpr float QUARTER_TURN = 90; constexpr float TAU = 6.2831855f; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float SPIN_EASE_START = 60; constexpr float SPIN_EASE_LENGTH = -60; constexpr float SPIN_SLOWDOWN = 6; diff --git a/src/menu_daily_challenge.cpp b/src/menu_daily_challenge.cpp index 83693be..6c25f19 100644 --- a/src/menu_daily_challenge.cpp +++ b/src/menu_daily_challenge.cpp @@ -27,12 +27,6 @@ constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr float BUTTON_HIDDEN = 96; constexpr int LANGUAGE_ENGLISH = 0; -// The daily streaks (REPENTOGON's EventCounter, the last two past its list). -constexpr int EVENT_DAILYS_PLAYED = 190; -constexpr int EVENT_DAILY_RUN_IS_ACTIVE = 191; -constexpr int EVENT_DAILYS_STREAK = 192; -constexpr int EVENT_DAILYS_BEST_STREAK = 521; -constexpr int EVENT_DAILYS_LOSING_STREAK = 522; // Where the texts sit: the player's name shrunk to fit its width, the countdown, and the streaks scaled down. constexpr float PLAYER_NAME_WIDTH = 175; @@ -148,8 +142,8 @@ void Menu_DailyChallenge::Init(Vector menuPosition) prompt.Initialize(PROMPT_LARGE); reset(); position = menuPosition; - if ((uint32_t)counters[EVENT_DAILYS_BEST_STREAK] < (uint32_t)counters[EVENT_DAILYS_STREAK]) - counters[EVENT_DAILYS_BEST_STREAK] = counters[EVENT_DAILYS_STREAK]; + if ((uint32_t)counters[EVENT_COUNTER_DAILYS_BEST_STREAK] < (uint32_t)counters[EVENT_COUNTER_DAILYS_STREAK]) + counters[EVENT_COUNTER_DAILYS_BEST_STREAK] = counters[EVENT_COUNTER_DAILYS_STREAK]; } // 008d0470 Loads the menu, the leaderboard's sheets, the popup and the prompt again. @@ -218,10 +212,10 @@ void Menu_DailyChallenge::run_start() manager.consecutiveResetCount = 0; if (isPractice) return; - if (data.eventCounters[EVENT_DAILY_RUN_IS_ACTIVE] != 0) - data.IncreaseEventCounter(EVENT_DAILYS_STREAK, -data.eventCounters[EVENT_DAILYS_STREAK]); - data.eventCounters[EVENT_DAILY_RUN_IS_ACTIVE] = 1; - data.IncreaseEventCounter(EVENT_DAILYS_PLAYED, 1); + if (data.eventCounters[EVENT_COUNTER_DAILY_RUN_IS_ACTIVE] != 0) + data.IncreaseEventCounter(EVENT_COUNTER_DAILYS_STREAK, -data.eventCounters[EVENT_COUNTER_DAILYS_STREAK]); + data.eventCounters[EVENT_COUNTER_DAILY_RUN_IS_ACTIVE] = 1; + data.IncreaseEventCounter(EVENT_COUNTER_DAILIES_PLAYED, 1); } // Moves the cursor a step, wrapping: playing needs the day unplayed, practice needs it played. @@ -378,12 +372,13 @@ static void streak_render(ANM2& sprite, Font& font, std::string_view null, const void Menu_DailyChallenge::streaks_render(Font& font, Vector origin) { std::array& counters = g_manager->persistentGameData.eventCounters; - uint32_t streak = (uint32_t)counters[EVENT_DAILYS_STREAK]; - uint32_t losingStreak = (uint32_t)counters[EVENT_DAILYS_LOSING_STREAK]; + uint32_t streak = (uint32_t)counters[EVENT_COUNTER_DAILYS_STREAK]; + uint32_t losingStreak = (uint32_t)counters[EVENT_COUNTER_DAILYS_LOSING_STREAK]; std::string current = losingStreak > streak ? std::format("-{}", losingStreak) : std::format("{}", streak); streak_render(dailyRunSprite, font, CURRENT_STREAK_NULL, current, origin); - streak_render(dailyRunSprite, font, BEST_STREAK_NULL, std::to_string(counters[EVENT_DAILYS_BEST_STREAK]), origin); + streak_render(dailyRunSprite, font, BEST_STREAK_NULL, std::to_string(counters[EVENT_COUNTER_DAILYS_BEST_STREAK]), + origin); } // 008cfd40 Draws the menu, and when it idles the player's name (shrunk to fit), the score while the second text shows diff --git a/src/menu_manager.cpp b/src/menu_manager.cpp index 2073518..32d5ed4 100644 --- a/src/menu_manager.cpp +++ b/src/menu_manager.cpp @@ -61,8 +61,6 @@ constexpr int KEY_REPEAT_DELAY = 49; constexpr int KEY_REPEAT_INTERVAL = 10; constexpr int CHARACTER_MENU_SHOWN = 1; constexpr int MUSIC_LAYER_CHARACTER = 0; -constexpr int EVENT_DAILYS_STREAK = 192; -constexpr int EVENT_DAILYS_BEST_STREAK = 521; KAGE::Graphics::ImagePtr menuColorModSurface; @@ -85,11 +83,6 @@ KColor kcolor_argb(uint32_t argb) return kcolor_make(channel(16), channel(8), channel(0), channel(24)); } -Vector vector_add(Vector a, Vector b) -{ - return vector_make(a.x + b.x, a.y + b.y); -} - // Whether a device's default bindings meet the test for an action: KeyConfigs' saved bindings and the analog action // values the device keeps are not taken over yet. static bool is_device_action(const KAGE::Input::InputDevice& device, ButtonAction action, ActionTest test) @@ -249,8 +242,8 @@ void MenuManager::menus_init() menuGame.Init(menu_position_get(MENU_GAME)); log_printf(LOG_INFO, "Menu Daily Init\n"); menuDailyChallenge.Init(menu_position_get(MENU_DAILY_RUN)); - if ((uint32_t)counters[EVENT_DAILYS_BEST_STREAK] < (uint32_t)counters[EVENT_DAILYS_STREAK]) - counters[EVENT_DAILYS_BEST_STREAK] = counters[EVENT_DAILYS_STREAK]; + if ((uint32_t)counters[EVENT_COUNTER_DAILYS_BEST_STREAK] < (uint32_t)counters[EVENT_COUNTER_DAILYS_STREAK]) + counters[EVENT_COUNTER_DAILYS_BEST_STREAK] = counters[EVENT_COUNTER_DAILYS_STREAK]; log_printf(LOG_INFO, "Menu Character Init\n"); menuCharacter.Init(menu_position_get(MENU_CHARACTER)); log_printf(LOG_INFO, "Menu SpecialSeed Init\n"); diff --git a/src/menu_manager.h b/src/menu_manager.h index 178eda0..3ab1e9b 100644 --- a/src/menu_manager.h +++ b/src/menu_manager.h @@ -206,7 +206,6 @@ extern KAGE::Graphics::ImagePtr menuColorModSurface; KColor kcolor_make(float red, float green, float blue, float alpha); KColor kcolor_argb(uint32_t argb); -Vector vector_add(Vector a, Vector b); bool is_action(ButtonAction action, ActionTest test, int* deviceId = nullptr); bool is_controller_action(int deviceId, ButtonAction action, ActionTest test); bool is_key_repeat(int heldFrames); diff --git a/src/music_manager.h b/src/music_manager.h index 940fd46..280e260 100644 --- a/src/music_manager.h +++ b/src/music_manager.h @@ -64,6 +64,8 @@ enum MusicId : int MUSIC_ARCADE_ROOM = 36, MUSIC_BOSS_OVER = 37, MUSIC_CHALLENGE_FIGHT = 38, + MUSIC_BOSS_RUSH = 39, + MUSIC_JINGLE_BOSS_RUSH_OUTRO = 40, MUSIC_BOSS3 = 41, MUSIC_MOTHER_BOSS = 43, MUSIC_DOGMA_BOSS = 44, @@ -78,6 +80,7 @@ enum MusicId : int MUSIC_ECHOES_REVERSE = 69, MUSIC_JINGLE_SECRET_ROOM_FIND = 85, MUSIC_TREASURE_JINGLE_FIRST = 87, + MUSIC_JINGLE_CHALLENGE_OUTRO = 92, MUSIC_GAME_START_JINGLE = 95, MUSIC_VOID_BOSS = 103, MUSIC_DOWNPOUR = 104, diff --git a/src/nightmare_scene.cpp b/src/nightmare_scene.cpp index 7f9fa1e..484d327 100644 --- a/src/nightmare_scene.cpp +++ b/src/nightmare_scene.cpp @@ -15,7 +15,6 @@ #include #include #include -#include constexpr std::string_view BACKGROUND_DEFAULT = "nightmare_bg.anm2"; constexpr std::string_view SCENE_ANIM = "Scene"; @@ -98,7 +97,6 @@ constexpr std::string_view INTRO_ANIM = "Intro"; constexpr int MUSIC_JINGLE_NIGHTMARE = 96; constexpr int MUSIC_DOGMA_NIGHTMARE = 65; constexpr int STAGE_VOID_INDEX = 9; -constexpr float DEGREES_TO_RADIANS = std::numbers::pi_v / 180; // The stage bar: its icons 27 apart on row 24, Isaac walking a slot over the scene's frames 10 to 40, and the clock's // span of five slots. Icon 17 is a stage not reached. diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index f308984..6e554ab 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -277,7 +277,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 60: return npc_eye_update(npc); case 62: - return (void)NpcAI::ENTITY_PIN(&npc); + return boss_pin_update(npc); case 63: return boss_famine_update(npc); case 64: @@ -555,7 +555,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 826: return npc_hardy_update(npc); case 827: - return (void)NpcAI::ENTITY_FACELESS(&npc); + return npc_faceless_update(npc); case 828: return (void)NpcAI::ENTITY_NECRO(&npc); case 829: @@ -565,7 +565,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 831: return (void)NpcAI::ENTITY_GUTTED_FATTY(&npc); case 832: - return (void)NpcAI::ENTITY_EXORCIST(&npc); + return npc_exorcist_update(npc); case 833: return (void)NpcAI::ENTITY_CANDLER(&npc); case 834: @@ -669,7 +669,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 904: return (void)NpcAI::ENTITY_SIREN(&npc); case 905: - return (void)NpcAI::ENTITY_HERETIC(&npc); + return boss_heretic_update(npc); case 906: return npc.Hornfel_UpdateAI(); case 907: diff --git a/src/npc_ai.h b/src/npc_ai.h index 93789aa..af7794a 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -8,83 +8,12 @@ #include #include -constexpr float PI_F = 3.1415927f; -constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; constexpr float RANDOM_HALF_TURN = 3.14f; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; -constexpr float RADIANS_TO_DEGREES = 57.295776f; constexpr float FULL_TURN_DEGREES = 360; constexpr int GURGLING_TURDLING = 2; constexpr float HALF_TURN_DEGREES = 180; constexpr float RIGHT_ANGLE_DEGREES = 90; -inline Vector vector_add(Vector a, Vector b) -{ - return vector_make(a.x + b.x, a.y + b.y); -} - -inline Vector vector_sub(Vector a, Vector b) -{ - return vector_make(a.x - b.x, a.y - b.y); -} - -inline Vector vector_scale(Vector v, float scale) -{ - return vector_make(v.x * scale, v.y * scale); -} - -inline float vector_dot(Vector a, Vector b) -{ - return a.x * b.x + a.y * b.y; -} - -inline float vector_length_squared(Vector v) -{ - return v.x * v.x + v.y * v.y; -} - -inline float vector_length(Vector v) -{ - return std::sqrt(v.x * v.x + v.y * v.y); -} - -inline bool vector_is_zero(Vector v) -{ - return v.x == 0 && v.y == 0; -} - -// Vector::Normalized: a unit vector along v, or v when it has no length. -inline Vector vector_normalized(Vector v) -{ - float length = vector_length(v); - return length > 0 ? vector_scale(v, 1 / length) : v; -} - -// Vector::Resized: v at a length, or v when it has none. -inline Vector vector_resized(Vector v, float length) -{ - float current = vector_length(v); - return current > 0 ? vector_scale(v, length / current) : v; -} - -// Vector::FromAngle 00a10350: the unit vector at an angle in degrees. -inline Vector vector_from_angle(float degrees) -{ - return vector_make(std::cos(degrees * DEGREES_TO_RADIANS), std::sin(degrees * DEGREES_TO_RADIANS)); -} - -// Vector::GetAngleDegrees 00a10390: a vector's angle in degrees. -inline float vector_angle(Vector v) -{ - return std::atan2(v.y, v.x) * RADIANS_TO_DEGREES; -} - -// random_float: a random fraction of one from the global generator. -inline float random_unit() -{ - return (float)Random() * RANDOM_UNIT_SCALE; -} - // Isaac::Random: a random number below max, or 0 for none. inline int random_below(int max) { diff --git a/src/npc_boil.cpp b/src/npc_boil.cpp index c1bf0e5..317d91a 100644 --- a/src/npc_boil.cpp +++ b/src/npc_boil.cpp @@ -77,8 +77,8 @@ static void boil_grow(Entity_NPC& npc) 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); + if (npc.variant == BOIL_SACK) npc.v1.x *= timescale_factor(BOIL_GROWTH_DAMP, npc.speedMultiplier); + npc.v1.x *= timescale_factor(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) diff --git a/src/npc_boom_fly.cpp b/src/npc_boom_fly.cpp index 45b4c39..a7527ab 100644 --- a/src/npc_boom_fly.cpp +++ b/src/npc_boom_fly.cpp @@ -136,7 +136,7 @@ static void boom_fly_carried_update(Entity_NPC& npc) { 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 grow = timescale_factor(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); diff --git a/src/npc_brain.cpp b/src/npc_brain.cpp index cea24b9..74310b1 100644 --- a/src/npc_brain.cpp +++ b/src/npc_brain.cpp @@ -64,7 +64,7 @@ static Vector brain_target_lead(Entity_NPC& npc) // 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.velocity = vector_scale(npc.velocity, timescale_factor(POISON_MIND_FRICTION, npc.speedMultiplier)); npc.stateFrame -= npc_ticks_get(npc); if (npc.stateFrame < 0 || npc.isCollidesWithGrid) { @@ -102,8 +102,8 @@ 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); + npc.velocity.x *= timescale_factor(BRAIN_FRICTION_X, npc.speedMultiplier); + npc.velocity.y *= timescale_factor(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); diff --git a/src/npc_caves.h b/src/npc_caves.h index dac6fbe..b4d7bb1 100644 --- a/src/npc_caves.h +++ b/src/npc_caves.h @@ -47,10 +47,3 @@ 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_deep_gaper.cpp b/src/npc_deep_gaper.cpp index 64c302d..ad18eac 100644 --- a/src/npc_deep_gaper.cpp +++ b/src/npc_deep_gaper.cpp @@ -1,5 +1,6 @@ #include "npc_depths.h" #include "boss_ai.h" +#include "room_grid.h" #include "sfx_manager.h" #include @@ -7,6 +8,8 @@ constexpr int DEEP_GAPER_HEAD_ODDS = 3; constexpr int DEEP_GAPER_HEADS = 6; constexpr int DEEP_GAPER_LEECH_HEAD = 6; +constexpr float DEEP_GAPER_LEECH_REACH = 80; +constexpr float DEEP_GAPER_LEECH_HEIGHT = -30; // Those in the room as it is entered lie under the water, unseen and untouchable, until the fight is on (its last // enemy gone, its plates pressed, or itself friendly). Then, every 4 frames, one time in 8 (or after 90 frames), with @@ -141,7 +144,7 @@ static void deep_gaper_rise(Entity_NPC& npc) } // 00560570 The Deep Gaper's AI: a gaper that may lie in wait under the water until the fight is on, then rises and -// walks after its prey. The leech headed one throws its leech as it dies. +// walks after its prey. The leech headed one throws its leech onto a free spot as it dies. void npc_deep_gaper_update(Entity_NPC& npc) { if (npc.state == NPC_STATE_INIT) deep_gaper_init(npc); @@ -150,6 +153,10 @@ void npc_deep_gaper_update(Entity_NPC& npc) else if (npc.state == NPC_STATE_ATTACK) deep_gaper_rise(npc); if (npc.isDead && npc.subtype == DEEP_GAPER_LEECH_HEAD) - reconstruction_missing("NpcAI::ENTITY_DEEP_GAPER 00560570: its leech (Entity_NPC::ThrowLeech 0055c4c0, from 30 " - "up onto a free spot within 80)"); + { + bool isWet = g_game->room->waterAmount > 0; + Vector spot = room_free_pickup_position_find( + {.position = npc.pos, .step = DEEP_GAPER_LEECH_REACH, .isAvoidActiveEntities = true, .isAllowPits = isWet}); + leech_throw({.position = npc.pos, .target = spot, .spawner = &npc, .height = DEEP_GAPER_LEECH_HEIGHT}); + } } diff --git a/src/npc_faceless.cpp b/src/npc_faceless.cpp new file mode 100644 index 0000000..a16d51c --- /dev/null +++ b/src/npc_faceless.cpp @@ -0,0 +1,350 @@ +#include "boss_ai.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "path_finder.h" +#include + +// The Faceless' states: asleep then walking, shooting, waking with a burst of blood, and summoning at the Heretic's +// pentagram (the Heretic's Exorcists, 832.1). +constexpr int FACELESS_WALKING = NPC_STATE_IDLE; +constexpr int FACELESS_WAKING = NPC_STATE_SUICIDE; +constexpr int FACELESS_SHOOTING = NPC_STATE_ATTACK; +constexpr int FACELESS_SUMMONING = NPC_STATE_SPECIAL; +constexpr int FACELESS_BLIND_VARIANT = 1; +constexpr int EXORCIST_FACELESS_VARIANT = 1; + +constexpr std::array SUMMON_ANIMS = {"Summon1", "Summon2", "Summon3", "Summon4", "Summon5"}; +constexpr std::array SUMMON_LOOP_ANIMS = {"SummonLoop1", "SummonLoop2", "SummonLoop3", + "SummonLoop4", "SummonLoop5"}; +constexpr int SUMMON_DEFAULT = 1; + +// Asleep until hurt, controlled, or a target (or a woken Faceless) comes within 80. Its anger (v1.x) grows with each +// hit and cools by 0.11 a frame, and drives how often it shoots. +constexpr float WAKE_REACH = 80; +constexpr float FACELESS_WALK_THRESHOLD = 0.1f; +constexpr float CHASE_SPEED = 0.6f; +constexpr int CHASE_PATH_MARKER = 900; +constexpr float WALK_FRICTION = 0.8f; +constexpr float ANGER_COOL = 0.11f; +constexpr float ANGER_SHOT = 7; +constexpr float SHOOT_CHANCE_PER_ANGER = 0.08f; +constexpr float SHOOT_CHANCE = 0.008f; +constexpr float EXORCIST_SHOOT_SHARE = 0.33f; +constexpr float MINECART_SHOOT_SHARE = 0.65f; +constexpr float CONTROLLED_SHOOT_RANGE = 1000; +constexpr int BLIND_GRUMBLE_EVERY = 50; +constexpr float BLIND_GRUMBLE_VOLUME = 0.7f; +constexpr int FACELESS_SPLAT_ODDS = 6; +constexpr float FACELESS_SPLAT_SIZE_MIN = 0.2f; +constexpr float FACELESS_SPLAT_SIZE_RANGE = 0.5f; + +// An Exorcist circles its target within 64 when it sees it, at a pace each one draws once from its own seed. +constexpr int TARGET_VELOCITY_EVERY = 30; +constexpr float CIRCLE_REACH_MAX = 64; +constexpr float CIRCLE_REACH_SHARE = 0.5f; +constexpr float CIRCLE_PUSH = 0.8f; +constexpr float FACELESS_FULL_TURN = 360; + +// The shots: a ring of six (larger and slower falling for the blind one), or the Exorcist's two opposite curving shots. +constexpr float FACELESS_RING_SPEED = 7; +constexpr float BLIND_RING_SPEED = 8; +constexpr float FACELESS_RING_SHOTS = 6; +constexpr float BLIND_SHOT_SCALE = 1.3f; +constexpr float BLIND_SHOT_FALL = -0.06f; +constexpr float EXORCIST_SHOT_SPEED = 7; +constexpr float POOF_HEIGHT = -14; +constexpr float BLIND_POOF_HEIGHT = -16; +constexpr float FACELESS_POOF_DEPTH = 4; +constexpr ColorMod FACELESS_PURPLE = {{0.8f, 0.3f, 1, 1}, {0, 0, 0, 0}, {0.15f, 0, 0.2f}}; + +// Waking: a burst of purple blood, gibs and a fire jet. +constexpr ColorMod WAKE_BLOOD = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; +constexpr float WAKE_JET_HEIGHT = -20; +constexpr int WAKE_GIBS_MIN = 3; +constexpr int WAKE_GIBS_RANGE = 5; +constexpr float WAKE_GIB_SPEED_MIN = 2; +constexpr float WAKE_GIB_SPEED_RANGE = 4; +constexpr int FACELESS_BLOOD_EXPLOSION_SMALL = 3; + +// A dying Faceless may get up again as a Gusher or Pacer, unless killed hard. +constexpr float REVIVE_HEALTH_MIN = -25; +constexpr int REVIVE_PACER_ODDS = 3; + +// Plays an overlay from its first frame. +static void overlay_restart(Entity_NPC& npc, std::string_view name) +{ + if (npc.sprite.SetOverlayAnimation(name) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); +} + +static bool is_overlay_done(Entity_NPC& npc) +{ + return !npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying; +} + +// Whether something wakes a sleeping Faceless: its target near, or another woken Faceless. +static bool is_woken(Entity_NPC& npc) +{ + if (npc.controllerID != -1 || npc.health < npc.maxHitPoints) return true; + + Room& room = *g_game->room; + for (size_t i = 0; i < room.entityList.updateEL.size(); i++) + { + Entity* other = room.entityList.updateEL[i]; + float distance = vector_length(vector_sub(npc.pos, other->pos)); + bool isTarget = npc.HasEntityFlags(FLAG_CHARM) + ? other->IsVulnerableEnemy(nullptr) && !other->HasEntityFlags(FLAG_FRIENDLY) + : other->type == ENTITY_PLAYER && !static_cast(other)->IsInvisible(); + if (isTarget && distance < WAKE_REACH) return true; + + bool isAwake = other->type == ENTITY_FACELESS && static_cast(other)->stateFrame != 0; + if (isAwake && distance < WAKE_REACH) return true; + } + return false; +} + +// Its shots: an Exorcist fires two opposite shots along its aim, the others a ring. +static void faceless_shoot(Entity_NPC& npc) +{ + Entity* poof = nullptr; + if (npc.type == ENTITY_EXORCIST) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (!vector_is_zero(npc.controllerMovement)) aim = vector_normalized(npc.controllerMovement); + + ProjectileParams params; + params.bulletFlags |= PROJECTILE_ORBIT_CW | PROJECTILE_NO_WALL_COLLIDE; + params.targetPosition = npc.pos; + params.isGridCollision = false; + Vector shot = vector_make(aim.x * EXORCIST_SHOT_SPEED, aim.y * EXORCIST_SHOT_SPEED); + npc.FireProjectiles(npc.pos, shot, PROJECTILES_SINGLE, params); + npc.FireProjectiles(npc.pos, vector_make(-shot.x, -shot.y), PROJECTILES_SINGLE, params); + poof = g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BULLET_POOF, .seed = Random()}); + poof->sprite.offset = vector_make(0, POOF_HEIGHT); + poof->renderDepthOffset = FACELESS_POOF_DEPTH; + poof->SetColor(FACELESS_PURPLE, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + else + { + bool isBlind = npc.variant == FACELESS_BLIND_VARIANT; + ProjectileParams params; + params.circleAngle = 0; + if (isBlind) + { + params.scale = BLIND_SHOT_SCALE; + params.fallingAccelModifier = BLIND_SHOT_FALL; + } + npc.FireProjectiles(npc.pos, vector_make(isBlind ? BLIND_RING_SPEED : FACELESS_RING_SPEED, FACELESS_RING_SHOTS), + PROJECTILES_RING, params); + poof = g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BULLET_POOF, .seed = Random()}); + poof->sprite.offset.y = isBlind ? BLIND_POOF_HEIGHT : POOF_HEIGHT; + poof->renderDepthOffset = FACELESS_POOF_DEPTH; + poof->sprite.offset.x = 0; + } + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + npc.v1.x = std::max(npc.v1.x - ANGER_SHOT, 0.0f); +} + +// An Exorcist that sees its target walks a circle about it, the circle turning at its own pace. +static void exorcist_circle(Entity_NPC& npc) +{ + Vector target = npc.CalcTargetPosition(0); + Entity* player = npc.GetPlayerTarget(); + if (npc.IsFrame(TARGET_VELOCITY_EVERY, npc.index)) npc.v2 = player->velocity; + if (!room_check_line(npc.pos, target, LINE_MODE_GROUND, 0)) + return npc.pathfinder.FindGridPath(target, CHASE_SPEED, CHASE_PATH_MARKER, DIRECT_PATH_FAR); + + RNG rng = {npc.initSeed + npc.index, 5, 9, 7}; + Vector away = vector_sub(npc.pos, target); + float drift = rng.RandomFloat() * (float)(g_game->frameCount - npc.spawnFrame); + float angle = (rng.RandomFloat() * FACELESS_FULL_TURN + (drift + drift)) * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + float reach = + std::min(std::max(std::sqrt(away.y * away.y + away.x * away.x) * CIRCLE_REACH_SHARE, 0.0f), CIRCLE_REACH_MAX); + target = vector_make(cosine * reach - sine * 0 + target.x, sine * reach + cosine * 0 + target.y); + npc.friction *= WALK_FRICTION; + npc.AddVelocity_divided(vector_scale(vector_normalized(vector_sub(target, npc.pos)), CIRCLE_PUSH), false); +} + +// Walking: it sleeps until woken, then chases, shooting more the angrier it is. +static void faceless_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", FACELESS_WALK_THRESHOLD); + if (npc.state == FACELESS_SHOOTING) + { + npc.UpdateControllerMovement(false); + if (npc.sprite.overlayAnimState.IsEventTriggered("Shoot")) faceless_shoot(npc); + if (is_overlay_done(npc)) + { + overlay_restart(npc, "Head"); + npc.state = FACELESS_WALKING; + } + } + else if (npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat((float)npc.sprite.GetFrame()); + + if (npc.stateFrame == 0 && is_woken(npc)) npc.stateFrame = 1; + if (Random() % FACELESS_SPLAT_ODDS == 0) + npc.MakeSplat(random_unit() * FACELESS_SPLAT_SIZE_RANGE + FACELESS_SPLAT_SIZE_MIN); + + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= WALK_FRICTION; + } + else if (npc.stateFrame == 0) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + npc.friction *= WALK_FRICTION; + } + else if (npc.type == ENTITY_EXORCIST && npc.controllerID == -1) exorcist_circle(npc); + else npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), CHASE_SPEED, CHASE_PATH_MARKER, DIRECT_PATH_FAR); + + if (npc.state != FACELESS_SHOOTING) + { + bool isShooting = false; + if (npc.controllerID != -1) + { + isShooting = npc.IsTargetInAttackRange(CONTROLLED_SHOOT_RANGE, 0, true); + if (isShooting) npc.UpdateControllerMovement(true); + } + else if (npc.spawnerType != ENTITY_HORNFEL) + { + float chance = std::sqrt(npc.v1.x) * SHOOT_CHANCE_PER_ANGER + SHOOT_CHANCE; + if (npc.type == ENTITY_EXORCIST) chance *= EXORCIST_SHOOT_SHARE; + if (npc.minecart) chance *= MINECART_SHOOT_SHARE; + if (npc.type == ENTITY_FACELESS && npc.variant == FACELESS_BLIND_VARIANT && npc.stateFrame > 0) chance = 1; + isShooting = random_unit() <= chance; + } + if (isShooting) + { + npc.sprite.PlayOverlay("Attack"); + npc.state = FACELESS_SHOOTING; + } + } + + bool isBlind = npc.type == ENTITY_FACELESS && npc.variant == FACELESS_BLIND_VARIANT; + if (isBlind && npc.GetIntervalTicks(BLIND_GRUMBLE_EVERY, (float)(npc.index % BLIND_GRUMBLE_EVERY)) != 0 && + Random() % 2 == 0) + npc.PlaySound(SOUND_BLOBBY_WIGGLE, BLIND_GRUMBLE_VOLUME, 2, false, 1); +} + +// Waking from the pentagram: a burst of purple blood and a fire jet, then it walks. +static void faceless_wake(Entity_NPC& npc) +{ + npc.sprite.PlayOverlay("Transition"); + if (npc.sprite.overlayAnimState.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + Entity* jet = g_game->Spawn( + {.position = npc.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_FIRE_JET, .seed = Random()}); + jet->Update(); + jet->sprite.offset = vector_make(0, WAKE_JET_HEIGHT); + jet->SetCollisionDamage(0); + Entity* burst = g_game->Spawn({.position = npc.pos, + .subType = FACELESS_BLOOD_EXPLOSION_SMALL, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + burst->SetColor(WAKE_BLOOD, -1, COLOR_PRIORITY_DEFAULT, false, true); + Entity* splat = g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->SetColor(WAKE_BLOOD, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + + for (int gibs = (int)(Random() % WAKE_GIBS_RANGE) + WAKE_GIBS_MIN; gibs != 0; gibs--) + { + Vector place = random_direction(); + Vector position = vector_make(place.x * npc.size * 0.5f + npc.pos.x, place.y * npc.size * 0.5f + npc.pos.y); + Vector heading = random_direction(); + float speed = random_unit() * WAKE_GIB_SPEED_RANGE + WAKE_GIB_SPEED_MIN; + Entity* gib = g_game->Spawn({.position = position, + .velocity = vector_make(heading.x * speed, heading.y * speed), + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = Random()}); + gib->SetColor(FACELESS_PURPLE, -1, COLOR_PRIORITY_DEFAULT, false, true); + gib->splatColor = FACELESS_PURPLE; + gib->Update(); + } + } + if (!is_overlay_done(npc)) return; + + npc.sprite.GetLayer(0)->isVisible = true; + npc.state = FACELESS_WALKING; + npc.targetPosition = vector_make(0, 0); + npc.sprite.SetFrame("WalkVert", 0); + overlay_restart(npc, "Head"); + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.stateFrame = 1; +} + +// Summoning at a pentagram point, its body hidden, until its countdown wakes it. +static void faceless_summon(Entity_NPC& npc) +{ + const AnimationData* overlay = npc.sprite.overlayAnimState.animData; + if (!overlay || !overlay->isLooping) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.sprite.GetLayer(0)->isVisible = false; + int point = npc.subtype >= 1 && npc.subtype <= (int)SUMMON_ANIMS.size() ? npc.subtype - 1 : SUMMON_DEFAULT; + npc.sprite.PlayOverlay(SUMMON_ANIMS[point]); + if (is_overlay_done(npc)) npc.sprite.PlayOverlay(SUMMON_LOOP_ANIMS[point]); + } + if (npc.stateFrame <= 0) return; + + npc.stateFrame -= npc_ticks_get(npc); + if (npc.stateFrame < 1) npc.state = FACELESS_WAKING; +} + +// 004faad0 The Faceless (and the Heretic's Exorcists): it sleeps until something comes near, then walks after its +// target firing rings of shots, more often the more it was hurt. Killed, it may rise again as a Gusher or Pacer. +void npc_faceless_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = FACELESS_WALKING; + npc.i1 = 0; + npc.v1.x = 0; + npc.stateFrame = 0; + npc.sprite.SetFrame("WalkVert", 0); + overlay_restart(npc, "Head"); + break; + case FACELESS_WALKING: + case FACELESS_SHOOTING: + faceless_walk(npc); + break; + case FACELESS_WAKING: + faceless_wake(npc); + break; + case FACELESS_SUMMONING: + faceless_summon(npc); + break; + } + + bool isBlind = npc.type == ENTITY_FACELESS && npc.variant == FACELESS_BLIND_VARIANT; + if (npc.isDead && npc.health > REVIVE_HEALTH_MIN && Random() % 2 == 0 && !isBlind) + { + npc.Morph(ENTITY_GUSHER, Random() % REVIVE_PACER_ODDS == 0 ? 1 : 0, 0, -1); + npc.health = npc.maxHitPoints; + npc.isDead = false; + } + + if (npc.pendingDamage > 0) npc.v1.x += npc.pendingDamage; + if (npc.v1.x > 0) npc.v1.x = std::max(npc.v1.x - ANGER_COOL, 0.0f); + if (!vector_is_zero(npc.targetPosition)) + npc.velocity = vector_make((npc.targetPosition.x - npc.pos.x) / npc.friction, + (npc.targetPosition.y - npc.pos.y) / npc.friction); +} + +// 004ec240 (the Faceless part) The Exorcist: the Heretic's summoned ones are Faceless. The plain Exorcist is not +// reconstructed yet. +void npc_exorcist_update(Entity_NPC& npc) +{ + if (npc.variant == EXORCIST_FACELESS_VARIANT) return npc_faceless_update(npc); + reconstruction_missing("NpcAI::ENTITY_EXORCIST 004ec240: the plain Exorcist"); +} diff --git a/src/npc_fly.cpp b/src/npc_fly.cpp index 5c47440..e556cd5 100644 --- a/src/npc_fly.cpp +++ b/src/npc_fly.cpp @@ -35,6 +35,15 @@ constexpr float SUCKER_SHOT_SPEED = 8; constexpr float SUCKER_HARD_SHOT_SPEED = 10; constexpr float BLOODFLY_RING_SHOTS = 6; constexpr float BLOODFLY_SHOT_SCALE = 1.8f; +// The Spit's death shot: lobbed high and slow at the player, bigger and green, splashing where it lands. +constexpr float SPIT_SHOT_TRAJECTORY = 10; +constexpr float SPIT_SHOT_ACCEL_DROP = 0.3f; +constexpr float SPIT_SHOT_SCALE = 1.6f; +constexpr float SPIT_SHOT_SLOW = 0.55f; +constexpr float SPIT_SHOT_RISE_SCALE = 0.7f; +constexpr float SPIT_SHOT_RISE = 13; +constexpr int SPIT_SHOT_COLOR_PRIORITY = 255; +constexpr ColorMod SPIT_SHOT_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; constexpr float MOTER_SPLIT_SPEED = 10; constexpr float MOTER_OVERKILL = -20; @@ -172,7 +181,16 @@ static void sucker_death(Entity_NPC& npc) break; } case SUCKER_SPIT: - reconstruction_missing("npc_fly_update 00506bd0: a Spit's death shot (FireBossProjectiles' projectile)"); + { + Entity_Projectile* shot = npc.FireBossProjectiles(1, npc.GetPlayerTarget()->pos, SPIT_SHOT_TRAJECTORY, {}); + shot->projectileFlags |= PROJECTILE_EXPLODE; + shot->fallingAccel -= SPIT_SHOT_ACCEL_DROP; + shot->scale = SPIT_SHOT_SCALE; + shot->velocity = vector_make(shot->velocity.x * SPIT_SHOT_SLOW, shot->velocity.y * SPIT_SHOT_SLOW); + shot->fallingSpeed = shot->fallingSpeed * SPIT_SHOT_RISE_SCALE - SPIT_SHOT_RISE; + shot->SetColor(SPIT_SHOT_COLOR, -1, SPIT_SHOT_COLOR_PRIORITY, false, true); + break; + } case SUCKER_SOUL: reconstruction_missing("npc_fly_update 00506bd0: a Soul Sucker's death (spawn_tracer_effect198)"); case SUCKER_INK: diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index 8956599..90e36bf 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -1,6 +1,7 @@ #include "npc_basement.h" #include "deathmatch_manager.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_player.h" #include "entity_tear.h" #include "game.h" @@ -329,6 +330,9 @@ 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 float BUTTER_BEAN_SUPER_PUSH = 16; +constexpr float BUTTER_BEAN_UNSOURCED_SIZE = 12; +constexpr LerpRange BUTTER_BEAN_SUPER_FRAMES = {.inMin = 10, .outMin = 20, .outMax = 1}; 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; @@ -413,7 +417,14 @@ void game_butter_bean_fart(const ButterBeanFart& fart) 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)"); + { + float sourceSize = fart.source ? fart.source->size : BUTTER_BEAN_UNSOURCED_SIZE; + LerpRange frames = BUTTER_BEAN_SUPER_FRAMES; + frames.inMax = radius; + float duration = std::floor(lerp_range(distance - (sourceSize + entity->size) + entity->mass, frames)); + entity->AddKnockback(EntityRef(fart.source), vector_scale(away, BUTTER_BEAN_SUPER_PUSH / distance), + (int)duration, true); + } } if (fart.source && fart.source->type == ENTITY_PLAYER && fart.isShowEffect) static_cast(fart.source)->ShootCandle({}); diff --git a/src/npc_gusher.cpp b/src/npc_gusher.cpp index 1dc4484..cac142d 100644 --- a/src/npc_gusher.cpp +++ b/src/npc_gusher.cpp @@ -7,7 +7,6 @@ // 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 SOUND_BLOBBY_WIGGLE = 3; constexpr float WALK_THRESHOLD_GUSHER = 0.1f; constexpr float GUSHER_DEADZONE = 0.1f; diff --git a/src/npc_guts.cpp b/src/npc_guts.cpp index 2d675f9..6c2279a 100644 --- a/src/npc_guts.cpp +++ b/src/npc_guts.cpp @@ -348,7 +348,7 @@ static void guts_move(Entity_NPC& npc) npc_push(npc, vector_scale(gap, -(speed * npc.aiFloat / distance))); if (vector_is_zero(npc.targetPosition)) return; - float keep = npc_friction_scaled(GUTS_FRICTION, npc.speedMultiplier); + float keep = timescale_factor(GUTS_FRICTION, npc.speedMultiplier); if (std::abs(gap.y) <= std::abs(gap.x)) npc.velocity.y = (npc.targetPosition.y - npc.pos.y) * GUTS_ALIGN * npc.speedMultiplier + keep * npc.velocity.y; else npc.velocity.x = (npc.targetPosition.x - npc.pos.x) * GUTS_ALIGN * npc.speedMultiplier + keep * npc.velocity.x; diff --git a/src/npc_hive.cpp b/src/npc_hive.cpp index b077479..3aabc11 100644 --- a/src/npc_hive.cpp +++ b/src/npc_hive.cpp @@ -2,6 +2,7 @@ #include "boss_ai.h" #include "game.h" #include "room.h" +#include "room_grid.h" #include #include @@ -45,6 +46,11 @@ constexpr float DEATH_SCATTER_MIN = 2; constexpr float DEATH_SCATTER = 6; constexpr float HIVE_OVERKILL = -20; +// A Willo hive throws a leech onto a free spot near it instead of a Willo, thrown up from 10. +constexpr float WILLO_LEECH_REACH = 80; +constexpr float WILLO_LEECH_SCATTER = 10; +constexpr float WILLO_LEECH_HEIGHT = -10; + static Entity* spawn_free(Entity_NPC& npc, int type, int variant, const Vector& position, const Vector& velocity, int subType) { @@ -168,7 +174,7 @@ static void hive_attack_start(Entity_NPC& npc) } // As it dies outright it lets loose its brood: flies (now and then a Pooter or attack fly) or the drowned and holy -// kinds' own, a Nest's big spider or Trite, a Willo hive's Willo. Fewer the more enemies are about. +// kinds' own, a Nest's big spider or Trite, a Willo hive's Willo (or leech). Fewer the more enemies are about. static void hive_death(Entity_NPC& npc) { int count = (int)std::ceil(DEATH_SPAWNS / ((float)npc.GetAliveEnemyCount() * DEATH_SPAWN_CROWD + 1)); @@ -184,7 +190,17 @@ static void hive_death(Entity_NPC& npc) reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's ring of flies"); if (npc.type == ENTITY_WILLO_HIVE) { - if (npc.variant != 1) reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: a Willo hive's leech (ThrowLeech)"); + if (npc.variant != 1) + { + bool isWet = g_game->room->waterAmount > 0; + Vector spot = room_free_pickup_position_find({.position = npc.pos, + .step = WILLO_LEECH_REACH, + .isAvoidActiveEntities = true, + .isAllowPits = isWet}); + Vector target = vector_add(spot, vector_scale(random_direction(), WILLO_LEECH_SCATTER)); + leech_throw({.position = npc.pos, .target = target, .spawner = &npc, .height = WILLO_LEECH_HEIGHT}); + continue; + } spawn_free(npc, ENTITY_WILLO, 0, npc.pos, {}, 0); continue; } diff --git a/src/npc_hush.cpp b/src/npc_hush.cpp index 6ce299f..a05f54c 100644 --- a/src/npc_hush.cpp +++ b/src/npc_hush.cpp @@ -264,7 +264,7 @@ void npc_hush_fly_update(Entity_NPC& npc) if (vector_length_squared(npc.velocity) > FLY_MAX_SPEED * FLY_MAX_SPEED) npc.velocity = vector_resized(npc.velocity, FLY_MAX_SPEED); npc.friction *= HUSH_FLY_FRICTION; - npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(1 / npc.friction, npc.speedMultiplier)); + npc.velocity = vector_scale(npc.velocity, timescale_factor(1 / npc.friction, npc.speedMultiplier)); npc.sprite.Play("Fly"); npc.targetPosition = {}; diff --git a/src/npc_maggot.cpp b/src/npc_maggot.cpp index babc6b5..bfd2dff 100644 --- a/src/npc_maggot.cpp +++ b/src/npc_maggot.cpp @@ -54,7 +54,6 @@ 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. @@ -196,16 +195,6 @@ struct MaggotFrame 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) { @@ -520,7 +509,7 @@ static void maggot_wander_update(Entity_NPC& npc, MaggotFrame& frame) 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); + npc.velocity.y *= timescale_factor(MAGGOT_FRICTION_Y, npc.speedMultiplier); if (npc.type == ENTITY_SPITTY && npc.variant == SPITTY_TAINTED && npc.sprite.IsEventTriggered("Shoot")) { @@ -555,7 +544,7 @@ static void dank_charge_update(Entity_NPC& npc, MaggotFrame& frame) else { npc.friction = 1; - float keep = 1 - npc_friction_scaled(DANK_STEER_FRICTION, npc.speedMultiplier); + float keep = 1 - timescale_factor(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); @@ -615,7 +604,7 @@ static void maggot_charge_update(Entity_NPC& npc, MaggotFrame& frame) if (npc.controllerID != -1) cell = npc.v2; if (npc.type != ENTITY_GURGLING) { - float keep = 1 - npc_friction_scaled(CHARGE_ALIGN_FRICTION, npc.speedMultiplier); + float keep = 1 - timescale_factor(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; @@ -836,7 +825,7 @@ void npc_maggot_update(Entity_NPC& npc) 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); + room_path_raise_at(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); diff --git a/src/npc_one_tooth.cpp b/src/npc_one_tooth.cpp index 4e9efb2..855c2f9 100644 --- a/src/npc_one_tooth.cpp +++ b/src/npc_one_tooth.cpp @@ -94,8 +94,8 @@ static void one_tooth_circle(Entity_NPC& npc, int ticks) // The original clamps the heading's x into the facing, which always lands on it. Vector heading = vector_normalized(move); heading.x = npc.sprite.isFlipX ? -1 : 1; - float ease = npc_friction_scaled(1 - (npc.controllerID == -1 ? ONE_TOOTH_EASE : CONTROLLED_ONE_TOOTH_EASE), - npc.speedMultiplier); + float ease = timescale_factor(1 - (npc.controllerID == -1 ? ONE_TOOTH_EASE : CONTROLLED_ONE_TOOTH_EASE), + npc.speedMultiplier); npc.velocity.x = (heading.x * ONE_TOOTH_SPEED - npc.velocity.x) * (1 - ease) + npc.velocity.x; npc.velocity.y = (heading.y * ONE_TOOTH_SPEED - npc.velocity.y) * (1 - ease) + npc.velocity.y; } diff --git a/src/npc_poky.cpp b/src/npc_poky.cpp index 18fab60..9b784d5 100644 --- a/src/npc_poky.cpp +++ b/src/npc_poky.cpp @@ -105,7 +105,7 @@ static void poky_dash(Entity_NPC& npc) npc.friction *= POKY_DASH_FRICTION; npc_push(npc, npc.targetPosition); Vector cell = g_game->room->GetGridPosition(npc.pathfinder.gridIndex); - float snap = npc_friction_scaled(POKY_LANE_SNAP, npc.speedMultiplier); + float snap = timescale_factor(POKY_LANE_SNAP, npc.speedMultiplier); if (std::abs(npc.targetPosition.x) <= std::abs(npc.targetPosition.y)) { npc.pos.x = npc.pos.x * POKY_LANE_SNAP + cell.x * POKY_LANE_SNAP; diff --git a/src/npc_vis.cpp b/src/npc_vis.cpp index 405f435..0d7f556 100644 --- a/src/npc_vis.cpp +++ b/src/npc_vis.cpp @@ -265,7 +265,7 @@ static void vis_versa_target(Entity_NPC& npc) if (vector_is_zero(npc.targetPosition)) npc.targetPosition = aim; else { - float ease = 1 - npc_friction_scaled(VIS_VERSA_CONTROL_EASE, npc.speedMultiplier); + float ease = 1 - timescale_factor(VIS_VERSA_CONTROL_EASE, npc.speedMultiplier); npc.targetPosition = vector_add(npc.targetPosition, vector_scale(vector_sub(aim, npc.targetPosition), ease)); } return; diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 3552f82..7d97c7e 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -831,8 +831,73 @@ bool PathFinder::HasPathToPos(const Vector& position, bool isIgnorePoop) return false; } -// 007e8010 -void PathFinder::SimulatePlayerMovement(const Vector&, float) +// 007e8010 Moves its owner as a player walks with that input, in two half steps: the input (capped at 1, without its +// vertical part for a falling grounded owner) scales with speed into the move direction and the way it faces, the +// velocity across it fades, it accelerates up to speed * 4.41 and is damped, more slowly while the slippery countdown +// lasts. A falling grounded owner keeps falling instead of being damped vertically. +void PathFinder::SimulatePlayerMovement(const Vector& input, float speed) { - reconstruction_missing("PathFinder::SimulatePlayerMovement 007e8010"); + constexpr int SLIPPERY_COUNTDOWN = 60; + constexpr float INPUT_SPEED_SHARE = 0.25f; + constexpr float FALL_PULL = 0.225f; + constexpr float MAX_SPEED_PER_SPEED = 4.41f; + constexpr float PUSH_DRY = -0.2f; + constexpr float PUSH_SLIPPERY = 0.5f; + constexpr float DRAG_DRY = 0.775f; + constexpr float DRAG_SLIPPERY = 0.96f; + constexpr float KEEP_DRY = 0.8f; + constexpr float ACCEL_BASE = 3; + constexpr float ACCEL_SCALE = 0.4f; + constexpr float ACCEL_SLIPPERY_SHARE = 0.25f; + auto lerp = [](float from, float to, float t) { + return from + (to - from) * t; + }; + + bool isFalling = entity->HasEntityFlags(FLAG_APPLY_GRAVITY) && entity->entityGridCollisionClass == GRIDCOLL_GROUND; + Vector walk = vector_make(input.x, isFalling ? 0 : input.y); + float length = vector_length(walk); + if (length > 1 && length > 0) walk = vector_make(input.x * (1 / length), walk.y * (1 / length)); + float scale = speed * INPUT_SPEED_SHARE + (1 - INPUT_SPEED_SHARE); + moveDirection = vector_make(scale * walk.x, scale * walk.y); + + if (std::fabs(moveDirection.x) > std::fabs(moveDirection.y)) + direction = moveDirection.x >= 0 ? PATH_DIRECTION_RIGHT : PATH_DIRECTION_LEFT; + else if (moveDirection.y < 0) direction = PATH_DIRECTION_UP; + else direction = moveDirection.y > 0 ? PATH_DIRECTION_DOWN : PATH_DIRECTION_NONE; + + if (entity->HasEntityFlags(FLAG_SLIPPERY_PHYSICS)) moveCountdown = SLIPPERY_COUNTDOWN; + else moveCountdown = std::max(moveCountdown - 1, 0); + float slippery = entity->HasEntityFlags(FLAG_SLOW) ? 0 : (float)moveCountdown / SLIPPERY_COUNTDOWN; + float pushShare = lerp(PUSH_DRY, PUSH_SLIPPERY, slippery); + float damping = std::sqrt(lerp(DRAG_DRY, DRAG_SLIPPERY, slippery)); + float maxSpeed = speed * MAX_SPEED_PER_SPEED; + Vector half = vector_scale(entity->velocity, 0.5f); + + for (int step = 0; step < 2; step++) + { + bool isMoving = moveDirection.x != 0 || moveDirection.y != 0; + if (isMoving && !isFalling) + { + float along = half.y * moveDirection.y + half.x * moveDirection.x; + Vector kept = vector_make(along * moveDirection.x, along * moveDirection.y); + float keep = std::sqrt(lerp(KEEP_DRY, 1, slippery)); + half = vector_make((half.x - kept.x) * keep + kept.x, (half.y - kept.y) * keep + kept.y); + } + Vector before = half; + + float push = pushShare * (half.y * moveDirection.y + half.x * moveDirection.x); + float accel = ((push > 0 ? push : 0) / speed + ACCEL_BASE) * ACCEL_SCALE; + accel = (accel * ACCEL_SLIPPERY_SHARE - accel) * slippery + accel; + half = vector_make(half.x + moveDirection.x * 0.5f * accel, half.y + moveDirection.y * 0.5f * accel); + + float lengthSquared = half.x * half.x + half.y * half.y; + if (slippery > 0 && lengthSquared > maxSpeed * maxSpeed) + { + float moved = std::sqrt(lengthSquared); + if (moved > 0) half = vector_scale(half, vector_length(before) / moved); + } + half.x *= damping; + half.y = isFalling ? half.y + FALL_PULL : half.y * damping; + } + entity->velocity = vector_make(half.x + half.x, half.y + half.y); } diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index 1eb7413..690daa9 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -38,6 +38,7 @@ enum EventCounter : int EVENT_COUNTER_ISAAC_KILLS = 11, EVENT_COUNTER_SATAN_KILLS = 13, EVENT_COUNTER_SHELL_GAMES_PLAYED = 14, + EVENT_COUNTER_DEVIL_DEALS_TAKEN = 16, EVENT_COUNTER_BLOOD_DONATIONS = 17, EVENT_COUNTER_SLOT_MACHINES_BROKEN = 18, EVENT_COUNTER_DONATIONS = 20, @@ -53,12 +54,16 @@ enum EventCounter : int EVENT_COUNTER_DELIRIUM_KILLS = 187, EVENT_COUNTER_RUN_MASK_LOW = 188, EVENT_COUNTER_DAILIES_PLAYED = 190, + EVENT_COUNTER_DAILY_RUN_IS_ACTIVE = 191, + EVENT_COUNTER_DAILYS_STREAK = 192, EVENT_COUNTER_MOTHER_KILLS = 491, EVENT_COUNTER_BEAST_KILLS = 492, EVENT_COUNTER_BATTERY_BUMS_KILLED = 494, EVENT_COUNTER_BATTERY_BUM_ITEMS = 495, EVENT_COUNTER_RUN_MASK_HIGH = 496, - EVENT_COUNTER_ONLINE_BEST_STREAK = 498 + EVENT_COUNTER_ONLINE_BEST_STREAK = 498, + EVENT_COUNTER_DAILYS_BEST_STREAK = 521, + EVENT_COUNTER_DAILYS_LOSING_STREAK = 522 }; // How a Checksum folds bytes in: 4-byte words added to the state rotated right by 1, or CRC-32. diff --git a/src/platform.cpp b/src/platform.cpp index 30c0cd9..f60ae5d 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -247,7 +247,8 @@ void Platform::engine_init() isEngineInitialized = true; } -// 00a71770 Shuts KAGE down: input, sound and graphics, then the framebuffer and the window. +// 00a71770 Shuts KAGE down: input, sound and graphics, then the framebuffer and the window, and SDL with its threads, +// so none still runs while the process exits. // Its EOS release, log closing, compressor, multiplayer threads, video manager and heaps have nothing here to free. void Platform::engine_shutdown() { @@ -262,6 +263,7 @@ void Platform::engine_shutdown() context = nullptr; window = nullptr; isEngineInitialized = false; + SDL_Quit(); } // Opens the window at its default size with its GL context and shows it, as Graphics::Manager::Init began. diff --git a/src/player_manager.cpp b/src/player_manager.cpp index fa93000..93d8527 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -1,6 +1,7 @@ #include "player_manager.h" #include "entity_effect.h" #include "entity_familiar.h" +#include "familiar_variants.h" #include "entity_npc.h" #include "entity_player.h" #include "boss_ai.h" @@ -802,7 +803,7 @@ void PlayerManager::trigger_new_room_effects() { bool isFamiliar = entity && entity->type == ENTITY_FAMILIAR; if (isFamiliar && (entity->variant == FAMILIAR_BLOOD_OATH || entity->variant == FAMILIAR_PASCHAL_CANDLE)) - reconstruction_missing("FUN_0062c8a0, the new room effects of Blood Oath and Paschal Candle"); + familiar_room_effects_sync(*static_cast(entity)); } } @@ -933,8 +934,7 @@ bool PlayerManager::replace_player(Entity_Player* oldPlayer, Entity_Player* newP auto* familiar = entity->type == ENTITY_FAMILIAR ? static_cast(entity) : nullptr; bool isRoomEffect = familiar && (familiar->variant == FAMILIAR_BLOOD_OATH || familiar->variant == FAMILIAR_PASCHAL_CANDLE); - if (isRoomEffect && familiar->player == newPlayer) - reconstruction_missing("FUN_0062c8a0, the new room effects of Blood Oath and Paschal Candle"); + if (isRoomEffect && familiar->player == newPlayer) familiar_room_effects_sync(*familiar); } newPlayer->RemoveStatusEffects(); newPlayer->EvaluateItems(); diff --git a/src/pocket_items.h b/src/pocket_items.h index a1478da..128e465 100644 --- a/src/pocket_items.h +++ b/src/pocket_items.h @@ -39,5 +39,6 @@ PocketUseEnd card_effect_run(PocketUse& use, int card); void pill_effect_run(PocketUse& use, int pillEffect, std::string_view name); void game_level_collectibles_reroll(Game& game); void game_charm_fart(const Vector& position, float radius, Entity* source); +bool game_enemy_devolve(Entity& entity, Entity** outEntity); void game_level_pickups_reroll(Game& game, uint32_t seed); bool teleport_random_room_of_types(Entity_Player& player, std::span roomTypes, bool isPreferUnvisited); diff --git a/src/room.cpp b/src/room.cpp index 4f7888e..9f821fe 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -7,6 +7,7 @@ #include "entity_npc.h" #include "game.h" #include "grid_entity_door.h" +#include "grid_entity_stairs.h" #include "log.h" #include "lua_engine.h" #include "manager.h" @@ -182,7 +183,6 @@ constexpr float DEAL_CHANCE_GOAT_HEAD = 66.6f; constexpr float DEAL_RECENT_SCALE = 0.25f; constexpr float DEAL_LAST_SCALE = 0.5f; constexpr uint32_t GREED_DEAL_WAVE = 11; -constexpr int COLLECTIBLE_PENTAGRAM = 51; constexpr int COLLECTIBLE_GOAT_HEAD = 215; // The doors of a cleared boss room: what unlocks them and the stages they open on, the secret exit kinds, the deal @@ -214,7 +214,6 @@ constexpr int CARD_SOUL_OF_CAIN = 83; constexpr int SECRET_SHOP_COLUMN = 10; constexpr int EFFECT_SHOP_LADDER = 156; constexpr int SOUND_SHOP_STAIRS = 916; -constexpr int STAIRS_SECRET_SHOP = 2; constexpr float DOOR_OUTLINE_OFFSET = 15; // The quest doors of the alternate path's second floors: the rooms holding them and the rooms they lead to. @@ -240,7 +239,6 @@ constexpr float RAIN_FADE = 0.02f; constexpr float RAIN_INTENSITY_MIN = 0.01f; constexpr float RAIN_PI = 3.14f; constexpr float QUARTER_TURN = 1.5707964f; -constexpr float DEGREES_TO_RADIANS = 0.017453292f; // The screen color: how much secret rooms wash it out, pitch black rooms brighten it and the Mines' lava tints it, // and how fast it fades. @@ -304,11 +302,6 @@ constexpr float MUSIC_CROSSFADE_INSTANT = 1; constexpr int TREASURE_JINGLE_COUNT = 4; -static float random_unit() -{ - return (float)Random() * 2.3283064e-10f; -} - static bool is_greed() { return g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; @@ -378,8 +371,8 @@ static void room_reset(Room& room) entity = nullptr; } room.doors.fill(nullptr); - g_game->ambush._isActive = false; - g_game->ambush._currentWave = 0; + g_game->ambush.isActive = false; + g_game->ambush.currentWave = 0; room.isCardAgainstHumanity = false; room.isInitialized = false; room.isFirstVisit = false; diff --git a/src/room.h b/src/room.h index d9425f3..51ed25f 100644 --- a/src/room.h +++ b/src/room.h @@ -28,6 +28,7 @@ constexpr uint32_t ROOM_DESCRIPTOR_FLAG_ALT_BOSS_MUSIC = 1 << 6; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_FLOODED = 1 << 8; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_PITCH_BLACK = 1 << 9; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_CURSED_MIST = 1 << 13; +constexpr uint32_t ROOM_DESCRIPTOR_FLAG_MAMA_MEGA = 1 << 14; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_NO_WALLS = 1 << 15; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED = 1 << 16; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT = 1 << 18; @@ -346,6 +347,9 @@ public: void greed_decorations_make(); bool SpawnGridEntity(int gridIndex, GridEntityType type, int variant, uint32_t seed, int varData); void RemoveGridEntity(int gridIndex, int pathTrail, DecorationRemoval removal); + void RemoveGridEntityImmediate(int gridIndex, int pathTrail, DecorationRemoval removal); + void RespawnEnemies(); + void MamaMegaExplosion(Vector position, Entity_Player* player); void RestoreState(); void hold_trigger_output_entities(); Entity* hold_entity_in_spawner(Entity& entity, int group); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index dec1c3b..fa5a7ea 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -49,7 +49,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 SOUND_DOOR_HEAVY_OPEN = 36; constexpr int SOUND_VAMP_GULP_CLEAR = 157; constexpr int SOUND_VAMP_DOUBLE_CLEAR = 614; constexpr int ACHIEVEMENT_LITTLE_CHAD = 25; diff --git a/src/room_config.h b/src/room_config.h index 8526784..bdf267b 100644 --- a/src/room_config.h +++ b/src/room_config.h @@ -11,6 +11,8 @@ constexpr int STAGE_SLOTS = 37; constexpr int MINIBOSS_SLOTS = 16; +// A challenge room's subtype for a boss challenge. +constexpr int CHALLENGE_SUBTYPE_BOSS = 1; // Which room set of a stage a lookup reads: the normal one, the Greed one, or the one the game's difficulty picks. enum RoomMode : int diff --git a/src/room_grid.cpp b/src/room_grid.cpp index f5a19cd..da7e0cd 100644 --- a/src/room_grid.cpp +++ b/src/room_grid.cpp @@ -1,4 +1,5 @@ #include "room_grid.h" +#include "capsule.h" #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" @@ -8,6 +9,7 @@ #include "npc_ai.h" #include "room.h" #include +#include #include // The partitions a query bit looks in, in the order QueryRadius goes through them. @@ -82,6 +84,62 @@ EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t return found; } +// 0041ab50 (EntityList::query_player_capsule_hits) The entities a capsule touches that queries may see: those of the +// partitions asked for within its bounding box, then the players, then the effects. +EntityList_EL entity_query_capsule(const Capsule& capsule, uint32_t partitions) +{ + EntityList& list = g_game->room->entityList; + EntityList_EL found; + Vector low{}; + Vector high{}; + capsule.get_bounding_box(low, high); + Vector center = vector_scale(vector_add(low, high), 0.5f); + Vector extent = vector_scale(vector_sub(high, low), 0.5f); + auto isTouched = [&](Entity* entity) { + return !entity->HasEntityFlags(FLAG_NO_QUERY) && Capsule::Collide(capsule, entity->GetCollisionCapsule({})); + }; + + for (const PartitionQuery& query : PARTITION_QUERIES) + if (partitions & query.bit) list.partitions[query.partition].query_box(found, center, extent); + if (partitions & QUERY_PLAYERS) + for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player); + std::erase_if(found, [&](Entity* entity) { return !isTouched(entity); }); + if (partitions & QUERY_EFFECTS) + for (Entity* effect : list.effectEL) + if (isTouched(effect)) found.push_back(effect); + return found; +} + +// 00589f90 (Room::CanSpawnObstacleAtPos) Whether an obstacle could stand on a position's cell (off the grid, as the +// room says of cell -1). +bool room_can_spawn_obstacle_at(const Vector& position, bool isForced) +{ + Room& room = *g_game->room; + 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); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + return room.CanSpawnObstacleAtPosition(isInside ? room.gridWidth * row + column : -1, isForced); +} + +// 004cdd80 (Room::RaiseGridPathAtPos) Raises the path cost of a position's cell to a level below 951, keeping its +// thousands, false off the grid. +bool room_path_raise_at(const Vector& position, int level) +{ + constexpr int PATH_LEVELS = 1000; + constexpr int PATH_LEVEL_MAX = 950; + + Room& room = *g_game->room; + 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); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return false; + uint32_t index = (uint32_t)(room.gridWidth * row + column); + if (index >= room.gridPaths.size() || level > PATH_LEVEL_MAX) return false; + + int current = room.gridPaths[index] % PATH_LEVELS; + if (current < level) room.gridPaths[index] = room.gridPaths[index] - current + level; + return true; +} + // 00456620 The grid entity on the cell at a position, if any. GridEntity* room_grid_entity_at(const Vector& position) { @@ -253,3 +311,13 @@ void Room::RemoveGridEntity(int gridIndex, int pathTrail, DecorationRemoval remo gridPaths[gridIndex] = pathTrail; pendingGridRemovals.insert(gridIndex); } + +// 0081e980 Removes a cell's grid entity at once, unless it is a kept decoration, leaving a path trail. +void Room::RemoveGridEntityImmediate(int gridIndex, int pathTrail, DecorationRemoval removal) +{ + if ((uint32_t)gridIndex >= ROOM_GRID_CELLS || !gridEntities[gridIndex]) return; + if (gridEntities[gridIndex]->type == GRID_DECORATION && removal == DECORATION_KEPT) return; + + gridPaths[gridIndex] = pathTrail; + delete std::exchange(gridEntities[gridIndex], nullptr); +} diff --git a/src/room_grid.h b/src/room_grid.h index c2cb1e3..8c0831e 100644 --- a/src/room_grid.h +++ b/src/room_grid.h @@ -40,7 +40,10 @@ struct GridDestroy }; EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t partitions); +EntityList_EL entity_query_capsule(const Capsule& capsule, uint32_t partitions); GridEntity* room_grid_entity_at(const Vector& position); +bool room_can_spawn_obstacle_at(const Vector& position, bool isForced); +bool room_path_raise_at(const Vector& position, int level); int room_clamped_grid_index_get(Room& room, Vector position); Vector room_free_pickup_position_find(const FreeSpotSearch& search); Vector room_free_tile_position_find(const Vector& position, float distanceThreshold); diff --git a/src/room_lighting.cpp b/src/room_lighting.cpp index 1cbe67e..892085c 100644 --- a/src/room_lighting.cpp +++ b/src/room_lighting.cpp @@ -174,14 +174,6 @@ Vector RandomVector(uint32_t seed) return vector_make(std::cos(angle), std::sin(angle)); } -// Vector::Rotated: v turned by an angle in degrees. -static Vector vector_rotated(Vector v, float degrees) -{ - float cos = std::cos(degrees * DEGREES_TO_RADIANS); - float sin = std::sin(degrees * DEGREES_TO_RADIANS); - return vector_make(v.x * cos - v.y * sin, v.y * cos + v.x * sin); -} - // A light color multiplied by an entity's sprite color. static ColorMod color_through(ColorMod color, const ColorMod& other) { @@ -320,9 +312,9 @@ static void player_light_render(Room& room, Entity_Player& player, Vector offset if (player.IsHologram()) strength *= HOLOGRAM_LIGHT; auto isCostume = [&](int collectible) { - return is_item_costume_visible(player, items.GetCollectible(collectible), -1); + return player.IsItemCostumeVisible(items.GetCollectible(collectible), -1); }; - bool isFlame = is_item_costume_visible(player, items.GetCollectible(COLLECTIBLE_FIRE_MIND_COSTUME), 0) || + bool isFlame = player.IsItemCostumeVisible(items.GetCollectible(COLLECTIBLE_FIRE_MIND_COSTUME), 0) || isCostume(COLLECTIBLE_FIRE_MIND) || player.IsNullItemCostumeVisible(NULL_ITEM_BRIMSTONE_FLAME, 0); bool isGhostly = isCostume(COLLECTIBLE_SPIRIT_OF_THE_NIGHT) || isCostume(COLLECTIBLE_TELEPATHY_BOOK) || isCostume(COLLECTIBLE_EYE_OF_THE_OCCULT); diff --git a/src/room_render.cpp b/src/room_render.cpp index d9f76b8..a6ce7f8 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -350,11 +350,6 @@ static bool is_curse_of_darkness() return (~Seeds::GetPreventedCurses() & curses & CURSE_OF_DARKNESS) != 0; } -static Vector vector_add(Vector a, Vector b) -{ - return vector_make(a.x + b.x, a.y + b.y); -} - // Sets the blend mode of a sprite's first layer. void layer_blend_set(ANM2& sprite, KAGE::Graphics::BlendType type) { @@ -438,20 +433,6 @@ Vector minecart_offset(Entity& entity) return frame ? frame->pos : Vector{}; } -// 0075d900 Whether an item's costume draws on a layer of the player's sprite, or on any layer for -1. -bool is_item_costume_visible(Entity_Player& player, ItemConfig_Item* item, int layer) -{ - int first = std::max(layer, 0); - int last = layer < 0 ? COSTUME_LAYER_COUNT : layer + 1; - - for (int i = first; i < last; i++) - { - int index = player.playerCostumeMap[i].index; - if (index >= 0 && player.costumeSpriteDescs[index].item == item) return true; - } - return false; -} - // The shared pixelation amount: full under Retro Vision, otherwise easing in and out over the game's pixelation timer. static float pixelation_amount(Game& game) { @@ -1109,9 +1090,9 @@ static void entity_glow_render(Room& room, Entity& entity, Vector offset) } ItemConfig& items = g_manager->itemConfig; - bool isFireMind = is_item_costume_visible(player, items.GetCollectible(COLLECTIBLE_FIRE_MIND_COSTUME), 0) || + bool isFireMind = player.IsItemCostumeVisible(items.GetCollectible(COLLECTIBLE_FIRE_MIND_COSTUME), 0) || player.HasCollectible(COLLECTIBLE_FIRE_MIND); - if (!isFireMind && !is_item_costume_visible(player, items.GetNullItem(NULL_ITEM_BRIMSTONE_FLAME), 0)) return; + if (!isFireMind && !player.IsItemCostumeVisible(items.GetNullItem(NULL_ITEM_BRIMSTONE_FLAME), 0)) return; Vector direction = RandomVector(rng.Next()); float distance = rng.RandomFloat() * FLAME_FLICKER; diff --git a/src/room_render.h b/src/room_render.h index 1486784..9bf6bde 100644 --- a/src/room_render.h +++ b/src/room_render.h @@ -60,6 +60,5 @@ KColor kcolor_apply(const ColorMod& color, const KColor& input); KColor image_texel_get(KAGE::Graphics::ImageBase& image, uint32_t x, uint32_t y); void room_ash_step_clear(Room& room, Vector foot); Vector minecart_offset(Entity& entity); -bool is_item_costume_visible(Entity_Player& player, ItemConfig_Item* item, int layer); void layer_blend_set(ANM2& sprite, KAGE::Graphics::BlendType type); void entity_light_render(Room& room, Entity& entity, Vector offset); diff --git a/src/room_special.h b/src/room_special.h index ca5cbb8..b6938be 100644 --- a/src/room_special.h +++ b/src/room_special.h @@ -52,4 +52,3 @@ void room_restock_trigger(Room& room, int gridIndex, int shopItemId); void room_restock_partial(Room& room); void game_random_room_move(Game& game, bool isErrorRoom, uint32_t seed, Entity_Player* player); void npc_shopkeeper_update(Entity_NPC& npc); -Entity_Player* player_nearest_find(const Vector& position); diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 00a52b2..6b42564 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -14,14 +14,12 @@ #include #include #include -#include constexpr const char* VERSUS_SCREEN_ANM2 = "gfx/ui/boss/versusscreen.anm2"; constexpr const char* OLD_ROOM_SURFACE = "Old Room Surface"; constexpr const char* NEW_ROOM_SURFACE = "New Room Surface"; constexpr const char* ANIMATION_DEATH_TELEPORT = "DeathTeleport"; constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); -constexpr float DEGREES_TO_RADIANS = std::numbers::pi_v / 180; constexpr int PIXELATION_DURATION = 30; constexpr int WALK_DURATION = 7; constexpr int UNDIRECTED_DURATION = 3; diff --git a/src/room_update.cpp b/src/room_update.cpp index 6bbc48f..c07fd11 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -5,6 +5,7 @@ #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" +#include "grid_entity_pit.h" #include "log.h" #include "manager.h" #include "room.h" @@ -13,8 +14,10 @@ #include "room_render.h" #include "seeds.h" #include +#include #include #include +#include // The grid paths an entity leaves: a permanent mark, the value it fades back to, and how fast it fades. constexpr int GRID_PATH_DECAY_FRAMES = 3; @@ -28,6 +31,8 @@ constexpr int GRID_TIMER_MAX = 99; constexpr int ROOM_CLEAR_DELAY = 10; constexpr int ROOM_CLEAR_DELAY_DUNGEON_EXIT = 20; constexpr int OUTPUT_GROUP_ROOM_CLEAR = 9; +// The fireplaces the pressure plates put out: red to normal, purple to blue. +constexpr std::array, 2> FIREPLACE_COOLINGS = {{{1, 0}, {3, 2}}}; constexpr int DUNGEON_ROTGUT = 2; constexpr int DUNGEON_ROTGUT_HEART = 3; @@ -152,7 +157,6 @@ constexpr int BOSS_MIN_MIN = 91; 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 uint32_t RNG_SHIFT_COUPON_1 = 1; constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; @@ -240,11 +244,6 @@ static bool is_greed() return g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; } -static float random_unit() -{ - return (float)Random() * 2.3283064e-10f; -} - static Entity* entity_spawn(int type, int variant, Vector position, Vector velocity, uint32_t seed) { return g_game->Spawn({.position = position, .velocity = velocity, .type = type, .variant = variant, .seed = seed}); @@ -396,9 +395,9 @@ static void clear_update(Room& room) bool isDungeon = room.roomType == ROOM_DUNGEON; int dungeonKind = isDungeon ? room.descriptor->data->subtype : 0; - if (!room.IsClear() && !game.ambush._isActive && !isEnemyLeft && room.roomClearDelay < 1) + if (!room.IsClear() && !game.ambush.isActive && !isEnemyLeft && room.roomClearDelay < 1) output_trigger(room, OUTPUT_GROUP_ROOM_CLEAR); - if (game.ambush._isActive || isEnemyLeft) + if (game.ambush.isActive || isEnemyLeft) { room.roomClearDelay = isDungeon && dungeonKind == DUNGEON_ROTGUT_HEART ? ROOM_CLEAR_DELAY_DUNGEON_EXIT : ROOM_CLEAR_DELAY; @@ -427,7 +426,6 @@ static void clear_update(Room& room) // 008024f0 The pressure plates, unless already triggered: the room remembers whether it has any, and once none of // its plain plates is left unpressed (or a reward plate is pressed) the plates count as triggered and the room's // fireplaces go out, red ones turning normal and purple ones blue. -// The fireplaces' morphs are not reconstructed yet. static void pressure_plates_update(Room& room) { if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED) return; @@ -451,9 +449,20 @@ static void pressure_plates_update(Room& room) if ((plates == 0 && !isRewardPressed) || unpressed != 0) return; room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED; - for (Entity* entity : room.entityList.updateEL) - if (is_npc_type(entity->type) && entity->type == ENTITY_FIREPLACE && (entity->variant == 1 || entity->variant == 3)) - reconstruction_missing("Room::update_pressure_plates 008024f0: the fireplaces' morph"); + for (size_t i = 0; i < room.entityList.updateEL.size(); i++) + { + Entity* entity = room.entityList.updateEL[i]; + if (!is_npc_type(entity->type) || entity->type != ENTITY_FIREPLACE) continue; + + auto& fireplace = *static_cast(entity); + for (auto [from, to] : FIREPLACE_COOLINGS) + { + if (fireplace.variant != from) continue; + fireplace.Morph(ENTITY_FIREPLACE, to, fireplace.subtype, -1); + fireplace.state = 0; + fireplace.Update(); + } + } } // Leaves through a door slot: the rewind state is saved and the door left recorded, a devil or angel room is made the @@ -776,8 +785,8 @@ static void walls_bleed_update(Room& room) } } -// Flush! fills the room with water, flooding it once nearly full, and water cools the lava down until it is gone. -// The pits' collisions under the changing water and lava are not reconstructed yet. +// Flush! fills the room with water, flooding it once nearly full, and water cools the lava down until it is gone, its +// pits solid once it hardens and the screen's color following. Flush!'s pits under the flood are not reconstructed yet. static void flood_update(Room& room) { if (room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_FLUSH) && room.roomType != ROOM_DUNGEON) @@ -795,9 +804,14 @@ static void flood_update(Room& room) float lava = room.lavaIntensity * LAVA_COOLING; if (lava < LAVA_SOLID && room.lavaIntensity >= LAVA_SOLID) - reconstruction_missing("Room::Update 00802980: the cooled lava's pits"); + for (int x = 1; x < room.gridWidth - 1; x++) + for (int y = 1; y < room.gridHeight - 1; y++) + { + GridEntity* grid = room.gridEntities[x + y * room.gridWidth]; + if (grid && grid->type == GRID_PIT) static_cast(grid)->UpdateCollision(); + } room.lavaIntensity = lava < LAVA_GONE ? 0 : lava; - reconstruction_missing("Room::Update 00802980: the cooling lava's screen color (FUN_00823540)"); + room.color_modifier_apply(); } // 00801ee0 Greed mode's waves: the wave timer runs down to the next wave (the wait cut short once the room is empty), @@ -880,7 +894,7 @@ void Room::Update() !(current.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CHALLENGE_DONE) && !entities_any(entityList, ENTITY_PICKUP, PICKUP_COLLECTIBLE)) game.ambush.StartChallenge(); - if ((roomType == ROOM_CHALLENGE || roomType == ROOM_BOSSRUSH) && game.ambush._isActive) game.ambush.Update(); + if ((roomType == ROOM_CHALLENGE || roomType == ROOM_BOSSRUSH) && game.ambush.isActive) game.ambush.Update(); if (isCardAgainstHumanity) card_against_humanity_fill(); int bosses = GetAliveBossesCount(); @@ -930,7 +944,7 @@ void Room::Update() flood_update(*this); bool isMamaMega = game.levelStateFlags & 1u << LEVEL_STATE_MAMA_MEGA && !(descriptor->flags & ROOM_DESCRIPTOR_FLAG_MAMA_MEGA); if (isMamaMega && isInitialized && game.frameCount - enterFrame == 1 && !game.IsPaused()) - reconstruction_missing("Room::MamaMegaExplosion 00820910"); + MamaMegaExplosion({}, nullptr); if (slowdownDuration > 0) slowdownDuration--; greed_wave_update(*this); update_ambient_sounds(); diff --git a/src/seeds.h b/src/seeds.h index cae9358..b36de2e 100644 --- a/src/seeds.h +++ b/src/seeds.h @@ -154,4 +154,13 @@ struct Seeds }; uint32_t Random(); + +constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; + +// random_float: a random fraction of one from the global generator. +inline float random_unit() +{ + return (float)Random() * RANDOM_UNIT_SCALE; +} + void random_seed(uint32_t seed); diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 71fe67d..f64879c 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -25,6 +25,7 @@ enum SoundLoop enum SoundId : int { SOUND_BIRD_FLAP = 2, + SOUND_BLOBBY_WIGGLE = 3, SOUND_BLOOD_LASER = 5, SOUND_BLOOD_LASER_SMALL = 6, SOUND_BLOOD_LASER_LARGE = 7, @@ -68,6 +69,7 @@ enum SoundId : int SOUND_TEAR_DETONATOR = 1063, SOUND_VENTRICLE_RAZOR = 1064, SOUND_DEVIL_CARD = 34, + SOUND_DOOR_HEAVY_OPEN = 36, SOUND_FART = 37, SOUND_FETUS_JUMP = 38, SOUND_FETUS_LAND = 40, @@ -215,10 +217,12 @@ enum SoundId : int SOUND_BONE_SNAP = 462, SOUND_BONE_DROP = 467, SOUND_BONE_BOUNCE = 499, + SOUND_TOOTH_AND_NAIL = 506, SOUND_SHOVEL_DIG = 464, SOUND_GOLD_HEART_DROP = 466, SOUND_CANDLE_LIGHT = 471, SOUND_BOSS2_DIVE = 474, + SOUND_BOSS2INTRO_PIPES_TURNON = 475, SOUND_DEMON_HIT = 477, SOUND_WOOD_PLANK_BREAK = 481, SOUND_BULLET_SHOT = 482, @@ -277,6 +281,9 @@ enum SoundId : int SOUND_DEATH_SPAWN_PREP = 929, SOUND_DEATH_HORSE_ATTACK = 930, SOUND_DEATH_HORSE_WOOSH = 931, + SOUND_PIN_DIVE = 932, + SOUND_PIN_POPUP = 933, + SOUND_PIN_SPIT = 935, SOUND_GISH_JUMP = 936, SOUND_GISH_JUMP_HIGH = 937, SOUND_GISH_SPIT = 938, @@ -340,6 +347,9 @@ enum SoundId : int SOUND_MONSTERS_NEXT_DOOR = 1008, SOUND_CAMBION_CONCEPTION = 1009, SOUND_IMMACULATE_CONCEPTION = 1010, + SOUND_CHARGEDBABY_BATTERY = 1011, + SOUND_CHARGEDBABY_CHARGE = 1012, + SOUND_CHARGEDBABY_STUN = 1013, SOUND_SHINYROCK_SHIMMER = 1014, SOUND_SISSYLONGLEG_CHARM = 1016, SOUND_NECROMANCER = 1049, @@ -347,6 +357,8 @@ enum SoundId : int SOUND_BAG_OF_CRAFTING = 1074, SOUND_GIANT_CHEST_OPEN = 1075, SOUND_BRAIN_MOVE = 1080, + SOUND_POISON_WARN = 590, + SOUND_POISON_HURT = 591, SOUND_POISON_MIND_HURT = 1081, SOUND_BUTTLICKER_GROWL = 1085, SOUND_POT_BREAK = 138, @@ -372,6 +384,7 @@ enum SoundId : int SOUND_HUSH_ROAR = 421, SOUND_HUSH_GROWL = 422, SOUND_HUSH_LOW_ROAR = 423, + SOUND_FRAIL_CHARGE = 424, SOUND_SISTERS_VIS_SCARE = 960, SOUND_RAGMEGA_BALL_ATTACK = 981, SOUND_RAGMEGA_BEAM = 982, @@ -393,6 +406,15 @@ enum SoundId : int SOUND_GNAWED_LEAF_STONE = 858, SOUND_BUTTER_DROP = 901, SOUND_TICK_BURN = 911, + SOUND_PORTAL_SPAWN = 162, + SOUND_VOID_CONSUME = 913, + SOUND_VOID_SUCCESS = 1071, + SOUND_CROOKED_PENNY = 851, + SOUND_MOVING_BOX_PACK = 892, + SOUND_MOVING_BOX_UNPACK = 893, + SOUND_SPIN_TO_WIN = 915, + SOUND_SHOVEL_DIG2 = 916, + SOUND_SHOVEL_HOLE_OPEN = 917, SOUND_VOID_FAIL = 1072, SOUND_ABYSS_SUCCESS = 1073, SOUND_ULTRA_GREED_SPINNING = 440, @@ -460,7 +482,23 @@ enum SoundId : int SOUND_LARYNX_SCREAM_HI = 577, SOUND_GLOWING_HOURGLASS_ACTIVATE = 861, SOUND_GLOWING_HOURGLASS_FIZZLE = 862, - SOUND_DECAP_ACTIVATE = 1046 + SOUND_DECAP_ACTIVATE = 1046, + SOUND_PORTAL_ENTITY_LOOP = 846, + SOUND_PORTAL_ENTITY_ENTER = 847, + SOUND_MEGABEAN_BLAST = 869, + SOUND_EXPLOSION_STRONG = 184, + SOUND_EXPLOSION_DEBRIS = 186, + SOUND_SOUL_PICKUP = 579, + SOUND_BOSS_EXPLOSION = 182, + SOUND_EXPLOSION_WEAK = 183, + SOUND_ROCKET_EXPLOSION = 587, + SOUND_GFUEL_EXPLOSION = 822, + SOUND_GFUEL_EXPLOSION_BIG = 823, + SOUND_GLITTER_BOMB = 866, + SOUND_REVERSE_EXPLOSION = 511, + SOUND_BEAST_LAVABALL_RISE = 814, + SOUND_DOGMA_JACOBS_ZAP = 551, + SOUND_DOGMA_JACOBS_DOT = 557 }; // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. diff --git a/src/tainted_characters.cpp b/src/tainted_characters.cpp index 2c84332..1f79a87 100644 --- a/src/tainted_characters.cpp +++ b/src/tainted_characters.cpp @@ -498,7 +498,7 @@ static EffectUpdateEnd anima_chain_head_update(Entity_Effect& chain) esau->entityRef = &chain; esau->entityCollisionClass = ENTCOLL_ALL; } - target->velocity = vector_scale(target->velocity, npc_friction_scaled(ANIMA_SLOW, target->speedMultiplier)); + target->velocity = vector_scale(target->velocity, timescale_factor(ANIMA_SLOW, target->speedMultiplier)); if (chain.timeout <= 0 || chain.timeout > ANIMA_BLINK_START) return EFFECT_UPDATE_FINISH; int interval = chain.timeout >= ANIMA_BLINK_SLOW_END ? ANIMA_BLINK_SLOW @@ -531,7 +531,7 @@ static EffectUpdateEnd anima_chain_peg_update(Entity_Effect& peg) return EFFECT_UPDATE_FINISH; } - peg.minRadius = lerp_clamped(peg.updateTime, 0, ANIMA_REACH_FRAMES, 0, 1); + peg.minRadius = lerp_range(peg.updateTime, {0, ANIMA_REACH_FRAMES, 0, 1}); peg.targetPosition = vector_add(peg.pos, vector_scale(vector_sub(head->pos, peg.pos), peg.minRadius)); if (head->isVisible && head->target) head->target->AddVelocity(vector_scale(vector_sub(peg.pos, head->target->pos), ANIMA_TUG), false); diff --git a/src/weapon.cpp b/src/weapon.cpp index d9092a1..0ee601c 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -97,19 +97,10 @@ enum CostumeLayers COSTUME_LAYERS_HEAD }; -// A vector turned by an angle in degrees. -static Vector vector_rotate(Vector v, float degrees) -{ - float radians = degrees * DEGREES_TO_RADIANS; - float cosine = std::cos(radians); - float sine = std::sin(radians); - return vector_make(v.x * cosine - v.y * sine, v.x * sine + v.y * cosine); -} - // A vector turned by a random angle within half a spread either side, or as it is without a spread. static Vector vector_spread(Vector v, float spreadAngle) { - return spreadAngle == 0 ? v : vector_rotate(v, (random_unit() - 0.5f) * spreadAngle); + return spreadAngle == 0 ? v : vector_rotated(v, (random_unit() - 0.5f) * spreadAngle); } // 009f9020 Makes the weapon of a type for an owner through the type's maker: tears (009f9260), the lasers @@ -1011,7 +1002,8 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn if (eyeMode != 0) shooter->tearDisplacement = (int8_t)eyeMode; else shooter->tearDisplacement = (int8_t)(eyeCount == 2 ? (eye == 0 ? -1 : 1) : -tear_displacement()); eyeSide = tear_displacement(); - if (is_shot_rotated()) shotDirection = vector_rotate(shotDirection, (float)eyeSide * SHOT_ROTATION_DEGREES); + if (is_shot_rotated()) + shotDirection = vector_rotated(shotDirection, (float)eyeSide * SHOT_ROTATION_DEGREES); if (kind.isChocolateMilk || kind.isNeptunus || params.numTears > 1 || shooter->HasCollectible(COLLECTIBLE_POLYPHEMUS) || shooter->HasCollectible(COLLECTIBLE_IPECAC)) eyeSide = 0; @@ -1064,7 +1056,7 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn extra_fire(vector_make(base.y, -base.x)); } for (int i = 0; i < params.numRandomDirTears; i++) - extra_fire(vector_rotate(base, random_unit() * FULL_TURN)); + extra_fire(vector_rotated(base, random_unit() * FULL_TURN)); if (eyeSide != 0) { diff --git a/src/weapon_monstros_lung.cpp b/src/weapon_monstros_lung.cpp index 020cd6f..763de33 100644 --- a/src/weapon_monstros_lung.cpp +++ b/src/weapon_monstros_lung.cpp @@ -212,8 +212,8 @@ void Weapon_MonstrosLung::Fire(const Vector& shootDirection, bool isShooting, bo { float angle = 0; if (params.numEyesActive > 1) - angle = lerp_clamped((float)i, 0, (float)params.numEyesActive - 1, -params.multiEyeAngle, - params.multiEyeAngle); + angle = lerp_range((float)i, + {0, (float)params.numEyesActive - 1, -params.multiEyeAngle, params.multiEyeAngle}); FireBurst(tear_vector_rotate(base, angle), perBurst, damageMultiplier); } if (params.isShootingBackwards) FireBurst(vector_make(-base.x, -base.y), perBurst, damageMultiplier); diff --git a/src/weapon_rockets.cpp b/src/weapon_rockets.cpp index d88c918..86e1d41 100644 --- a/src/weapon_rockets.cpp +++ b/src/weapon_rockets.cpp @@ -356,6 +356,15 @@ static void target_render(Entity_Effect& effect, const Vector&) line.RenderFrame(draw, 0, effect.sprite); } +// Whether a player's rockets burst into their shots: Brimstone, Mom's Knife, Technology or Tech X, held or fired. +bool is_rocket_burst(Entity_Player& player) +{ + return player.HasCollectible(COLLECTIBLE_BRIMSTONE) || player.HasWeaponType(WEAPON_BRIMSTONE) || + player.HasCollectible(COLLECTIBLE_MOMS_KNIFE) || player.HasWeaponType(WEAPON_KNIFE) || + player.HasCollectible(COLLECTIBLE_TECHNOLOGY) || player.HasWeaponType(WEAPON_LASER) || + player.HasCollectible(COLLECTIBLE_TECH_X) || player.HasWeaponType(WEAPON_TECH_X); +} + // 005d4380 (variant 31) A rocket falling on its target: it drops toward it, shows its landing frame at the end, and // blows up with its player's tear effects and twenty times its damage (Brimstone, Mom's Knife, Technology and Tech X // add a burst of their shots). @@ -373,11 +382,7 @@ static EffectUpdateEnd rocket_update(Entity_Effect& effect) if (player) { TearParams params = player->GetTearHitParams(WEAPON_ROCKETS, 1, random_below(2) * 2 - 1, spawner); - bool isBurst = player->HasCollectible(COLLECTIBLE_BRIMSTONE) || player->HasWeaponType(WEAPON_BRIMSTONE) || - player->HasCollectible(COLLECTIBLE_MOMS_KNIFE) || player->HasWeaponType(WEAPON_KNIFE) || - player->HasCollectible(COLLECTIBLE_TECHNOLOGY) || player->HasWeaponType(WEAPON_LASER) || - player->HasCollectible(COLLECTIBLE_TECH_X) || player->HasWeaponType(WEAPON_TECH_X); - if (isBurst) params.tearFlags.set(TEAR_SAD_BOMB); + if (is_rocket_burst(*player)) params.tearFlags.set(TEAR_SAD_BOMB); blast.tearFlags = params.tearFlags; blast.color = params.tearColor; blast.damage = params.tearDamage * ROCKET_DAMAGE_SCALE; diff --git a/src/weapon_rockets.h b/src/weapon_rockets.h index d7a0a76..26a57ca 100644 --- a/src/weapon_rockets.h +++ b/src/weapon_rockets.h @@ -24,4 +24,5 @@ struct Weapon_Rockets : Weapon }; Weapon* weapon_rocket_make(WeaponType type); +bool is_rocket_burst(Entity_Player& player); std::span weapon_effect_behaviours();